Vim Across Reboots

Every now and then you have to reboot, even on Linux. In firefox, I usually have a lot of tabs open, often in multiple firefox windows. On reboot, I use the splendid “restore previous session” functionality.

Most often, I also have a lot of files open in many instances of vim or (mostly) gvim. When I am working on code I open many tabs, usually each with multiple windows containing the code I am visiting during my work.

I knew that vim has :mksession to save a session (open files, tabs, windows, settings, etc), and vim -S will restore it. But it is cumbersome to go through all vim instances and save the session to some file, then restart all those sessions. Without an organized approach you end up with a bunch of stray session files all over the place.

I also knew about the “vimserver” and “remote” functionality. But only today I got the idea to combine these to carry my vim sessions across a reboot in a way that is almost as convenient as firefox’s “restore previous session”.

The magic lies in two very short shell scripts: and The first goes through the list of open vim instances and for each instance stores its session to a file in ~/.vim/sessions, then quits it. (If there already are session files from the last run, those are moved to a backup subdirectory beforehand, so they don’t affect the next run of the restore script.)

mkdir -p $SESSIONSDIR/backup/
mv -b -f $SESSIONSDIR/session-* $SESSIONSDIR/backup/
for VIMSERVER in $(vim --serverlist); do
  vim --servername $VIMSERVER --remote-send "^[^[:mks $SESSIONSDIR/session-$VIMSERVER^M:wqa^M"

Note that the “^[” and “^M” sequences shown above actually need to be the verbatim Escape and Enter key presses. Markdown doesn’t show them, so I replaced them with the characters they are displayed with. If you copy & paste the above you need to replace these (in vim by pressing “Ctrl-V, Escape” and “Ctrl-V, Enter”, respectively). Or just download the linked script, which contains the verbatim key codes.

The second one goes through the session files stored by, then starts a gvim instance for each that recovers the session.

for VIMSESSION in $(ls $SESSIONSDIR/session-*); do
  gvim --servername ${VIMSESSION#*session-} -S $VIMSESSION

Super simple and super convenient :-). I am sure it can be somewhat more automated, but I’ll leave that to another day.