How do I clear undo history for the current buffer in Vim?
Answer
:let s:u=&l:undolevels | setlocal undolevels=-1 | execute "normal! a\<BS>\<Esc>" | let &l:undolevels=s:u
Explanation
Sometimes you finish a risky refactor and want a clean undo boundary before handing the buffer off or continuing with unrelated edits. Vim can reset the current buffer's undo tree by temporarily setting undolevels to -1 and performing a tiny no-op edit. This is an advanced move, but it is useful when old undo states are no longer meaningful.
How it works
:let s:u=&l:undolevelsstores the current local undo limit:setlocal undolevels=-1tells Vim to drop undo information for the next change:execute "normal! a\<BS>\<Esc>"performs a minimal insert/backspace edit to trigger that reset:let &l:undolevels=s:urestores your previous undo setting
After this sequence, undo history before the reset point is gone for the current buffer. New edits build a fresh undo chain.
Example
Before reset: 120+ undo entries from an earlier mass rewrite
After reset: clean undo history starting from the current state
This is especially helpful after huge macro-driven edits where stepping through historical states is noisy and slow.
Tips
- Use this intentionally; you cannot recover discarded undo states afterward
- Prefer buffer-local (
setlocal) so you do not affect other open files - If you rely on persistent undo files, this still resets the in-memory tree for the current buffer session