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

How do I create a self-repeating macro that runs until there is nothing left to process?

Answer

@q (inside macro recording)

Explanation

A recursive macro calls itself as its last action, causing it to repeat indefinitely until it hits an error (like reaching end of file or failing a search). This is a powerful technique for processing every line, match, or occurrence in a file without needing to know the count in advance.

How it works

The trick relies on two properties:

  1. When you start recording into register q with qq, the register is cleared at the start. Any existing @q inside the macro body will call the empty register (a no-op) the first time — which is why you must populate q via qq then include @q at the end.
  2. When the macro encounters an error (e.g., search fails, motion hits buffer boundary), Vim aborts the macro chain — cleanly stopping recursion.

Recording sequence:

qq                 " start recording into register q (clears q first)
{your commands}    " the action to repeat
@q                 " recurse: call q from inside q
q                  " stop recording
@q                 " trigger the macro — it will run until an error stops it

Example

Delete every blank line in the file:

qq                 " start recording
/^$<CR>            " find next blank line
dd                 " delete it
@q                 " recurse
q                  " stop recording
@q                 " run — stops automatically when no blank lines remain

Tips

  • The macro must make forward progress on each iteration, or it will loop forever (no error to stop it)
  • Use j or a search to advance the cursor between iterations
  • For a fixed count, 10@q is simpler — use recursion only when the count is unknown
  • :[range]normal @q applies the macro to a range without recursion (often cleaner for line-by-line work)

Next

How do I paste back a small deletion (like a deleted character) while in insert mode?