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

How do I make a macro repeat itself until it fails?

Answer

qaq qa...@aq @a

Explanation

A recursive macro calls itself at the end of its recording, causing it to repeat indefinitely until a command inside it fails (like a search hitting the end of the file). This is one of the most powerful macro techniques in Vim — it lets you apply a complex editing sequence to every match in a buffer without counting repetitions.

How it works

  • qaq clears register a to prevent a stale recursive call during recording
  • qa starts recording into register a
  • ... is your editing sequence — it must include a command that can fail (like /pattern<CR>, n, or j)
  • @a calls register a (itself) recursively
  • q stops recording
  • @a executes the macro — it runs, then calls itself, runs again, and so on until one of the commands inside fails

Example

Delete every line containing "DEBUG" by searching and deleting:

qaq
qa/DEBUG<CR>dd@aq
@a

The macro searches for the next "DEBUG" line, deletes it, then calls itself. When no more matches exist, the search fails and the macro stops.

Tips

  • Always clear the register first with qaq — otherwise the old macro content executes during recording
  • The "failure" that stops recursion is any command that produces an error (failed search, movement past end of file, etc.)
  • For line-by-line processing, use j as the failing command — the macro stops at the last line
  • Prefer :g/DEBUG/d for simple cases — recursive macros shine when the editing logic is too complex for :global

Next

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