FileType-Specific Settings

Alex R. Young
usevim
Published in
1 min readJul 5, 2012

Vim can run commands when reading or writing files, and this is known as an autocommand. Automatic commands can be combined with FileType and set to apply settings that only apply to a certain type of file. This takes the form au FileType type set commands. For example, to ensure Ruby files wrap at 80 characters and use a tabstop of two the following line could be added to your ~/.vimrc:

au FileType ruby set tw=80 ts=2

The {options} argument to :set can be repeated, and here I've supplied two arguments. This pattern is really great for those of us who work with multiple languages with different styles.

I like this example taken from Ryan Tomayko’s dotfiles/.vimrc:

au FileType gitcommit set tw=68 spell

This will cause Vim to wrap at 68 characters and turn on spell checking, but only for Git commit messages.

The FileType argument is an "autocommand event". There are lots of others. In Ryan's ~/.vimrc, we also see BufRead and BufNewFile:

au BufRead,BufNewFile *.svg        set ft=svg
au BufRead,BufNewFile *.haml set ft=haml

These are used to set the correct FileType when starting to edit a new file.

Vim’s documentation includes a warning about the power of automatic commands. To read more, check out the following:

  • :help autocommand -- a gentle introduction, with the warning message
  • :help :au -- the command itself
  • :help :set
  • :help autocmd-events-abc

--

--