How do I embed per-file Vim settings directly in a source file using modelines?
Answer
# vim: set ts=4 sw=4 et:
Explanation
Vim's modeline feature lets you embed editor settings directly into a file. When Vim opens the file, it reads these settings and applies them automatically — no plugin or project configuration needed. This is useful for enforcing project-specific indentation, file format, or syntax overrides on a per-file basis.
How it works
Add a modeline anywhere in the first or last modelines lines of the file (default: 5 lines). The format is:
# vim: set key=value key2=value2:
or the shorthand:
# vim: ts=4 sw=4 et:
Vim recognizes modelines by looking for vi: or vim: followed by options. The modeline must appear within a comment appropriate to the file type.
Ensure modeline reading is enabled (it is on by default, but some distros disable it):
set modeline
set modelines=5
Example
At the top or bottom of a Python file:
# vim: set ts=4 sw=4 et ft=python:
In a Makefile (tabs required):
# vim: set noet ts=8:
In C:
/* vim: set ts=2 sw=2 et: */
When Vim opens the file, it silently applies tabstop=4 shiftwidth=4 expandtab (or whichever settings you specify) before you even start editing.
Tips
- Modelines are read from the first
Nand lastNlines, whereNis controlled byset modelines=N - Avoid using
setinside the colon form — bothvim: set opt:andvim: optwork - Security note: Neovim restricts dangerous options (like
shell) in modelines for safety - Override
modelinesper project usingexrcor a.editorconfigtool instead if you want a more universal approach