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

How do I run a macro until it can no longer proceed without specifying an exact count?

Answer

100@a

Explanation

When you give a large count to a macro — such as 100@a — Vim automatically stops replaying the macro as soon as any step inside it fails. This makes it safe to say "run up to 100 times" even if the file only has 10 matching lines: the macro stops at the natural end of the data rather than throwing an error.

How it works

A macro fails (and stops) when any command inside it cannot complete. Common stopping conditions:

  • A search (/pattern<CR>) that finds no more matches
  • A motion (j, w, etc.) that reaches the end of the file
  • A substitute that finds nothing to replace

By giving a count large enough to exceed the number of items in the file, you effectively say "repeat until done."

Example

Suppose you have a macro in register a that reformats one CSV row and then moves down to the next line. To process an unknown number of rows:

99@a

Vim runs the macro repeatedly. When j can no longer move down (end of file), the macro stops — even if the count hasn't been reached.

Tips

  • Use a count like 999 or 9999 when you genuinely don't know how many iterations are needed.
  • This technique works because Vim treats a failed motion inside a macro as a reason to abort the entire repeat sequence.
  • If the macro uses a search, make sure wrapscan (ws) is disabled (:set nowrapscan) so the search doesn't wrap back to the top and repeat forever.
  • For more control, consider a recursive macro (qaqqa...@aq) that explicitly calls itself.

Next

How do I visually select a double-quoted string including the quotes themselves?