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

How do I create a recursive macro that repeats itself until it fails?

Answer

qqqqqq{edits}@qq

Explanation

A recursive macro calls itself at the end of its sequence, creating a loop that automatically repeats until a motion or command fails (such as hitting the last line or finding no more matches). This eliminates the need to guess a repeat count — the macro runs exactly as many times as needed and stops on its own.

How it works

  • qqq — clear register q first (critical: prevents the old macro from running when @q is encountered during recording)
  • qq — start recording into register q
  • {edits} — your actual editing commands (must include a motion that will eventually fail)
  • @q — call register q recursively (the macro calls itself)
  • q — stop recording
  • @q — execute the macro to kick it off

The macro stops automatically when any command in the sequence fails — typically a motion like j on the last line or n with no more search matches.

Example

Add a semicolon to the end of every line from the cursor to the end of the file:

qqqqqqA;<Esc>j@qq
@q
Before:
  let x = 1
  let y = 2
  let z = 3

After:
  let x = 1;
  let y = 2;
  let z = 3;

Tips

  • Always clear the register first with qqq — if register q already contains a macro, the @q inside your recording will execute the old one mid-recording
  • The fail-and-stop behavior relies on Vim aborting a macro when any command errors — this is by design
  • Combine with search: qqqqqqn{edits}@qq processes every search match until none remain
  • Prefer recursive macros over 999@q — they are self-terminating and more precise

Next

How do I ignore whitespace changes when using Vim's diff mode?