Is there a command to undo the last operation performed while in insert mode?

I just pasted text from the wrong register using <C-r>, and I have two options:

  1. Delete by hand what I just pasted and start over.
  2. Switch to normal mode, hit u and lose the text I typed before hitting <C-r>.

Is there a better way?

up vote 16 down vote accepted

Vim offers a limited ability to specify the scope of an undoable change with the Ctrl-G u command, which breaks the undo sequence. See

:help i_CTRL-G_u

In your case, the solution would be to remap <C-R> like this:

:inoremap <C-R> <C-G>u<C-R>

Then typing <C-O>u will undo just the changes made since you typed <C-R>. See

:help i_CTRL-O
  • 1
    That's brilliant, I didn't know about this command. There's quite a long delay between typing <C-O>u and seeing the result on the screen (about 4 seconds), any idea on how could I get rid of that? – zool Aug 28 '15 at 8:35
  • I noticed that, too. I don't know; I'll try to find out. – garyjohn Aug 28 '15 at 14:49
  • Hey there, is it possible you meant <CR> (carriage return) instead of <C-R> (ctrl-r) ? – Derwent Aug 7 at 1:31
  • No. The original question had to do with the behavior of <C-R>, so that's what the mapping uses. However, you could replace <C-R> with <CR> in that mapping to have the undo sequence interrupted by a <CR> instead. More examples may be found at :help i_CTRL-G_u. – garyjohn Aug 7 at 6:11

From insert mode:

  1. If your pasted text is smaller than one line (which is what your 2nd point implies), simply hit <C-u> to remove all characters before cursor in the current line.

  2. If pasted text is more than one line, your 2nd solution would work better, adapted as follows: <C-o>u.

Both points above will start and stay - or finish - in insert mode; they are actually the same with your proposed solutions, just made shorter :)

You could try <C-w> (deletes a word to the left) or <C-u> (clear characters before cursor when pressed once, deletes linebreak when pressed a second time). See :help i_CTRL-W and :help i_CTRL-U.

If you paste a lot from a register it is of course faster to undo your changes, you can use insert-normal-mode with <C-o> for that (execute one normal mode command then go back to insert mode).

In general it is helpful to chunk your edits into small pieces by often going back to normal mode, so that you have fine-grained undo possibilities.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.