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

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 you
  • zf works with any motion or text object: zfap folds a paragraph, zf} folds to the next blank line, zf20j folds 20 lines down
  • In visual mode, select lines first, then press zf to fold the selection
  • :set foldmethod=manual must 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 :mkview and restore with :loadview
  • Use zR to open all folds at once and zM to close all folds
  • Combine with zf/pattern to fold from the current line to the next match of a search pattern
  • If zf does not work, check that :set foldmethod? returns manual

Next

How do I return to normal mode from absolutely any mode in Vim?