Vim copy preserving cursor location

1

I would like to have a shortcut in vim that performs a line duplication, without messing up the cursor's position. Simply yanking and pasting always moves the cursor to the beginning of the next line, so I think I need to do this in two steps: copying the beginning of the line and then the end of the line. What I was trying is this:

noremap <C-S-d> y0O<ESC>pkéy$lgp`[

with hjkl remapped to jklé. (without remapping it would look like this: y0O<ESC>pjly$kgp`[.)

This does not seem to work as a command though, even though when I test it key by key, it mangaes just fine. I wonder what is wrong with this macro?

Adam Hunyadi

Posted 2017-06-04T14:03:01.387

Reputation: 217

Answers

2

One problem I see is that noremap maps the value of the left-hand side to the value of the right-hand side without remapping. Basically, the right-hand side is always considered as just built-in mappings.

You could use map instead of noremap, or you could use the original mappings in the left-hand side. This seems to work fine for me:

noremap <C-S-d> y0O<ESC>pjly$kgp`[

Incidentally, here's how I duplicate lines, just so you can have a different approach to think about:

nnoremap zj mz"yyy"yP`z
nnoremap zk mz"yyy"yP`zk

The steps for duplicating are:

  • Save the current position in the z mark with mz
  • Copy line into the y register with "yyy
  • Paste line above with "yP
  • Go to the original position with `z

For me, this keeps the cursor position in the right place.

Andrew Radev

Posted 2017-06-04T14:03:01.387

Reputation: 326