Skip to content

Instantly share code, notes, and snippets.

@g0xA52A2A
Last active December 30, 2020 13:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g0xA52A2A/85d55ab933535b7c76fc7ea6d913a1d4 to your computer and use it in GitHub Desktop.
Save g0xA52A2A/85d55ab933535b7c76fc7ea6d913a1d4 to your computer and use it in GitHub Desktop.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment