How do I create custom folds to collapse specific sections of code?
Answer
zf{motion}
Explanation
Vim supports several fold methods, but manual folding with zf gives you precise control over exactly which lines to collapse. This is useful when you want to temporarily hide sections of a file without changing settings or adding fold markers to the source code.
How it works
zf{motion}— creates a fold from the current line to wherever{motion}takes youzfworks with any motion or text object:zfapfolds a paragraph,zf}folds to the next blank line,zf20jfolds 20 lines down- In visual mode, select lines first, then press
zfto fold the selection :set foldmethod=manualmust be active (this is the default in many configurations)
Example
Fold the body of a function spanning lines 10-25:
" Position cursor on line 10, then:
zf25G
Or fold the current paragraph:
zfap
Or select lines visually and fold:
V20jzf
After folding, the collapsed lines appear as a single line showing the fold count. Use zo to open, zc to close, and zd to delete the fold.
Tips
- Manual folds are lost when you close the buffer unless you save them with
:mkviewand restore with:loadview - Use
zRto open all folds at once andzMto close all folds - Combine with
zf/patternto fold from the current line to the next match of a search pattern - If
zfdoes not work, check that:set foldmethod?returnsmanual