1 ;;; desktop.el --- save partial status of Emacs when killed -*- lexical-binding: t -*-
3 ;; Copyright (C) 1993-1995, 1997, 2000-2018 Free Software Foundation,
6 ;; Author: Morten Welinder <terra@diku.dk>
7 ;; Keywords: convenience
8 ;; Favorite-brand-of-beer: None, I hate beer.
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
27 ;; Save the Desktop, i.e.,
28 ;; - some global variables
29 ;; - the list of buffers with associated files. For each buffer also
31 ;; - the default directory
33 ;; - the mark & mark-active
35 ;; - some local variables
36 ;; - frame and window configuration
38 ;; To use this, use customize to turn on desktop-save-mode or add the
39 ;; following line somewhere in your init file:
41 ;; (desktop-save-mode 1)
43 ;; For further usage information, look at the section
44 ;; (info "(emacs)Saving Emacs Sessions") in the GNU Emacs Manual.
46 ;; When the desktop module is loaded, the function `desktop-kill' is
47 ;; added to the `kill-emacs-hook'. This function is responsible for
48 ;; saving the desktop when Emacs is killed. Furthermore an anonymous
49 ;; function is added to the `after-init-hook'. This function is
50 ;; responsible for loading the desktop when Emacs is started.
54 ;; Variables `desktop-buffer-mode-handlers' and `desktop-minor-mode-handlers'
55 ;; are supplied to handle special major and minor modes respectively.
56 ;; `desktop-buffer-mode-handlers' is an alist of major mode specific functions
57 ;; to restore a desktop buffer. Elements must have the form
59 ;; (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
61 ;; Functions listed are called by `desktop-create-buffer' when `desktop-read'
62 ;; evaluates the desktop file. Buffers with a major mode not specified here,
63 ;; are restored by the default handler `desktop-restore-file-buffer'.
64 ;; `desktop-minor-mode-handlers' is an alist of functions to restore
65 ;; non-standard minor modes. Elements must have the form
67 ;; (MINOR-MODE . RESTORE-FUNCTION).
69 ;; Functions are called by `desktop-create-buffer' to restore minor modes.
70 ;; Minor modes not specified here, are restored by the standard minor mode
71 ;; function. If you write a module that defines a major or minor mode that
72 ;; needs a special handler, then place code like
74 ;; (defun foo-restore-desktop-buffer
76 ;; (add-to-list 'desktop-buffer-mode-handlers
77 ;; '(foo-mode . foo-restore-desktop-buffer))
81 ;; (defun bar-desktop-restore
83 ;; (add-to-list 'desktop-minor-mode-handlers
84 ;; '(bar-mode . bar-desktop-restore))
86 ;; in the module itself. The mode function must either be autoloaded,
87 ;; or of the form "foobar-mode" and defined in library "foobar", so that
88 ;; desktop can guess how to load its definition.
89 ;; See the docstrings of `desktop-buffer-mode-handlers' and
90 ;; `desktop-minor-mode-handlers' for more info.
94 ;; Conventional minor modes (see node "Minor Mode Conventions" in the elisp
95 ;; manual) are handled in the following way:
96 ;; When `desktop-save' saves the state of a buffer to the desktop file, it
97 ;; saves as `desktop-minor-modes' the list of names of those variables in
98 ;; `minor-mode-alist' that have a non-nil value.
99 ;; When `desktop-create' restores the buffer, each of the symbols in
100 ;; `desktop-minor-modes' is called as function with parameter 1.
101 ;; The variables `desktop-minor-mode-table' and `desktop-minor-mode-handlers'
102 ;; are used to handle non-conventional minor modes. `desktop-save' uses
103 ;; `desktop-minor-mode-table' to map minor mode variables to minor mode
104 ;; functions before writing `desktop-minor-modes'. If a minor mode has a
105 ;; variable name that is different form its function name, an entry
107 ;; (NAME RESTORE-FUNCTION)
109 ;; should be added to `desktop-minor-mode-table'. If a minor mode should not
110 ;; be restored, RESTORE-FUNCTION should be set to nil. `desktop-create' uses
111 ;; `desktop-minor-mode-handlers' to lookup minor modes that needs a restore
112 ;; function different from the usual minor mode function.
113 ;; ---------------------------------------------------------------------------
115 ;; By the way: don't use desktop.el to customize Emacs -- the file .emacs
116 ;; in your home directory is used for that. Saving global default values
117 ;; for buffers is an example of misuse.
119 ;; PLEASE NOTE: The kill ring can be saved as specified by the variable
120 ;; `desktop-globals-to-save' (by default it isn't). This may result in saving
121 ;; things you did not mean to keep. Use M-x desktop-clear RET.
123 ;; Thanks to hetrick@phys.uva.nl (Jim Hetrick) for useful ideas.
124 ;; avk@rtsg.mot.com (Andrew V. Klein) for a dired tip.
125 ;; chris@tecc.co.uk (Chris Boucher) for a mark tip.
126 ;; f89-kam@nada.kth.se (Klas Mellbourn) for a mh-e tip.
127 ;; kifer@sbkifer.cs.sunysb.edu (M. Kifer) for a bug hunt.
128 ;; treese@lcs.mit.edu (Win Treese) for ange-ftp tips.
129 ;; pot@cnuce.cnr.it (Francesco Potortì) for misc. tips.
130 ;; ---------------------------------------------------------------------------
133 ;; Recognize more minor modes.
141 (defvar desktop-file-version
"208"
142 "Version number of desktop file format.
143 Used at desktop read to provide backward compatibility.")
145 (defconst desktop-native-file-version
208
146 "Format version of the current desktop package, an integer.")
147 (defvar desktop-io-file-version nil
148 "The format version of the current desktop file (an integer) or nil.")
149 ;; Note: Historically, the version number is embedded in the entry for
150 ;; each buffer. It is highly inadvisable for different buffer entries
151 ;; to have different format versions.
153 ;; ----------------------------------------------------------------------------
154 ;; USER OPTIONS -- settings you might want to play with.
155 ;; ----------------------------------------------------------------------------
157 (defgroup desktop nil
158 "Save status of Emacs when you exit."
162 (define-minor-mode desktop-save-mode
163 "Toggle desktop saving (Desktop Save mode).
164 With a prefix argument ARG, enable Desktop Save mode if ARG is positive,
165 and disable it otherwise. If called from Lisp, enable the mode if ARG
168 When Desktop Save mode is enabled, the state of Emacs is saved from
169 one session to another. In particular, Emacs will save the desktop when
170 it exits (this may prompt you; see the option `desktop-save'). The next
171 time Emacs starts, if this mode is active it will restore the desktop.
173 To manually save the desktop at any time, use the command `\\[desktop-save]'.
174 To load it, use `\\[desktop-read]'.
176 Once a desktop file exists, Emacs will auto-save it according to the
177 option `desktop-auto-save-timeout'.
179 To see all the options you can set, browse the `desktop' customization group.
181 For further details, see info node `(emacs)Saving Emacs Sessions'."
184 (if desktop-save-mode
185 (desktop-auto-save-enable)
186 (desktop-auto-save-disable)))
188 (defun desktop-save-mode-off ()
189 "Disable `desktop-save-mode'. Provided for use in hooks."
190 (desktop-save-mode 0))
192 (defcustom desktop-save
'ask-if-new
193 "Specifies whether the desktop should be saved when it is killed.
194 A desktop is killed when the user changes desktop or quits Emacs.
198 ask-if-new -- ask if no desktop file exists, otherwise just save.
199 ask-if-exists -- ask if desktop file exists, otherwise don't save.
200 if-exists -- save if desktop file exists, otherwise don't save.
202 The desktop is never saved when `desktop-save-mode' is nil.
203 The variables `desktop-dirname' and `desktop-base-file-name'
204 determine where the desktop is saved."
207 (const :tag
"Always save" t
)
208 (const :tag
"Always ask" ask
)
209 (const :tag
"Ask if desktop file is new, else do save" ask-if-new
)
210 (const :tag
"Ask if desktop file exists, else don't save" ask-if-exists
)
211 (const :tag
"Save if desktop file exists, else don't" if-exists
)
212 (const :tag
"Never save" nil
))
216 (defcustom desktop-auto-save-timeout auto-save-timeout
217 "Number of seconds of idle time before auto-saving the desktop.
218 The desktop will be auto-saved when this amount of idle time have
219 passed after some change in the window configuration.
220 This applies to an existing desktop file when `desktop-save-mode' is enabled.
221 Zero or nil means disable auto-saving due to idleness."
222 :type
'(choice (const :tag
"Off" nil
)
223 (integer :tag
"Seconds"))
224 :set
(lambda (symbol value
)
225 (set-default symbol value
)
227 (if (and (integerp value
) (> value
0))
228 (desktop-auto-save-enable value
)
229 (desktop-auto-save-disable))))
233 (defcustom desktop-load-locked-desktop
'ask
234 "Specifies whether the desktop should be loaded if locked.
239 If the value is nil, or `ask' and the user chooses not to load the desktop,
240 the normal hook `desktop-not-loaded-hook' is run."
243 (const :tag
"Load anyway" t
)
244 (const :tag
"Don't load" nil
)
245 (const :tag
"Ask the user" ask
))
249 (defcustom desktop-base-file-name
250 (convert-standard-filename ".emacs.desktop")
251 "Name of file for Emacs desktop, excluding the directory part."
255 (defcustom desktop-base-lock-name
256 (convert-standard-filename ".emacs.desktop.lock")
257 "Name of lock file for Emacs desktop, excluding the directory part."
262 (defcustom desktop-path
(list user-emacs-directory
"~")
263 "List of directories to search for the desktop file.
264 The base name of the file is specified in `desktop-base-file-name'."
265 :type
'(repeat directory
)
267 :version
"23.2") ; user-emacs-directory added
269 (defcustom desktop-missing-file-warning nil
270 "If non-nil, offer to recreate the buffer of a deleted file.
271 Also pause for a moment to display message about errors signaled in
272 `desktop-buffer-mode-handlers'.
274 If nil, just print error messages in the message buffer."
279 (defcustom desktop-no-desktop-file-hook nil
280 "Normal hook run when `desktop-read' can't find a desktop file.
281 Run in the directory in which the desktop file was sought.
282 May be used to show a dired buffer."
287 (defcustom desktop-not-loaded-hook nil
288 "Normal hook run when the user declines to re-use a desktop file.
289 Run in the directory in which the desktop file was found.
290 May be used to deal with accidental multiple Emacs jobs."
293 :options
'(desktop-save-mode-off save-buffers-kill-emacs
)
296 (defcustom desktop-after-read-hook nil
297 "Normal hook run after a successful `desktop-read'.
298 May be used to show a buffer list."
301 :options
'(list-buffers)
304 (defcustom desktop-save-hook nil
305 "Normal hook run before the desktop is saved in a desktop file.
306 Run with the desktop buffer current with only the header present.
307 May be used to add to the desktop code or to truncate history lists,
312 (defcustom desktop-globals-to-save
313 '(desktop-missing-file-warning
320 "List of global variables saved by `desktop-save'.
321 An element may be variable name (a symbol) or a cons cell of the form
322 \(VAR . MAX-SIZE), which means to truncate VAR's value to at most
323 MAX-SIZE elements (if the value is a list) before saving the value.
324 Feature: Saving `kill-ring' implies saving `kill-ring-yank-pointer'."
325 :type
'(repeat (restricted-sexp :match-alternatives
(symbolp consp
)))
328 (defcustom desktop-globals-to-clear
330 kill-ring-yank-pointer
332 search-ring-yank-pointer
334 regexp-search-ring-yank-pointer
)
335 "List of global variables that `desktop-clear' will clear.
336 An element may be variable name (a symbol) or a cons cell of the form
337 \(VAR . FORM). Symbols are set to nil and for cons cells VAR is set
338 to the value obtained by evaluating FORM."
339 :type
'(repeat (restricted-sexp :match-alternatives
(symbolp consp
)))
343 (defcustom desktop-clear-preserve-buffers
344 '("\\*scratch\\*" "\\*Messages\\*" "\\*server\\*" "\\*tramp/.+\\*"
346 "List of buffers that `desktop-clear' should not delete.
347 Each element is a regular expression. Buffers with a name matched by any of
348 these won't be deleted."
349 :version
"23.3" ; added Warnings - bug#6336
350 :type
'(repeat string
)
354 (defcustom desktop-locals-to-save
355 '(desktop-locals-to-save ; Itself! Think it over.
361 change-log-default-name
365 buffer-file-coding-system
369 indicate-buffer-boundaries
371 show-trailing-whitespace
)
372 "List of local variables to save for each buffer.
373 The variables are saved only when they really are local. Conventional minor
374 modes are restored automatically; they should not be listed here."
375 :type
'(repeat symbol
)
378 (defcustom desktop-buffers-not-to-save
"\\` "
379 "Regexp identifying buffers that are to be excluded from saving.
380 This is in effect only for buffers that don't visit files.
381 To exclude buffers that visit files, use `desktop-files-not-to-save'
382 or `desktop-modes-not-to-save'."
383 :type
'(choice (const :tag
"None" nil
)
385 :version
"24.4" ; skip invisible temporary buffers
388 ;; Skip tramp and ange-ftp files
389 (defcustom desktop-files-not-to-save
390 "\\(\\`/[^/:]*:\\|(ftp)\\'\\)"
391 "Regexp identifying files whose buffers are to be excluded from saving.
392 The default value excludes buffers visiting remote files."
393 :type
'(choice (const :tag
"None" nil
)
397 ;; We skip TAGS files to save time (tags-file-name is saved instead).
398 (defcustom desktop-modes-not-to-save
400 "List of major modes whose buffers should not be saved."
401 :type
'(repeat symbol
)
404 (defcustom desktop-restore-frames t
405 "When non-nil, save and restore the frame and window configuration.
406 See related options `desktop-restore-reuses-frames',
407 `desktop-restore-in-current-display', and `desktop-restore-forces-onscreen'."
412 (defcustom desktop-restore-in-current-display t
413 "Controls how restoring of frames treats displays.
414 If t, restores frames into the current display.
415 If nil, restores frames into their original displays (if possible).
416 If `delete', deletes frames on other displays instead of restoring them."
417 :type
'(choice (const :tag
"Restore in current display" t
)
418 (const :tag
"Restore in original display" nil
)
419 (const :tag
"Delete frames in other displays" delete
))
423 (defcustom desktop-restore-forces-onscreen t
424 "If t, restores frames that are fully offscreen onscreen instead.
425 If `all', also restores frames that are partially offscreen onscreen.
427 Note that checking of frame boundaries is only approximate.
428 It can fail to reliably detect frames whose onscreen/offscreen state
429 depends on a few pixels, especially near the right / bottom borders
431 :type
'(choice (const :tag
"Only fully offscreen frames" t
)
432 (const :tag
"Also partially offscreen frames" all
)
433 (const :tag
"Do not force frames onscreen" nil
))
437 (defcustom desktop-restore-reuses-frames t
438 "If t, restoring frames reuses existing frames.
439 If nil, deletes existing frames.
440 If `keep', keeps existing frames and does not reuse them."
441 :type
'(choice (const :tag
"Reuse existing frames" t
)
442 (const :tag
"Delete existing frames" nil
)
443 (const :tag
"Keep existing frames" :keep
))
447 (defcustom desktop-file-name-format
'absolute
448 "Format in which desktop file names should be saved.
450 absolute -- Absolute file name.
451 tilde -- Relative to ~.
452 local -- Relative to directory of desktop file."
453 :type
'(choice (const absolute
) (const tilde
) (const local
))
457 (defcustom desktop-restore-eager t
458 "Number of buffers to restore immediately.
459 Remaining buffers are restored lazily (when Emacs is idle).
460 If value is t, all buffers are restored immediately."
461 :type
'(choice (const t
) integer
)
465 (defcustom desktop-lazy-verbose t
466 "Verbose reporting of lazily created buffers."
471 (defcustom desktop-lazy-idle-delay
5
472 "Idle delay before starting to create buffers.
473 See `desktop-restore-eager'."
479 (defvar-local desktop-save-buffer nil
480 "When non-nil, save buffer status in desktop file.
482 If the value is a function, it is called by `desktop-save' with argument
483 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
484 file along with the state of the buffer for which it was called.
486 When file names are returned, they should be formatted using the call
487 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
489 Later, when `desktop-read' evaluates the desktop file, auxiliary information
490 is passed as the argument DESKTOP-BUFFER-MISC to functions in
491 `desktop-buffer-mode-handlers'.")
494 (defvar desktop-buffer-mode-handlers nil
495 "Alist of major mode specific functions to restore a desktop buffer.
496 Functions listed are called by `desktop-create-buffer' when `desktop-read'
497 evaluates the desktop file. List elements must have the form
499 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
501 Buffers with a major mode not specified here, are restored by the default
502 handler `desktop-restore-file-buffer'.
504 Handlers are called with argument list
506 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
508 Furthermore, they may use the following variables:
510 `desktop-file-version'
511 `desktop-buffer-major-mode'
512 `desktop-buffer-minor-modes'
513 `desktop-buffer-point'
514 `desktop-buffer-mark'
515 `desktop-buffer-read-only'
516 `desktop-buffer-locals'
518 If a handler returns a buffer, then the saved mode settings
519 and variable values for that buffer are copied into it.
521 Modules that define a major mode that needs a special handler should contain
524 (defun foo-restore-desktop-buffer
526 (add-to-list \\='desktop-buffer-mode-handlers
527 \\='(foo-mode . foo-restore-desktop-buffer))
529 The major mode function must either be autoloaded, or of the form
530 \"foobar-mode\" and defined in library \"foobar\", so that desktop
531 can guess how to load the mode's definition.")
534 (put 'desktop-buffer-mode-handlers
'risky-local-variable t
)
536 (defcustom desktop-minor-mode-table
537 '((defining-kbd-macro nil
)
541 (erc-track-minor-mode nil
)
543 "Table mapping minor mode variables to minor mode functions.
544 Each entry has the form (NAME RESTORE-FUNCTION).
545 NAME is the name of the buffer-local variable indicating that the minor
546 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
547 RESTORE-FUNCTION nil means don't try to restore the minor mode.
548 Only minor modes for which the name of the buffer-local variable
549 and the name of the minor mode function are different have to be added to
550 this table. See also `desktop-minor-mode-handlers'."
551 :type
'(alist :key-type
(symbol :tag
"Minor mode")
552 :value-type
(list :tag
"Restore function"
553 (choice (const nil
) function
)))
557 (defvar desktop-minor-mode-handlers nil
558 "Alist of functions to restore non-standard minor modes.
559 Functions are called by `desktop-create-buffer' to restore minor modes.
560 List elements must have the form
562 (MINOR-MODE . RESTORE-FUNCTION).
564 Minor modes not specified here, are restored by the standard minor mode
567 Handlers are called with argument list
569 (DESKTOP-BUFFER-LOCALS)
571 Furthermore, they may use the following variables:
573 `desktop-file-version'
574 `desktop-buffer-file-name'
575 `desktop-buffer-name'
576 `desktop-buffer-major-mode'
577 `desktop-buffer-minor-modes'
578 `desktop-buffer-point'
579 `desktop-buffer-mark'
580 `desktop-buffer-read-only'
581 `desktop-buffer-misc'
583 When a handler is called, the buffer has been created and the major mode has
584 been set, but local variables listed in desktop-buffer-locals has not yet been
587 Modules that define a minor mode that needs a special handler should contain
590 (defun foo-desktop-restore
592 (add-to-list \\='desktop-minor-mode-handlers
593 \\='(foo-mode . foo-desktop-restore))
595 The minor mode function must either be autoloaded, or of the form
596 \"foobar-mode\" and defined in library \"foobar\", so that desktop
597 can guess how to load the mode's definition.
599 See also `desktop-minor-mode-table'.")
602 (put 'desktop-minor-mode-handlers
'risky-local-variable t
)
604 ;; ----------------------------------------------------------------------------
605 (defvar desktop-dirname nil
606 "The directory in which the desktop file should be saved.")
608 (defun desktop-full-file-name (&optional dirname
)
609 "Return the full name of the desktop file in DIRNAME.
610 DIRNAME omitted or nil means use `desktop-dirname'."
611 (expand-file-name desktop-base-file-name
(or dirname desktop-dirname
)))
613 (defun desktop-full-lock-name (&optional dirname
)
614 "Return the full name of the desktop lock file in DIRNAME.
615 DIRNAME omitted or nil means use `desktop-dirname'."
616 (expand-file-name desktop-base-lock-name
(or dirname desktop-dirname
)))
618 (defconst desktop-header
619 ";; --------------------------------------------------------------------------
620 ;; Desktop File for Emacs
621 ;; --------------------------------------------------------------------------
622 " "*Header to place in Desktop file.")
624 (defvar desktop-delay-hook nil
625 "Hooks run after all buffers are loaded; intended for internal use.")
627 (defvar desktop-file-checksum nil
628 "Checksum of the last auto-saved contents of the desktop file.
629 Used to avoid writing contents unchanged between auto-saves.")
631 (defvar desktop-saved-frameset nil
632 "Saved state of all frames.
633 Only valid during frame saving & restoring; intended for internal use.")
635 ;; ----------------------------------------------------------------------------
636 ;; Desktop file conflict detection
637 (defvar desktop-file-modtime nil
638 "When the desktop file was last modified to the knowledge of this Emacs.
639 Used to detect desktop file conflicts.")
641 (defvar desktop-var-serdes-funs
645 (mapcar #'marker-position mr
))
647 (mapcar #'copy-marker mr
))))
648 "Table of serialization/deserialization functions for variables.
649 Each record is a list of form: (var serializer deserializer).
650 These records can be freely reordered, deleted, or new ones added.
651 However, for compatibility, don't modify the functions for existing records.")
653 (defun desktop-owner (&optional dirname
)
654 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
655 Return nil if no desktop file found or no Emacs process is using it.
656 DIRNAME omitted or nil means use `desktop-dirname'."
658 (file (desktop-full-lock-name dirname
)))
659 (and (file-exists-p file
)
662 (insert-file-contents-literally file
)
663 (goto-char (point-min))
664 (setq owner
(read (current-buffer)))
668 (defun desktop-claim-lock (&optional dirname
)
669 "Record this Emacs process as the owner of the desktop file in DIRNAME.
670 DIRNAME omitted or nil means use `desktop-dirname'."
671 (write-region (number-to-string (emacs-pid)) nil
672 (desktop-full-lock-name dirname
)))
674 (defun desktop-release-lock (&optional dirname
)
675 "Remove the lock file for the desktop in DIRNAME.
676 DIRNAME omitted or nil means use `desktop-dirname'."
677 (let ((file (desktop-full-lock-name dirname
)))
678 (when (file-exists-p file
) (delete-file file
))))
680 ;; ----------------------------------------------------------------------------
681 (defun desktop-truncate (list n
)
682 "Truncate LIST to at most N elements destructively."
683 (let ((here (nthcdr (1- n
) list
)))
687 ;; ----------------------------------------------------------------------------
689 (defun desktop-clear ()
691 This kills all buffers except for internal ones and those with names matched by
692 a regular expression in the list `desktop-clear-preserve-buffers'.
693 Furthermore, it clears the variables listed in `desktop-globals-to-clear'.
694 When called interactively and `desktop-restore-frames' is non-nil, it also
695 deletes all frames except the selected one (and its minibuffer frame,
699 (setq desktop-io-file-version nil
)
700 (dolist (var desktop-globals-to-clear
)
702 (set-default var nil
)
703 (set-default var
(eval (cdr var
)))))
704 (let ((preserve-regexp (concat "\\`\\("
705 (mapconcat (lambda (regexp)
706 (concat "\\(" regexp
"\\)"))
707 desktop-clear-preserve-buffers
710 (dolist (buffer (buffer-list))
711 (let ((bufname (buffer-name buffer
)))
712 (unless (or (eq (aref bufname
0) ?\s
) ;; Don't kill internal buffers
713 (string-match-p preserve-regexp bufname
))
714 (kill-buffer buffer
)))))
715 (delete-other-windows)
716 (when (and desktop-restore-frames
717 ;; Non-interactive calls to desktop-clear happen before desktop-read
718 ;; which already takes care of frame restoration and deletion.
719 (called-interactively-p 'any
))
720 (let* ((this (selected-frame))
721 (mini (window-frame (minibuffer-window this
)))) ; in case they differ
722 (dolist (frame (sort (frame-list) #'frameset-minibufferless-first-p
))
724 (unless (or (eq frame this
)
726 ;; Don't delete daemon's initial frame, or
727 ;; we'll never be able to close the last
728 ;; client's frame (Bug#26912).
729 (if (daemonp) (not (frame-parameter frame
'client
)))
730 (frame-parameter frame
'desktop-dont-clear
))
731 (delete-frame frame
))
733 (delay-warning 'desktop
(error-message-string err
))))))))
735 ;; ----------------------------------------------------------------------------
736 (unless noninteractive
737 (add-hook 'kill-emacs-hook
#'desktop-kill
))
739 (defun desktop-kill ()
740 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
741 If the desktop should be saved and `desktop-dirname'
742 is nil, ask the user where to save the desktop."
743 (when (and desktop-save-mode
744 (let ((exists (file-exists-p (desktop-full-file-name))))
745 (or (eq desktop-save t
)
746 (and exists
(eq desktop-save
'if-exists
))
747 ;; If it exists, but we aren't using it, we are going
748 ;; to ask for a new directory below.
749 (and exists desktop-dirname
(eq desktop-save
'ask-if-new
))
751 (or (memq desktop-save
'(ask ask-if-new
))
752 (and exists
(eq desktop-save
'ask-if-exists
)))
753 (y-or-n-p "Save desktop? ")))))
754 (unless desktop-dirname
755 (setq desktop-dirname
756 (file-name-as-directory
758 (read-directory-name "Directory for desktop file: " nil nil t
)))))
760 (desktop-save desktop-dirname t
)
762 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
763 (signal (car err
) (cdr err
))))))
764 ;; If we own it, we don't anymore.
765 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
767 ;; ----------------------------------------------------------------------------
768 (defun desktop-list* (&rest args
)
769 (and args
(apply #'cl-list
* args
)))
771 ;; ----------------------------------------------------------------------------
772 (defun desktop-buffer-info (buffer)
773 "Return information describing BUFFER.
774 This function is not pure, as BUFFER is made current with
777 Returns a list of all the necessary information to recreate the
778 buffer, which is (in order):
780 `uniquify-buffer-base-name';
784 list of minor-modes,;
788 auxiliary information given by `desktop-save-buffer';
790 auxiliary information given by `desktop-var-serdes-funs'."
793 ;; base name of the buffer; replaces the buffer name if managed by uniquify
794 ,(and (fboundp 'uniquify-buffer-base-name
) (uniquify-buffer-base-name))
796 ,(desktop-file-name (buffer-file-name) desktop-dirname
)
801 (dolist (minor-mode (mapcar #'car minor-mode-alist
) ret
)
802 (and (boundp minor-mode
)
803 (symbol-value minor-mode
)
804 (let* ((special (assq minor-mode desktop-minor-mode-table
))
805 (value (cond (special (cadr special
))
806 ((get minor-mode
:minor-mode-function
))
807 ((functionp minor-mode
) minor-mode
))))
808 (when value
(cl-pushnew value ret
))))))
809 ;; point and mark, and read-only status
811 ,(list (mark t
) mark-active
)
813 ;; auxiliary information
814 ,(when (functionp desktop-save-buffer
)
815 (funcall desktop-save-buffer desktop-dirname
))
817 ,(let ((loclist (buffer-local-variables))
819 (dolist (local desktop-locals-to-save
)
820 (let ((here (assq local loclist
)))
823 ((member local loclist
)
826 ,@(when (>= desktop-io-file-version
208)
828 (mapcar (lambda (record)
829 (let ((var (car record
)))
831 (funcall (cadr record
) (symbol-value var
)))))
832 desktop-var-serdes-funs
)))))
834 ;; ----------------------------------------------------------------------------
835 (defun desktop--v2s (value)
836 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
837 SEXP is an sexp that when evaluated yields VALUE.
838 QUOTE may be `may' (value may be quoted),
839 `must' (value must be quoted), or nil (value must not be quoted)."
841 ((or (numberp value
) (null value
) (eq t value
) (keywordp value
))
844 (let ((copy (copy-sequence value
)))
845 (set-text-properties 0 (length copy
) nil copy
)
846 ;; Get rid of text properties because we cannot read them.
851 (let* ((pass1 (mapcar #'desktop--v2s value
))
852 (special (assq nil pass1
)))
855 ,@(mapcar (lambda (el)
856 (if (eq (car el
) 'must
)
857 `',(cdr el
) (cdr el
)))
859 (cons 'may
`[,@(mapcar #'cdr pass1
)]))))
865 (let ((q.sexp
(desktop--v2s (car p
))))
866 (push q.sexp newlist
))
869 (let ((last (desktop--v2s p
)))
871 (push last newlist
)))
872 (if (assq nil newlist
)
874 `(,(if use-list
* 'desktop-list
* 'list
)
875 ,@(mapcar (lambda (el)
876 (if (eq (car el
) 'must
)
877 `',(cdr el
) (cdr el
)))
878 (nreverse newlist
))))
881 (nreverse (if use-list
* (cdr newlist
) newlist
)))
882 ,@(if use-list
* (cdar newlist
)))))))
884 (cons nil
`(symbol-function
885 ',(intern-soft (substring (prin1-to-string value
) 7 -
1)))))
887 (let ((pos (marker-position value
))
888 (buf (buffer-name (marker-buffer value
))))
890 `(let ((mk (make-marker)))
891 (add-hook 'desktop-delay-hook
893 (set-marker mk
,pos
(get-buffer ,buf
))))
896 (cons 'may
"Unprintable entity"))))
898 ;; ----------------------------------------------------------------------------
899 (defun desktop-value-to-string (value)
900 "Convert VALUE to a string that when read evaluates to the same value.
901 Not all types of values are supported."
902 (let* ((print-escape-newlines t
)
905 (float-output-format nil
)
906 (quote.sexp
(desktop--v2s value
))
907 (quote (car quote.sexp
))
909 (txt (prin1-to-string (cdr quote.sexp
))))
914 ;; ----------------------------------------------------------------------------
915 (defun desktop-outvar (varspec)
916 "Output a setq statement for variable VAR to the desktop file.
917 The argument VARSPEC may be the variable name VAR (a symbol),
918 or a cons cell of the form (VAR . MAX-SIZE),
919 which means to truncate VAR's value to at most MAX-SIZE elements
920 \(if the value is a list) before saving the value."
923 (setq var
(car varspec
) size
(cdr varspec
))
926 (when (and (integerp size
)
929 (desktop-truncate (eval var
) size
))
933 (desktop-value-to-string (symbol-value var
))
936 ;; ----------------------------------------------------------------------------
937 (defun desktop-save-buffer-p (filename bufname mode
&rest _dummy
)
938 "Return t if buffer should have its state saved in the desktop file.
939 FILENAME is the visited file name, BUFNAME is the buffer name, and
940 MODE is the major mode.
941 \n\(fn FILENAME BUFNAME MODE)"
942 (let ((case-fold-search nil
)
943 (no-regexp-to-check (not (stringp desktop-files-not-to-save
)))
946 (not (stringp desktop-buffers-not-to-save
))
947 (not (string-match-p desktop-buffers-not-to-save bufname
)))
948 (not (memq mode desktop-modes-not-to-save
))
950 (or no-regexp-to-check
951 (not (string-match-p desktop-files-not-to-save filename
))))
952 (and (memq mode
'(dired-mode vc-dir-mode
))
953 (or no-regexp-to-check
954 (not (setq dired-skip
955 (with-current-buffer bufname
956 (string-match-p desktop-files-not-to-save
957 default-directory
))))))
959 (null dired-skip
) ; bug#5755
960 (with-current-buffer bufname desktop-save-buffer
)))
963 ;; ----------------------------------------------------------------------------
964 (defun desktop-file-name (filename dirname
)
965 "Convert FILENAME to format specified in `desktop-file-name-format'.
966 DIRNAME must be the directory in which the desktop file will be saved."
969 ((eq desktop-file-name-format
'tilde
)
970 (let ((relative-name (file-relative-name (expand-file-name filename
) "~")))
972 ((file-name-absolute-p relative-name
) relative-name
)
973 ((string= "./" relative-name
) "~/")
974 ((string= "." relative-name
) "~")
975 (t (concat "~/" relative-name
)))))
976 ((eq desktop-file-name-format
'local
) (file-relative-name filename dirname
))
977 (t (expand-file-name filename
))))
980 ;; ----------------------------------------------------------------------------
981 (defun desktop--check-dont-save (frame)
982 (not (frame-parameter frame
'desktop-dont-save
)))
984 (defconst desktop--app-id
`(desktop .
,desktop-file-version
))
986 (defun desktop-save-frameset ()
987 "Save the state of existing frames in `desktop-saved-frameset'.
988 Frames with a non-nil `desktop-dont-save' parameter are not saved."
989 (setq desktop-saved-frameset
990 (and desktop-restore-frames
993 :name
(concat user-login-name
"@" (system-name))
994 :predicate
#'desktop--check-dont-save
))))
997 (defun desktop-save (dirname &optional release only-if-changed version
)
998 "Save the desktop in a desktop file.
999 Parameter DIRNAME specifies where to save the desktop file.
1000 Optional parameter RELEASE says whether we're done with this
1001 desktop. If ONLY-IF-CHANGED is non-nil, compare the current
1002 desktop information to that in the desktop file, and if the
1003 desktop information has not changed since it was last saved then
1004 do not rewrite the file.
1006 This function can save the desktop in either format version
1007 208 (which only Emacs 25.1 and later can read) or version
1008 206 (which is readable by any Emacs from version 22.1 onwards).
1009 By default, it will use the same format the desktop file had when
1010 it was last saved, or version 208 when writing a fresh desktop
1013 To upgrade a version 206 file to version 208, call this command
1014 explicitly with a bare prefix argument: C-u M-x desktop-save.
1015 You are recommended to do this once you have firmly upgraded to
1016 Emacs 25.1 (or later). To downgrade a version 208 file to version
1017 206, use a double command prefix: C-u C-u M-x desktop-save.
1018 Confirmation will be requested in either case. In a non-interactive
1019 call, VERSION can be given as an integer, either 206 or 208, which
1020 will be accepted as the format version in which to save the file
1021 without further confirmation."
1023 ;; Or should we just use (car desktop-path)?
1024 (let ((default (if (member "." desktop-path
)
1026 user-emacs-directory
)))
1027 (read-directory-name "Directory to save desktop file in: "
1031 current-prefix-arg
))
1032 (setq desktop-dirname
(file-name-as-directory (expand-file-name dirname
)))
1034 (let ((eager desktop-restore-eager
)
1035 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
1037 (or (not new-modtime
) ; nothing to overwrite
1038 (equal desktop-file-modtime new-modtime
)
1039 (yes-or-no-p (if desktop-file-modtime
1040 (if (time-less-p desktop-file-modtime
1042 "Desktop file is more recent than the one loaded. Save anyway? "
1043 "Desktop file isn't the one loaded. Overwrite it? ")
1044 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
1045 (unless release
(error "Desktop file conflict")))
1047 ;; If we're done with it, release the lock.
1048 ;; Otherwise, claim it if it's unclaimed or if we created it.
1050 (desktop-release-lock)
1051 (unless (and new-modtime
(desktop-owner)) (desktop-claim-lock)))
1053 ;; What format are we going to write the file in?
1054 (setq desktop-io-file-version
1056 ((equal version
'(4))
1057 (if (or (eq desktop-io-file-version
208)
1058 (yes-or-no-p "Save desktop file in format 208 \
1059 \(Readable by Emacs 25.1 and later only)? "))
1061 (or desktop-io-file-version desktop-native-file-version
)))
1062 ((equal version
'(16))
1063 (if (or (eq desktop-io-file-version
206)
1064 (yes-or-no-p "Save desktop file in format 206 \
1065 \(Readable by all Emacs versions since 22.1)? "))
1067 (or desktop-io-file-version desktop-native-file-version
)))
1068 ((memq version
'(206 208))
1070 ((null desktop-io-file-version
) ; As yet, no desktop file exists.
1071 desktop-native-file-version
)
1073 desktop-io-file-version
)))
1077 ";; -*- mode: emacs-lisp; lexical-binding:t; coding: utf-8-emacs; -*-\n"
1079 ";; Created " (current-time-string) "\n"
1080 ";; Desktop file format version " (format "%d" desktop-io-file-version
) "\n"
1081 ";; Emacs version " emacs-version
"\n")
1082 (save-excursion (run-hooks 'desktop-save-hook
))
1083 (goto-char (point-max))
1084 (insert "\n;; Global section:\n")
1085 ;; Called here because we save the window/frame state as a global
1086 ;; variable for compatibility with previous Emacsen.
1087 (desktop-save-frameset)
1088 (unless (memq 'desktop-saved-frameset desktop-globals-to-save
)
1089 (desktop-outvar 'desktop-saved-frameset
))
1090 (mapc #'desktop-outvar desktop-globals-to-save
)
1091 (setq desktop-saved-frameset nil
) ; after saving desktop-globals-to-save
1092 (when (memq 'kill-ring desktop-globals-to-save
)
1094 "(setq kill-ring-yank-pointer (nthcdr "
1095 (int-to-string (- (length kill-ring
) (length kill-ring-yank-pointer
)))
1098 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
1099 (dolist (l (mapcar #'desktop-buffer-info
(buffer-list)))
1100 (let ((base (pop l
)))
1101 (when (apply #'desktop-save-buffer-p l
)
1103 (if (or (not (integerp eager
))
1106 (setq eager
(1- eager
))))
1107 "desktop-create-buffer"
1108 "desktop-append-buffer-args")
1110 (format "%d" desktop-io-file-version
))
1111 ;; If there's a non-empty base name, we save it instead of the buffer name
1112 (when (and base
(not (string= base
"")))
1113 (setcar (nthcdr 1 l
) base
))
1115 (insert "\n " (desktop-value-to-string e
)))
1118 (setq default-directory desktop-dirname
)
1119 ;; When auto-saving, avoid writing if nothing has changed since the last write.
1120 (let* ((beg (and only-if-changed
1122 (goto-char (point-min))
1123 ;; Don't check the header with changing timestamp
1124 (and (search-forward "Global section" nil t
)
1125 ;; Also skip the timestamp in desktop-saved-frameset
1126 ;; if it's saved in the first non-header line
1127 (search-forward "desktop-saved-frameset"
1128 (line-beginning-position 3) t
)
1129 ;; This is saved after the timestamp
1130 (search-forward (format "%S" desktop--app-id
) nil t
))
1132 (checksum (and beg
(md5 (current-buffer) beg
(point-max) 'utf-8-emacs
))))
1133 (unless (and checksum
(equal checksum desktop-file-checksum
))
1134 (let ((coding-system-for-write 'utf-8-emacs
))
1135 (write-region (point-min) (point-max) (desktop-full-file-name) nil
'nomessage
))
1136 (setq desktop-file-checksum checksum
)
1137 ;; We remember when it was modified (which is presumably just now).
1138 (setq desktop-file-modtime
(nth 5 (file-attributes (desktop-full-file-name)))))))))))
1140 ;; ----------------------------------------------------------------------------
1142 (defun desktop-remove ()
1143 "Delete desktop file in `desktop-dirname'.
1144 This function also sets `desktop-dirname' to nil."
1146 (when desktop-dirname
1147 (let ((filename (desktop-full-file-name)))
1148 (setq desktop-dirname nil
)
1149 (when (file-exists-p filename
)
1150 (delete-file filename
)))))
1152 (defvar desktop-buffer-args-list nil
1153 "List of args for `desktop-create-buffer'.")
1155 (defvar desktop-lazy-timer nil
)
1157 ;; ----------------------------------------------------------------------------
1158 (defun desktop-restoring-frameset-p ()
1159 "True if calling `desktop-restore-frameset' will actually restore it."
1160 (and desktop-restore-frames desktop-saved-frameset
(display-graphic-p) t
))
1162 (defun desktop-restore-frameset ()
1163 "Restore the state of a set of frames.
1164 This function depends on the value of `desktop-saved-frameset'
1165 being set (usually, by reading it from the desktop)."
1166 (when (desktop-restoring-frameset-p)
1167 (frameset-restore desktop-saved-frameset
1168 :reuse-frames
(eq desktop-restore-reuses-frames t
)
1169 :cleanup-frames
(not (eq desktop-restore-reuses-frames
'keep
))
1170 :force-display desktop-restore-in-current-display
1171 :force-onscreen desktop-restore-forces-onscreen
)))
1173 ;; Just to silence the byte compiler.
1174 ;; Dynamically bound in `desktop-read'.
1175 (defvar desktop-first-buffer
)
1176 (defvar desktop-buffer-ok-count
)
1177 (defvar desktop-buffer-fail-count
)
1179 ;; FIXME Interactively, this should have the option to prompt for dirname.
1181 (defun desktop-read (&optional dirname
)
1182 "Read and process the desktop file in directory DIRNAME.
1183 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1184 directories listed in `desktop-path'. If a desktop file is found, it
1185 is processed and `desktop-after-read-hook' is run. If no desktop file
1186 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1187 This function is a no-op when Emacs is running in batch mode.
1188 It returns t if a desktop file was loaded, nil otherwise."
1190 (unless noninteractive
1191 (setq desktop-dirname
1192 (file-name-as-directory
1195 ;; If DIRNAME is specified, use it.
1196 (and (< 0 (length dirname
)) dirname
)
1197 ;; Otherwise search desktop file in desktop-path.
1198 (let ((dirs desktop-path
))
1201 (desktop-full-file-name (car dirs
)))))
1202 (setq dirs
(cdr dirs
)))
1203 (and dirs
(car dirs
)))
1204 ;; If not found and `desktop-path' is non-nil, use its first element.
1205 (and desktop-path
(car desktop-path
))
1206 ;; Default: .emacs.d.
1207 user-emacs-directory
))))
1208 (if (file-exists-p (desktop-full-file-name))
1209 ;; Desktop file found, but is it already in use?
1210 (let ((desktop-first-buffer nil
)
1211 (desktop-buffer-ok-count 0)
1212 (desktop-buffer-fail-count 0)
1213 (owner (desktop-owner))
1214 ;; Avoid desktop saving during evaluation of desktop buffer.
1216 (desktop-autosave-was-enabled))
1218 (memq desktop-load-locked-desktop
'(nil ask
))
1219 (or (null desktop-load-locked-desktop
)
1221 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1222 Using it may cause conflicts. Use it anyway? " owner
)))))
1223 (let ((default-directory desktop-dirname
))
1224 (setq desktop-dirname nil
)
1225 (run-hooks 'desktop-not-loaded-hook
)
1226 (unless desktop-dirname
1227 (message "Desktop file in use; not loaded.")))
1228 (desktop-lazy-abort)
1229 ;; Temporarily disable the autosave that will leave it
1230 ;; disabled when loading the desktop fails with errors,
1231 ;; thus not overwriting the desktop with broken contents.
1232 (setq desktop-autosave-was-enabled
1233 (memq #'desktop-auto-save-set-timer
1234 ;; Use the global value of the hook, in case some
1235 ;; feature makes window-configuration-change-hook
1236 ;; buffer-local, and puts there stuff which
1237 ;; doesn't include our timer.
1239 'window-configuration-change-hook
)))
1240 (desktop-auto-save-disable)
1241 ;; Evaluate desktop buffer and remember when it was modified.
1242 (setq desktop-file-modtime
(nth 5 (file-attributes (desktop-full-file-name))))
1243 (load (desktop-full-file-name) t t t
)
1244 ;; If it wasn't already, mark it as in-use, to bother other
1245 ;; desktop instances.
1246 (unless (eq (emacs-pid) owner
)
1248 (desktop-claim-lock)
1249 (file-error (message "Couldn't record use of desktop file")
1252 (unless (desktop-restoring-frameset-p)
1253 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1254 ;; We want buffers existing prior to evaluating the desktop (and
1255 ;; not reused) to be placed at the end of the buffer list, so we
1258 (nreverse (cdr (memq desktop-first-buffer
(nreverse (buffer-list))))))
1259 (switch-to-buffer (car (buffer-list))))
1260 (run-hooks 'desktop-delay-hook
)
1261 (setq desktop-delay-hook nil
)
1262 (desktop-restore-frameset)
1263 (run-hooks 'desktop-after-read-hook
)
1264 (message "Desktop: %s%d buffer%s restored%s%s."
1265 (if desktop-saved-frameset
1266 (let ((fn (length (frameset-states desktop-saved-frameset
))))
1267 (format "%d frame%s, "
1268 fn
(if (= fn
1) "" "s")))
1270 desktop-buffer-ok-count
1271 (if (= 1 desktop-buffer-ok-count
) "" "s")
1272 (if (< 0 desktop-buffer-fail-count
)
1273 (format ", %d failed to restore" desktop-buffer-fail-count
)
1275 (if desktop-buffer-args-list
1276 (format ", %d to restore lazily"
1277 (length desktop-buffer-args-list
))
1279 (unless (desktop-restoring-frameset-p)
1280 ;; Bury the *Messages* buffer to not reshow it when burying
1281 ;; the buffer we switched to above.
1282 (when (buffer-live-p (get-buffer "*Messages*"))
1283 (bury-buffer "*Messages*"))
1284 ;; Clear all windows' previous and next buffers, these have
1285 ;; been corrupted by the `switch-to-buffer' calls in
1286 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1287 ;; brute force fix and should be replaced by a more subtle
1288 ;; strategy eventually.
1289 (walk-window-tree (lambda (window)
1290 (set-window-prev-buffers window nil
)
1291 (set-window-next-buffers window nil
))))
1292 (setq desktop-saved-frameset nil
)
1293 (if desktop-autosave-was-enabled
(desktop-auto-save-enable))
1295 ;; No desktop file found.
1296 (let ((default-directory desktop-dirname
))
1297 (run-hooks 'desktop-no-desktop-file-hook
))
1298 (message "No desktop file.")
1301 ;; ----------------------------------------------------------------------------
1303 (defun desktop-change-dir (dirname)
1304 "Change to desktop saved in DIRNAME.
1305 Kill the desktop as specified by variables `desktop-save-mode' and
1306 `desktop-save', then clear the desktop and load the desktop file in
1308 (interactive "DChange to directory: ")
1309 (setq dirname
(file-name-as-directory (expand-file-name dirname desktop-dirname
)))
1312 (desktop-read dirname
))
1314 ;; ----------------------------------------------------------------------------
1316 (defun desktop-save-in-desktop-dir ()
1317 "Save the desktop in directory `desktop-dirname'."
1320 (desktop-save desktop-dirname
)
1321 (call-interactively 'desktop-save
))
1322 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname
)))
1324 ;; ----------------------------------------------------------------------------
1326 (defvar desktop-auto-save-timer nil
)
1328 (defun desktop-auto-save-enable (&optional timeout
)
1329 (when (and (integerp (or timeout desktop-auto-save-timeout
))
1330 (> (or timeout desktop-auto-save-timeout
) 0))
1331 (add-hook 'window-configuration-change-hook
#'desktop-auto-save-set-timer
)))
1333 (defun desktop-auto-save-disable ()
1334 (remove-hook 'window-configuration-change-hook
#'desktop-auto-save-set-timer
)
1335 (desktop-auto-save-cancel-timer))
1337 (defun desktop-auto-save ()
1338 "Save the desktop periodically.
1339 Called by the timer created in `desktop-auto-save-set-timer'."
1340 (when (and desktop-save-mode
1341 (integerp desktop-auto-save-timeout
)
1342 (> desktop-auto-save-timeout
0)
1343 ;; Avoid desktop saving during lazy loading.
1344 (not desktop-lazy-timer
)
1345 ;; Save only to own desktop file.
1346 (eq (emacs-pid) (desktop-owner))
1348 (desktop-save desktop-dirname nil t
)))
1350 (defun desktop-auto-save-set-timer ()
1351 "Set the desktop auto-save timer.
1352 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1353 integer, start a new idle timer to call `desktop-auto-save' after that many
1354 seconds of idle time.
1355 This function is called from `window-configuration-change-hook'."
1356 (desktop-auto-save-cancel-timer)
1357 (when (and (integerp desktop-auto-save-timeout
)
1358 (> desktop-auto-save-timeout
0))
1359 (setq desktop-auto-save-timer
1360 (run-with-idle-timer desktop-auto-save-timeout nil
1361 'desktop-auto-save
))))
1363 (defun desktop-auto-save-cancel-timer ()
1364 (when desktop-auto-save-timer
1365 (cancel-timer desktop-auto-save-timer
)
1366 (setq desktop-auto-save-timer nil
)))
1368 ;; ----------------------------------------------------------------------------
1370 (defun desktop-revert ()
1371 "Revert to the last loaded desktop."
1373 (unless desktop-dirname
1374 (error "Unknown desktop directory"))
1375 (unless (file-exists-p (desktop-full-file-name))
1376 (error "No desktop file found"))
1378 (desktop-read desktop-dirname
))
1380 (defvar desktop-buffer-major-mode
)
1381 (defvar desktop-buffer-locals
)
1382 (defvar auto-insert
) ; from autoinsert.el
1383 ;; ----------------------------------------------------------------------------
1384 (defun desktop-restore-file-buffer (buffer-filename
1387 "Restore a file buffer."
1388 (when buffer-filename
1389 (if (or (file-exists-p buffer-filename
)
1390 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1392 (if desktop-missing-file-warning
1393 (y-or-n-p (concat msg
" Re-create buffer? "))
1396 (let* ((auto-insert nil
) ; Disable auto insertion
1397 (coding-system-for-read
1398 (or coding-system-for-read
1399 (cdr (assq 'buffer-file-coding-system
1400 desktop-buffer-locals
))))
1401 (buf (find-file-noselect buffer-filename
:nowarn
)))
1403 (switch-to-buffer buf
)
1404 (error (pop-to-buffer buf
)))
1405 (and (not (eq major-mode desktop-buffer-major-mode
))
1406 (functionp desktop-buffer-major-mode
)
1407 (funcall desktop-buffer-major-mode
))
1411 (defun desktop-load-file (function)
1412 "Load the file where auto loaded FUNCTION is defined.
1413 If FUNCTION is not currently defined, guess the library that defines it
1414 and try to load that."
1415 (if (fboundp function
)
1416 (autoload-do-load (symbol-function function
) function
)
1417 ;; Guess that foobar-mode is defined in foobar.
1418 ;; TODO rather than guessing or requiring an autoload, the desktop
1419 ;; file should record the name of the library.
1420 (let ((name (symbol-name function
)))
1421 (if (string-match "\\`\\(.*\\)-mode\\'" name
)
1422 (with-demoted-errors "Require error in desktop-load-file: %S"
1423 (require (intern (match-string 1 name
)) nil t
))))))
1425 ;; ----------------------------------------------------------------------------
1426 ;; Create a buffer, load its file, set its mode, ...;
1427 ;; called from Desktop file only.
1429 (defun desktop-create-buffer
1444 (setq desktop-io-file-version file-version
)
1446 (let ((desktop-file-version file-version
)
1447 (desktop-buffer-file-name buffer-filename
)
1448 (desktop-buffer-name buffer-name
)
1449 (desktop-buffer-major-mode buffer-majormode
)
1450 (desktop-buffer-minor-modes buffer-minormodes
)
1451 (desktop-buffer-point buffer-point
)
1452 (desktop-buffer-mark buffer-mark
)
1453 (desktop-buffer-read-only buffer-readonly
)
1454 (desktop-buffer-misc buffer-misc
)
1455 (desktop-buffer-locals buffer-locals
))
1456 ;; To make desktop files with relative file names possible, we cannot
1457 ;; allow `default-directory' to change. Therefore we save current buffer.
1458 (save-current-buffer
1459 ;; Give major mode module a chance to add a handler.
1460 (desktop-load-file desktop-buffer-major-mode
)
1461 (let ((buffer-list (buffer-list))
1463 (condition-case-unless-debug err
1464 (funcall (or (cdr (assq desktop-buffer-major-mode
1465 desktop-buffer-mode-handlers
))
1466 'desktop-restore-file-buffer
)
1467 desktop-buffer-file-name
1469 desktop-buffer-misc
)
1471 (message "Desktop: Can't load buffer %s: %s"
1473 (error-message-string err
))
1474 (when desktop-missing-file-warning
(sit-for 1))
1476 (if (bufferp result
)
1477 (setq desktop-buffer-ok-count
(1+ desktop-buffer-ok-count
))
1478 (setq desktop-buffer-fail-count
(1+ desktop-buffer-fail-count
))
1480 ;; Restore buffer list order with new buffer at end. Don't change
1481 ;; the order for old desktop files (old desktop module behavior).
1482 (unless (< desktop-file-version
206)
1483 (dolist (buf buffer-list
)
1484 (and (buffer-live-p buf
)
1486 (when result
(bury-buffer result
)))
1488 (unless (or desktop-first-buffer
(< desktop-file-version
206))
1489 (setq desktop-first-buffer result
))
1491 (unless (equal (buffer-name) desktop-buffer-name
)
1492 (rename-buffer desktop-buffer-name t
))
1494 (cond ((equal '(t) desktop-buffer-minor-modes
) ; backwards compatible
1496 ((equal '(nil) desktop-buffer-minor-modes
) ; backwards compatible
1499 (dolist (minor-mode desktop-buffer-minor-modes
)
1500 ;; Give minor mode module a chance to add a handler.
1501 (desktop-load-file minor-mode
)
1502 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers
))))
1504 (funcall handler desktop-buffer-locals
)
1505 (when (functionp minor-mode
)
1506 (funcall minor-mode
1)))))))
1507 ;; Even though point and mark are non-nil when written by
1508 ;; `desktop-save', they may be modified by handlers wanting to set
1509 ;; point or mark themselves.
1510 (when desktop-buffer-point
1513 ;; Evaluate point. Thus point can be something like
1514 ;; '(search-forward ...
1515 (eval desktop-buffer-point
)
1516 (error (message "%s" (error-message-string err
)) 1))))
1517 (when desktop-buffer-mark
1518 (if (consp desktop-buffer-mark
)
1520 (move-marker (mark-marker) (car desktop-buffer-mark
))
1521 (if (car (cdr desktop-buffer-mark
))
1522 (activate-mark 'dont-touch-tmm
)))
1523 (move-marker (mark-marker) desktop-buffer-mark
)))
1524 ;; Never override file system if the file really is read-only marked.
1525 (when desktop-buffer-read-only
(setq buffer-read-only desktop-buffer-read-only
))
1526 (dolist (this desktop-buffer-locals
)
1528 ;; An entry of this form `(symbol . value)'.
1530 (make-local-variable (car this
))
1531 (set (car this
) (cdr this
)))
1532 ;; An entry of the form `symbol'.
1533 (make-local-variable this
)
1535 ;; adjust `buffer-display-time' for the downtime. e.g.,
1536 ;; * if `buffer-display-time' was 8:00
1537 ;; * and emacs stopped at `desktop-file-modtime' == 11:00
1538 ;; * and we are loading the desktop file at (current-time) 12:30,
1539 ;; -> then we restore `buffer-display-time' as 9:30,
1540 ;; for the sake of `clean-buffer-list': preserving the invariant
1541 ;; "how much time the user spent in Emacs without looking at this buffer".
1542 (setq buffer-display-time
1543 (if buffer-display-time
1544 (time-add buffer-display-time
1545 (time-subtract nil desktop-file-modtime
))
1547 (unless (< desktop-file-version
208) ; Don't misinterpret any old custom args
1548 (dolist (record compacted-vars
)
1551 (deser-fun (nth 2 (assq var desktop-var-serdes-funs
))))
1552 (if deser-fun
(set var
(funcall deser-fun
(cadr record
))))))))
1555 ;; ----------------------------------------------------------------------------
1556 ;; Backward compatibility -- update parameters to 205 standards.
1557 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1558 mim pt mk ro tl fc cfs cr buffer-misc
)
1559 (desktop-create-buffer 205 buffer-filename buffer-name
1560 buffer-majormode
(cdr mim
) pt mk ro
1562 (list (cons 'truncate-lines tl
)
1563 (cons 'fill-column fc
)
1564 (cons 'case-fold-search cfs
)
1565 (cons 'case-replace cr
)
1566 (cons 'overwrite-mode
(car mim
)))))
1568 (defun desktop-append-buffer-args (&rest args
)
1569 "Append ARGS at end of `desktop-buffer-args-list'.
1570 ARGS must be an argument list for `desktop-create-buffer'."
1571 (setq desktop-buffer-args-list
(nconc desktop-buffer-args-list
(list args
)))
1572 (unless desktop-lazy-timer
1573 (setq desktop-lazy-timer
1574 (run-with-idle-timer desktop-lazy-idle-delay t
'desktop-idle-create-buffers
))))
1576 (defun desktop-lazy-create-buffer ()
1577 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1578 (when desktop-buffer-args-list
1579 (let* ((remaining (length desktop-buffer-args-list
))
1580 (args (pop desktop-buffer-args-list
))
1581 (buffer-name (nth 2 args
))
1582 (msg (format "Desktop lazily opening %s (%s remaining)..."
1583 buffer-name remaining
)))
1584 (when desktop-lazy-verbose
1586 (let ((desktop-first-buffer nil
)
1587 (desktop-buffer-ok-count 0)
1588 (desktop-buffer-fail-count 0))
1589 (apply #'desktop-create-buffer args
)
1590 (run-hooks 'desktop-delay-hook
)
1591 (setq desktop-delay-hook nil
)
1592 (bury-buffer (get-buffer buffer-name
))
1593 (when desktop-lazy-verbose
1594 (message "%s%s" msg
(if (> desktop-buffer-ok-count
0) "done" "failed")))))))
1596 (defun desktop-idle-create-buffers ()
1597 "Create buffers until the user does something, then stop.
1598 If there are no buffers left to create, kill the timer."
1600 (while (and repeat desktop-buffer-args-list
)
1601 (save-window-excursion
1602 (desktop-lazy-create-buffer))
1603 (setq repeat
(sit-for 0.2))
1604 (unless desktop-buffer-args-list
1605 (cancel-timer desktop-lazy-timer
)
1606 (setq desktop-lazy-timer nil
)
1607 (message "Lazy desktop load complete")
1611 (defun desktop-lazy-complete ()
1612 "Run the desktop load to completion."
1614 (let ((desktop-lazy-verbose t
))
1615 (while desktop-buffer-args-list
1616 (save-window-excursion
1617 (desktop-lazy-create-buffer)))
1618 (message "Lazy desktop load complete")))
1620 (defun desktop-lazy-abort ()
1621 "Abort lazy loading of the desktop."
1623 (when desktop-lazy-timer
1624 (cancel-timer desktop-lazy-timer
)
1625 (setq desktop-lazy-timer nil
))
1626 (when desktop-buffer-args-list
1627 (setq desktop-buffer-args-list nil
)
1628 (when (called-interactively-p 'interactive
)
1629 (message "Lazy desktop load aborted"))))
1631 ;; ----------------------------------------------------------------------------
1632 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1633 ;; command line, we do the rest of what it takes to use desktop, but do it
1634 ;; after finishing loading the init file.
1635 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1636 ;; functions are processed after `after-init-hook'.
1640 (let ((key "--no-desktop"))
1641 (when (member key command-line-args
)
1642 (setq command-line-args
(delete key command-line-args
))
1643 (desktop-save-mode 0)))
1644 (when desktop-save-mode
1646 (setq inhibit-startup-screen t
))))
1650 ;;; desktop.el ends here