'pasting with overwrite by motion in vim
Consider the following, frequent situation.
do_something("argument to use");
do_something_else("here I want the same argument es above");
I have copied the second line from somewhere else. But it has the wrong argument. I want to have it the same argument as the line above. So I move up there to the a of argument… and press in normal mode yt" (=yank till "). This copies everything within and excluding the quotes. Then I move one line down to the h of here… where I want to replace everything within these quotes with what I have just copied, something like rt" (=replace till ") but r is already used to replace a single character. Is that possible?
PS: I know in this case I could just copy the first line and add the _else to do_something. But this is just an example and I somehow can't believe there is no way to do it like I described in vim.
Solution 1:[1]
You can do this using visual mode. When your cursor is on the h, simply press:
vt"p
venables visual mode.t"will move your cursor to right before the"and select everything on its way.pwill paste over the selected text.
Solution 2:[2]
I need this so often, I wrote a plugin to simplify and allow maximum speed: ReplaceWithRegister.
This plugin offers a two-in-one gr command that replaces text covered by a {motion} / text object, 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. It transparently handles many corner cases and allows for a quick repeat via the standard . command. Should you not like it, its page has links to alternatives.
Solution 3:[3]
As an alternative to the visual mode solution, you could use the black hole register to delete the text on the second line before pasting the correct version.
"_di"P
"_di"delete between the""(same as"_dt"if you are at the start of the quote)Pthe above leaves the cursor over the closing"so paste the text before the cursor.
Solution 4:[4]
you can also use c{motion} and then in insert mode use CTRL-R0 to paste the last yanked content.
ci"<C-R>0
ci"deletes between""and then goes to inesrt mode<C-R>{register}will paste the content content in register{register}in the current cursur position in insert mode, and the 0 register contains the result of the most recent yank command (:h "0).
i've found this solution easier to hit than "_di"P, while still enabling pasting multiple times.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sander Vanhove |
| Solution 2 | Ingo Karkat |
| Solution 3 | Holloway |
| Solution 4 | Bar Tzadok |
