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
:wwrites the buffer to disk++pis 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 %:hthen:winstead
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:was an equivalent - You can map this for convenience in your config:
nnoremap <leader>W :w ++p<CR>