Automatically reload current file in vim after code formatter has run on save

1.9k views Asked by At

I am trying to to acheive the following every time a file is saved in Vim under Windows 10 (Vim 8.2):

  1. Auto format the file (using an external tool, e.g. Uncrustify)
  2. Reload the formatted file in Vim (I want to see the newly formatted file)

Right now I am able using autocmd to autoformat the file, by adding the following to my .vimrc:

autocmd BufWritePost * silent! !start /min Autoformat.bat <afile>

The problem is that the file contents is not updated on the screen (I still see the unformatted file). I have to go out of focus and come back to see a prompt to reload the file. What is missing to refresh the file?

After some research, I have tried the following so far:

  1. Add autocmd BufWritePost * !edit (manually, it works)
  2. Add autocmd BufWritePost * !redraw

but it does not seem to work.


Note: The silent! !start /min silence the annoying command prompt that used to flash by on every save (on Windows).


The following worked for me on Windows:

set autoread
autocmd BufWritePost * silent! !C:\Users\epoirier\Documents\BufWritePost.bat <afile>
autocmd BufWritePost * redraw!

I still see the console flashing by for (less than) a second, but I can live with that since Vim reloads the file automaticaly and I can keep working.

1

There are 1 answers

6
MarcoLucidi On BEST ANSWER

can't test this on Windows 10 right now, but on Linux I'm trying a similar setup that works:

autocmd BufWritePost * silent! !start /min Autoformat.bat <afile>
autocmd BufWritePost * edit
autocmd BufWritePost * redraw!

file reload is triggered with edit (as you already discovered) without prepending !

! executes a shell command but edit is a vim command, we don't need ! before the command (same thing applies to redraw).

redraw! is necessary because silent can mess up the screen when used for an external command.


an alternative (and I think better suited) solution to reload the file is by using autoread option instead of triggering edit. from :help autoread:

'autoread' 'ar'

When a file has been detected to have been changed outside of Vim and it has not been changed inside of Vim, automatically read it again.

lines on .vimrc become:

set autoread
autocmd BufWritePost * silent! !start /min Autoformat.bat <afile>
autocmd BufWritePost * redraw!