Better way to copy lines

Hey guys, was wondering if any of you guys have a better way off doing this.

Say I have a file which have 100 lines of code. I turned on relative numbering. I’m on line 20 for example. I saw something that is 10 lines up from the current line I am in. I want to yank 2 lines from that point (10 lines above), to the current line I am in. Currently I’m doing this:-

10k2yy10jp

Which is move 10 lines up (10k), yank 2 lines (2yy), move back 10 line (10j) and paste (p)

Is there a way i can do this, which is yanking from 10 lines above without moving to it in the first place?

Two options that I’ve used:

Vim supports ex mode commands like :copy which can be used from anywhere as you specify the source. So in this case you could do :-10,-9copy. which breaks down as:

  • -10,-9 define the range from 10 lines up, to 9 lines up (this can work with absolute line numbers as well, but this is the syntax for relative numbering)
  • copy - copy these lines (you can use the shorter alias t in place of copy)
  • . - the current line (copy after the current line, like p in normal mode.

That’s likely the most complete / direct answer to your question, but I don’t often use that despite it’s directness. Instead, I’d go with 10ky2j<C-o>, which breaks down to:

  • 10k - jump up 10 lines
  • y2j - yank two lines (same functionality as 2yy, but I like the way y<motion|text-obj> works consistently / for all motions and text objects, not just linewise like yy)
  • <C-o> jump back to starting line

Although the first option is more direct, I find the second to be better as it’s made up of pieces that I use constantly and remember more readily.

Hope that helps!

– Chris

1 Like

Hey thanks!

Yes the 10ky... do feel familiar. I didn’t know <C-o> jumps back to starting line. This feels much better then 10j to get back to the starting line. Thanks for the tip! :smile: