Vim will not create parent directories if they do not exist on write.
A common method to ensure the path exists is to use an autocmd
to
check if the parent path exists and if not create it.
function! MkDir(path) abort
if !isdirectory(a:path)
call mkdir(a:path, 'p')
endif
endfunction
augroup MkDir
autocmd!
autocmd BufWritePre * call MkDir(expand('<afile>:p:h'))
augroup END
This is effective but hardly efficient. Every time we write any buffer we check for the existence of the parent path.
Firstly the BufWritePre
event can be swapped for the BufNewFile
event, the
later being triggered far less often. However this means if we open a new file
but choose to abandon it (not writing it) we now have inadvertently created
a path on disk. Instead of immediately creating the path we want to defer it to
when/if the buffer is written. So upon editing a new file check if its parent
path exists, if not set up a buffer local one shot autocmd
to create the path
prior to any attempt to write it.
function! MkDir(path) abort
if !isdirectory(a:path)
execute "autocmd MkDir BufWritePre <buffer>"
\ "call mkdir(" . a:path . ", 'p')"
\ "| autocmd! MkDir * <buffer>"
endif
endfunction
augroup MkDir
autocmd!
autocmd BufNewFile * call MkDir(expand('<afile>:p:h'))
augroup END
This checks the path once and only creates it (if needed) on write.