11

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?

Drew
  • 75,699
  • 9
  • 109
  • 225
Christian Herenz
  • 365
  • 2
  • 14

1 Answers1

3

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.

Faried Nawaz
  • 191
  • 7
  • 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.... – Christian Herenz Apr 05 '18 at 16:41
  • 1
    I've edited my answer to add the code for your .emacs. – Faried Nawaz Apr 06 '18 at 14:29