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

How do I create a recursive macro that runs until it encounters an error?

Answer

qa...@aq

Explanation

A recursive macro calls itself at the end of its recording, causing it to repeat until a motion or search fails. This is the most powerful way to apply a transformation to an unknown number of occurrences without manually counting.

How it works

  • qa — start recording into register a
  • Perform your transformation commands
  • @a — call the macro itself (recursion)
  • q — stop recording
  • Run @a — the macro repeats until any command fails (e.g., search reaches end of file)

Example

" Clear register first to prevent premature execution
qaq
" Record: find next TODO, delete the line, repeat
qa/TODO<CR>dd@aq
@a
Before:
code line 1
// TODO: fix this
code line 2
// TODO: refactor
code line 3

After @a:
code line 1
code line 2
code line 3

Tips

  • Always clear the register first with qaq (empty recording) to prevent old content from interfering
  • The macro stops when any command fails — use /pattern to control where it stops
  • This replaces 999@a with a cleaner, self-terminating approach
  • If the macro doesn't stop, press <C-c> to interrupt

Next

How do I return to normal mode from absolutely any mode in Vim?