How do I embed Vim settings directly in a file so they apply automatically when it is opened?
Answer
# vim: set tabstop=2 shiftwidth=2 expandtab :
Explanation
A modeline is a specially formatted comment that Vim reads when it opens a file and applies as local settings — no plugin or project-level vimrc required. Any collaborator who opens the file in Vim gets the same editor settings without any configuration.
How it works
Vim scans the first and last few lines of each file (controlled by modelines, default 5) for the pattern vim: or ex:. The general form is:
vim: set option1=val option2 nooption3 :
The trailing space-colon ( :) closes the modeline and is required. Settings use the same syntax as :set: plain word enables an option, no prefix disables it, option=value sets a value.
Example
At the top or bottom of a YAML file:
# vim: set tabstop=2 shiftwidth=2 expandtab :
In a Makefile where tabs are required:
# vim: set noexpandtab tabstop=4 :
In a script without a recognisable extension:
# vim: set filetype=bash :
Vim applies these as buffer-local settings (equivalent to :setlocal) each time the file is opened.
Tips
- Enable modeline support explicitly if it is off:
:set modeline modelines=5in your vimrc (some distros ship Vim withnomodelinefor security reasons) - The option
modelinescontrols how many lines from the top and bottom Vim checks — increase it if you place the modeline deep in the file - Use
vi:instead ofvim:for compatibility with the original Vi and other editors that honour modelines - Neovim enables modelines by default; check with
:set modeline?