3

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?

2 Answers 2

5

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.

2
  • I would recommend using another map zjis a fold related map. Aug 4, 2022 at 12:14
  • 1
    this is clever, thank you for contributing it! there is a corner case I found almost immediately where this doesn't work as expected: when the cursor is at the start of the line. in this case, while it preserves the cursor position, it omits the first character in the line. the fix is to replace y0 with v0y, which covers this case. Mar 23, 2023 at 10:31
1

Andrew's answer is nearly perfect; it just doesn't work as expected when invoked at the start of a line. Here's a slightly modified keymapping which resolves this:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .