Search code examples
vimvi

How to paste over without overwriting register


Does anyone know of a way to paste over a visually selected area without having the selection placed in the default register?

I know I can solve the problem by always pasting from an explicit register. But it's a pain in the neck to type "xp instead of just p


Solution

  • "{register}p won't work as you describe. It will replace the selection with the content of the register. You will have instead to do something like:

    " I haven't found how to hide this function (yet)
    function! RestoreRegister()
      let @" = s:restore_reg
      return ''
    endfunction
    
    function! s:Repl()
        let s:restore_reg = @"
        return "p@=RestoreRegister()\<cr>"
    endfunction
    
    " NB: this supports "rp that replaces the selection by the contents of @r
    vnoremap <silent> <expr> p <sid>Repl()
    

    Which should be fine as long as you don't use a plugin that has a non-nore vmap to p, and that expects a register to be overwritten.

    This code is available as a script there. Ingo Karkat also defined a plugin solving the same issue.