How to only undo pasted text in vim

osxvim

TL;DR; version – How do I undo text that was pasted in from my OS copy buffer without undoing other text that was typed in since I went into insert mode?

Longer description:

  1. Put something in your OS copy buffer (e.g. highlight some text and do Command-c on Mac)
  2. Go into insert mode in vim ( i )
  3. Type something ( e.g. asdf)
  4. Without exiting insert mode, paste from your copy buffer into vim ( Command-v on Mac)
  5. Hit escape
  6. Try to undo the paste ( u )

It undoes everything from the last time you went into insert mode. In otherwords, it clears out asdf plus all the text I pasted in.

How do I just undo the text that pasted in? Do I have to always go out of insert mode and back in before I paste text just to have the option to undo the pasted text?

Best Answer

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.