How do I embed Vim settings inside a file using modelines?
Answer
vim: set ts=2 sw=2 et:
Explanation
Modelines are special comments at the top or bottom of a file that Vim reads to apply file-specific settings. They let you enforce coding standards per-file — indentation, textwidth, filetype — without relying on project-wide configuration.
How it works
- Place the modeline in the first or last 5 lines of the file
- Format:
vim: set {options}:orvim: {options} - Vim reads modelines automatically if
modelineoption is enabled - Settings are applied as
:setlocal(file-local only)
Example
# Python file with 4-space indentation
# vim: set ts=4 sw=4 et:
// JavaScript file with 2-space indentation
// vim: set ts=2 sw=2 et:
/* C file with tabs */
/* vim: set noet ts=8 sw=8: */
Tips
modelinesoption controls how many lines are checked (default 5)- Modelines run in sandbox mode for security — they can't execute shell commands
- Common options:
ts(tabstop),sw(shiftwidth),et(expandtab),tw(textwidth),ft(filetype) - Disable modelines for security:
:set nomodeline(risky files from untrusted sources)