Skip to content

Instantly share code, notes, and snippets.

@romainl
Last active March 20, 2022 08:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save romainl/6e4c15dfc4885cb4bd64688a71aa7063 to your computer and use it in GitHub Desktop.
Save romainl/6e4c15dfc4885cb4bd64688a71aa7063 to your computer and use it in GitHub Desktop.
Dealing with autocommands

Dealing with autocommands

Anatomy of a minimal autocommand

autocmd BufNewFile,BufRead *.foo set filetype=html
  • BufNewFile,BufRead is the list of events that trigger this autocommand.
  • *.foo is the pattern we want to match against the data returned by the event.
  • set filetype=html is the command we want to execute when the pattern matches the data returned by the event.

Optional features

autocmd[!] [groupname] BufNewFile,BufRead *.foo [nested] set filetype=html
  • ! removes every autocommand of the current group for the given events and pattern.
  • groupname puts the autocommand in group groupname.
  • nested allows autocommands to trigger other events and thus other autocommands.

Risky business

As the online documentation says:

`:autocmd` adds to the list of autocommands regardless of whether they are
already present.  When your .vimrc file is sourced twice, the autocommands
will appear twice.  To avoid this, define your autocommands in a group, so
that you can easily clear them:

augroup vimrc
  autocmd!	" Remove all vimrc autocommands
  au BufNewFile,BufRead *.html so <sfile>:h/html.vim
augroup END

Piling-up autocommands is in fact a very common cause of performance issues. Fortunately, fixing our hare-brained autocommand is rather easy:

augroup mygroup
    autocmd!
    autocmd BufNewFile,BufRead *.foo set filetype=html
augroup END

PROTIP

But do we have to put an augroup and an autocmd! around every freaking autocmd? Well, no. Of course we don't. The idea is to assign every autocommand to a group that's properly reset when you :source $MYVIMRC. This can be done like this…

  • Place your group somewhere near the top of your vimrc:

    augroup mygroup
            ^^^^^^^
        autocmd!
    augroup END
    
  • Use that group in your autocommands:

    autocmd mygroup BufNewFile,BufRead *.foo set filetype=html
            ^^^^^^^
    

My Vim-related gists.

@alesandar
Copy link

By trying your tip, I get E471: Argument required. It's pointing to the second line here:

augroup mygroup
    augroup!
augroup END

autocmd mygroup BufNewFile,BufRead *.foo set filetype=html

Tested with a clean configuration file (the only contents of $MYVIMRC are the lines above).
NVIM v0.3.1. and VIM v8.1.542

@monokuai
Copy link

monokuai commented Dec 6, 2018

Doesn't has augroup! to be aucmd! in the Pro Tip section?

@romainl
Copy link
Author

romainl commented Jan 27, 2019

Duh… Typo fixed. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment