vimtricks.wiki Concise Vim tricks, one at a time.

How do I prevent cursor movement in insert mode from splitting the undo block?

Answer

inoremap <Left> <C-g>U<Left>

Explanation

In insert mode, any cursor movement — including arrow keys, Home, and End — causes Vim to split the undo block at that point. This means pressing u after moving the cursor mid-insert only undoes back to the movement, not to where you started typing. <C-g>U suppresses this split, telling Vim to keep the surrounding insert in a single undo step.

How it works

  • <C-g>U is a two-key sequence available in insert mode
  • When prepended to a cursor motion, it marks that motion as "non-breaking" — it does not start a new undo block
  • The motion still moves the cursor; only the undo-split behaviour is suppressed
  • Most useful when you remap arrow keys or navigation keys for inline editing comfort

Add these to your vimrc to fix all four arrow directions:

inoremap <Left>  <C-g>U<Left>
inoremap <Right> <C-g>U<Right>
inoremap <Up>    <C-g>U<Up>
inoremap <Down>  <C-g>U<Down>

Example

Without remapping, inserting foo bar and then pressing <Left><Left><Left> to fix a typo splits undo into two chunks. With <C-g>U<Left>, the entire session stays one undo block:

Type: "foo baz" → move left three → overwrite 'z' with 'r' → type more
Undo with u: restores the entire insert, not just the last segment

Tips

  • <C-g>U only works directly before a cursor motion; it has no effect otherwise
  • This technique is used internally by plugins like vim-rsi and similar readline-style insert-mode plugins
  • It does not affect <C-o> (which exits to normal mode for one command and always splits the undo block intentionally)

Next

How do I build a macro programmatically using Vimscript instead of recording it?