49

How To Add A File Extension To vim Syntax Highlighting


Posted by Artem Russakovskii on April 2nd, 2008 in Databases, Linux, Programming

Updated: July 8th, 2009

Today I was asked a question about defining custom extensions for vim syntax highlighting such that, for example, vim would know that example.lmx is actually of type xml and apply xml syntax highlighting to it. I know vim already automatically does it not just based on extension but by looking for certain strings inside the text, like <?xml but what if my file doesn't have such strings?

image

After digging around I found the solution. Add the following to ~/.vimrc (the vim configuration file):

1
2
3
syntax on
filetype on
au BufNewFile,BufRead *.lmx set filetype=xml

After applying it, my .lmx file is highlighted:

image

Same principle works, for instance, for mysql dumps that I have to do from time to time. If they don't have a .sql extension, you'll get something like:

image

After

1
2
3
syntax on
filetype on
au BufNewFile,BufRead *.dump set filetype=sql

everything is fine:

image

But why and how does it work, you ask?

:help au :au[tocmd] [group] {event} {pat} [nested] {cmd}

Add {cmd} to the list of commands that Vim will execute automatically on {event} for a file matching {pat}.
:help BufNewFile When starting to edit a file that doesn't exist.
:help BufRead When starting to edit a new buffer, after reading the file into the buffer.
:help filetype will actually tell this whole story in part B.

And that's how you do it, folks.

● ● ●
Artem Russakovskii is a San Francisco programmer and blogger. Follow Artem on Twitter (@ArtemR) or subscribe to the RSS feed.

In the meantime, if you found this article useful, feel free to buy me a cup of coffee below.