87

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.

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Running Turtle
  • 12,360
  • 20
  • 55
  • 73

2 Answers2

113

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 *
peterh
  • 11,875
  • 18
  • 85
  • 108
Alex Howell
  • 1,311
  • 1
  • 9
  • 3
  • 3
    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 ? – Running Turtle Jan 10 '11 at 22:11
  • 3
    @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. – blueyed Jun 03 '11 at 10:00
  • This works, but what if you want to pass the full path to the file. Is it possible? https://stackoverflow.com/questions/51272435/vim-autocommand-on-write-pass-full-file-path – Maciej Krawczyk Jul 10 '18 at 19:06
  • 1
    How to do this quietly in the background so you won't get the output? – botenvouwer Feb 20 '19 at 18:24
  • 3
    @botenvouwer Try `:autocmd BufWritePost * silent !run_tests.sh `. 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. – tremby Jul 11 '19 at 22:02
  • 5
    and for before save it's `BufWritePre` – andorov Sep 26 '19 at 16:14
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.
Siwei
  • 19,858
  • 7
  • 75
  • 95