Autocommand groups give you the opportunity to organize your autocommands, which is a quite useful feature in and of itself.
Say you are writing a plugin. Grouping your plugin's autocommands under your own namespace makes sense, if only because it lets you enable/disable your autocommands at will.
Your vimrc
is not fundamentally different from a plugin/foo.vim
so, all you get with autocommand groups is basically more control over your setup.
In practice…
If you don't assign them to a group, autocommands are "installed" in the global group by default. Installing related autocommands in their own group not only makes things clearer but it allows you to prevent the dreaded "pile-up" effect very easily and with a single !
:
augroup spam versus autocmd! Foo * foo
autocmd! autocmd! Bar * bar
autocmd Foo * foo
autocmd Bar * bar
augroup END
On the left, the whole group is uninstalled at once, before each autocommand of that group is properly installed. Neat.
On the right, Vim will wastefully run through the same "uninstall/install" routine for each autocommand. Dirty.
But you don't have to write that whole block every time if you don't want to. Autocommands can be assigned directly to a group so you can define a group somewhere:
augroup spam
autocmd!
augroup END
and put your autocommands where you want, even in another script:
autocmd spam Foo * foo
autocmd spam Bar * bar
This would give you:
- namespacing
- pile-up prevention
- order
- flexibility
--- EDIT ---
Grouping autocommands is not the only way to prevent the pile-up problem. If you don't like the augroup
ceremonial, you can simply append a !
to :autocmd
:
autocmd! Foo * foo
to uninstall any already installed autocommand on the Foo
event and the *
pattern before adding a new one. It definitely works in the simplest cases but it doesn't scale up very well.
It is too easy to fall into the habit of using that !
systematically, thinking it's a silver bullet, and create hard to debug problems down the line. For example, the snippet below installs two autocommands in the user's vimrc
:
" line 23 of ~/.vimrc
autocmd! Syntax * echom 'hi_1'
" line 414
autocmd! Syntax * echom 'hi_2' | echom 'hi_3'
But the second autocommand will uninstall the first one and only one will be executed in the end… an issue easily avoided with a group:
" line 10 of ~/.vimrc
augroup MyStuff
autocmd!
augroup
" line 26
autocmd MyStuff Syntax * echom 'hi_1'
" line 417
autocmd MyStuff Syntax * echom 'hi_2' | echom 'hi_3'