As you may know, in the editor wars, I come down firmly on the side of vim. Vim is a lean and effective modal editor, contrasted with emacs. One of the features of Vim that I enjoy using (but did not know about until recently!) is modelines. A modeline is a small piece of text that you can put at the end of a file to give your editor an instruction. It is generally placed in a comment. For example, if I’m editing Python, I never, ever want to use soft tabs (well, I generally don’t like soft tabs anyway), so I might put something like the following at the end of a file:
# vim:expandtab ts=4 sw=4
When vim opens this file, it will parse that line and pass the space-separated arguments to “set”. So this is equivalent to my typing in :set expandtab ts=4 sw=4.
Another great usage of these is for setting syntax highlighting. Vim is generally good at guessing the file type for syntax highlighting from the stuffix of the file. For example,
will be detected as a Python file and highlighted appropriately. But what about a file like
? It should be highlighted as an Apache configuration file, but the suffix
tells Vim nothing. The solution here is to use a modeline. My Apache configuration files end in the line
# vim:syntax=apache filetype=apache
which makes it a lot easier to read them.
There are a few different formats. The first (and simplest) is what I showed above: a comment character, a space, the text
vim:, then a space-separated list of arguments. There may not be any non-argument text on the line. This means that the following is invalid:
/* vim:expandtab ts=4 sw=4 */
Obviously, this is a bit annoying, because there are lots of comment-formats that require both an opening and an ending (C, Pascal, and SML come to mind immediately). There is, thus, an alternate syntax:
/* vim: set expandtab ts=4 sw=4: */
Note that the set statement is now delimited by colons on both sides. This is important! If you leave off the trailing colon, Vim will get very unhappy with you.
Another handy feature of modelines is that you can limit them by version. For example, if I want to use something that was introduced in Vim 6.0, I could use the following:
# vim600: set expandtab
means “any version of Vim 600 or later”, where 600 in Vim versions translates to 6.0.0.
- Modelines are not generally enabled for root. Since they’re possibly-sketchy code that runs automatically when you open a file, it’s considered (wisely) a security risk to run them as root
- Modelines might not be turned on in your default config at all. To turn them on, add