vimtricks.wiki Concise Vim tricks, one at a time.

How do I save a file and automatically create missing parent directories in Neovim?

Answer

:w ++p

Explanation

Neovim's :w ++p flag automatically creates any missing intermediate directories when writing a file. Instead of getting an E212: Can't open file for writing error and running !mkdir -p separately, you can create the directories and write in one step.

How it works

  • :w writes the buffer to disk
  • ++p is a Neovim-specific write modifier (available since Neovim 0.8) that creates all missing parent directories in the file path
  • Standard Vim does not support ++p — use :!mkdir -p %:h then :w instead

Example

Opening a new file in a directory tree that doesn't exist yet:

:e src/utils/helpers/string.lua
" Edit the file...
:w ++p
" Neovim creates src/utils/helpers/ automatically and writes the file

Without ++p, this would fail with:

E212: Can't open file for writing

Tips

  • Works with :saveas ++p {newpath} to save to a new location with parent creation
  • In standard Vim, use :call mkdir(expand('%:h'), 'p') then :w as an equivalent
  • You can map this for convenience in your config:
nnoremap <leader>W :w ++p<CR>

Next

How do I duplicate every line matching a pattern, placing a copy directly below each one?