Learn Practice Daily golf Reference

How to duplicate a line in Vim

In Normal mode, press yyp: yy copies the line and p pastes the copy right below it. yyP puts the copy above instead, and :t. ↵ duplicates the line without touching any register.

Try it here

Two more test cases

Each new test case starts as a copy of an old one. On the first case, yyp. Then go down to the empty-string case and duplicate it the other way, with :t. and ↵.

1 of 2Duplicate this line with yyp
2// [input, expected length]
1const cases = [
3 ['abc', 3],
+ ['abc', 3],
1 ['', 0],
2];
NORMALLoading the editor…1/20.0s3:3

This editor needs a keyboard. Read on, and play it at your computer.

KeysWhat it does
yypDuplicate the line; the copy goes below and the cursor moves onto it.
yyPDuplicate the line; the copy goes above.
yy3pThree copies below the line.
:t. ↵Duplicate the line without changing any register.
:t-1 ↵Duplicate it above, without changing any register.
3yypDuplicate a block of three lines, starting with this one, below the third.
yapPDuplicate the paragraph you are in, blank line and all.
V, extend, y, PDuplicate the lines you selected, above the selection.
:5,8t8 ↵Duplicate lines 5 to 8 right below line 8.

Why yyp works

Vim has no duplicate command because it doesn't need one. yy yanks the whole line, and a line you yanked as a line is put back as a line: p opens a new line below the current one and puts the copy there, wherever the cursor is. So yyp is a copy of the line, right under it, with the cursor on the copy, ready to change it.

The count goes on the paste for copies, and on the yank for size. yy3p gives three copies of one line; 3yyp yanks three lines and pastes one copy of all three, after the first of them. To put the copy of a block under the whole block, use 3yy, then 2j to its last line, then p, or :t with line numbers.

Duplicate and change

Most duplicates are about to be edited: a new test case, another field in a struct, one more route. After yyp the cursor is already on the copy, so the edit follows straight away. ciw changes the word under the cursor, :s/old/new/ changes the copy alone, and . repeats your last change on the next copy if you made several with yy3p.