Vim:保存时创建父目录

编程入门 行业动态 更新时间:2024-10-27 10:22:14
本文介绍了Vim:保存时创建父目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如果我调用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 15:53:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/834258.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目录   Vim

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!