Vim: Create a Directory

07/05/20191 Min Read — In Vim, DevTools

Let's say that you create a new file in a buffer:

:e src/components/header/header.component.jsx

What happens if you didn't create the header directory first?

E212: Can't open file for writing: no such file or directory

What now?

You can still create the directory and save the file. In NeoVim, you can use the inbuilt terminal to issue the following command:

:!mkdir src/components/header

That's not very convenient. There's a shorthand syntax:

:!mkdir -p %:h

Slightly better. % is for the name of the current file, %h is for the current directory (the "head" of the path). mkdir -p is the standard UNIX command to create a folder if it doesn't exist yet. You have to prefix it with ! in the NeoVim terminal.

Write VimScript

You can take a look at the different solutions on StackOverflow.

Here is the highest-voted solution which works on my machine:

function s:MkNonExDir(file, buf)
if empty(getbufvar(a:buf, '&buftype')) && a:file!~#'\v^\w+\:\/'
let dir=fnamemodify(a:file, ':h')
if !isdirectory(dir)
call mkdir(dir, 'p')
endif
endif
endfunction
augroup BWCCreateDir
autocmd!
autocmd BufWritePre * :call s:MkNonExDir(expand('<afile>'), +expand('<abuf>'))
augroup END

Plugin?

The prolific Tim Pope wrote a plugin that adds UNIX shell command utilities to (Neo)Vim. It has the funny name vim-eunuch.

The command :Mkdir creates a directory, relative to the current file's containing folder.

Further Reading