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

How do I prevent autocommands from being registered multiple times when re-sourcing my vimrc?

Answer

augroup MyGroup | autocmd! | augroup END

Explanation

Every time you run :source $MYVIMRC or :source % to reload your config, any bare autocmd calls are appended to Vim's autocommand table — no checking for duplicates. After a few reloads, a single event handler fires two, three, or ten times. This causes subtle bugs like multiple format-on-save triggers or cascading linting runs.

The fix is to wrap every autocommand in a named augroup and start it with autocmd!, which clears the group before re-adding the commands.

How it works

augroup MyGroup
  autocmd!                          " Clear all autocmds in this group
  autocmd BufWritePre *.go :GoFmt   " Re-add your commands fresh
augroup END
  • augroup MyGroup — creates (or reopens) an autocommand group
  • autocmd! — removes all autocommands in the current group (scoped to MyGroup only, not other groups)
  • Each subsequent autocmd is registered fresh in MyGroup
  • augroup END — closes the group

Example

Without augroup, sourcing vimrc twice registers the autocmd twice:

Before fix: source vimrc 3 times → format-on-save fires 3 times per save

With augroup:

After fix: source vimrc any number of times → format-on-save fires exactly once

Tips

  • Use a unique group name per feature or plugin section to avoid cross-contamination
  • autocmd! with no pattern clears the entire group; autocmd! BufWritePre *.go clears only matching entries
  • In Neovim Lua, use vim.api.nvim_create_augroup('MyGroup', { clear = true }) for the same guarantee

Next

How do I mark and delete multiple files at once from within Vim's built-in file explorer netrw?