autocmd event to execute a command on :wq - vimscript?

☆樱花仙子☆ 提交于 2019-12-14 01:16:55

问题


I want to execute system("cp /home/currently_opened_file.txt /somewhere/else") when I exit vim with :wq. Is there an autocmd event for that? Or any other way to do it?


回答1:


Update:

The OP noted in comments that this combination did exactly what was wanted (execute the command only on :wq).

:autocmd BufWritePost * :autocmd VimLeave * :!cp % /somewhere/else

Original answer:

You can hook the BufWritePost event. This will run the command on every write, not only when you use :wq to leave the file.

:autocmd BufWritePost * :!cp % /somewhere/else

I suppose you could try hooking the BufDelete event (before deleting a buffer from the buffer list), but that seems like it would be problematic, as buffers are used for more than file editors. They are also used for things like quicklists, the help viewer, etc.

There are some events that take place when you are quitting, which could be an option.

QuitPre        when using :quit, before deciding whether to quit
VimLeavePre    before exiting Vim, before writing the viminfo file
VimLeave       before exiting Vim, after writing the viminfo file

You can see the full list using :help autocmd-events.

Also note that you can restrict what matches the event. For instance, if you only want this to happen for HTML files and CSS files, you could use this:

:autocmd QuitPre *.html,*.css :!cp % /somewhere/else

I suspect you will need to experiment and see what works for you.




回答2:


It looks like you need to automatically cascade the writing of a file to another location. My DuplicateWrite plugin provides comfortable commands to set up such. (The plugin page has links to alternative plugins.)

:DuplicateWrite /somewhere/else


来源:https://stackoverflow.com/questions/39100915/autocmd-event-to-execute-a-command-on-wq-vimscript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!