This is related to/a continuation of How do I replace-paste yanked text in vim without yanking the deleted lines?

In summary, vnoremap p "_dP is used to paste over visually selected text without overwriting the "* register with the replaced text. That way, subsequent visually-selected pastes are kept the same.

That remap works as expected except when a characterwise visual selection goes to the end of the line. I'm trying to figure out a way to handle this conditionally, so that:

  • in that specific case, do "_dp
  • otherwise, do "_dP

I'm thinking of vnoremap p to a vimscript function that checks for that specific case, i.e. "if visual selection is characterwise and cursor is at the end of the line", and execute accordingly.

meta - if vimscript is the answer, maybe I should post to StackOverflow?


It works with:

vnoremap <expr> p (getregtype() ==# 'v' && col(".") == col("$") - 1 ? '"_dp' : '"_dP')

For conditional remapping, you can use an expression mapping (:help map-expr). I don't know if this already works for you, but it should get you started:

:vnoremap <expr> p (getregtype() ==# 'v' && col("'>") == col('$') ? '"_dp' : '"_dP')
  • This got me what I needed, thanks. Problem with this exact line is col("'>" keeps using the visual selection previous to the one I'm using right now, and col('$') returns 'last column + 1'. – Kache Mar 26 '13 at 17:57

Using the black hole register can be a solution to two problems: you want to keep your numbered registers to only contain explicitly yanked text or you want to be able to paste the same text multiple times.

For the first problem, using "_d instead of d is the right tool because none of what you delete will appear in any register.

For the second problem, combining "_d and p or P inevitably creates problems because of cursor position and the orientation of p and P.

Ingo's answer seems to be a perfect compromise.

But if you don't care about the state of your numbered registers, an alternative is to use the "0 register which always contains the latest yanked text and is not impacted by c or d?

Test yank: foo, yanked with yiw.

Test line: Lorem [i]psum dolor sit amet., with the cursor on the i of ipsum.

Test selection: v$.

Loremfoo <-- trailing whitespace and mashed text, bad

Lorem foo <-- good

Lorem foo <-- good

Test selection: vee.

Lorem foo sit amet. <-- good

Lorem  foosit amet. <-- bad

Lorem foo sit amet. <-- good
  • This could definitely be a solution (although I find "0p kinda verbose), but it turns out I got exactly what I was looking for. – Kache Mar 26 '13 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.