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
zxcloses all manually opened folds (those opened withzoorzO), then reapplies the fold calculation from scratch- It also applies
foldlevel: folds at levels abovefoldlevelare closed, folds at or below are opened - A related command,
zX, does the same but ignoresfoldleveland simply closes all folds to their defined state zuundoes the effect ofzxby 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 offoldlevel zxrespects your currentfoldlevelsetting, sozxafter:set foldlevel=1will close all but the top-level folds- For
foldmethod=expr,zxre-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
zRthenzxto reset to a fully-open state without losing the fold structure