This might be better for super user, but I figure as a tool of the trade it might be a better topic for here. I find often when editing in vim that I exit out, run some script that I am testing, and then go back into vim (yes I realize I can use :!command to run things from vim) I was just wondering if there is a way to hook something to run when the file is saved (:w)?
4 Answers
See :he :autocmd
and :he BufWritePost
The line would look like this:
:autocmd BufWritePost /path/to/file/or/pattern !command <afile>
If the <afile>
thing does not work use %:p
.
- 1,060
- 8
- 8
I got the "getting back to vim" part, but I'm not sure how to hit the ":w" command itself (which would be very handy, since that's quite reflexive for me)
w | silent execute "! myscript" | redraw!
I think it may be better for superuser as well.
- 439
- 1
- 3
- 8
This is blatant self-promotion, but I wrote a Vim plugin that will trigger certain shell scripts to be run after specific Vim autocmd
events. For example, a script named .bufwritepost.vimhook.sh
would be run (synchronously) every time the BufWritePost
command is fired. You could then easily include whatever arbitrary logic you want for doing stuff inside that script. The plugin assumes specific naming conventions of these scripts and also supports "hook" scripts which trigger only on files matching certain names or having certain extensions. And of course, you are free to choose any autocmd
event you wish, although I have found BufWritePost
fits most of my use cases.
Full details: https://github.com/ahw/vim-hooks
- 11
- 2