Skip to main content

Command Palette

Search for a command to run...

Undo That Survives Closing the File

Updated
2 min readView as Markdown
S
I'm Sushanth, a high school senior in Hyderabad, India. This is where I write about the things I spend time on: learning from mistakes, building things in code, and the tools I actually work with day to day. I hold the Candidate Master title and a FIDE International Master norm, earned across roughly 140 rated tournaments in six countries. I stopped competing in 2025, but the habit competition taught me, sitting down after every loss and figuring out exactly where I went wrong, shapes how I approach everything else. On the technical side, I've gone deep on C/C++ through Duke University and University of London coursework. I'm also someone who likes a good terminal workflow and enjoys exploring (and abandoning) productivity tools. Expect posts on Neovim, tmux, what broke this week, and whatever I'm tinkering with.

Two lines that mean u still works a week later, and why the other two safety nets got turned off once this one existed.

Vim's undo history normally dies with the buffer. Close the file, reopen it, and whatever you deleted an hour ago is gone for good, no matter how many times you press u. This never sat right with me, and it turns out fixing it is two lines:

opt.swapfile = false
opt.backup   = false
opt.undofile = true
opt.undodir  = vim.fn.expand("~/.vim/undodir")

undofile tells Neovim to write the undo tree to disk instead of keeping it only in memory, and undodir says where. Close the file, quit, come back a week later, open the same file, hit u, and it goes past the point where this session started. The history isn't scoped to how long the buffer stayed open, it's scoped to the file itself.

What I like about sitting right above those two lines is swapfile and backup, both off. Those are the other two ways Vim tries to protect you from losing work: swap files for crash recovery, backup files for a copy of what existed before you saved over it. Both disabled here, on purpose, because undofile does a better version of what they're both trying to do, a full history you can step through, not just a single snapshot or a recovery file you have to go find and manually diff against. Turning off two safety nets only makes sense once you understand the third one actually covers more ground.

The place this mattered wasn't some dramatic near-loss, just an ordinary afternoon where I'd deleted a chunk of a function, closed the file to go work on something else, and came back to it the next day still convinced I'd have to retype it from memory. u worked exactly like it would have five minutes after I'd deleted it. No git history to dig through, no diff to reconstruct, just undo reaching back across a session boundary I'd assumed was permanent.

It's a small setting, two options really, and it's the kind of thing you don't notice is missing until the one day you need it and it isn't there.