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

How do I run a recorded macro on every line in a range without using a count?

Answer

:[range]norm @{register}

Explanation

The :normal command executes normal-mode keystrokes on each line in a range — including macro playback. Combining :norm @{register} with a range lets you apply a macro to exactly the lines you want, without needing to pre-calculate how many times to repeat it.

How it works

  • :[range] — any Ex range: % for all lines, 1,10 for specific lines, '<,'> for a visual selection, /start/,/end/ for pattern-delimited blocks
  • norm — short for :normal; runs the following keystrokes as if typed in normal mode on each line
  • @{register} — plays back the macro stored in the named register

If the macro errors on a line (e.g., a pattern is not found), use :silent! norm @{register} to suppress errors and continue to the next line.

Example

Suppose register q holds I- <Esc> (prepend - to a line). Given:

apple
banana
cherry

Running :%norm @q transforms all three lines:

- apple
- banana
- cherry

To apply only to a subset, use a range:

:2,3norm @q

Tips

  • Visual range: select lines in visual mode, then type :norm @q — Vim inserts '<,'> automatically
  • Error tolerance: prefix with silent! to keep going even if the macro fails on some lines: :% silent! norm @q
  • Without a macro: :norm works with any normal-mode keystrokes too — e.g., :%norm A; appends a semicolon to every line
  • Compare with [count]@q which runs the macro N times sequentially; :norm @q runs it once per line, resetting cursor position for each line

Next

How do I rename a variable across all case variants (snake_case, camelCase, MixedCase) at once?