vim toggling buffer overwrite behavior when deleting

前端 未结 2 1913
粉色の甜心
粉色の甜心 2020-12-11 08:38

Vim is great, but like many people I get really annoyed when I want to copy, delete, then paste -- the yank buffer gets overwritten by the delete action.

Now I know

2条回答
  •  一整个雨季
    2020-12-11 09:12

    I think trying to "turn-off" the side effects for every delete/change command would be overly difficult if not impossible. The basic ways to handle this situation:

    • Use the black hole ("_) register with your delete or change commands. e.g. "_dd
    • Use the "0 register which contains the most recent yank with your paste commands. e.g. "0p
    • Yanking the text to a named register. e.g. "ayy then later doing "ap

    I personally lean toward the "0p approach as this is fits with how my mind works.

    Now seeing you asked for no such work-arounds I have provided some functions that alter the paste commands to toggle between my so called paste_copy and nopaste_copy mode. nopaste_copy being Vim's default behavior. Put the following in your ~/.vimrc:

    function! PasteCopy(cmd, mode)
      let reg = ""
      if exists('g:paste_copy') && g:paste_copy == 1 && v:register == '"'
        let reg = '"0'
      elseif v:register != '"'
        let reg = '"' . v:register
      endif
      let mode = ''
      if a:mode == 'v'
        let mode = 'gv'
      endif
      exe "norm! " . mode . reg . a:cmd
    endfunction
    
    command! -bar -nargs=0 TogglePasteCopy let g:paste_copy = exists('g:paste_copy') && g:paste_copy == 1 ? 0 : 1echo g:paste_copy ? '  paste_copy' : 'nopaste_copy'
    
    nnoremap  p :call PasteCopy('p', 'n')
    nnoremap  P :call PasteCopy('P', 'n')
    nnoremap  ]p :call PasteCopy(']p', 'n')
    nnoremap  [p :call PasteCopy('[p', 'n')
    nnoremap  ]P :call PasteCopy(']P', 'n')
    nnoremap  [P :call PasteCopy('[P', 'n')
    vnoremap  p :call PasteCopy('p', 'v')
    vnoremap  P :call PasteCopy('P', 'v')
    

    You can toggle your paste_copy mode via :TogglePasteCopy. You may prefer a mapping like so

    nnoremap tp :TogglePasteCopy
    

    As a closing piece of advice I would highly suggest using "0p or using a named register over this approach as they are native to vim and there is one less "mode" to worry about.

提交回复
热议问题