Using Modelines in Vim

I'm working on a book at the moment, and there are strict guidelines on formatting. One thing which is tripping me up is that all code samples must use two spaces for indentation. I normally have my editor set to 4 spaces, so I was looking for a good way to keep just these files consistent in their layout. Enter vim's modelines feature!

You may have seen this, a comment line at the start or end of a document which gives the settings for vim to use, something like this:

/* vim: set sw=2: */

This is a modeline in vim. I tried adding my own at the top of my sourcefiles, but vim seemed to ignore them. It turns out that modelines are disabled in vim by default (for security reasons) but you can easily turn them on in your .vimrc with:

:set modeline

The only change I want to make is the tab sizes which is why I use the line above. The vim modeline documentation is the best place to go if you want to add options of your own to this line

2 thoughts on “Using Modelines in Vim

  1. Thanks for the useful info (in your vim modeline post)! My vim shipped with the default [code]set modelines=0[/code] so I had to set that to >0 in my .vimrc too. With this modelines setting the modeline setting seems superfluous to me, but ah well.

  2. I don't think this is correct. From the VI auto-setting man page (:help auto-setting)...

    Note that for the first form all of the rest of the line is used, thus a line
    /* vi:ts=4: */ ~
    will give an error message for the trailing "*/". This line is OK:
    /* vi:set ts=4: */ ~

    If an error is detected the rest of the line is skipped.

    I think that is why your code may not have worked...

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.