How do I write autocommands that don't duplicate when I reload my vimrc?
Answer
augroup name | autocmd! | autocmd ... | augroup END
Explanation
Autocommand groups (augroup) with autocmd! prevent duplicate autocommands from accumulating every time you source your vimrc. Without them, reloading your config adds the same autocommand again and again.
The problem
" BAD: This adds a duplicate autocmd every time vimrc is sourced
autocmd BufWritePre * :%s/\s\+$//e
After sourcing 5 times, the trailing whitespace removal runs 5 times on every save.
The solution
" GOOD: Clear the group before redefining
augroup TrimWhitespace
autocmd!
autocmd BufWritePre * :%s/\s\+$//e
augroup END
autocmd! clears all autocommands in the group before adding new ones.
Practical examples
" Filetype-specific settings
augroup FileTypeSettings
autocmd!
autocmd FileType python setlocal tabstop=4 shiftwidth=4
autocmd FileType go setlocal noexpandtab tabstop=4
autocmd FileType javascript setlocal tabstop=2 shiftwidth=2
autocmd FileType markdown setlocal spell wrap linebreak
augroup END
" Auto-save on focus lost
augroup AutoSave
autocmd!
autocmd FocusLost * silent! wall
augroup END
" Highlight yanked text briefly (Neovim)
augroup YankHighlight
autocmd!
autocmd TextYankPost * silent! lua vim.highlight.on_yank()
augroup END
Tips
- Always use
augroup+autocmd!in your vimrc — never bareautocmd - The group name can be anything descriptive
- In Neovim, you can also use the Lua API:
vim.api.nvim_create_augroup() :autocmd(no arguments) lists all defined autocommands:autocmd GroupNamelists autocommands in a specific group- Documented under
:help autocmd-groups