0

I've got clipboard=unnamed which means that when I copy from somewhere outside Vim, I can just "put" it into Vim without any additional thought. Most is the time this is perfectly adequate.

Except if I want to delete some text before pasting, in which case the deleted text occupies the * register and my old copy is nowhere to be found!

This operation is catered for within Vim because any yank also populates the 0 register, but copies from outside Vim obviously don't do this.

What can I do?

2 Answers 2

2

I do not use :set clipboard+=unnamed, but rather prefer to explicitly tell Vim when to use the clipboard and when not.

For your case, you can use P while in visual mode, which does not alter the unnamed register, so I would map to something like this:

xnoremap <leader>P "+P

And then you can select what you want to be overridden and use <leader>P to paste from the clipboard and it would also not change your unnamed register.

0

It looks like something like the following would be as good a start as any:

function! Foo()
    let clip = getreg('*')
    normal "*p
    call setreg('*', clip)
endfunction
xnoremap <key> <Cmd>call Foo()<CR>

where we…

  1. define a visual mode mapping on <key>,
  2. back-up the current content of register *,
  3. put the content of register *, which replaces its content with the previously selected text,
  4. restore register * from our backup.

Now, pressing <key> should replace the visually selected text with what you just copied outside of Vim.

Note that this quick and dirty solution adds a new mapping, which might not suit your needs ("without any additional thought"). A broader solution that could be mapped to p without losing functionality might be achievable but it will certainly be a bit more involved.

It could also be expanded to update register 0 for maximum "canonicalness".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.