How do I run a normal mode command on every line in a visual selection?
Answer
:'<,'>norm I//
Explanation
After making a visual selection, :norm {commands} executes normal-mode keystrokes on every line in the range. This is one of the most powerful bulk-editing patterns in Vim — any sequence of normal-mode commands you can type interactively can be applied to hundreds of lines at once.
How it works
- Select lines with
V(linewise visual) - Type
:— Vim automatically fills in:'<,'> - Add
norm {commands}where{commands}is any normal-mode sequence - Vim visits each line in the selection and replays the command sequence from the start of that line
Example
To prepend // to each selected line (quick-and-dirty comment block):
foo()
bar()
baz()
Select all three lines with V, then type :norm I// and press <CR>:
// foo()
// bar()
// baz()
Or to append a semicolon to each line: :'<,'>norm A;
Tips
- Works with any motion, operator, or keystroke:
:'<,'>norm ddto delete lines,:'<,'>norm ~to toggle case of the first character - Use
:'<,'>norm @qto replay a macro on each line — though:normwith inline commands is faster for simple operations - Unlike macros,
:normresets to the beginning of each line on every iteration, making it more predictable - Combine with a range like
:%norm A,to append a comma to every line in the file