如何在Vim中替换粘贴粘贴的文本而不删除删除的行?


39

因此,我通常会发现自己将文本从一个点复制到另一点,同时覆盖粘贴新文本的旧文本:

blah1
newtext
blah2
wrong1
blah3
wrong2
blah4

假设我在视觉上标记newtext并上了y句。现在,我选择wrong1(可以是任何东西,不一定是一个字),然后p单击newtext。但是,如果我现在这样做的wrong2话,它将被替换为wrong1代替newtext

因此,如何防止缓冲区中的文本与当前正在覆盖的文本交换?

编辑1

尽管我很喜欢建议的建议(既然发现了:dis命令,我想我将开始更多地使用寄存器),但是我将对jinfield的答案进行修改,因为我不使用交换模式。

vnoremap p "0p
vnoremap P "0P
vnoremap y "0y
vnoremap d "0d

完美地完成了把戏。

编辑2

我太快了;romainl的解决方案正是我在寻找的解决方案,而没有Edit 1中的hack 。
其实vnoremap p "_dP就足够了!
因此,更改接受的答案。


2
嘿,fyi,我已经使用了很久了vnoremap p "_dP map,我注意到它对于一行中的最后一个单词/字符来说效果不佳。我已经回到了vnoremap p "0pvnoremap P "0Pset clipboard=unnamed(对于OSX)
Kache14,2014年

vnoremap p "_dP去除粘贴上的空白。编辑1完美地工作。
瓦茨拉夫·卡萨尔

Answers:


21

我的.vimrc中有这些映射:

" delete without yanking
nnoremap <leader>d "_d
vnoremap <leader>d "_d

" replace currently selected text with default register
" without yanking it
vnoremap <leader>p "_dP

"_是“黑洞寄存器”,根据:help "_

“在写入该寄存器时,什么都不会发生。可用于删除文本而不会影响普通寄存器。从该寄存器中读取时,不会返回任何内容。{Vi无此功能}”


1
我已经使用了它,vnoremap p "_dP map并注意到它对于一行中的最后一个单词/字符来说效果不佳。我已经回到了vnoremap p "0pvnoremap P "0Pset clipboard=unnamed(对于OSX)
Kache14,2014年

vnoremap p "_dP停止在选择模式下为我工作,但vnoremap <leader>p "_dP确实起作用
whitesiroi 2015年

1
也许<leader>是我应该知道要替换为某个占位符的占位符,但这仅在我删除它后才起作用。这是什么意思?
哈什布朗

1
@Hashbrown, :help mapleader
romainl

小警告:vnoremap <leader>p映射在缓冲区的最后一行上无法正常工作,因为一旦删除缓冲区的最后一行,您现在就位于倒数第二行,并且P将粘贴在该行的上方,而不是下面。
卡尔

13

除了标准缓冲区外,您还可以将文本拖入命名缓冲区中,然后从这些命名缓冲区中放入文本。最多可以使用26个命名缓冲区(每个字母一个)。使用双引号和字母访问命名缓冲区。例子:

"dyy -将当前行拉入缓冲区d。
"a7yy-将接下来的7行拉入缓冲区a。
"dP-将缓冲区d的内容放在光标之前。
"ap-将缓冲区a的内容放在光标之后

另外一件很酷的事情,如果您使用大写字母而不是小写字母,即"Dyy当前行将追加到缓冲区d而不是替换它。O`Reilly书中的更多详细信息:http ://docstore.mik.ua/orelly/unix/vi/ch04_03.htm


3
很酷的东西。我知道缓冲区,但是没有将缓冲区与这个问题联系起来。"a一切仍然繁琐,但是还可以。
bitmask

4

put在可视模式下使用时,您要替换的文本wrong1被'unamed'寄存器的内容覆盖。

这实际上是通过在选择之后“放入”寄存器然后删除选择来实现的。问题在于此删除操作现在存储在unnamed寄存器中,并将用于下一步put操作。

根据的解决方案:h v_p是将其拉入一个命名寄存器(如)"0y,然后"0p根据需要使用多次。如果您经常这样做,则映射<leader>y<leader>p使用命名寄存器可能会有所帮助。

:map <leader>y "0y
:map <leader>p "0p

有关更多帮助,请参见:

:help v_p
:help map

这种解决方案似乎是最有用的,除非vim本身出现了一些聪明的方法。
Yugal Jindle 2013年

4

"0寄存器粘贴很重要,要知道,但是您经常需要多次替换。如果您将其.设为可重复操作,则可以使用garyjohn暗示的运算符。在vim Wiki上有解释:

yiw     yank inner word (copy word under cursor, say "first". Same as above).
...     Move the cursor to another word (say "second").
ciw<C-r>0   select "second", then replace it with "first" If you are at the start of the word then cw<C-r>0 is sufficient.
...     Move the cursor to another word (say "third").
.   select "third", then replace it with "first". 

