Create file inside new directory in vim in one step?
vim
Solution
Try the following command:
function s:MKDir(...)
if !a:0
\|| stridx('`+', a:1[0])!=-1
\|| a:1=~#'\v\\@<![ *?[%#]'
\|| isdirectory(a:1)
\|| filereadable(a:1)
\|| isdirectory(fnamemodify(a:1, ':p:h'))
return
endif
return mkdir(fnamemodify(a:1, ':p:h'), 'p')
endfunction
command -bang -bar -nargs=? -complete=file E :call s:MKDir(<f-args>) | e<bang> <args>
This command is intended to be a replacement for built-in `:e`.
Conditions in which mkdir is not run (in order):
- Command is run without arguments
- Command is run with ``generate filename`` or ``=generate_filename()`` backticks filename generators or with `+command`/`++opt` switches.
- Command contains more then one argument or has unescaped special characters.
- Argument is a directory.
- Argument is an existing file.
- Argument is a file in an existing directory.
In last three cases nothing should be done, second and third cases are not impossible to handle, just more complicated.
The above is ready for adding a `cnoreabbrev`:
cnoreabbrev <expr> e ((getcmdtype() is# ':' && getcmdline() is# 'e')?'E':'e')
`-complete=file` spoils things: it add not only completion, but also arguments processing (thus checking for
`-bar` makes you unable to use ``="String"`` because `"` now starts a comment. Without `-bar` it is not a `:e` emulation because you can’t do `E file | another command`.
Another version:
function s:MKDir(...) if !a:0 \|| isdirectory(a:1) \|| filereadable(a:1) \|| isdirectory(fnamemodify(a:1, ':p:h')) return endif return mkdir(fnamemodify(a:1, ':p:h'), 'p') endfunction command -bang -bar -nargs=? -complete=file E :call s:MKDir(<f-args>) | e<bang> <args>
Problem
While in vim I want to create a new file called `blog_spec.rb` inside `[working directory]/spec/models/`, but the directory doesn't exist yet? What's the fastest way to create the directory and start editing the file? Any oneliners?