How to Copy/Paste with Vim Registers

A basic introduction

123234345

--

Copying and pasting in Vim is a little different than with most other editors. When you yank (copy) or delete text, it gets put into registers. According to the Vim documentation, there are nine types of registers. I’m only going to mention a few of them here, because some of them go beyond what most people would need.

The Unnamed Register

If you yank (copy) text with the ‘y’ key or delete text with ‘c’, ‘d’, ‘s’, or ‘x’, the text will automatically get put into the unnamed register. You can then use ‘p’ or ‘P’ to paste it back on the page somewhere else. This is a common way to copy and paste in Vim.

Numbered Registers: “0 to “9

If you’re in command mode (press ESC to get there), you can type :reg to view a list of all registers. A history of your copied and deleted text will be listed there. You can access previous items in the register history by using “0, “1, “2, all the way up to “9. Typing the quote mark and the number of the register is then followed by p or P to paste the register in the file.

The Named Registers: “a to “z and “A to “Z

If you want to copy some text into a specific register that is named with a letter, just prefix the yank or delete with the register that you want to store it in. For example, to copy an entire line into register “a, type ”ayy. The “a attached the text to the “a register, and yy “yanks” (copies) the current line into that register. You can verify this by typing :reg to view the list of registers.

If you use a capital letter rather than a lowercase one, it will append the text into that register rather than replace it.

For example, if register “a holds the text “print” and you then put some text “ thing[i]” into register “A, it will append the second bit of text to the first leaving you with “print thing[i]” in the “a register. You can then paste your concatenated text in the “a register with “ap.

Other Useful Registers

To paste the filename, use “%.

To paste the last entered command from the command-line, use register “:. For example, if you just did a command-line search and replace like :%s/foo/bar/gc and want to paste that command somewhere in a file, type “:p.

Your last search is stored in the “/ register.

The external clipboard is in register “+. I most often use “+gp.

You can paste the results of an expression by typing “=. Vim will put you on the command line where you can type something like 8*9 or any other expression (see :help expressions). Press enter to go back to the file and p or P to paste the result.

Learning More

Vim has excellent built-in documentation, and there is more that can be done with registers. Just go into command mode by pressing ESC and type :help registers to view the relevant docs. Or click here. If you get stuck, type vimtutor in a terminal window to start an interactive Vim tutorial.

--

--