Quick Tip: Add automatic syntax highlighting to custom file types in VIM

v1m.pngVIM is an awesome text editor and syntax highlighting is one of its many awesome features. To enable VIM syntax highlighting globally for all users, simply uncomment Syntax on in the VIM config file (which is typically /etc/vimrc).

So long as your VIM version supports syntax highlighting, VIM will automagically highlight syntax for most common files. That's great, but sometimes you might run into a situation where you're working with a file VIM doesn't support out of the box. Let's say you really, really would like it to. Here's how...

The example I'm using here is the Vyatta config file (BTW, not to digress, but Vyatta is a super awesome, flexible and capable Open Source router/firewall solution that runs on commodity x86 hardware). Anyway, by default, VIM doesn't automatically syntax highlight the Vyatta config file, config.boot. You can always enable it manually every time you open the file, by typing something like:

:set syntax=perl

But that gets old quick, and so I'm going to setup VIM to automatically highlight the syntax for this file.

First, make sure your VIM version supports syntax highlight by turning it on manually. If VIM complains, you probably just need to update to the latest version (using whatever software update facility is appropriate for your Linux distribution).

Secondly, create two files in your home directory:

cd ~
touch .vimrc
touch .vimcustomfiletypes

Edit .vimrc and add:

"turn on syntax highlighting
syntax on
"load your custom syntax highlight filetypes file
so ~/.vimcustomfiletypes

Edit .vimcustomfiletypes and add:

augroup filetype
au!
au! BufRead,BufNewFile *.boot*    set filetype=cpp
augroup END

The above will use cpp (e.g. C++) syntax highlight rules for files which contain .boot in the filename (like Vyatta's config.boot). There are other ways to identify the file besides the file name, just take a look at the VIM documentation. Also, if none of the provided syntax highlight rule sets work for you, you could define your own. I haven't had the need to do that (yet?).

So, next time we open the Vyatta config.boot file, instead of boring 'ol this:

no hightlight

We get this:

with highlight

And that's an improvement.

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).