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

How do I jump to the start of the next or previous fold?

Answer

zj

Explanation

When your file uses folds, zj and zk let you navigate directly to fold boundaries — jumping to the start of the next fold below or the end of the previous fold above. This is different from [z and ]z, which move within the fold you're already inside.

How it works

  • zj — move the cursor to the start of the next fold (downward), regardless of whether it's open or closed
  • zk — move the cursor to the end of the previous fold (upward)
  • Both motions are inclusive of closed folds, so they work even when folds are collapsed
  • They work with any fold method: manual, indent, expr, marker, or syntax

Example

1: function foo() {     ← fold start
2:   return 1
3: }                    ← fold end
4: function bar() {     ← fold start
5:   return 2
6: }                    ← fold end

With the cursor on line 2 (inside foo), pressing zj moves to line 4 — the start of the next fold (bar). Pressing zk from there moves to line 3 — the end of the previous fold.

Tips

  • Compare with [z / ]z, which navigate to the start/end of the current fold you're inside
  • zj and zk are linewise motions and can be used with operators: d2zj deletes from the cursor to the end of the second next fold
  • Combine with visual mode to select complete fold blocks: Vzj selects from the current line to the top of the next fold

Next

How do I duplicate every line matching a pattern, placing a copy directly below each one?