How do I only undo pasted text in vim?

One way is explicitly dropping out and back into insert mode before the paste. If you extend the paste commands, you can also automatically set an undo point before the paste:

" Any text fragment pasted in insert mode should be undone separately, without
" destroying what was typed before.
inoremap <C-R> <C-G>u<C-R>

The above is for the built-in i_CTRL-R command. I don't know how Command-v is implemented in MacVim, but prepending <C-G>u to the :imap command should achieve the same effect.


In MacVim, you need to unmap the Edit > Paste menu item in order to override the shortcut, then you can remap Cmd-V (D-v in MacVim parlance) to the appropriate command in each mode. I added this to my ~/.gvimrc and now everything works wonderfully:

macmenu Edit.Paste key=<nop>
noremap <D-v> "*P
cnoremap <D-v> <C-r><C-o>*
inoremap <D-v> <C-g>u<C-r><C-o>*

The <C-g>u is necessary only in insert mode to fix the undo history; the noremap and cnoremap are simply to restore the default paste behavior in the normal and command modes.

Thanks to Ingo Karkat for pointing me in the right direction here.

Tags:

Vim

Osx