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

How do I record a self-repeating recursive macro that automatically stops when it hits an error?

Answer

qa{motions}@aq

Explanation

A recursive macro is one that calls itself at the end of its own recording. When played back, it runs, invokes itself again, runs again, and so on — until a motion fails (e.g., end of file is reached, a search has no more matches, or a required text object isn't found). At that point Vim aborts the macro silently and the repetition stops.

This is a powerful alternative to N@a (running N times blindly) — the recursive approach naturally terminates at the right point without you having to count lines.

How it works

  1. qa — start recording into register a (any register works)
  2. {motions} — perform the operation you want to repeat (e.g., move to next line, make a change)
  3. @a — call register a recursively at the end of the recording
  4. q — stop recording
  5. @a — trigger the first call; the macro runs until it fails

The recursion terminates automatically because Vim stops the whole chain when any command errors (a failed motion, a search with no match, etc.).

Example

Append a semicolon to every line that doesn't already have one:

qa
:s/[^;]$/&;/<CR>
j
@a
q

Then run @a from the first line. The macro processes each line, moves down with j, calls itself, and stops when j reaches the last line and fails.

Tips

  • Use qq then immediately record — this initializes the register to empty, preventing stale data from a previous recording from being invoked if @q is called during setup
  • Start with the cursor at the top of the region you want to process
  • If the macro runs forever, press <C-c> to interrupt it
  • The macro stops on the FIRST failure — design your motions so failure happens at the natural end point

Next

How do I open the directory containing the current file in netrw from within Vim?