How do I define autocmds safely so they don't duplicate when my vimrc is re-sourced?
Answer
:augroup
Explanation
Wrapping autocmds in a named augroup with autocmd! at the start prevents duplicate autocommands from accumulating every time your vimrc is sourced. Without this pattern, re-sourcing your config (e.g., after editing it) registers the same autocmd multiple times, causing subtle bugs like formatters running twice or settings applying repeatedly.
How it works
augroup MySettings
autocmd!
autocmd FileType python setlocal expandtab shiftwidth=4 tabstop=4
autocmd BufWritePre *.go :silent !gofmt -w %
augroup END
augroup MySettingsopens a named group; all subsequentautocmddefinitions belong to itautocmd!(with no arguments inside a group) clears all autocmds in the group before re-registering themaugroup ENDcloses the group- Without
autocmd!, every:source ~/.vimrcadds another copy of each autocmd
Example
Without augroup, re-sourcing your vimrc causes this:
" After 3 re-sources of vimrc:
:autocmd
FileType python setlocal expandtab ← runs 3 times!
FileType python setlocal expandtab
FileType python setlocal expandtab
With the augroup pattern, the group is cleared and re-registered exactly once, every time.
Tips
- Use a unique group name per logical set of autocmds (e.g.,
augroup PythonSettings,augroup GoSettings) - Check all registered autocmds with
:autocmdor:autocmd {GroupName}to see only one group's events - Delete an entire group's autocmds with
:autocmd! MySettings(from outside the group) - In Neovim, consider
vim.api.nvim_create_augroupwithclear = trueas the Lua equivalent