I would like to increase the granularity of the undo command in Vim. Since undo resets itself after each entering into normal mode, I would like to replace the usual enter (<CR>
) as used in insert mode, with <Esc>
and o
. Thus, I should be able to undo line by line when writing. (Yes, I know I have to add <C-g>u
also, but this is another issue not relevant to my problem).
I've added this line to .vimrc
:
inoremap <CR> <Esc>o
What happens, however, is that after each enter, the cursor jumps down and one column to the right (no, there is no trailing space in my vimrc-line :)). If I now press enter again, it jumps directly down, e.g. it stays on the second column. But if I write something first and press enter, it jumps again one down and one to the right.
You had the right gut feeling about <C-G>u
. Reading Vim's help a down from :help i_CTRL-G_u
, we find the following small example:
:inoremap <CR> <C-]><C-G>u<CR>
This starts a new undo block at each line break. It also expands abbreviations before this.
This sounds as if it was exactly what you're looking for: you can undo line by line. It also does not trigger any (additional) side effects that changing modes might bring with them.
My answer fails to provide an explanation as to why the mapping in the question is not working. I trust in other users to provide some background.
As a side note: when I tried the mapping in the question in Vim 9.0, no additional space was inserted. However, it also failed to undo by line.