How can I create a folder if it doesn't exist, from .vimrc?

Viewed 16766

I don't like how Vim clutters up my folders with backup files, so I have the following line in my .vimrc file:

set backupdir=~/.vim_backup

However, sometimes this folder doesn't exist because of new machines where I am copying my user files over.

How can I create this folder automatically if it doesn't exist, from within .vimrc? Or is there some better way to deal with this situation?

8 Answers

I wanted a solution to this that works on both Linux and on Windows (with Cygwin binaries on the path.) - my Vim config is shared between the two.

One problem is that 'mkdir' is, I think, built-in to the cmd shell on windows, so it can't be overridden by putting the Cygwin mkdir executable earlier in the path.

I solved this by invoking a new bash shell to perform the action: From there, 'mkdir' always means whatever mkdir executable is on the path:

!bash -c "mkdir -p ~/.vim-tmp"

However, this has the problem that. on Windows at least, it pops up a new window for the cmd shell that '!' invokes. Don't want that every time I start vim. Then I discovered the vim function 'system', which invokes a new cmd shell (the icon appears in the Windows taskbar) but the window is minimised. Hence:

call system("bash -c \"mkdir -p ~/.vim-tmp\"")

Ugly but works.

I have a command in my vimrc that enables me to make a directory corresponding to the buffer presently frontmost:

nmap <silent> ,md :!mkdir -p %:p:h<CR>

This can be used to create a directory any place you care to put one locally or remotely via netrw if you the permissions to do so.

This is built into Vim, so you can simply:

call mkdir($HOME . "/tmp")

You can also specify the p flag to have the command operate in the same way mkdir -p would:

call mkdir($HOME . "/tmp", "p")

For details see :help mkdir or the vim manual online.

This is what I am currently using in my .vimrc file and I think it looks quite clean and simple:

if empty(glob($HOME . '/.vim/undodir'))
  call mkdir($HOME . '/.vim/undodir', 'p')
endif
Related