Automatically create directory upon editing (with confirmation)

7 Points

Andrew Radev Andrew Radev

9 years ago

If I edit a file in a directory that doesn't yet exist, it's usually because I forgot to create the directory first. This autocommand asks whether it should do that for me.

If this happens to be a mistake (maybe I'm not where I thought I would be), I can easily enter "n" at the prompt to cancel the process. If you'd rather not have the confirmation dialog at all, just remove the relevant if-clause.

augroup ensure_directory_exists
  autocmd!
  autocmd BufNewFile * call s:EnsureDirectoryExists()
augroup END

function! s:EnsureDirectoryExists()
  let required_dir = expand("%:h")

  if !isdirectory(required_dir)
    " Remove this if-clause if you don't need the confirmation
    if !confirm("Directory '" . required_dir . "' doesn't exist. Create it?")
      return
    endif

    try
      call mkdir(required_dir, 'p')
    catch
      echoerr "Can't create '" . required_dir . "'"
    endtry
  endif
endfunction