vimtricks.wiki Concise Vim tricks, one at a time.

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 N and last N lines, where N is controlled by set modelines=N
  • Avoid using set inside the colon form — both vim: set opt: and vim: opt work
  • Security note: Neovim restricts dangerous options (like shell) in modelines for safety
  • Override modelines per project using exrc or a .editorconfig tool instead if you want a more universal approach

Next

What is the difference between the inner word (iw) and inner WORD (iW) text objects in Vim?