31.25. Saving Emacs Sessions

You can use the Desktop library to save the state of Emacs from one session to another. Saving the state means that Emacs starts up with the same set of buffers, major modes, buffer positions, and so on that the previous Emacs session had.

To use Desktop, you should use the Customization buffer (Section 32.2.2) to set desktop-enable to a non-nil value, or add these lines at the end of your .emacs file:

(desktop-load-default)
(desktop-read)

The first time you save the state of the Emacs session, you must do it manually, with the command M-x desktop-save. Once you have done that, exiting Emacs will save the state again--not only the present Emacs session, but also subsequent sessions. You can also save the state at any time, without exiting Emacs, by typing M-x desktop-save again.

In order for Emacs to recover the state from a previous session, you must start it with the same current directory as you used when you started the previous session. This is because desktop-read looks in the current directory for the file to read. This means that you can have separate saved sessions in different directories; the directory in which you start Emacs will control which saved session to use.

The variable desktop-files-not-to-save controls which files are excluded from state saving. Its value is a regular expression that matches the files to exclude. By default, remote (ftp-accessed) files are excluded; this is because visiting them again in the subsequent session would be slow. If you want to include these files in state saving, set desktop-files-not-to-save to "^$". Section 16.12.

The Saveplace library provides a simpler feature that records your position in each file when you kill its buffer (or kill Emacs), and jumps to the same position when you visit the file again (even in another Emacs session). Use M-x toggle-save-place to turn on place-saving in a given file. Customize the option save-place to turn it on for all files in each session.