Vim:保存时创建父目录 [英] Vim: Creating parent directories on save

查看:25
本文介绍了Vim:保存时创建父目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我调用 vim foo/bar/somefilefoo/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