Thursday 17 December 2009

Linux Tips: Vim autoconfigure for different filetypes

Thanks to Ajay Somani, over at http://ajayfromiiit.wordpress.com/ for this post that finally helped me solve a long term gripe with vim.

When I'm in 'programmer' mode, I use vim with syntax highlight turned on.
When I'm in 'wannabe fiction writer' mode, I use it with spell check turned on.

And these two personas keep fighting like Jekyll and Hyde. Because I have both of these turned on, vim insists on syntax highlighting my fiction, interpreting apostrophes as quotes and then coloring everything after them. Worse still, it spell-checks my C-code. It'll highlight some text in red, and then spell-check it, and decide it's mis-spelt, and thus surround it in a background colored.... red. This results in large blocks of red-on-red text that cannot be... uh... read.

The solution, it turns out, is to add this magic line to my vimrc:

autocmd BufEnter *.txt set spell



Basically autocmd is a way of specifying a vim command...

I don't believe this, vim is coloring every instance of its own name in purple as I type this. I'm pretty sure it's doing this out of pure vanity.

... anyways autocmd specifies commands to be run when an event happens. the 'BufEnter' event, though it doesn't sound like it has anything to do with files (and indeed, sounds vaguely rude) gets run whenever you start editing a new document (which by and large, means a file). It takes a command which is a pattern to match a file name. Then you supply the command, in my example 'set spell', which only turns spelling on for .txt files. So:

autocmd BufEnter <file pattern> <command>

Another useful one, I find, is:

autocmd BufEnter *.xml set nosyntax

Because I'm often confronted by .xml documents that have no line breaks, and are just one HUGE line. This really upsets vim if you have syntax highlighting turned on, because I think it normally does syntax hilighting a line at a time, not bothering with those lines that aren't being displayed. But when faced with an xml document that's just a single giant line, it has to highlight the whole document, and the user can go off and make a cup of tea while it does so.

I'm sure there are lots of other uses for the various events that autocmd supports, and if anyone knows any, I encourage them to comment here!

No comments:

Post a Comment