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

How do I embed Vim settings directly in a file so they apply automatically when opened?

Answer

vim: set {options} :

Explanation

A modeline is a specially formatted comment at the top or bottom of a file that Vim reads and applies as local settings. It lets you embed editor configuration — indentation, filetype, textwidth — directly in the file, overriding your vimrc for that specific file.

Syntax

Vim checks the first and last few lines of each file (controlled by modelines option, default 5).

Two accepted formats:

vim: set {options} :

or:

vim: {options}

Wrapped in a comment appropriate for the language:

# vim: set ts=4 sw=4 et :
// vim: set ts=2 sw=2 et :
<!-- vim: set ft=html tw=80 : -->

Common options in modelines

Option Meaning
ts=4 tabstop — display width of tab character
sw=2 shiftwidth — indentation width
et expandtab — use spaces instead of tabs
ft=python filetype — override auto-detection
tw=80 textwidth — auto-wrap at this column
fdm=marker foldmethod — use {{{/}}} fold markers
noet noexpandtab — use real tabs

Example

A Python file with custom settings:

#!/usr/bin/env python3
# vim: set ts=4 sw=4 et fdm=indent :

def main():
    pass

Tips

  • :set modeline must be enabled (it is on by default, but some distros disable it in system vimrc)
  • For security, modelines cannot run arbitrary commands — only set options are allowed
  • modelines=0 disables modeline processing entirely (for security-conscious setups)
  • Use :setlocal in ftplugin files as an alternative to modelines for per-filetype settings that don't clutter the file

Next

How do I run a search and replace only within a visually selected region?