How do I duplicate a visual selection of lines in Vim?
Answer
:'<,'>copy'>
Explanation
How it works
The :copy command (or its abbreviation :t) duplicates lines to a specified destination. When used with a visual selection range, it duplicates all selected lines.
The full command :'<,'>copy'> breaks down as:
'<,'>- The visual selection range (auto-filled when you press:in visual mode)copy- The copy/duplicate command (also aliased as:t)'>- The destination: right after the last line of the selection
So you only need to type copy'> (or even shorter: t'>) after the auto-filled range.
Variations:
:'<,'>t'>- Same thing using the shorter:talias:'<,'>t0- Copy selection to the top of the file:'<,'>t$- Copy selection to the bottom of the file:'<,'>t42- Copy selection below line 42:'<,'>t'<-1- Copy selection above itself
This is much more efficient than y then p because it is a single command and does not alter any registers. Your yank register remains unchanged.
Example
Starting with this code:
def greet():
print("hello")
print("world")
- Move to line 2, press
Vthenjto select both print lines - Type
:'<,'>t'>and press Enter
Result:
def greet():
print("hello")
print("world")
print("hello")
print("world")
The selected lines are duplicated immediately below without affecting your registers.