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

How do I create a self-referential recursive macro that repeats until it fails?

Answer

qqq then qq{commands}@qq

Explanation

A recursive macro in Vim calls itself at the end of its body, repeating automatically until one of its commands fails. This lets you process an unbounded number of items without knowing the count in advance — the macro stops naturally when it hits a dead end, such as no more search matches or the cursor reaching end of file.

How it works

  • qqq — clears register q so the initial @q at the end of the recording is a no-op (not a leftover macro)
  • qq — starts recording into register q
  • {your commands} — the operations to perform on each iteration
  • @q — the recursive call; Vim invokes the macro again, which will halt automatically when any command in the body fails
  • q — stops recording

Once recorded, trigger the loop with @q. It runs until failure, then stops silently.

Example

Delete the first word from every line until end of file:

qqq            " clear register q
qqdw0j@qq      " record: delete word, go to col 0, move down, recurse
@q             " start the loop

The macro runs until j fails on the last line, at which point the chain halts.

Tips

  • The stop condition is implicit — any failed command (motion, search, substitution) breaks the chain
  • Use nnoremap in a wrapper to run it safely, or prefix with :silent to suppress error messages: :silent! normal @q
  • If the macro is getting stuck in an infinite loop, press <C-c> to interrupt
  • For a known repeat count, {N}@q is simpler — but the recursive pattern shines when the count is unknown

Next

How do I highlight all occurrences of a yanked word without typing a search pattern?