I have the following in my .emacs:

(desktop-save-mode 1)
(setq desktop-restore-eager 10)
(setq desktop-save t)

Often I have a lot of buffers open (100 or so), then this really helps - as emacs is loading buffers only when not beeing busy with something else.

Now, sometimes the following happens: I close emacs before I want to shut down my laptop. Then I realize - I need to edit one more file quickly - so I open emacs again, perform the editing, and then close it. If this happens within a short amount of time, then desktop-save-mode was not able to restore all previously saved buffers. In this case, when I now close emacs again, only the buffers that were restored are saved and the state before the initial shutdown is lost.

Is there a way to make the desktop-save only happening, if the previously saved desktop has been completely restored?

1 Answer 1


There's a hook you can use: desktop-after-read-hook. Add a function to set a variable after the desktop state is restored. Using defadvice around desktop-save, check if the variable is set before saving the state.

I'm on Emacs 25.3.1, and this is the code I used:

(defvar *my-desktop-save* nil
  "Should I save the desktop when Emacs is shutting down?")

(add-hook 'desktop-after-read-hook
          (lambda () (setq *my-desktop-save* t)))

(advice-add 'desktop-save :around
            (lambda (fn &rest args)
              (if (bound-and-true-p *my-desktop-save*)
                  (apply fn args))))

Add it to your .emacs, and restart it.

  • Hi thanks, this should indeed do the trick. However, my emacs Lisp skills are a bit limited. Could you maybe expand your answer to include a lisp snippet from which I could start experimenting.... Apr 5, 2018 at 16:41
  • 1
    I've edited my answer to add the code for your .emacs. Apr 6, 2018 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.