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

How do I force Vim to recompute all folds in the current window?

Answer

zx

Explanation

The zx command resets and recomputes all folds in the current window based on the current foldmethod. This is useful when folds become stale — for example, after adding code that should create new folds, or after changing foldmethod without reopening the file.

How it works

  • zx closes all manually opened folds (those opened with zo or zO), then reapplies the fold calculation from scratch
  • It also applies foldlevel: folds at levels above foldlevel are closed, folds at or below are opened
  • A related command, zX, does the same but ignores foldlevel and simply closes all folds to their defined state
  • zu undoes the effect of zx by restoring previously open/closed states

Example

After adding a new function to a file with foldmethod=indent, Vim may not automatically detect it as a new fold. Pressing zx forces the recalculation:

:set foldmethod=indent
" add new indented block, old fold view is stale
zx
" folds are now recomputed and reflect current indentation

Tips

  • Use zX (uppercase) to recompute and close all folds regardless of foldlevel
  • zx respects your current foldlevel setting, so zx after :set foldlevel=1 will close all but the top-level folds
  • For foldmethod=expr, zx re-evaluates the expression for every line — useful when the expression depends on buffer state that has changed
  • If you want to open all folds first, use zR then zx to reset to a fully-open state without losing the fold structure

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?