Search code examples
vimcopy-paste

Vim - Prevent cursor from moving when yanking to a mark


I typically use marks to cut/paste in Vim.

To yank the text between lines 4 and 12, I do the following:

  1. move cursor to line 4
  2. type mx to place a mark named x
  3. move cursor to line 12
  4. type y'x to yank the text between lines 4 and 12

After doing this, the cursor moves back to line #4.

Is there a way to make the cursor stay where it is (without moving back to the mark)?

If anybody has a better ways to do the same thing, that would be great, too...

Thanks in advance!


Update:

I used FDinoff's answer to create a mapping that is making me one happy camper:

nnoremap YY y'x<C-O>

This yanks from the cursor to the mark named x, then returns the cursor to where it was.

This has already saved me tons of time. Thanks again!


Solution

  • The reason you jump to line 4 is because you are using yank with a backwards motion.

                                *y* *yank*
    ["x]y{motion}       Yank {motion} text [into register x].  When no
                characters are to be yanked (e.g., "y0" in column 1),
                this is an error when 'cpoptions' includes the 'E'
                flag.
    

    The motion in question is 'x which is jump to mark x. The cursor is moved to the beginning of the yanked part which in this case is line 4 since you were yanking from line 12.

    However things you could do.

    1. Use a range for an ex command line mode yank. The range is . (current line) to 'x (mark x). If the range is backwards with will ask you is you meant the other direction. This won't move your cursor. :.,'xy

    2. Or you could use <C-o> will will jump you back to the last place you jumped from. (which was mentioned in the comments.)

    3. Or you could use '] or `]. These commands will jump you the last character of the the last yanked text.