问题描述
限时送ChatGPT账号..如果我调用 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.
我知道我可以切换到 shell 或从 Vim 执行 :!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屋!
更多推荐
[db:关键词]
发布评论