How do I run a normal mode command on every line in a range?
Answer
:{range}normal {commands}
Explanation
The :normal command executes normal mode keystrokes from the command line. Combined with a range, it runs those keystrokes on every line in the range. This is like a mini macro that you do not need to record first.
How it works
:{range}normal {commands}executes{commands}in normal mode on each line in{range}:%normal A;appends a semicolon to every line in the file:10,20normal dddeletes lines 10 through 20 (one at a time):'<,'>normal @aruns macroaon each line in the visual selection
Example
Given these lines (selected visually):
let x = 1
let y = 2
let z = 3
Running :'<,'>normal A; produces:
let x = 1;
let y = 2;
let z = 3;
Tips
- Use
:normal!(with bang) to ignore user mappings and use default Vim commands - Combine with
:gfor conditional execution::g/TODO/normal dd - You can chain multiple keystrokes:
:%normal I//comments out every line - For complex sequences, use
exewith special keys::exe "normal! i\<C-r>0"