I would like to set an autocommand that automatically resources the file whenever I save it, as now I am doing something like:

:w | so %

Whenever I save something.

What would be the correct 'event' to do this with? For example:

augroup uncompress
    au (BufWritePre? BufWritePost? BufWrite? BufWriteCmd? FileWritePre? etc.) *.vim  :so %<CR>
augroup END

What is the main difference between BufWrite and FileWrite ? From the docs it seems pretty similar:

BufferWritePre starting to write the whole buffer to a file

FileWritePre starting to write part of a buffer to a file

2 Answers 2


While answering questions here , I often write little Vim script files to test something. To automatically source the file, I use the following command:

command! VimTest autocmd BufWritePost <buffer> redraw! | source % | echo 'Sourced ' . fnamemodify(expand('%'), ':t')

When I decide that the current script should be re-sourced on every save, I execute :VimTest.

This installs a buffer-local autocmd that

  1. forces a redraw (to remove Vim's write message filename <lines>L, chars>C)
  2. sources the just saved file
  3. Prints that the file was sourced.

In this special case I do it without a augroup, that I would normally always recommend.

See :h autocmd-buflocal.

  • I see. Why do you cuse the BurWritePost event here (as opposed to FileWritePost or some of the other events)? Could you please explain why that event is the best suited for this particular task?
    – David542
    Jun 22, 2020 at 17:36
  • @David542 This is a buffer-local autocmd (I've added the help topic), so FileWritePost wouldn't make sense. Just when the current buffer is saved, run the commands.
    – Ralf
    Jun 22, 2020 at 18:27

BufWritePost is the event you typically want. It needs to be a Post event because you want to source the contents of the file after they've been saved.

It's conceivable you might also want to cover FileWritePost, in case you want to also source a *.vim file when you write it through an operation taking a range, such as :'<,'>w newfile.vim with a Visual selection, to create a new Vimscript file with only parts of the current buffer, perhaps you're splitting a function into its own script file...

Also note you should use <afile> for the path of the file that matched the autocmd. It's not necessarily %, especially in the FileWritePost case.

You might also want to cover the vimrc file through the same rule. You need to list its possible paths explicitly, since they don't really match *.vim.

augroup vimscript_source
  au BufWritePost,FileWritePost *.vim,~/.vimrc,~/.vim/vimrc source <afile>
augroup END

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.