How to automatically execute a shell command after saving a file in Vim?
Asked Answered
G

2

88

This is because I'd like to automatically run tests after each file save.

I have looked at autocmd and BufWritePost but cannot make it work.

Gastrectomy answered 7/1, 2011 at 16:26 Comment(0)
E
115

This runs run_tests.sh after any file is saved, with the current filename as the only parameter:

:autocmd BufWritePost * !run_tests.sh <afile>

View the auto-command with:

:autocmd BufWritePost *

And remove all auto-commands from the previous with:

:autocmd! BufWritePost *
Ellingson answered 7/1, 2011 at 17:12 Comment(6)
Is there a way to to something like this ?: if a file named tests.html is present in the current directory OR in the directory just above then run command testprog tests.html OR cd .. testprog tests.html ?Gastrectomy
@Running Turle: I would create a function for this and then use it in an autocmd. Use filereadable() to test if there is a file and then act accordingly.Afterimage
This works, but what if you want to pass the full path to the file. Is it possible? #51272935Gravity
How to do this quietly in the background so you won't get the output?Stratigraphy
@Stratigraphy Try :autocmd BufWritePost * silent !run_tests.sh <afile>. Output will still be written to the console, but vim won't wait for you to acknowledge. Send a "quiet"/"silent" option to your specific command or add >/dev/null to blackhole its output if need be.Orelle
and for before save it's BufWritePreAntitragus
M
1

put this into your .vimrc file:

(take raml2html doc/api.raml > public/api_doc.html as a command example)

autocmd BufWritePost,FileWritePost *.raml silent! !raml2html doc/api.raml > public/api_doc.html

notice:

  • silent! will hide all the output of this command
  • :silent if you are using vim7.3-, and silent! if using vim7.3+
  • need to quit and restart vim, to make .vimrc take effect.
Metallophone answered 11/12, 2022 at 0:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.