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

How do I create a macro that runs continuously until it hits an error?

Answer

@q

Explanation

A recursive macro is a macro that calls itself as its last step, causing it to loop automatically until an operation fails (such as reaching the end of the file or finding no more matches). This eliminates the need to guess a repeat count with 100@q — the macro simply runs until it can't continue.

How it works

The trick relies on the fact that Vim stops executing a macro the moment any command fails. The setup is:

  1. Clear the register first: qqq — records an empty macro into q, ensuring @q inside the new recording does nothing on the first pass
  2. Record the recursive macro: qq → perform your action → end with @qq
  3. Run it once: @q

On each iteration, the macro performs its action then calls @q again. When any step in the action fails (for example j fails on the last line), Vim aborts silently and execution stops.

Example

Add a semicolon to the end of every line in a file:

qqq           " Step 1: clear register q
qqA;<Esc>j@qq " Step 2: record recursive macro
@q            " Step 3: run it

Breaking down the macro A;<Esc>j@q:

  • A; — append ; at end of line
  • <Esc> — return to normal mode
  • j — move down one line (fails on last line, stopping recursion)
  • @q — call this macro recursively

Tips

  • Always clear the target register before recording (qqq for register q) so the embedded @q is a no-op during the first recording pass
  • Any failing motion or command acts as the termination condition: n (no more matches), /pattern (no match), etc.
  • For very large files, a recursive macro can be slower than :%norm @q; use the latter when performance matters
  • Use a letter register (qz) rather than numbered registers, which are overwritten by yank/delete operations

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?