Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

replace

vim

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?

like image 402
Kosta Kontos Avatar asked May 24 '12 08:05

Kosta Kontos


People also ask

How do I replace a word with yanked in Vim?

Move the cursor to another word (say "third"). Repeat the operation (change word and replace it with "first"). Move the cursor to another word and press . to repeat the change. Yank inner text (text containing cursor which is in quotes).

How do I yank a character in Vim?

Copying (Yanking) To copy text, place the cursor in the desired location and press the y key followed by the movement command. Below are some helpful yanking commands: yy - Yank (copy) the current line, including the newline character.

How do I search and replace in Vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.


1 Answers

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 .

like image 105
Stefan Avatar answered Oct 13 '22 02:10

Stefan