如果我调用vim foo/bar/somefile但foo/bar尚未存在,Vim拒绝保存.
我知道我可以切换到一个shell或:!mkdir foo/bar从Vim 做,但我很懒惰:)有没有办法让Vim在保存缓冲区时自动执行此操作?
ZyX*_*ZyX 88
augroup BWCCreateDir
autocmd!
autocmd BufWritePre * if expand("<afile>")!~#'^\w\+:/' && !isdirectory(expand("%:h")) | execute "silent! !mkdir -p ".shellescape(expand('%:h'), 1) | redraw! | endif
augroup END
Run Code Online (Sandbox Code Playgroud)
注意条件:expand("<afile>")!~#'^\w\+:/'将阻止vim为文件创建目录ftp://*,!isdirectory并将阻止昂贵的mkdir调用.
更新:更好的解决方案,也检查非空buftype和使用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
Run Code Online (Sandbox Code Playgroud)
Dam*_*let 18
基于对我的问题的建议,这是我最终得到的:
function WriteCreatingDirs()
execute ':silent !mkdir -p %:h'
write
endfunction
command W call WriteCreatingDirs()
Run Code Online (Sandbox Code Playgroud)
这定义了:W命令.理想情况下,我想有所有的:w!,:wq,:wq!,:wall等工作相同,但我不知道是否有可能基本上没有重新实现他们所有的自定义功能.
此代码将提示您使用 创建目录:w,或者直接使用:w!:
augroup vimrc-auto-mkdir
autocmd!
autocmd BufWritePre * call s:auto_mkdir(expand('<afile>:p:h'), v:cmdbang)
function! s:auto_mkdir(dir, force)
if !isdirectory(a:dir)
\ && (a:force
\ || input("'" . a:dir . "' does not exist. Create? [y/N]") =~? '^y\%[es]$')
call mkdir(iconv(a:dir, &encoding, &termencoding), 'p')
endif
endfunction
augroup END
Run Code Online (Sandbox Code Playgroud)
我把它添加到我的〜/ .vimrc中
cnoremap mk. !mkdir -p <c-r>=expand("%:h")<cr>/
如果我需要在我类型来创建我的目录:mk.,并将其替换为"!的mkdir -p /路径/要/我的/文件/",并让我之前,我调用它查看命令.
我不明白为什么每个人都尝试复杂的功能。这足以创建父文件夹
:!mkdir -p %:p:h
Run Code Online (Sandbox Code Playgroud)
mkdir -p是创建父文件夹的 shell 命令%:p:h是文件夹路径
% :vim启动时给出的路径:vim foo/bar/file.ext:p: 给出完整路径:/home/user/foo/bar/file.ext:h:从最终字符串中删除文件名:/home/user/foo/bar%:h也可以工作并给出相对路径:foo/bar