3

当您将文本拖入未命名的寄存器*时,副本也会放入寄存器0中。每次替换选定的文本时,只需从0寄存器中粘贴即可。看到

:help registers

此外,如果您要用相同的单词替换多个单词,则只需移至要替换的单词的开头并输入即可.。这将重复上一次的编辑操作。看到

:help single-repeat

*您放入和放入的存储位置称为寄存器。缓冲区是您要编辑的东西,通常是磁盘上文件的副本。


1

我经常需要它,为此我写了一个插件:ReplaceWithRegister

这个插件提供了一个gr二合一的命令,用寄存器的内容替换{motion},整行或当前选择所覆盖的文本;旧文本将被删除到黑洞寄存器中,也就是说,它已经消失了。


1

由于类似vnoremap p "_dP(我也尝试过xc)在行的开头和结尾都有问题,所以我最终这样做了:vnoremap p :<C-U>let @p = @+<CR>gvp:let @+ = @p<CR>我发现它比现有的插件更简单(也无法使用现成的插件set clipboard=unnamedplus)。所以它的作用是:

  • 切换到命令模式
  • 删除范围(C-U
  • 备份+寄存器(由于unnamedplus,替代品"*具体取决于您的配置)p
  • 恢复选择并粘贴
  • 再次切换到命令模式
  • 恢复注册

完善!这是完全符合我预期的这些选项中的第一个。谢谢!
贾米斯·查尔斯

1

这就是我使用的(从我的.vimrc文件中复制的)用于Windows风格的控件+ X剪切/控件+ C复制/控件+ V粘贴/控件+ S保存/控件+ F查找/控件+ H替换行为。

smartpaste()函数应包含您要查找的内容,即一种无需突出显示所选内容即可粘贴突出显示的文本的方法。

" Windows common keyboard shortcuts and pasting behavior {{{

" Uncomment to enable debugging.
" Check debug output with :messages
let s:debug_smart_cut = 0
let s:debug_smart_copy = 0
let s:debug_smart_paste = 0

function! SmartCut()
    execute 'normal! gv"+c'

    if visualmode() != "\<C-v>" " If not Visual-Block mode
        " Trim the last \r\n | \n | \r character in the '+' buffer
        " NOTE: This messes up Visual-Block pasting.
        let @+ = substitute(@+,'\(\r\?\n\|\r\)$','','g')
    endif

    if exists("s:debug_smart_cut") && s:debug_smart_cut
        echomsg "SmartCut '+' buffer: " . @+
    endif
endfunction

function! SmartCopy()
    execute 'normal! gv"+y'

    if visualmode() != "\<C-v>" " If not Visual-Block mode
        " Trim the last \r\n | \n | \r character in the '+' buffer
        " NOTE: This messes up Visual-Block pasting.
        let @+ = substitute(@+,'\(\r\?\n\|\r\)$','','g')
    endif

    if exists("s:debug_smart_copy") && s:debug_smart_copy
        echomsg "SmartCopy '+' buffer: " . @+
    endif
endfunction

" Delete to black hole register before pasting. This function is a smarter version of "_d"+P or "_dp to handle special cases better.
" SOURCE: http://stackoverflow.com/questions/12625722/vim-toggling-buffer-overwrite-behavior-when-deleting
function! SmartPaste()
    let mode = 'gv'

    let delete = '"_d'

    let reg = '"+'

    " See :help '> for more information. Hint: if you select some text and press ':' you will see :'<,'>
    " SOURCE: http://superuser.com/questions/723621/how-can-i-check-if-the-cursor-is-at-the-end-of-a-line
    " SOURCE: http://stackoverflow.com/questions/7262536/vim-count-lines-in-selected-range
    " SOURCE: https://git.zug.fr/config/vim/blob/master/init.vim
    " SOURCE: https://git.zug.fr/config/vim/blob/master/after/plugin/zzzmappings.vim
    let currentColumn = col(".")
    let currentLine = line(".")
    let lastVisibleLetterColumn = col("$") - 1
    let lastLineOfBuffer = line("$")
    let selectionEndLine = line("'>")
    let selectionEndLineLength = len(getline(selectionEndLine))
    let nextLineLength = len(getline(currentLine + 1))
    let selectionStartColumn = col("'<")
    let selectionEndColumn = col("'>")

    " If selection does not include or go beyond the last visible character of the line (by also selecting the invisible EOL character)
    if selectionEndColumn < selectionEndLineLength
        let cmd = 'P'

        if exists("s:debug_smart_paste") && s:debug_smart_paste
            echomsg "SmartPaste special case #1"
        endif

    " If attempting to paste on a blank last line
    elseif selectionEndLineLength == 0 && selectionEndLine == lastLineOfBuffer
        let cmd = 'P'

        if exists("s:debug_smart_paste") && s:debug_smart_paste
            echomsg "SmartPaste special case #2"
        endif

    " If selection ends after the last visible character of the line (by also selecting the invisible EOL character) and next line is not blank and not the last line
    elseif selectionEndColumn > selectionEndLineLength && nextLineLength > 0 && selectionEndLine != lastLineOfBuffer
        let cmd = 'P'

        if exists("s:debug_smart_paste") && s:debug_smart_paste
            echomsg "SmartPaste special case #3"
        endif

    " If selection ends after the last visible character of the line (by also selecting the invisible EOL character), or the line is visually selected (Shift + V), and next line is the last line
    elseif selectionEndColumn > selectionEndLineLength && selectionEndLine == lastLineOfBuffer
        " SOURCE:  http://vim.wikia.com/wiki/Quickly_adding_and_deleting_empty_lines

        " Fixes bug where if the last line is fully selected (Shift + V) and a paste occurs, that the paste appears to insert after the first character of the line above it because the delete operation [which occurs before the paste]
        " is causing the caret to go up a line, and then 'p' cmd causes the paste to occur after the caret, thereby pasting after the first letter of that line.
        " However this but does not occur if there's a blank line underneath the selected line, prior to deleting it, as the cursor goes down after the delete in that situation.
        call append(selectionEndLine, "")

        let cmd = 'p'

        if exists("s:debug_smart_paste") && s:debug_smart_paste
            echomsg "SmartPaste special case #4"
        endif

    else
        let cmd = 'p'

        if exists("s:debug_smart_paste") && s:debug_smart_paste
            echomsg "SmartPaste default case"
        endif
    endif

    if exists("s:debug_smart_paste") && s:debug_smart_paste
        echomsg "SmartPaste debug info:"
        echomsg "    currentColumn: " . currentColumn
        echomsg "    currentLine: " . currentLine
        echomsg "    lastVisibleLetterColumn: " . lastVisibleLetterColumn
        echomsg "    lastLineOfBuffer: " . lastLineOfBuffer
        echomsg "    selectionEndLine: " . selectionEndLine
        echomsg "    selectionEndLineLength: " . selectionEndLineLength
        echomsg "    nextLineLength: " . nextLineLength
        echomsg "    selectionStartColumn: " . selectionStartColumn
        echomsg "    selectionEndColumn: " . selectionEndColumn
        echomsg "    cmd: " . cmd
        echo [getpos("'<")[1:2], getpos("'>")[1:2]]
        echo "visualmode(): " . visualmode()
        echo "mode(): " . mode()
    endif

    if visualmode() != "\<C-v>" " If not Visual-Block mode
        " Trim the last \r\n | \n | \r character in the '+' buffer
        " NOTE: This messes up Visual-Block pasting.
        let @+ = substitute(@+,'\(\r\?\n\|\r\)$','','g')
    endif

    try
        execute 'normal! ' . mode . delete . reg . cmd
    catch /E353:\ Nothing\ in\ register\ +/
    endtry

    " Move caret one position to right
    call cursor(0, col(".") + 1)
endfunction

" p or P delete to black hole register before pasting
" NOTE: <C-u> removes the '<,'> visual-selection from the command line. See :h c_CTRL-u
vnoremap <silent> p :<C-u>call SmartPaste()<CR>
vnoremap <silent> P :<C-u>call SmartPaste()<CR>

" MiddleMouse delete to black hole register before pasting
nnoremap <MiddleMouse> "+p " Changes default behavior from 'P' mode to 'p' mode for normal mode middle-mouse pasting
" NOTE: <C-u> removes the '<,'> visual-selection from the command line. See :h c_CTRL-u
vnoremap <silent> <MiddleMouse> :<C-u>call SmartPaste()<CR>
inoremap <MiddleMouse> <C-r><C-o>+

" Disable weird multi-click things you can do with middle mouse button
" SOURCE: http://vim.wikia.com/wiki/Mouse_wheel_for_scroll_only_-_disable_middle_button_paste
noremap <2-MiddleMouse> <Nop>
inoremap <2-MiddleMouse> <Nop>
noremap <3-MiddleMouse> <Nop>
inoremap <3-MiddleMouse> <Nop>
noremap <4-MiddleMouse> <Nop>
inoremap <4-MiddleMouse> <Nop>

if os != "mac" " NOTE: MacVim provides Command+C|X|V|A|S and undo/redo support and also can Command+C|V to the command line by default
    " SOURCE: https://opensource.apple.com/source/vim/vim-62.41.2/runtime/macmap.vim.auto.html
    " NOTE: Only copy and paste are possible in the command line from what i can tell.
    "       Their is no undo for text typed in the command line and you cannot paste text onto a selection of text to replace it.
    cnoremap <C-c> <C-y>
    cnoremap <C-v> <C-r>+
    " TODO: Is their a select-all for the command line???

    " Cut, copy, and paste support for visual and insert mode (not for normal mode)
    " SOURCE: http://superuser.com/questions/10588/how-to-make-cut-copy-paste-in-gvim-on-ubuntu-work-with-ctrlx-ctrlc-ctrlv
    " NOTE: <C-u> removes the '<,'> visual-selection from the command line. See :h c_CTRL-u
    vnoremap <silent> <C-x> :<C-u>call SmartCut()<CR>
    vnoremap <silent> <C-c> :<C-u>call SmartCopy()<CR>
    vnoremap <silent> <C-v> :<C-u>call SmartPaste()<CR>
    inoremap <C-v> <C-r><C-o>+

    " Select-all support for normal, visual, and insert mode
    " http://vim.wikia.com/wiki/Using_standard_editor_shortcuts_in_Vim
    nnoremap <C-a> ggVG
    vnoremap <C-a> ggVG
    inoremap <C-a> <Esc>ggVG

    " Save file support for normal, visual, and insert mode
    " SOURCE: http://vim.wikia.com/wiki/Map_Ctrl-S_to_save_current_or_new_files
    " If the current buffer has never been saved, it will have no name,
    " call the file browser to save it, otherwise just save it.
    command -nargs=0 -bar Update if &modified |
                                \    if empty(bufname('%')) |
                                \        browse confirm write |
                                \    else |
                                \        confirm write |
                                \    endif |
                                \endif
    nnoremap <silent> <C-s> :update<CR>
    " NOTE: <C-u> removes the '<,'> visual-selection from the command line. See :h c_CTRL-u
    vnoremap <silent> <C-s> :<C-u>update<CR>V
    " NOTE: <C-o> executes a normal-mode command without leaving insert mode. See :help ins-special-special
    "inoremap <silent> <C-s> <C-o>:update<CR>
    "
    " <C-o> doesn't seem to work while also using the "Open the OmniCompletion menu as you type" code while the menu is visible.
    " Doing "call feedkeys("\<C-x>\<C-o>", "n")" to perform omni completion seems to be the issue.
    " However doing "call feedkeys("\<C-x>\<C-i>", "n")" to perform keywork completion seems to work without issue.
    "
    " Workaround will exit insert mode to execute the command and then enter insert mode.
    inoremap <silent> <C-s> <Esc>:update<CR>I

    " Undo and redo support for normal, visual, and insert mode
    nnoremap <C-z> <Esc>u
    nnoremap <C-y> <Esc><C-r>

    " NOTE: <C-u> removes the '<,'> visual-selection from the command line. See :h c_CTRL-u
    vnoremap <C-z> :<C-u>uV
    vnoremap <C-y> :<C-u><C-r>V

    inoremap <C-z> <Esc>uI
    inoremap <C-y> <Esc><C-r>I

    function! Find()
        let wordUnderCursor = expand('<cword>')
        if len(wordUnderCursor) > 0
            execute 'promptfind ' . wordUnderCursor
        else
            execute 'promptfind'
        endif
    endfunction

    function! Replace()
        let wordUnderCursor = expand('<cword>')
        if len(wordUnderCursor) > 0
            execute 'promptrepl ' . wordUnderCursor
        else
            execute 'promptrepl'
        endif
    endfunction

    " Find and Find/Replace support for normal, visual, and insert mode
    nnoremap <C-f> :call Find()<CR>
    nnoremap <C-h> :call Replace()<CR>

    " NOTE: <C-u> removes the '<,'> visual-selection from the command line. See :h c_CTRL-u
    vnoremap <C-f> :<C-u>call Find()<CR>
    vnoremap <C-h> :<C-u>call Replace()<CR>

    " NOTE: <C-o> executes a normal-mode command without leaving insert mode. See :help ins-special-special
    inoremap <C-f> <C-o>:call Find()<CR>
    inoremap <C-h> <C-o>:call Replace()<CR>
endif

" }}} Windows common keyboard shortcuts and pasting behavior

-1

tl; dr-vnoremap p“ _c *

这是我的完整映射的列表:
“修复寄存器复制/粘贴
nnoremap DD” * dd
nnoremap D“ * d
vnoremap D” d
nnoremap d“ _d
nnoremap dd” _dd
vnoremap d“ _d
nnoremap s” _s
vnoremap s“ _s
nnoremap c“ _c
vnoremap c” _c
nnoremap x“ _x
vnoremap x” _x
vnoremap p“ _c

“在新行
nnoremap,p op 上粘贴
nnoremap,P Op

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.