How do I automatically fold code based on indentation level?
Answer
:set foldmethod=indent
Explanation
Setting foldmethod=indent tells Vim to create folds based on the indentation level of each line. Lines with deeper indentation become nested folds. This works instantly with any file — no syntax rules or markers needed.
How it works
:set foldmethod=indent
:set foldlevel=1 " Start with top-level folds open
Vim automatically groups consecutive lines at the same or deeper indentation into folds.
Fold commands
zo " Open fold under cursor
zc " Close fold under cursor
za " Toggle fold under cursor
zR " Open ALL folds in the file
zM " Close ALL folds in the file
zr " Reduce fold level by one (open one level)
zm " Increase fold level by one (close one level)
Example
With Python code:
def outer():
def inner():
return 1
return inner()
After :set foldmethod=indent, the inner function body becomes a fold nested inside the outer function fold.
All fold methods
| Method | Description |
|---|---|
manual |
You create folds manually with zf |
indent |
Folds based on indentation |
syntax |
Folds based on syntax highlighting |
expr |
Custom fold expression (Vimscript) |
marker |
Folds between {{{ and }}} markers |
diff |
Folds unchanged text in diff mode |
Tips
indentis the easiest fold method for Python, YAML, and other indentation-based formats- Set
foldlevelstartin your vimrc to control initial fold state:set foldlevelstart=99 " Start with all folds open - Use
syntaxfolding for C-like languages with braces