Setting values, and running commands, for a specific filetype

Sometimes you want to configure something for a specific filetype. For example, you might want to have the default textwidth set to 80 characters for Ruby files, but 120 for markdown. More advanced users may want to have custom functions run for a specific filetype.

The best location for this is ~/.vim/ftplugin/<filetype>.vim In this case <filetype> is the name of the filetype not the extension.

If you’re not sure what the official name of a filetype is you can ask vim by opening a file of that type and saying :set filetype?. If you do this for a Markdown file, for example, Vim will respond with filetype=markdown.

If Vim doesn’t know it will respond with filetype=

Within that <filetype>.vim file you put whatever commands you want Vim to run when it opens that file. To set the different text widths described above you’d do the following.

In ~/.vim/ftplugin/ruby.vim you’d have a line that said

setlocal textwidth=80

In ~/.vim/ftplugin/markdown.vim you’d have a line that said

setlocal textwidth=120

Note that we’re using setlocal so that it just affects the current buffer instead of set which is for making global configurations.