Introduction
Vim modelines allow individual files to specify editor settings (like tab width, filetype, or encoding) directly in the file content. When modelines is set to 0 or nomodeline is enabled, these directives are silently ignored:
# In the file header or footer:
# vim: set ts=4 sw=4 et:
# Vim opens the file but ignores these settingsThis is common in security-hardened Vim configurations where modelines are disabled to prevent malicious files from executing arbitrary Vim commands.
Symptoms
- Modeline comments in files have no effect on Vim behavior
:set modelines?returnsmodelines=0- Tab width, encoding, or filetype settings in modelines are not applied
- Modelines work on other machines but not on this one
- Security policy or distribution default disables modelines
Common Causes
modelinesset to 0 in system-wide vimrc (/etc/vim/vimrc)- Security hardening (e.g., CIS benchmarks) disables modelines
nomodelineset in user's.vimrc- Modeline format is incorrect (Vim is strict about modeline syntax)
- Modeline is beyond the first/last
modelineslines of the file
Step-by-Step Fix
- 1.Check the current modelines setting:
- 2.```vim
- 3.:set modelines?
- 4." If it shows modelines=0, modelines are disabled
- 5.
` - 6.Enable modelines in your
.vimrc: - 7.```vim
- 8." Allow modelines in the first and last 5 lines of a file
- 9.set modelines=5
- 10.
` - 11.Verify modeline format is correct. Vim supports two formats:
- 12.```vim
- 13.# Format 1: ex command style
- 14.# vim: set ts=4 sw=4 et:
# Format 2: set option style # vim: ts=4 sw=4 et
# Format 3: with filetype # vim: filetype=python ts=4 sw=4 et ```
- 1.Modeline must be in the first or last lines of the file (within
modelinesrange): - 2.```python
- 3.# First line of the file
- 4.# vim: ts=4 sw=4 et
def my_function():
print("hello")
``
Or at the end:
``python
def my_function():
print("hello")
# vim: ts=4 sw=4 et ```
- 1.For security, restrict which options modelines can set:
- 2.```vim
- 3." In newer Vim versions, modelines can only set a limited set of options
- 4." by default. Dangerous options like ! commands are blocked.
- 5." To allow additional safe options:
- 6.let g:modeline_sandbox = 1
- 7.
`
Prevention
- Set
modelines=5as a reasonable default for most workflows - Only enable modelines if you trust the files you are editing
- For shared or untrusted files, keep
modelines=0for security - Document the modeline format your team uses in the project's coding standards
- Test modeline processing after Vim upgrades as security defaults may change
- Use EditorConfig (
.editorconfig) as a safer alternative to modelines for team-wide settings - Add modeline syntax checking to your CI pipeline if your team relies on modelines
- Keep modelines minimal - only set essential options like
ts,sw,et, andfiletype