Vim can do this, though it may be a bit clunky and take some setup.
romainl gets you partway with session
. The missing bits are swap files, :preserve
, and the &
flag for cpoptions
.
Swap files are intended for recovery if Vim or your system crashes. They enable you to recover any unsaved changes (with some limitations, see :he swap-file
). However, when Vim exits normally, it deletes any swap files it was using, even if the buffer had unsaved changes.
That's where :preserve
and cpoptions
's &
come in. :preserve
forces Vim to write all buffers to their swap files immediately (as opposed to the standard after 4 seconds or 200 characters, or whatever your options have set it to). Doing :set cpoptions+=&
tells Vim not to delete swap files saved with :preserve
when exiting normally.
Unfortunately, Vim does not automatically clean up swap files when recovering from them, so you can soon end up with a directory looking like this:
.foo.txt.swn
.foo.txt.swo
.foo.txt.swp
foo.txt
You can delete the older ones manually, but Vim will only automatically offer to recover if there is a *.swp
file where it would put its new swap file. The :recover
command will force Vim to look for swap files to recover from.
By using autocommands, you can automate preserving (probably with the QuitPre
event) and recovering (probably with BufRead
or BufReadPost
). Recover.vim is a plugin that might work as a friendlier alternative for managing recovering. It appears to also handle cleaning up swap files. I'm not sure how it would handle a directory with a .swo
but no .swp
file. You may still need to use :recover
for that case.
vim-obsession is another plugin that claims to make handling sessions much easier.