How do I fold and unfold sections of code to hide details I'm not working on?
Answer
zf / zo / zc / za
Explanation
Vim's folding system lets you collapse blocks of code into a single line, hiding the details so you can focus on the structure. You can fold manually, by indent level, by syntax, or by markers — and toggle folds open and closed with single-key commands.
How it works
zf{motion}creates a manual fold over the specified range (e.g.,zf%folds from the current brace to its match)zoopens (unfolds) the fold under the cursorzccloses (folds) the fold under the cursorzatoggles the fold under the cursor — opens it if closed, closes it if openzRopens all folds in the entire filezMcloses all folds in the entire filezddeletes the fold under the cursor (manual folds only)
Fold methods
Vim supports several fold methods, set with :set foldmethod={method}:
:set foldmethod=manual " Create folds by hand with zf
:set foldmethod=indent " Fold based on indentation level
:set foldmethod=syntax " Fold based on language syntax rules
:set foldmethod=marker " Fold between {{{ and }}} markers
:set foldmethod=expr " Fold based on a custom expression
:set foldmethod=diff " Fold unchanged text in diff mode
The indent method is the easiest to start with — it automatically creates folds for every indented block with zero configuration.
Example
Enable indent-based folding:
:set foldmethod=indent
Given a file with nested code, Vim automatically creates folds at each indentation level. The folded view might look like:
function processOrder(order) {
+-- 8 lines: let total = 0;------------------
}
function validateInput(data) {
+-- 5 lines: if (!data) {--------------------
}
Press zo on a folded line to expand it, zc to collapse it again, or za to toggle.
Tips
- Use
zfwith visual mode for easy manual folds: select lines withV, then presszfto fold them zfapcreates a fold over the current paragraph,zf%folds from the current bracket to its match- Set
foldlevelstart=99in your vimrc to open files with all folds expanded by default::set foldlevelstart=99 - Use
zjandzkto jump to the next and previous fold boundary [zjumps to the start of the current open fold,]zjumps to the end:set foldcolumn=2adds a narrow column on the left showing fold indicators visually- For syntax folding in specific languages, ensure
filetype plugin indent onis in your vimrc - Combine folding with
:set foldmethod=indentand:set foldlevel=1to see only top-level structures with one command