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 groupautocmd!— removes all autocommands in the current group (scoped toMyGrouponly, not other groups)- Each subsequent
autocmdis registered fresh inMyGroup 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 *.goclears only matching entries- In Neovim Lua, use
vim.api.nvim_create_augroup('MyGroup', { clear = true })for the same guarantee