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 filenormal @{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
maandmb, then use:'a,'b normal @qfor flexible ranges without memorising line numbers - Combine with
:{range}normal! ggor similar commands for any repeatable Normal mode operation, not just macros - The location list and visual selection equivalents are
:'<,'>norm @qand:g/pattern/norm @qfor pattern-filtered execution