Vim File Type Configuration

Vim has been my primary text editor for more than 15 years, but even though I use it on a daily basis, my configuration hasn’t changed much over time. When I set up a new workstation, I stumbled upon the filetype plugin that I wasn’t aware of. Using this plugin, you can import different vim configuration files depending on the type of the file you’re editing.

My configuration has always been modularized, but until recently, I used the low-level autocmd feature to config source files depending on the type of the file I was editing. Here’s how it looked in my vimrc:

autocmd BufNewFile,BufRead *.[ch] source ~/.vim/vimrc-c
autocmd BufNewFile,BufRead *.py source ~/.vim/vimrc-python
autocmd BufNewFile,BufRead *.xml source ~/.vim/vimrc-xml
autocmd BufNewFile,BufRead *.html source ~/.vim/vimrc-html

I was able to clean that up a bit using the filetype plugin. But first, the plugin needs to be enabled in the main vimrc file:

filetype plugin on

The plugin uses file type detection that may also scan the beginning of the file to figure out its type. The built-in detection routines are more robust than my simple file name checks.

For each type of file you work with, you place a configuration file in ~/.vim/after/ftplugin/TYPE.vim, where TYPE is one of vim’s supported file types. You can get the full list from $VIMRUNTIME/ftplugin/. Run ":echo $VIMRUNTIME" in vim if you don’t know the location of vim’s runtime directory (on my system, it’s /usr/share/vim/vim74/).

When programming Python, for example, I don’t ever want to use tab characters, and I indent code blocks using four spaces. To make this happen, I created the file ~/.vim/after/ftplugin/python.vim with the following content:

set tabstop=8
set shiftwidth=4
set softtabstop=4
set expandtab

There’s a lot more to the filetype plugin than discussed here. See the documentation for more advanced use cases, like writing your own autodetection mechanisms.

This entry was posted in productivity and tagged , . Bookmark the permalink.

1 Response to Vim File Type Configuration

  1. GLorieul says:

    Exactly what I was looking for, thanks !

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s