Kosta Kontos
Kosta Kontos

Reputation: 4322

vim: How do I replace a character under my cursor with previously yanked text (more than once)?

Let's say I've yanked 3 characters "foo" into my clipboard by using a visual select + yank, ie: 'vllly'

Then I've moved my cursor to another character (let's call this character x) on line 5 which I'd like to replace with what I yanked previously, namely foo.

I can use 'p' to paste foo after x, or 'P' to paste foo before x, but I want to replace x with foo.

I can use 'vp' to replace x with foo, but this only works once, as it leaves me with x in my clipboard. In other words, if I move to my next occurrence of x and hit vp again, it doesn't replace it with foo.

Sure, I could do a search / replace by using :s/x/foo/gc and then ignoring all occurrences of x that I don't wish to replace, but this is a little tedious to type, particularly when all I need to do is replace 2 or 3 occurrences of x that are very close to my cursor but not on the same line (ie: lines 2, 3 and 7).

So currently I'm using :2,7s/x/foo/gc but I wonder if there is a way to move my cursor to x and hit [insert magic button here] to replace it with foo. And then I can move to my next occurrence of x and hit [magic button] again and boom, it's replaced x with foo again.

As much as it pains me to use this analogy, imagine you're typing in notepad, and you select 3 characters, hit Ctrl+c to copy them into your clipboard, and then highlight x, and hit Ctrl+v to replace it with foo. Then you highlight another x, and hit Ctrl+v again, and so on.

How do I do this in vim?

Upvotes: 34

Views: 40932

Answers (5)

Ingo Karkat
Ingo Karkat

Reputation: 172510

I need this so often, I wrote a plugin for that: ReplaceWithRegister.

This plugin offers a two-in-one gr command that replaces text covered by a {motion}, entire line(s) or the current selection with the contents of a register; the old text is deleted into the black-hole register, i.e. it's gone.

Upvotes: 0

Stefan
Stefan

Reputation: 114138

What about s<C-r>0, this can be repeated with .

  • s deletes the character under the curser and puts you into insert mode.
  • <C-r>0 inserts register 0, which holds the yanked text.

You can also use s and type foo manually, which is also repeatable with .

Upvotes: 58

William Pursell
William Pursell

Reputation: 212198

This is less than ideal, but if you yank to named buffer a (eg yank with "ay), you can use x"aP. Use your favorite map to make it a single keystroke.

Upvotes: 0

Raimondi
Raimondi

Reputation: 5303

Paste from the 0 register with v"0p.

Upvotes: 7

Habi
Habi

Reputation: 3300

Copy your "foo" into another register, e.g. register a:

"ay

Then visually select the character you want to replace with "foo" and press

"aP

Upvotes: 2

Related Questions