Sumit Dhingra
Sumit Dhingra

Reputation: 123

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

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?

Upvotes: 3

Views: 2493

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172510

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

Upvotes: 0

Dan Lowe
Dan Lowe

Reputation: 56498

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.

Upvotes: 4

Related Questions