How do you override vim options via comments in a python source code file?

Question:

I would like to set some vim options in one file in the comments section.

For example, I would like to set this option in one file

set syntax=python

The file does not have a .py extension and I am not interested in making my vim installation recognise all files with this extension as python files.

I know this can be done because I have seen it, but my googling for this has not yet been fruitful.

Asked By: Paul D. Eden

||

Answers:

You’re wanting a modeline syntax, e.g.

# vim: set syntax=python:

See: Modeline magic at Vim Wikia for more details.

Answered By: Harper Shelby

I haven’t used vim much, but I think what you want is to add a line like the following to the end of your file:

# vim: set syntax=python:
Answered By: Ben Blank

You override the Vim options by adding the modeline near the top or the bottom of the file, such as:

// vim: set syntax=python:

or:

/* vim: set syntax=python: */

or like:

# vim: set syntax=python ts=4 :

Other examples (from wikia):

// vim: noai_ts=4:sw=4
   -or-
/* vim: noai_ts=4:sw=4
*/
   -or-
/* vim: set noai ts=4 sw=4: */
   -or-
/* vim: set fdm=expr fde=getline(v:lnum)=~'{'?'>1':'1': */

Here is the example which I’m using (on the last line of the file):

# vim: set ts=2 sts=2 et sw=2 ft=python:

Few highlights:

  • Vim executes a modeline only when modeline is set to modeline or a possitive integer and you’re not root (some OS such as Debian, Ubuntu, Gentoo, OSX, etc. disable modelines by default for security reasons), so you need to add set modeline into your ~/.vimrc file (:e $MYVIMRC),
  • the line must be in the first or last few lines,
  • space between the opening comment and vim: is required,
  • location where vim checks for the modeline is controlled by the modelines variable (see: :help 'modelines'),
  • with set, the modeline ends at the first colon (:),
  • text other than “vim:” can be recognised as a modeline.

Related:

Answered By: kenorb
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.