I would like to have a Paste + Override shortcut, which should basically have the behaviour of going into Replace-mode, typing everything currently in the clipboard, exiting Replace-mode.

How can I approach this?

  • 3
    What's wrong with selecting (visually) the region you want to replace, followed by p?
    – VanLaser
    Sep 26 '16 at 15:43

You could start with a maping, say, RR:

nmap <buffer> <expr> RR 'R' . substitute(@*, '<', '<lt>', 'g') . '<esc>'

Handles basic scenarios well enough.

I don't know if it will behave as you would expect for complex stuff, e.g. block selection. But for basics -- will work.


After searching the help, one option is described at

:help put-Visual-mode

However, this would require you to do the work of selecting what text gets replaced. For many cases, this is quick, easy, and reliable, but your question specifically wants something to just replace exactly that many characters.

My idea is to write a function that calculates the length of what's in the unnamed register "" (which is always the last yank, unless you used the "_ register to skip this rule), and first deletes that many characters (without modifying the unnamed register), and then does a put of "" into that spot.

Assuming you treat a tab character as one character, we will use strwidth(). If you want the equivalent spaces, you should use strdisplaywidth() instead.

function MyReplace()
  let y=strwidth(@")
  exec "normal \"_" . y . "x"
  exec "normal P"

Then bring your cursor to the right spot and :call MyReplace()

This can be replaced with a more convenient key combination through mapping or similar.

Limitations: This doesn't work if you are trying to replace up to the end of the current line (or past it). This is because of how the cursor moves after "x" if you just bump up against the last character. An easy hack for this would be to add a dummy character to the end of the line first, then remove it after.

However, if you are starting closer to the end of line than the # of characters in your buffer, you will replace some characters BEFORE The cursor, because of how x works. If you wanted to delete newline characters just the same as normal characters, and you can find a version of the x command that deletes the next character no matter what, comment it here.

  • Note that I put this function exactly as typed at the bottom of my .vimrc
    – Starman
    Nov 24 '16 at 22:31

Your Answer

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