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

How do I run a macro on every line in a specific line number range?

Answer

:{range} normal @{reg}

Explanation

The :normal command lets you execute Normal mode keystrokes over a range of lines. By combining it with an explicit line range like 5,10, you can apply a macro precisely to specific lines — no need to visually select them or count repetitions.

How it works

  • :{range} is any Ex range: absolute (5,10), relative (.,.+5), mark-based ('a,'b), or % for the whole file
  • normal @{reg} executes the macro stored in register {reg} on each line in the range
  • Vim moves to column 1 of each line in turn and runs the macro; if the macro fails on a line, Vim silently continues to the next
  • Use normal! (with a bang) to bypass user-defined key mappings — important in scripts and functions

Example

Suppose register q holds the macro Iconst <Esc>A;<Esc> (prepend const and append ;). Given:

name = "Alice"
age = 30
score = 95

With the three lines at positions 5–7, running :5,7 normal @q produces:

const name = "Alice";
const age = 30;
const score = 95;

Tips

  • This is more surgical than :%normal @q (all lines) and more predictable than {N}@q (runs N times from current position)
  • Mark a region with ma and mb, then use :'a,'b normal @q for flexible ranges without memorising line numbers
  • Combine with :{range}normal! gg or similar commands for any repeatable Normal mode operation, not just macros
  • The location list and visual selection equivalents are :'<,'>norm @q and :g/pattern/norm @q for pattern-filtered execution

Next

How do I see a summary of all previous quickfix lists from my current session and navigate between them?