As far as I know there is no setting or some such to do this. But not all is lost, we can of course use the
This is executed before the buffer is written to the disk. So we can create the directory there if it doesn't exist yet.
autocmd BufWritePre * call mkdir(expand("<afile>:p:h"), "p")
<afile> refers to the file we're trying to save;
:p is a modifier to expand it to the full pathname (rather than relative), and
:h removes the last path component (the file).
- We then call
mkdir() if required. We need the
p flag for
mkdir() to make all parents directories (i.e. in the case of
nonexistent/more_nonexisting/file), which also ensures it won't error out if the directory already exists.
You could, of course, also run the
mkdir() command from the Vim commandline, or bind it to a keybind, ie:
nnoremap <Leader>m :call mkdir(expand("%:p:h"), "p")<CR>
Here I used
% instead of
<afile>, since that's only valid from within an autocommand (
% refers to the currently active buffer, which would not work with
:wa for example;
<afile> refers to the filename of the buffer that triggers the autocmd).
You can also ask for a confirmation before writing a directory if you want. See this question for more details: How can I stop Vim from writing a file in BufWritePre autocommand?
The above snippet will create the directory on the first write (
:w). You could, if you wanted, also create the directory when you first open it (i.e. just after typing
vim ...) by using the
BufNewFile autocmd instead of
There is also a plugin called auto_mkdir which is effectively the same a the above.
On this page
there is a slightly expanded snippet which also asks you if you want to create the directory first, which some may consider to be useful. It also has converts the filename of the encoding before writing it:
call mkdir(iconv(expand("%:p:h"), &encoding, &termencoding), 'p')
I'm not sure if this is actually required though, but if you mix encodings a lot and get weird filenames, you could try it.
I put all of the above in an
auto_mkdir2.vim plugin for easier installation.