Vim: How to Copy & Paste
Most Vim tutorials and cheatsheets out there will cover how to copy and paste. Pasting is the easy part. Let’s talk about copying!
Copying
To copy the current line (line in which the cursor is placed), simply
press double lower y
(yy
) or single upper case
y
(Y
).
yy
or Y
: copies/yanks the current line,
including the newline character at the end of the line.
To copy a specific number of lines under the cursor (beginning from
the current location of the cursor) simply precede the command with the
number of lines that you wish to copy, i.e., Nyy
(where N
is the number of lines).
You can also use the following operation to copy two lines:
:.,+yank
where the dot (.) refers to the current line and plus sign (+) means plus one line below the cursor.
So, in order to use this syntax to copy 3 lines, use 3yy
or :.,+2yank
will work.
You can also copy a specific number of lines above the
cursor From the current cursor location use yN-1k
, where
N-1
is the number of lines you want to copy. So, to copy
two lines from the current position of the cursor, press (in normal
mode, or escape mode), y2-1k
, or y1k
.
To copy 5 lines above the current cursor position:
y4k
You can also use other operations. for example, to copy only the fifth line just above the cursor:
Copying & Pasting
:-4yank
You can can copy lines and paste them right above the cursor in one
shot using the operation :Nt-
, where N
is the
line number you want to copy.
You can can copy specific line number and paste right below the
cursor directly using the operation :Nt.
, where
N
is the line number you want to copy.
For example, to copy line two and paste just above the current cursor position;
:2t-
To copy line two and paste just below the current cursor position;
:2t.
The above commands also work with a range of lines rather than a
single line, such as :4,7t.
will yank lines 4-7 and paste
them below the cursor.
Pasting
p
or P
: pastes one or more lines, basically
whatever is in the buffer, under or above the cursor respectively.