Manually breaking the undo sequence
You can manually break the undo sequence in Insert mode with <C-G>u
. From the help:
CTRL-G u break undo sequence, start new change
Example
iHello<C-G>u world!<Esc>u
This will leave you with the text
Hello
Breakdown of commands
i " Enter Insert mode
Hello " Type 'Hello'
<C-G>u " Break the undo sequence
world! " Type ' world!'
<Esc> " Return to Normal mode
u " Undo
Automatic solution
Finer-grained undo-level control
Here's a small snippet of VimScript that uses <C-G>u
to create undo breaks when you start deleting text, and also when you start entering text again after a deletion.
function! s:start_delete(key)
let l:result = a:key
if !s:deleting
let l:result = "\<C-G>u".l:result
endif
let s:deleting = 1
return l:result
endfunction
function! s:check_undo_break(char)
if s:deleting
let s:deleting = 0
call feedkeys("\<BS>\<C-G>u".a:char, 'n')
endif
endfunction
augroup smartundo
autocmd!
autocmd InsertEnter * let s:deleting = 0
autocmd InsertCharPre * call s:check_undo_break(v:char)
augroup END
inoremap <expr> <BS> <SID>start_delete("\<BS>")
inoremap <expr> <C-W> <SID>start_delete("\<C-W>")
inoremap <expr> <C-U> <SID>start_delete("\<C-U>")
Notes
This will work for <BS>
, <C-W>
(delete a word), and <C-U>
(delete to beginning of line). If there are more ways to delete in Insert mode, they can be supported by adding additional inoremap
calls at the end.
:help
files about it ... See: How do I debug my vimrc file?... Also, using<C-c>
to exit insert mode may have side-effects (see this) and may be part of the problem ... I would suggest usingEsc
or<C-[>
(see this)