Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

vim

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.

like image 830
Paul D. Eden Avatar asked Dec 17 '08 21:12

Paul D. Eden


3 Answers

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

# vim: set syntax=python:

See: Modeline magic at Vim Wikia for more details.

like image 159
Harper Shelby Avatar answered Sep 28 '22 10:09

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:
like image 24
Ben Blank Avatar answered Sep 28 '22 12:09

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:

  • Modeline magic at Vim wikia
  • Vim modeline vulnerabilities at SS or Google: vim modeline vulnerability
like image 25
kenorb Avatar answered Sep 28 '22 12:09

kenorb