In the buffer
You are writing release notes. On the second line you press A, type Added retry logic., press <C-g>u, type Dropped the old cache., then press <Esc>:
## 2.4.1
Fixed the login timeout. Added retry logic. Dropped the old cache.
^
The second sentence was wrong. After typing u:
## 2.4.1
Fixed the login timeout. Added retry logic.
^
One u removes only the text typed after <C-g>u. A second u removes Added retry logic. too. Without the <C-g>u, the first u takes out both sentences and leaves Fixed the login timeout. with the cursor on its final period.
When you would reach for it
You stay in insert mode for a long time: a paragraph of prose, a commit message, a long docstring. Then you regret the last sentence, press <Esc>u, and the whole paragraph disappears, because vim counts everything from i to <Esc> as one change. Typing <C-g>u at the points you might want to return to, such as the end of each sentence, gives u a place to stop. It costs two keystrokes and does not interrupt your typing.
Gotchas
<C-g>usplits undo, not repeat. After the insert in the example, moving to another line and typing.appends both sentences, not only the last one. The dot command still sees one insert fromAto<Esc>.- Each break adds a step to the undo history. With a break after every sentence, getting back to the state before a long paragraph takes one
uper sentence. Use a count like10u, or:earlier 1fto go back to the last save in one move. - Some keys already break undo without being asked. In an interactive session, arrow keys in insert mode close the current undo step and start a new one. That is why an insert that included
<Left>sometimes undoes in two pieces.<C-g>Uin front of<Left>or<Right>keeps the movement inside the same undo step, which matters to mappings that move the cursor, like ones that insert a closing bracket. - Classic vi has no equivalent. In vi,
uundoes the last change and a seconduredoes it, so there is no history to cut into steps.
Variants
:inoremap . .<C-g>u
Makes every period a checkpoint. After typing Tests pass. Migration pending. in one insert, a single u removes only Migration pending. Map ? the same way if you write prose in vim. Be aware that this applies to every period, including the ones in code.
:inoremap <C-u> <C-g>u<C-u>
<C-u> in insert mode deletes everything you typed on the line. With this mapping, u after <Esc> brings the deleted text back. Vim’s defaults.vim sets this mapping, and Neovim has it built in.
:inoremap <C-w> <C-g>u<C-w>
Does the same for <C-w>, which deletes the word before the cursor. Type Tests pass, then <C-w>, then <Esc>u, and the deleted pass comes back. Neovim has this mapping built in as well.