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

How do I open or close a fold and all its nested folds at once?

Answer

zO and zC

Explanation

zO and zC are the recursive counterparts to zo and zc. While the lowercase versions act only on a single fold level, zO opens every nested fold under the cursor in one step, and zC closes the fold under the cursor and all folds nested inside it. This is invaluable when navigating deeply nested code structures where you want to fully expand or collapse a section without pressing zo repeatedly.

How it works

  • zOOpen all folds recursively from the cursor position downward. No matter how many levels deep the nesting goes, every fold under the cursor is opened.
  • zCClose the fold containing the cursor, along with all nested sub-folds inside it, collapsing the entire subtree in one keystroke.

Contrast with the global commands zR (open all folds in the file) and zM (close all folds in the file): zO/zC scope their action to the fold under the cursor only.

Example

Suppose you have a function with nested if blocks and loops, all using foldmethod=indent:

def outer():           ← cursor here
    +-- 3 lines: if x --------
    +-- 5 lines: for item ----

Pressing zO fully expands outer() and every collapsed block inside it:

def outer():
    if x:
        do_something()
    for item in items:
        if item.valid:
            process(item)

Pressing zC from anywhere inside outer() collapses back to a single fold line.

Tips

  • Pair with zM to collapse everything first, then use zO to selectively expand just the function you care about.
  • zv is a lighter alternative — it opens just enough folds to reveal the cursor line without touching sibling folds.
  • Works with all fold methods: manual, indent, syntax, marker, and expr.

Next

What is the difference between zt and z-Enter when scrolling the current line to the top of the screen?