Question

With insertions, it is very easy to both wipe out a word/section and insert over it, like so

  • cw delete until end of word (with space) then go to insert mode
  • ce delete until end of word (without space) then go to insert mode
  • c3w delete until end of the next 3 words (with space) then go to insert mode
  • ct. delete until before period then go to insert mode
  • c$ delete until end of line then go to insert mode

How do I do this with paste operations? Often times I have a line like so

var name = "John Smith"
var name = "Jane Smith"

And I change it to

var name = "John Lee"
var name = "Jane Smith"

And yank (yw) "Lee", but now if I delete (dw) "Smith" from "Jane Smith", I no longer have "Lee" in the register to paste back. I know I can use the named registers. Also, I am sure I can use visual mode. However, I figured since this is a pretty common task, there would be a way to use the movement operators (e, w, t/T, f/F,$,0) with the paste command to specify what to paste over.

Was it helpful?

Solution

I think visual mode is the way to go. You just enable visual mode with v or V (if you want to overwrite whole lines at the time), use the movement operators in the usual way to select the area to be replaced and then paste. You take advantage of what you already know.

Vp overwrites the current line. vwp overwrites the current word.

You can find an overview of the alternatives at the Vim Wikia.

OTHER TIPS

Oh yes, what you want is the ultra convenient (sarcasm) blackhole register: select in visual mode the part you want to replace, using the movement you want (like vw), then "_xP.

The black hole register _ is a special register akin to /dev/null. The operation " sets the destination register for the text you are about to replace, and thus "_ ensures that the unwanted "Smith" hits the blackhole register. Thus, "Lee" is preserved in the " register. I'd recommend using macros to help if you're doing this many times in a row.

I no longer have "Lee" in the register to paste back.

Actually, Lee is in reg:0, there are at least two ways to paste back.

Method 1

  • move cursor to Lee, yw
  • move cursor to Smith, dw
  • "0P

Method 2

  • move cursor to Lee, yw
  • move cursor to Smith, cw
  • Ctrl-R+0

You can always make a custom mapping, I have the following:

nnoremap ,pw viw"0p

Which pastes over the inner word (iw) the last yanked text. Note that I'm using the 0 register, so I can paste as many times as I want, without loosing the yanked text. Unfortunately you need to write some other mappings. I like to have a mapping to paste inside quote, inside brackets and inside parentheses:

nnoremap ,pi" vi""0p
nnoremap ,pi] vi]"0p
nnoremap ,pi) vi)"0p
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top