Vim:在保存时创建父目录 [英] Vim: Creating parent directories on save
问题描述
如果我调用vim foo/bar/somefile
但foo/bar
不存在,Vim拒绝保存.
If I invoke vim foo/bar/somefile
but foo/bar
don't already exist, Vim refuses to save.
我知道我可以从Vim切换到shell或执行:!mkdir foo/bar
,但是我很懒:)
有什么方法可以使Vim在保存缓冲区时自动执行此操作?
I know I could switch to a shell or do :!mkdir foo/bar
from Vim but I'm lazy :)
Is there a way to make Vim do that automatically when it saves the buffer?
推荐答案
augroup BWCCreateDir
autocmd!
autocmd BufWritePre * if expand("<afile>")!~#'^\w\+:/' && !isdirectory(expand("%:h")) | execute "silent! !mkdir -p ".shellescape(expand('%:h'), 1) | redraw! | endif
augroup END
注意条件:expand("<afile>")!~#'^\w\+:/'
将阻止vim为诸如ftp://*
的文件创建目录,而!isdirectory
将阻止昂贵的mkdir调用.
Note the conditions: expand("<afile>")!~#'^\w\+:/'
will prevent vim from creating directories for files like ftp://*
and !isdirectory
will prevent expensive mkdir call.
更新:更好的解决方案,它也检查非空buftype并使用mkdir()
:
Update: sligtly better solution that also checks for non-empty buftype and uses mkdir()
:
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
这篇关于Vim:在保存时创建父目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!