How do I run a macro on every line in a visual selection?
Answer
:'<,'>normal @a
Explanation
The :'<,'>normal @a command executes the macro stored in register a on every line within the current visual selection. This is one of the most powerful macro techniques in Vim, letting you apply a recorded transformation to a specific set of lines.
How it works
- First, record a macro into register
awithqa...q - Select lines in visual line mode with
Vand movement keys - Type
:normal @a— Vim automatically prepends'<,'>to scope the command to your selection - The macro runs once on each line in the selection, with the cursor starting at the beginning of each line
Example
Suppose you want to wrap each line in quotes. Record a macro:
qaI"<Esc>A"<Esc>q
Given the text:
apple
banana
cherry
date
Select all four lines with ggVG, then type :normal @a<CR>. The result:
"apple"
"banana"
"cherry"
"date"
The macro runs on each selected line independently.
Tips
- If the macro fails on a line (e.g., a search within the macro finds no match), Vim stops on that line but continues to the next
- Use
:'<,'>normal @afor visual selections, or:%normal @ato run the macro on every line in the file - Use
:10,20normal @ato run the macro on lines 10 through 20 - Use
:g/pattern/normal @ato run the macro only on lines matching a pattern - Always test your macro on a single line first before applying it to a range
- The
:normalcommand executes keystrokes as if typed in normal mode, so your macro runs in the same context as if you pressed@amanually on each line