Copying and pasting lines

4.8
(94)

I often need to duplicate whole lines in my code, especially when writing CSS. The slow way is to navigate to the line I want, yank it, go back and paste it. The most efficient way I can think to do that is to jump by searching with / and pressing <CR>. Then yank the line with yy. Then use the jump list, <ctrl-o>, to bounce back. And press p to paste the line below or P to paste the line above. Let’s watch a screencast of this method first:

But there is another way! And it doesn’t involve moving around at all. In fact, your cursor can stay in the same place and you can do this with one command, the ex :yank command:

  • :<line number>yank – copies the line number specified to your default register

Once you’ve yanked, just paste with p or P and you’re done. But wait, there’s more! There’s an even better way. Use the ex :copy command:

  • :<line number>copy. – copies the line number specified and pastes it to the line below

Now you’ve done the whole operation in a single command. But we’re not done yet! The ex :copy command has an alias t. Putting it all together:

  • :<line number>t. – copies the line number specified and pastes it to the line below

You can also use + or - before the line number to turn it into a relative line number. Or even use a range of lines with a comma. Here are some examples of this in action:

  • :281t. – Copy line 281 and paste it below the current line
  • :-10t. – Copy the line 10 lines above the current line and paste it below the current line
  • :+8t. – Copy the line 8 lines after the current line and paste it below
  • :10,20t. – Copy lines 10 to 20 and paste them below
  • :t20 – Copy the current line and paste it below line 20

Now here’s a screencast of the same operation I did in the beginning, but using this new method:

How useful was this tip?

Average rating 4.8 / 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

92 Posts

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

2 thoughts on “Copying and pasting lines”

Leave a reply

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