vimtricks.wiki Concise Vim tricks, one at a time.

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)
  • zo opens (unfolds) the fold under the cursor
  • zc closes (folds) the fold under the cursor
  • za toggles the fold under the cursor — opens it if closed, closes it if open
  • zR opens all folds in the entire file
  • zM closes all folds in the entire file
  • zd deletes 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 zf with visual mode for easy manual folds: select lines with V, then press zf to fold them
  • zfap creates a fold over the current paragraph, zf% folds from the current bracket to its match
  • Set foldlevelstart=99 in your vimrc to open files with all folds expanded by default: :set foldlevelstart=99
  • Use zj and zk to jump to the next and previous fold boundary
  • [z jumps to the start of the current open fold, ]z jumps to the end
  • :set foldcolumn=2 adds a narrow column on the left showing fold indicators visually
  • For syntax folding in specific languages, ensure filetype plugin indent on is in your vimrc
  • Combine folding with :set foldmethod=indent and :set foldlevel=1 to see only top-level structures with one command

Next

How do I edit multiple lines at once using multiple cursors in Vim?