且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Vim:保存时创建父目录

更新时间:2023-10-06 12:54:22

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