Pasting multiple times

4.7
(94)

Has this ever happened to you? You have some chunk of text or code and you want to copy and paste it to several places. Maybe you’re replacing one whole function or method with another. You select the lines and then press y to yank them. Then you move to the new location, select the lines you want to replace and press p to paste over top of them. Now you go to the next spot, highlight the lines you want to paste over and press p again. Instead of your initial text, you get the text you just pasted over top of. Ugh!

The naive solution is to go back and yank the lines again, paste again, yank again, paste again, etc. y p y p y p… But there is a better way! There is: paste with "0p instead of just p. But let’s understand what’s happening here.

When yanking (copying) and pasting in Vim, you’re taking advantage of what Vim calls Registers. Think of these like a set of multiple clipboards, each identifiably by a character (and see :help registers for much more). Except one of those registers is not identifiable by a character and it’s called the unnamed register.

Vim automatically stores any text you yank in the unnamed register. That’s where you paste from when you just use p. But Vim also stores any text you paste over in the unnamed register so by pasting over other text, you’re clobbering the text that was stored in there. Fortunately, Vim also stores the last text yanked in the register called 0. To paste from a register besides the unnamed one, you use a " followed by the register character, followed by p. So "0p will paste from the 0 register, which automatically contains the last yanked text.

You can see the contents of your registers at any time with :reg. It’s really helpful to look at them and see what’s going on here. I’ve also includes a demo video.

  • When I copy text with y, Vim puts it in the unnamed register and the 0 register. Both those registers contain the same thing.
  • When I paste over with p, Vim puts what I pasted over into the unnamed register but the 0 register still contains my original yanked text.
  • That means that if I paste with p, I’ll get the last thing I pasted over but if I paste with "0p, then I’ll paste with the last yanked text. Which is exactly what we want!

How useful was this tip?

Average rating 4.7 / 5. Vote count: 94

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

81 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts

2 thoughts on “Pasting multiple times”

Leave a reply

Your email address will not be published. Required fields are marked *