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

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 MySettings opens a named group; all subsequent autocmd definitions belong to it
  • autocmd! (with no arguments inside a group) clears all autocmds in the group before re-registering them
  • augroup END closes the group
  • Without autocmd!, every :source ~/.vimrc adds 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 :autocmd or :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_augroup with clear = true as the Lua equivalent

Next

How do I load plugins without a plugin manager using Vim's built-in package system?