Vim: copy and paste
Yank and put inside vim, select lines and blocks, and paste from your computer into vim over SSH without broken indentation.
Vim words
Vim calls copying yank (y) and pasting put (p). Deleting with d also copies, so “delete” is really “cut”.
Inside vim (normal mode)
| What | Keys |
|---|---|
| Copy the line | yy |
| Copy 5 lines | 5yy |
| Copy a word | yw |
| Copy to the end of the line | y$ |
| Copy the whole file | ggyG |
| Cut the line | dd |
| Paste after / before the cursor | p / P |
| Paste a line below / above | p / P (after yy or dd) |
With a selection (visual mode)
- Move to the start.
- Press
v(characters),V(whole lines) orCtrl+V(a rectangular block). - Move to extend the selection.
- Press
yto copy,dto cut,>to indent. - Go to the target and press
p.
Block selection example: comment out lines 10 to 20.
:10 go to line 10
Ctrl+V start a block
10j extend 10 lines down
I insert at the start of each line
# type the character
Esc apply to all lines
Copy lines by number
| What | Command |
|---|---|
| Copy lines 10 to 20 below line 30 | :10,20t30 |
| Move lines 10 to 20 below line 30 | :10,20m30 |
| Delete lines 10 to 20 | :10,20d |
Paste from your computer over SSH
Pasting into a terminal is just fast typing. In insert mode vim’s auto-indent then adds indentation to every line, and your YAML ends up as a staircase.
| Fix | How |
|---|---|
| Paste mode | :set paste, i, paste, Esc, :set nopaste |
| Most modern terminals | Already handled (“bracketed paste”, vim 8+). Try a normal paste first. |
Copy from vim to your computer
Over SSH, vim can’t reach your computer’s clipboard. Two simple options:
- Select with the mouse in your terminal. If vim grabs the mouse, hold
Shift(Windows Terminal, most Linux terminals) orOption(macOS iTerm2) while selecting, or run:set mouse=. - Show the file with
cat fileand copy from the terminal.
On a desktop with vim-gtk3 installed, "+y copies to and "+p pastes from the system clipboard.
Registers (the short version)
Vim has many clipboards called registers. :reg shows them. Useful one: "0p pastes the last yank, even after you deleted something in between (a delete overwrites the default register, not register 0).