33

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?

3 Answers 3

20

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
6
  • 2
    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?
    – mrzool
    Commented Aug 28, 2015 at 8:35
  • I noticed that, too. I don't know; I'll try to find out.
    – garyjohn
    Commented Aug 28, 2015 at 14:49
  • Hey there, is it possible you meant <CR> (carriage return) instead of <C-R> (ctrl-r) ?
    – Derwent
    Commented Aug 7, 2018 at 1:31
  • 1
    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
    Commented Aug 7, 2018 at 6:11
  • 1
    @mrzool In relation to delay I created bug report about it: "Ctrl+o u" in Insert mode is performed with a about 3 seconds delay Commented Jun 9 at 13:54
10

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 :)

10

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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