Skip to content
Vim

Folding (Collapse Code)

Hide regions of code to focus on structure with fold methods.

By EZ4Code Team
foldoutlinenavigation

Code

:set foldmethod=manual   " manually create folds
:set foldmethod=indent   " fold by indentation level
:set foldmethod=marker   " fold by {{{ }}} markers
:set foldmethod=syntax   " fold based on syntax (slow on big files)
:set foldmethod=expr     " custom 'foldexpr'

" Manual folds (visual select then :fold)
zf                      " create fold over motion/selection
zd                      " delete fold under cursor
zD                      " delete fold recursively
zo / zc                 " open / close fold
zr / zm                 " reduce / increase fold level (whole buffer)
zR / zM                 " open all / close all folds
[z / ]z                 " jump to start / end of current fold
zn                      " temporarily disable folding (no fold)

" Recommended for modern dev:
" :set foldmethod=expr
" :set foldexpr=nvim_treesitter#foldexpr()  " (Neovim treesitter)

Explanation

Folding collapses regions so you can navigate large files. foldmethod determines strategy: indent is the most universally useful (Python, YAML); marker uses {{{ }}}; syntax uses language rules. zf creates a manual fold; zo/zc open/close; zR/zM open/close everything. zr/zm change fold level incrementally. In LSP/treesitter setups, foldmethod=expr with a language-aware foldexpr gives the best result. Folds persist per buffer in the view; :mkview/:loadview can save them across sessions.

More Vim Snippets