vimtricks.wiki Concise Vim tricks, one at a time.

How do I prevent duplicate autocommands when reloading vimrc?

Answer

augroup name | autocmd! | ... | augroup END

Explanation

Using augroup with autocmd! inside prevents duplicate autocommands from accumulating when you reload your vimrc.

How it works

  • augroup name starts a named group
  • autocmd! clears all autocommands in the group
  • Define new autocommands
  • augroup END closes the group

Example

augroup MyGroup
    autocmd!
    autocmd BufWritePre * :%s/\s\+$//e
    autocmd FileType python setlocal tabstop=4
augroup END

Tips

  • Without augroup + autocmd!, each :source ~/.vimrc adds duplicates
  • Name groups descriptively
  • Each group can contain multiple autocommands
  • autocmd! at the start of the group clears the old ones
  • This is the standard pattern for vimrc autocommands

Next

How do you yank a single word into a named register?