Vim: Creating parent directories on save

前端 未结 6 1809
一生所求
一生所求 2020-12-07 08:32

If I invoke vim foo/bar/somefile but foo/bar don\'t already exist, Vim refuses to save.

I know I could switch to a shell or do :!mkdi

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 09:29

    I think I managed to do this in three lines, combining what others are saying on this answer.

    This seems to do the trick:

    if has("autocmd")
      autocmd BufWritePre * :silent !mkdir -p %:p:h
    end
    

    It attempts to create the folder automatically when saving a buffer. If anything bad happens (i.e. permission issues) it will just shut up and let the file write fail.

    If anyone sees any obvious flaws, please post a comment. I'm not very versed in vimscript.

    EDIT: Notes thanks to ZyX

    • This will not work if your folders have spaces on them (apparently they are not properly escaped or something)
    • Or if you are doing pseudo files.
    • Or if you are sourcing your vimrc.
    • But son, it is short.

提交回复
热议问题