Fix ambiguity in nil DST flag
[emacs.git] / lisp / desktop.el
bloba9fa2873b3b9f1677559569f81d42ee38e3e7073
1 ;;; desktop.el --- save partial status of Emacs when killed -*- lexical-binding: t -*-
3 ;; Copyright (C) 1993-1995, 1997, 2000-2018 Free Software Foundation,
4 ;; Inc.
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/>.
25 ;;; Commentary:
27 ;; Save the Desktop, i.e.,
28 ;; - some global variables
29 ;; - the list of buffers with associated files. For each buffer also
30 ;; - the major mode
31 ;; - the default directory
32 ;; - the point
33 ;; - the mark & mark-active
34 ;; - buffer-read-only
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.
52 ;; Special handling.
53 ;; -----------------
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
75 ;; ...
76 ;; (add-to-list 'desktop-buffer-mode-handlers
77 ;; '(foo-mode . foo-restore-desktop-buffer))
79 ;; or
81 ;; (defun bar-desktop-restore
82 ;; ...
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.
92 ;; Minor modes.
93 ;; ------------
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 ;; ---------------------------------------------------------------------------
131 ;; TODO:
133 ;; Recognize more minor modes.
134 ;; Save mark rings.
136 ;;; Code:
138 (require 'cl-lib)
139 (require 'frameset)
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."
159 :group 'frames)
161 ;;;###autoload
162 (define-minor-mode desktop-save-mode
163 "Toggle desktop saving (Desktop Save mode).
165 When Desktop Save mode is enabled, the state of Emacs is saved from
166 one session to another. In particular, Emacs will save the desktop when
167 it exits (this may prompt you; see the option `desktop-save'). The next
168 time Emacs starts, if this mode is active it will restore the desktop.
170 To manually save the desktop at any time, use the command `\\[desktop-save]'.
171 To load it, use `\\[desktop-read]'.
173 Once a desktop file exists, Emacs will auto-save it according to the
174 option `desktop-auto-save-timeout'.
176 To see all the options you can set, browse the `desktop' customization group.
178 For further details, see info node `(emacs)Saving Emacs Sessions'."
179 :global t
180 :group 'desktop
181 (if desktop-save-mode
182 (desktop-auto-save-enable)
183 (desktop-auto-save-disable)))
185 (defun desktop-save-mode-off ()
186 "Disable `desktop-save-mode'. Provided for use in hooks."
187 (desktop-save-mode 0))
189 (defcustom desktop-save 'ask-if-new
190 "Specifies whether the desktop should be saved when it is killed.
191 A desktop is killed when the user changes desktop or quits Emacs.
192 Possible values are:
193 t -- always save.
194 ask -- always ask.
195 ask-if-new -- ask if no desktop file exists, otherwise just save.
196 ask-if-exists -- ask if desktop file exists, otherwise don't save.
197 if-exists -- save if desktop file exists, otherwise don't save.
198 nil -- never save.
199 The desktop is never saved when `desktop-save-mode' is nil.
200 The variables `desktop-dirname' and `desktop-base-file-name'
201 determine where the desktop is saved."
202 :type
203 '(choice
204 (const :tag "Always save" t)
205 (const :tag "Always ask" ask)
206 (const :tag "Ask if desktop file is new, else do save" ask-if-new)
207 (const :tag "Ask if desktop file exists, else don't save" ask-if-exists)
208 (const :tag "Save if desktop file exists, else don't" if-exists)
209 (const :tag "Never save" nil))
210 :group 'desktop
211 :version "22.1")
213 (defcustom desktop-auto-save-timeout auto-save-timeout
214 "Number of seconds of idle time before auto-saving the desktop.
215 The desktop will be auto-saved when this amount of idle time have
216 passed after some change in the window configuration.
217 This applies to an existing desktop file when `desktop-save-mode' is enabled.
218 Zero or nil means disable auto-saving due to idleness."
219 :type '(choice (const :tag "Off" nil)
220 (integer :tag "Seconds"))
221 :set (lambda (symbol value)
222 (set-default symbol value)
223 (ignore-errors
224 (if (and (integerp value) (> value 0))
225 (desktop-auto-save-enable value)
226 (desktop-auto-save-disable))))
227 :group 'desktop
228 :version "24.4")
230 (defcustom desktop-load-locked-desktop 'ask
231 "Specifies whether the desktop should be loaded if locked.
232 Possible values are:
233 t -- load anyway.
234 nil -- don't load.
235 ask -- ask the user.
236 If the value is nil, or `ask' and the user chooses not to load the desktop,
237 the normal hook `desktop-not-loaded-hook' is run."
238 :type
239 '(choice
240 (const :tag "Load anyway" t)
241 (const :tag "Don't load" nil)
242 (const :tag "Ask the user" ask))
243 :group 'desktop
244 :version "22.2")
246 (defcustom desktop-base-file-name
247 (convert-standard-filename ".emacs.desktop")
248 "Name of file for Emacs desktop, excluding the directory part."
249 :type 'file
250 :group 'desktop)
252 (defcustom desktop-base-lock-name
253 (convert-standard-filename ".emacs.desktop.lock")
254 "Name of lock file for Emacs desktop, excluding the directory part."
255 :type 'file
256 :group 'desktop
257 :version "22.2")
259 (defcustom desktop-path (list user-emacs-directory "~")
260 "List of directories to search for the desktop file.
261 The base name of the file is specified in `desktop-base-file-name'."
262 :type '(repeat directory)
263 :group 'desktop
264 :version "23.2") ; user-emacs-directory added
266 (defcustom desktop-missing-file-warning nil
267 "If non-nil, offer to recreate the buffer of a deleted file.
268 Also pause for a moment to display message about errors signaled in
269 `desktop-buffer-mode-handlers'.
271 If nil, just print error messages in the message buffer."
272 :type 'boolean
273 :group 'desktop
274 :version "22.1")
276 (defcustom desktop-no-desktop-file-hook nil
277 "Normal hook run when `desktop-read' can't find a desktop file.
278 Run in the directory in which the desktop file was sought.
279 May be used to show a dired buffer."
280 :type 'hook
281 :group 'desktop
282 :version "22.1")
284 (defcustom desktop-not-loaded-hook nil
285 "Normal hook run when the user declines to re-use a desktop file.
286 Run in the directory in which the desktop file was found.
287 May be used to deal with accidental multiple Emacs jobs."
288 :type 'hook
289 :group 'desktop
290 :options '(desktop-save-mode-off save-buffers-kill-emacs)
291 :version "22.2")
293 (defcustom desktop-after-read-hook nil
294 "Normal hook run after a successful `desktop-read'.
295 May be used to show a buffer list."
296 :type 'hook
297 :group 'desktop
298 :options '(list-buffers)
299 :version "22.1")
301 (defcustom desktop-save-hook nil
302 "Normal hook run before the desktop is saved in a desktop file.
303 Run with the desktop buffer current with only the header present.
304 May be used to add to the desktop code or to truncate history lists,
305 for example."
306 :type 'hook
307 :group 'desktop)
309 (defcustom desktop-globals-to-save
310 '(desktop-missing-file-warning
311 tags-file-name
312 tags-table-list
313 search-ring
314 regexp-search-ring
315 register-alist
316 file-name-history)
317 "List of global variables saved by `desktop-save'.
318 An element may be variable name (a symbol) or a cons cell of the form
319 \(VAR . MAX-SIZE), which means to truncate VAR's value to at most
320 MAX-SIZE elements (if the value is a list) before saving the value.
321 Feature: Saving `kill-ring' implies saving `kill-ring-yank-pointer'."
322 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
323 :group 'desktop)
325 (defcustom desktop-globals-to-clear
326 '(kill-ring
327 kill-ring-yank-pointer
328 search-ring
329 search-ring-yank-pointer
330 regexp-search-ring
331 regexp-search-ring-yank-pointer)
332 "List of global variables that `desktop-clear' will clear.
333 An element may be variable name (a symbol) or a cons cell of the form
334 \(VAR . FORM). Symbols are set to nil and for cons cells VAR is set
335 to the value obtained by evaluating FORM."
336 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
337 :group 'desktop
338 :version "22.1")
340 (defcustom desktop-clear-preserve-buffers
341 '("\\*scratch\\*" "\\*Messages\\*" "\\*server\\*" "\\*tramp/.+\\*"
342 "\\*Warnings\\*")
343 "List of buffers that `desktop-clear' should not delete.
344 Each element is a regular expression. Buffers with a name matched by any of
345 these won't be deleted."
346 :version "23.3" ; added Warnings - bug#6336
347 :type '(repeat string)
348 :group 'desktop)
350 ;;;###autoload
351 (defcustom desktop-locals-to-save
352 '(desktop-locals-to-save ; Itself! Think it over.
353 truncate-lines
354 case-fold-search
355 case-replace
356 fill-column
357 overwrite-mode
358 change-log-default-name
359 line-number-mode
360 column-number-mode
361 size-indication-mode
362 buffer-file-coding-system
363 buffer-display-time
364 indent-tabs-mode
365 tab-width
366 indicate-buffer-boundaries
367 indicate-empty-lines
368 show-trailing-whitespace)
369 "List of local variables to save for each buffer.
370 The variables are saved only when they really are local. Conventional minor
371 modes are restored automatically; they should not be listed here."
372 :type '(repeat symbol)
373 :group 'desktop)
375 (defcustom desktop-buffers-not-to-save "\\` "
376 "Regexp identifying buffers that are to be excluded from saving.
377 This is in effect only for buffers that don't visit files.
378 To exclude buffers that visit files, use `desktop-files-not-to-save'
379 or `desktop-modes-not-to-save'."
380 :type '(choice (const :tag "None" nil)
381 regexp)
382 :version "24.4" ; skip invisible temporary buffers
383 :group 'desktop)
385 ;; Skip tramp and ange-ftp files
386 (defcustom desktop-files-not-to-save
387 "\\(\\`/[^/:]*:\\|(ftp)\\'\\)"
388 "Regexp identifying files whose buffers are to be excluded from saving.
389 The default value excludes buffers visiting remote files."
390 :type '(choice (const :tag "None" nil)
391 regexp)
392 :group 'desktop)
394 ;; We skip TAGS files to save time (tags-file-name is saved instead).
395 (defcustom desktop-modes-not-to-save
396 '(tags-table-mode)
397 "List of major modes whose buffers should not be saved."
398 :type '(repeat symbol)
399 :group 'desktop)
401 (defcustom desktop-restore-frames t
402 "When non-nil, save and restore the frame and window configuration.
403 See related options `desktop-restore-reuses-frames',
404 `desktop-restore-in-current-display', and `desktop-restore-forces-onscreen'."
405 :type 'boolean
406 :group 'desktop
407 :version "24.4")
409 (defcustom desktop-restore-in-current-display t
410 "Controls how restoring of frames treats displays.
411 If t, restores frames into the current display.
412 If nil, restores frames into their original displays (if possible).
413 If `delete', deletes frames on other displays instead of restoring them."
414 :type '(choice (const :tag "Restore in current display" t)
415 (const :tag "Restore in original display" nil)
416 (const :tag "Delete frames in other displays" delete))
417 :group 'desktop
418 :version "24.4")
420 (defcustom desktop-restore-forces-onscreen t
421 "If t, restores frames that are fully offscreen onscreen instead.
422 If `all', also restores frames that are partially offscreen onscreen.
424 Note that checking of frame boundaries is only approximate.
425 It can fail to reliably detect frames whose onscreen/offscreen state
426 depends on a few pixels, especially near the right / bottom borders
427 of the screen."
428 :type '(choice (const :tag "Only fully offscreen frames" t)
429 (const :tag "Also partially offscreen frames" all)
430 (const :tag "Do not force frames onscreen" nil))
431 :group 'desktop
432 :version "24.4")
434 (defcustom desktop-restore-reuses-frames t
435 "If t, restoring frames reuses existing frames.
436 If nil, deletes existing frames.
437 If `keep', keeps existing frames and does not reuse them."
438 :type '(choice (const :tag "Reuse existing frames" t)
439 (const :tag "Delete existing frames" nil)
440 (const :tag "Keep existing frames" :keep))
441 :group 'desktop
442 :version "24.4")
444 (defcustom desktop-file-name-format 'absolute
445 "Format in which desktop file names should be saved.
446 Possible values are:
447 absolute -- Absolute file name.
448 tilde -- Relative to ~.
449 local -- Relative to directory of desktop file."
450 :type '(choice (const absolute) (const tilde) (const local))
451 :group 'desktop
452 :version "22.1")
454 (defcustom desktop-restore-eager t
455 "Number of buffers to restore immediately.
456 Remaining buffers are restored lazily (when Emacs is idle).
457 If value is t, all buffers are restored immediately."
458 :type '(choice (const t) integer)
459 :group 'desktop
460 :version "22.1")
462 (defcustom desktop-lazy-verbose t
463 "Verbose reporting of lazily created buffers."
464 :type 'boolean
465 :group 'desktop
466 :version "22.1")
468 (defcustom desktop-lazy-idle-delay 5
469 "Idle delay before starting to create buffers.
470 See `desktop-restore-eager'."
471 :type 'integer
472 :group 'desktop
473 :version "22.1")
475 ;;;###autoload
476 (defvar-local desktop-save-buffer nil
477 "When non-nil, save buffer status in desktop file.
479 If the value is a function, it is called by `desktop-save' with argument
480 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
481 file along with the state of the buffer for which it was called.
483 When file names are returned, they should be formatted using the call
484 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
486 Later, when `desktop-read' evaluates the desktop file, auxiliary information
487 is passed as the argument DESKTOP-BUFFER-MISC to functions in
488 `desktop-buffer-mode-handlers'.")
490 ;;;###autoload
491 (defvar desktop-buffer-mode-handlers nil
492 "Alist of major mode specific functions to restore a desktop buffer.
493 Functions listed are called by `desktop-create-buffer' when `desktop-read'
494 evaluates the desktop file. List elements must have the form
496 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
498 Buffers with a major mode not specified here, are restored by the default
499 handler `desktop-restore-file-buffer'.
501 Handlers are called with argument list
503 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
505 Furthermore, they may use the following variables:
507 `desktop-file-version'
508 `desktop-buffer-major-mode'
509 `desktop-buffer-minor-modes'
510 `desktop-buffer-point'
511 `desktop-buffer-mark'
512 `desktop-buffer-read-only'
513 `desktop-buffer-locals'
515 If a handler returns a buffer, then the saved mode settings
516 and variable values for that buffer are copied into it.
518 Modules that define a major mode that needs a special handler should contain
519 code like
521 (defun foo-restore-desktop-buffer
523 (add-to-list \\='desktop-buffer-mode-handlers
524 \\='(foo-mode . foo-restore-desktop-buffer))
526 The major mode function must either be autoloaded, or of the form
527 \"foobar-mode\" and defined in library \"foobar\", so that desktop
528 can guess how to load the mode's definition.")
530 ;;;###autoload
531 (put 'desktop-buffer-mode-handlers 'risky-local-variable t)
533 (defcustom desktop-minor-mode-table
534 '((defining-kbd-macro nil)
535 (isearch-mode nil)
536 (vc-mode nil)
537 (vc-dired-mode nil)
538 (erc-track-minor-mode nil)
539 (savehist-mode nil))
540 "Table mapping minor mode variables to minor mode functions.
541 Each entry has the form (NAME RESTORE-FUNCTION).
542 NAME is the name of the buffer-local variable indicating that the minor
543 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
544 RESTORE-FUNCTION nil means don't try to restore the minor mode.
545 Only minor modes for which the name of the buffer-local variable
546 and the name of the minor mode function are different have to be added to
547 this table. See also `desktop-minor-mode-handlers'."
548 :type '(alist :key-type (symbol :tag "Minor mode")
549 :value-type (list :tag "Restore function"
550 (choice (const nil) function)))
551 :group 'desktop)
553 ;;;###autoload
554 (defvar desktop-minor-mode-handlers nil
555 "Alist of functions to restore non-standard minor modes.
556 Functions are called by `desktop-create-buffer' to restore minor modes.
557 List elements must have the form
559 (MINOR-MODE . RESTORE-FUNCTION).
561 Minor modes not specified here, are restored by the standard minor mode
562 function.
564 Handlers are called with argument list
566 (DESKTOP-BUFFER-LOCALS)
568 Furthermore, they may use the following variables:
570 `desktop-file-version'
571 `desktop-buffer-file-name'
572 `desktop-buffer-name'
573 `desktop-buffer-major-mode'
574 `desktop-buffer-minor-modes'
575 `desktop-buffer-point'
576 `desktop-buffer-mark'
577 `desktop-buffer-read-only'
578 `desktop-buffer-misc'
580 When a handler is called, the buffer has been created and the major mode has
581 been set, but local variables listed in desktop-buffer-locals has not yet been
582 created and set.
584 Modules that define a minor mode that needs a special handler should contain
585 code like
587 (defun foo-desktop-restore
589 (add-to-list \\='desktop-minor-mode-handlers
590 \\='(foo-mode . foo-desktop-restore))
592 The minor mode function must either be autoloaded, or of the form
593 \"foobar-mode\" and defined in library \"foobar\", so that desktop
594 can guess how to load the mode's definition.
596 See also `desktop-minor-mode-table'.")
598 ;;;###autoload
599 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
601 ;; ----------------------------------------------------------------------------
602 (defvar desktop-dirname nil
603 "The directory in which the desktop file should be saved.")
605 (defun desktop-full-file-name (&optional dirname)
606 "Return the full name of the desktop file in DIRNAME.
607 DIRNAME omitted or nil means use `desktop-dirname'."
608 (expand-file-name desktop-base-file-name (or dirname desktop-dirname)))
610 (defun desktop-full-lock-name (&optional dirname)
611 "Return the full name of the desktop lock file in DIRNAME.
612 DIRNAME omitted or nil means use `desktop-dirname'."
613 (expand-file-name desktop-base-lock-name (or dirname desktop-dirname)))
615 (defconst desktop-header
616 ";; --------------------------------------------------------------------------
617 ;; Desktop File for Emacs
618 ;; --------------------------------------------------------------------------
619 " "*Header to place in Desktop file.")
621 (defvar desktop-delay-hook nil
622 "Hooks run after all buffers are loaded; intended for internal use.")
624 (defvar desktop-file-checksum nil
625 "Checksum of the last auto-saved contents of the desktop file.
626 Used to avoid writing contents unchanged between auto-saves.")
628 (defvar desktop-saved-frameset nil
629 "Saved state of all frames.
630 Only valid during frame saving & restoring; intended for internal use.")
632 ;; ----------------------------------------------------------------------------
633 ;; Desktop file conflict detection
634 (defvar desktop-file-modtime nil
635 "When the desktop file was last modified to the knowledge of this Emacs.
636 Used to detect desktop file conflicts.")
638 (defvar desktop-var-serdes-funs
639 (list (list
640 'mark-ring
641 (lambda (mr)
642 (mapcar #'marker-position mr))
643 (lambda (mr)
644 (mapcar #'copy-marker mr))))
645 "Table of serialization/deserialization functions for variables.
646 Each record is a list of form: (var serializer deserializer).
647 These records can be freely reordered, deleted, or new ones added.
648 However, for compatibility, don't modify the functions for existing records.")
650 (defun desktop-owner (&optional dirname)
651 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
652 Return nil if no desktop file found or no Emacs process is using it.
653 DIRNAME omitted or nil means use `desktop-dirname'."
654 (let (owner
655 (file (desktop-full-lock-name dirname)))
656 (and (file-exists-p file)
657 (ignore-errors
658 (with-temp-buffer
659 (insert-file-contents-literally file)
660 (goto-char (point-min))
661 (setq owner (read (current-buffer)))
662 (integerp owner)))
663 owner)))
665 (defun desktop-claim-lock (&optional dirname)
666 "Record this Emacs process as the owner of the desktop file in DIRNAME.
667 DIRNAME omitted or nil means use `desktop-dirname'."
668 (write-region (number-to-string (emacs-pid)) nil
669 (desktop-full-lock-name dirname)))
671 (defun desktop-release-lock (&optional dirname)
672 "Remove the lock file for the desktop in DIRNAME.
673 DIRNAME omitted or nil means use `desktop-dirname'."
674 (let ((file (desktop-full-lock-name dirname)))
675 (when (file-exists-p file) (delete-file file))))
677 ;; ----------------------------------------------------------------------------
678 (defun desktop-truncate (list n)
679 "Truncate LIST to at most N elements destructively."
680 (let ((here (nthcdr (1- n) list)))
681 (when (consp here)
682 (setcdr here nil))))
684 ;; ----------------------------------------------------------------------------
685 ;;;###autoload
686 (defun desktop-clear ()
687 "Empty the Desktop.
688 This kills all buffers except for internal ones and those with names matched by
689 a regular expression in the list `desktop-clear-preserve-buffers'.
690 Furthermore, it clears the variables listed in `desktop-globals-to-clear'.
691 When called interactively and `desktop-restore-frames' is non-nil, it also
692 deletes all frames except the selected one (and its minibuffer frame,
693 if different)."
694 (interactive)
695 (desktop-lazy-abort)
696 (setq desktop-io-file-version nil)
697 (dolist (var desktop-globals-to-clear)
698 (if (symbolp var)
699 (set-default var nil)
700 (set-default var (eval (cdr var)))))
701 (let ((preserve-regexp (concat "\\`\\("
702 (mapconcat (lambda (regexp)
703 (concat "\\(" regexp "\\)"))
704 desktop-clear-preserve-buffers
705 "\\|")
706 "\\)\\'")))
707 (dolist (buffer (buffer-list))
708 (let ((bufname (buffer-name buffer)))
709 (unless (or (eq (aref bufname 0) ?\s) ;; Don't kill internal buffers
710 (string-match-p preserve-regexp bufname))
711 (kill-buffer buffer)))))
712 (delete-other-windows)
713 (when (and desktop-restore-frames
714 ;; Non-interactive calls to desktop-clear happen before desktop-read
715 ;; which already takes care of frame restoration and deletion.
716 (called-interactively-p 'any))
717 (let* ((this (selected-frame))
718 (mini (window-frame (minibuffer-window this)))) ; in case they differ
719 (dolist (frame (sort (frame-list) #'frameset-minibufferless-first-p))
720 (condition-case err
721 (unless (or (eq frame this)
722 (eq frame mini)
723 ;; Don't delete daemon's initial frame, or
724 ;; we'll never be able to close the last
725 ;; client's frame (Bug#26912).
726 (if (daemonp) (not (frame-parameter frame 'client)))
727 (frame-parameter frame 'desktop-dont-clear))
728 (delete-frame frame))
729 (error
730 (delay-warning 'desktop (error-message-string err))))))))
732 ;; ----------------------------------------------------------------------------
733 (unless noninteractive
734 (add-hook 'kill-emacs-hook #'desktop-kill))
736 (defun desktop-kill ()
737 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
738 If the desktop should be saved and `desktop-dirname'
739 is nil, ask the user where to save the desktop."
740 (when (and desktop-save-mode
741 (let ((exists (file-exists-p (desktop-full-file-name))))
742 (or (eq desktop-save t)
743 (and exists (eq desktop-save 'if-exists))
744 ;; If it exists, but we aren't using it, we are going
745 ;; to ask for a new directory below.
746 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
747 (and
748 (or (memq desktop-save '(ask ask-if-new))
749 (and exists (eq desktop-save 'ask-if-exists)))
750 (y-or-n-p "Save desktop? ")))))
751 (unless desktop-dirname
752 (setq desktop-dirname
753 (file-name-as-directory
754 (expand-file-name
755 (read-directory-name "Directory for desktop file: " nil nil t)))))
756 (condition-case err
757 (desktop-save desktop-dirname t)
758 (file-error
759 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
760 (signal (car err) (cdr err))))))
761 ;; If we own it, we don't anymore.
762 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
764 ;; ----------------------------------------------------------------------------
765 (defun desktop-list* (&rest args)
766 (and args (apply #'cl-list* args)))
768 ;; ----------------------------------------------------------------------------
769 (defun desktop-buffer-info (buffer)
770 "Return information describing BUFFER.
771 This function is not pure, as BUFFER is made current with
772 `set-buffer'.
774 Returns a list of all the necessary information to recreate the
775 buffer, which is (in order):
777 `uniquify-buffer-base-name';
778 `buffer-file-name';
779 `buffer-name';
780 `major-mode';
781 list of minor-modes,;
782 `point';
783 `mark';
784 `buffer-read-only';
785 auxiliary information given by `desktop-save-buffer';
786 local variables;
787 auxiliary information given by `desktop-var-serdes-funs'."
788 (set-buffer buffer)
790 ;; base name of the buffer; replaces the buffer name if managed by uniquify
791 ,(and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
792 ;; basic information
793 ,(desktop-file-name (buffer-file-name) desktop-dirname)
794 ,(buffer-name)
795 ,major-mode
796 ;; minor modes
797 ,(let (ret)
798 (dolist (minor-mode (mapcar #'car minor-mode-alist) ret)
799 (and (boundp minor-mode)
800 (symbol-value minor-mode)
801 (let* ((special (assq minor-mode desktop-minor-mode-table))
802 (value (cond (special (cadr special))
803 ((get minor-mode :minor-mode-function))
804 ((functionp minor-mode) minor-mode))))
805 (when value (cl-pushnew value ret))))))
806 ;; point and mark, and read-only status
807 ,(point)
808 ,(list (mark t) mark-active)
809 ,buffer-read-only
810 ;; auxiliary information
811 ,(when (functionp desktop-save-buffer)
812 (funcall desktop-save-buffer desktop-dirname))
813 ;; local variables
814 ,(let ((loclist (buffer-local-variables))
815 (ll nil))
816 (dolist (local desktop-locals-to-save)
817 (let ((here (assq local loclist)))
818 (cond (here
819 (push here ll))
820 ((member local loclist)
821 (push local ll)))))
823 ,@(when (>= desktop-io-file-version 208)
824 (list
825 (mapcar (lambda (record)
826 (let ((var (car record)))
827 (list var
828 (funcall (cadr record) (symbol-value var)))))
829 desktop-var-serdes-funs)))))
831 ;; ----------------------------------------------------------------------------
832 (defun desktop--v2s (value)
833 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
834 SEXP is an sexp that when evaluated yields VALUE.
835 QUOTE may be `may' (value may be quoted),
836 `must' (value must be quoted), or nil (value must not be quoted)."
837 (cond
838 ((or (numberp value) (null value) (eq t value) (keywordp value))
839 (cons 'may value))
840 ((stringp value)
841 ;; Get rid of unreadable text properties.
842 (if (condition-case nil (read (format "%S" value)) (error nil))
843 (cons 'may value)
844 (let ((copy (copy-sequence value)))
845 (set-text-properties 0 (length copy) nil copy)
846 (cons 'may copy))))
847 ((symbolp value)
848 (cons 'must value))
849 ((vectorp value)
850 (let* ((pass1 (mapcar #'desktop--v2s value))
851 (special (assq nil pass1)))
852 (if special
853 (cons nil `(vector
854 ,@(mapcar (lambda (el)
855 (if (eq (car el) 'must)
856 `',(cdr el) (cdr el)))
857 pass1)))
858 (cons 'may `[,@(mapcar #'cdr pass1)]))))
859 ((consp value)
860 (let ((p value)
861 newlist
862 use-list*)
863 (while (consp p)
864 (let ((q.sexp (desktop--v2s (car p))))
865 (push q.sexp newlist))
866 (setq p (cdr p)))
867 (when p
868 (let ((last (desktop--v2s p)))
869 (setq use-list* t)
870 (push last newlist)))
871 (if (assq nil newlist)
872 (cons nil
873 `(,(if use-list* 'desktop-list* 'list)
874 ,@(mapcar (lambda (el)
875 (if (eq (car el) 'must)
876 `',(cdr el) (cdr el)))
877 (nreverse newlist))))
878 (cons 'must
879 `(,@(mapcar #'cdr
880 (nreverse (if use-list* (cdr newlist) newlist)))
881 ,@(if use-list* (cdar newlist)))))))
882 ((subrp value)
883 (cons nil `(symbol-function
884 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
885 ((markerp value)
886 (let ((pos (marker-position value))
887 (buf (buffer-name (marker-buffer value))))
888 (cons nil
889 `(let ((mk (make-marker)))
890 (add-hook 'desktop-delay-hook
891 (lambda ()
892 (set-marker mk ,pos (get-buffer ,buf))))
893 mk))))
894 (t ; Save as text.
895 (cons 'may "Unprintable entity"))))
897 ;; ----------------------------------------------------------------------------
898 (defun desktop-value-to-string (value)
899 "Convert VALUE to a string that when read evaluates to the same value.
900 Not all types of values are supported."
901 (let* ((print-escape-newlines t)
902 (print-length nil)
903 (print-level nil)
904 (float-output-format nil)
905 (quote.sexp (desktop--v2s value))
906 (quote (car quote.sexp))
907 (print-quoted t)
908 (txt (prin1-to-string (cdr quote.sexp))))
909 (if (eq quote 'must)
910 (concat "'" txt)
911 txt)))
913 ;; ----------------------------------------------------------------------------
914 (defun desktop-outvar (varspec)
915 "Output a setq statement for variable VAR to the desktop file.
916 The argument VARSPEC may be the variable name VAR (a symbol),
917 or a cons cell of the form (VAR . MAX-SIZE),
918 which means to truncate VAR's value to at most MAX-SIZE elements
919 \(if the value is a list) before saving the value."
920 (let (var size)
921 (if (consp varspec)
922 (setq var (car varspec) size (cdr varspec))
923 (setq var varspec))
924 (when (boundp var)
925 (when (and (integerp size)
926 (> size 0)
927 (listp (eval var)))
928 (desktop-truncate (eval var) size))
929 (insert "(setq "
930 (symbol-name var)
932 (desktop-value-to-string (symbol-value var))
933 ")\n"))))
935 ;; ----------------------------------------------------------------------------
936 (defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
937 "Return t if buffer should have its state saved in the desktop file.
938 FILENAME is the visited file name, BUFNAME is the buffer name, and
939 MODE is the major mode.
940 \n\(fn FILENAME BUFNAME MODE)"
941 (let ((case-fold-search nil)
942 (no-regexp-to-check (not (stringp desktop-files-not-to-save)))
943 dired-skip)
944 (and (or filename
945 (not (stringp desktop-buffers-not-to-save))
946 (not (string-match-p desktop-buffers-not-to-save bufname)))
947 (not (memq mode desktop-modes-not-to-save))
948 (or (and filename
949 (or no-regexp-to-check
950 (not (string-match-p desktop-files-not-to-save filename))))
951 (and (memq mode '(dired-mode vc-dir-mode))
952 (or no-regexp-to-check
953 (not (setq dired-skip
954 (with-current-buffer bufname
955 (string-match-p desktop-files-not-to-save
956 default-directory))))))
957 (and (null filename)
958 (null dired-skip) ; bug#5755
959 (with-current-buffer bufname desktop-save-buffer)))
960 t)))
962 ;; ----------------------------------------------------------------------------
963 (defun desktop-file-name (filename dirname)
964 "Convert FILENAME to format specified in `desktop-file-name-format'.
965 DIRNAME must be the directory in which the desktop file will be saved."
966 (cond
967 ((not filename) nil)
968 ((eq desktop-file-name-format 'tilde)
969 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
970 (cond
971 ((file-name-absolute-p relative-name) relative-name)
972 ((string= "./" relative-name) "~/")
973 ((string= "." relative-name) "~")
974 (t (concat "~/" relative-name)))))
975 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
976 (t (expand-file-name filename))))
979 ;; ----------------------------------------------------------------------------
980 (defun desktop--check-dont-save (frame)
981 (not (frame-parameter frame 'desktop-dont-save)))
983 (defconst desktop--app-id `(desktop . ,desktop-file-version))
985 (defun desktop-save-frameset ()
986 "Save the state of existing frames in `desktop-saved-frameset'.
987 Frames with a non-nil `desktop-dont-save' parameter are not saved."
988 (setq desktop-saved-frameset
989 (and desktop-restore-frames
990 (frameset-save nil
991 :app desktop--app-id
992 :name (concat user-login-name "@" (system-name))
993 :predicate #'desktop--check-dont-save))))
995 ;;;###autoload
996 (defun desktop-save (dirname &optional release only-if-changed version)
997 "Save the desktop in a desktop file.
998 Parameter DIRNAME specifies where to save the desktop file.
999 Optional parameter RELEASE says whether we're done with this
1000 desktop. If ONLY-IF-CHANGED is non-nil, compare the current
1001 desktop information to that in the desktop file, and if the
1002 desktop information has not changed since it was last saved then
1003 do not rewrite the file.
1005 This function can save the desktop in either format version
1006 208 (which only Emacs 25.1 and later can read) or version
1007 206 (which is readable by any Emacs from version 22.1 onwards).
1008 By default, it will use the same format the desktop file had when
1009 it was last saved, or version 208 when writing a fresh desktop
1010 file.
1012 To upgrade a version 206 file to version 208, call this command
1013 explicitly with a bare prefix argument: C-u M-x desktop-save.
1014 You are recommended to do this once you have firmly upgraded to
1015 Emacs 25.1 (or later). To downgrade a version 208 file to version
1016 206, use a double command prefix: C-u C-u M-x desktop-save.
1017 Confirmation will be requested in either case. In a non-interactive
1018 call, VERSION can be given as an integer, either 206 or 208, which
1019 will be accepted as the format version in which to save the file
1020 without further confirmation."
1021 (interactive (list
1022 ;; Or should we just use (car desktop-path)?
1023 (let ((default (if (member "." desktop-path)
1024 default-directory
1025 user-emacs-directory)))
1026 (read-directory-name "Directory to save desktop file in: "
1027 default default t))
1030 current-prefix-arg))
1031 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
1032 (save-excursion
1033 (let ((eager desktop-restore-eager)
1034 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
1035 (when
1036 (or (not new-modtime) ; nothing to overwrite
1037 (equal desktop-file-modtime new-modtime)
1038 (yes-or-no-p (if desktop-file-modtime
1039 (if (time-less-p desktop-file-modtime
1040 new-modtime)
1041 "Desktop file is more recent than the one loaded. Save anyway? "
1042 "Desktop file isn't the one loaded. Overwrite it? ")
1043 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
1044 (unless release (error "Desktop file conflict")))
1046 ;; If we're done with it, release the lock.
1047 ;; Otherwise, claim it if it's unclaimed or if we created it.
1048 (if release
1049 (desktop-release-lock)
1050 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
1052 ;; What format are we going to write the file in?
1053 (setq desktop-io-file-version
1054 (cond
1055 ((equal version '(4))
1056 (if (or (eq desktop-io-file-version 208)
1057 (yes-or-no-p "Save desktop file in format 208 \
1058 \(Readable by Emacs 25.1 and later only)? "))
1060 (or desktop-io-file-version desktop-native-file-version)))
1061 ((equal version '(16))
1062 (if (or (eq desktop-io-file-version 206)
1063 (yes-or-no-p "Save desktop file in format 206 \
1064 \(Readable by all Emacs versions since 22.1)? "))
1066 (or desktop-io-file-version desktop-native-file-version)))
1067 ((memq version '(206 208))
1068 version)
1069 ((null desktop-io-file-version) ; As yet, no desktop file exists.
1070 desktop-native-file-version)
1072 desktop-io-file-version)))
1074 (with-temp-buffer
1075 (insert
1076 ";; -*- mode: emacs-lisp; lexical-binding:t; coding: utf-8-emacs; -*-\n"
1077 desktop-header
1078 ";; Created " (current-time-string) "\n"
1079 ";; Desktop file format version " (format "%d" desktop-io-file-version) "\n"
1080 ";; Emacs version " emacs-version "\n")
1081 (save-excursion (run-hooks 'desktop-save-hook))
1082 (goto-char (point-max))
1083 (insert "\n;; Global section:\n")
1084 ;; Called here because we save the window/frame state as a global
1085 ;; variable for compatibility with previous Emacsen.
1086 (desktop-save-frameset)
1087 (unless (memq 'desktop-saved-frameset desktop-globals-to-save)
1088 (desktop-outvar 'desktop-saved-frameset))
1089 (mapc #'desktop-outvar desktop-globals-to-save)
1090 (setq desktop-saved-frameset nil) ; after saving desktop-globals-to-save
1091 (when (memq 'kill-ring desktop-globals-to-save)
1092 (insert
1093 "(setq kill-ring-yank-pointer (nthcdr "
1094 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
1095 " kill-ring))\n"))
1097 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
1098 (dolist (l (mapcar #'desktop-buffer-info (buffer-list)))
1099 (let ((base (pop l)))
1100 (when (apply #'desktop-save-buffer-p l)
1101 (insert "("
1102 (if (or (not (integerp eager))
1103 (if (zerop eager)
1105 (setq eager (1- eager))))
1106 "desktop-create-buffer"
1107 "desktop-append-buffer-args")
1109 (format "%d" desktop-io-file-version))
1110 ;; If there's a non-empty base name, we save it instead of the buffer name
1111 (when (and base (not (string= base "")))
1112 (setcar (nthcdr 1 l) base))
1113 (dolist (e l)
1114 (insert "\n " (desktop-value-to-string e)))
1115 (insert ")\n\n"))))
1117 (setq default-directory desktop-dirname)
1118 ;; When auto-saving, avoid writing if nothing has changed since the last write.
1119 (let* ((beg (and only-if-changed
1120 (save-excursion
1121 (goto-char (point-min))
1122 ;; Don't check the header with changing timestamp
1123 (and (search-forward "Global section" nil t)
1124 ;; Also skip the timestamp in desktop-saved-frameset
1125 ;; if it's saved in the first non-header line
1126 (search-forward "desktop-saved-frameset"
1127 (line-beginning-position 3) t)
1128 ;; This is saved after the timestamp
1129 (search-forward (format "%S" desktop--app-id) nil t))
1130 (point))))
1131 (checksum (and beg (md5 (current-buffer) beg (point-max) 'utf-8-emacs))))
1132 (unless (and checksum (equal checksum desktop-file-checksum))
1133 (let ((coding-system-for-write 'utf-8-emacs))
1134 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
1135 (setq desktop-file-checksum checksum)
1136 ;; We remember when it was modified (which is presumably just now).
1137 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
1139 ;; ----------------------------------------------------------------------------
1140 ;;;###autoload
1141 (defun desktop-remove ()
1142 "Delete desktop file in `desktop-dirname'.
1143 This function also sets `desktop-dirname' to nil."
1144 (interactive)
1145 (when desktop-dirname
1146 (let ((filename (desktop-full-file-name)))
1147 (setq desktop-dirname nil)
1148 (when (file-exists-p filename)
1149 (delete-file filename)))))
1151 (defvar desktop-buffer-args-list nil
1152 "List of args for `desktop-create-buffer'.")
1154 (defvar desktop-lazy-timer nil)
1156 ;; ----------------------------------------------------------------------------
1157 (defun desktop-restoring-frameset-p ()
1158 "True if calling `desktop-restore-frameset' will actually restore it."
1159 (and desktop-restore-frames desktop-saved-frameset (display-graphic-p) t))
1161 (defun desktop-restore-frameset ()
1162 "Restore the state of a set of frames.
1163 This function depends on the value of `desktop-saved-frameset'
1164 being set (usually, by reading it from the desktop)."
1165 (when (desktop-restoring-frameset-p)
1166 (frameset-restore desktop-saved-frameset
1167 :reuse-frames (eq desktop-restore-reuses-frames t)
1168 :cleanup-frames (not (eq desktop-restore-reuses-frames 'keep))
1169 :force-display desktop-restore-in-current-display
1170 :force-onscreen desktop-restore-forces-onscreen)))
1172 ;; Just to silence the byte compiler.
1173 ;; Dynamically bound in `desktop-read'.
1174 (defvar desktop-first-buffer)
1175 (defvar desktop-buffer-ok-count)
1176 (defvar desktop-buffer-fail-count)
1178 ;; FIXME Interactively, this should have the option to prompt for dirname.
1179 ;;;###autoload
1180 (defun desktop-read (&optional dirname)
1181 "Read and process the desktop file in directory DIRNAME.
1182 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1183 directories listed in `desktop-path'. If a desktop file is found, it
1184 is processed and `desktop-after-read-hook' is run. If no desktop file
1185 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1186 This function is a no-op when Emacs is running in batch mode.
1187 It returns t if a desktop file was loaded, nil otherwise."
1188 (interactive)
1189 (unless noninteractive
1190 (setq desktop-dirname
1191 (file-name-as-directory
1192 (expand-file-name
1194 ;; If DIRNAME is specified, use it.
1195 (and (< 0 (length dirname)) dirname)
1196 ;; Otherwise search desktop file in desktop-path.
1197 (let ((dirs desktop-path))
1198 (while (and dirs
1199 (not (file-exists-p
1200 (desktop-full-file-name (car dirs)))))
1201 (setq dirs (cdr dirs)))
1202 (and dirs (car dirs)))
1203 ;; If not found and `desktop-path' is non-nil, use its first element.
1204 (and desktop-path (car desktop-path))
1205 ;; Default: .emacs.d.
1206 user-emacs-directory))))
1207 (if (file-exists-p (desktop-full-file-name))
1208 ;; Desktop file found, but is it already in use?
1209 (let ((desktop-first-buffer nil)
1210 (desktop-buffer-ok-count 0)
1211 (desktop-buffer-fail-count 0)
1212 (owner (desktop-owner))
1213 ;; Avoid desktop saving during evaluation of desktop buffer.
1214 (desktop-save nil)
1215 (desktop-autosave-was-enabled))
1216 (if (and owner
1217 (memq desktop-load-locked-desktop '(nil ask))
1218 (or (null desktop-load-locked-desktop)
1219 (daemonp)
1220 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1221 Using it may cause conflicts. Use it anyway? " owner)))))
1222 (let ((default-directory desktop-dirname))
1223 (setq desktop-dirname nil)
1224 (run-hooks 'desktop-not-loaded-hook)
1225 (unless desktop-dirname
1226 (message "Desktop file in use; not loaded.")))
1227 (desktop-lazy-abort)
1228 ;; Temporarily disable the autosave that will leave it
1229 ;; disabled when loading the desktop fails with errors,
1230 ;; thus not overwriting the desktop with broken contents.
1231 (setq desktop-autosave-was-enabled
1232 (memq #'desktop-auto-save-set-timer
1233 ;; Use the global value of the hook, in case some
1234 ;; feature makes window-configuration-change-hook
1235 ;; buffer-local, and puts there stuff which
1236 ;; doesn't include our timer.
1237 (default-value
1238 'window-configuration-change-hook)))
1239 (desktop-auto-save-disable)
1240 ;; Evaluate desktop buffer and remember when it was modified.
1241 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1242 (load (desktop-full-file-name) t t t)
1243 ;; If it wasn't already, mark it as in-use, to bother other
1244 ;; desktop instances.
1245 (unless (eq (emacs-pid) owner)
1246 (condition-case nil
1247 (desktop-claim-lock)
1248 (file-error (message "Couldn't record use of desktop file")
1249 (sit-for 1))))
1251 (unless (desktop-restoring-frameset-p)
1252 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1253 ;; We want buffers existing prior to evaluating the desktop (and
1254 ;; not reused) to be placed at the end of the buffer list, so we
1255 ;; move them here.
1256 (mapc #'bury-buffer
1257 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1258 (switch-to-buffer (car (buffer-list))))
1259 (run-hooks 'desktop-delay-hook)
1260 (setq desktop-delay-hook nil)
1261 (desktop-restore-frameset)
1262 (run-hooks 'desktop-after-read-hook)
1263 (message "Desktop: %s%d buffer%s restored%s%s."
1264 (if desktop-saved-frameset
1265 (let ((fn (length (frameset-states desktop-saved-frameset))))
1266 (format "%d frame%s, "
1267 fn (if (= fn 1) "" "s")))
1269 desktop-buffer-ok-count
1270 (if (= 1 desktop-buffer-ok-count) "" "s")
1271 (if (< 0 desktop-buffer-fail-count)
1272 (format ", %d failed to restore" desktop-buffer-fail-count)
1274 (if desktop-buffer-args-list
1275 (format ", %d to restore lazily"
1276 (length desktop-buffer-args-list))
1277 ""))
1278 (unless (desktop-restoring-frameset-p)
1279 ;; Bury the *Messages* buffer to not reshow it when burying
1280 ;; the buffer we switched to above.
1281 (when (buffer-live-p (get-buffer "*Messages*"))
1282 (bury-buffer "*Messages*"))
1283 ;; Clear all windows' previous and next buffers, these have
1284 ;; been corrupted by the `switch-to-buffer' calls in
1285 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1286 ;; brute force fix and should be replaced by a more subtle
1287 ;; strategy eventually.
1288 (walk-window-tree (lambda (window)
1289 (set-window-prev-buffers window nil)
1290 (set-window-next-buffers window nil))))
1291 (setq desktop-saved-frameset nil)
1292 (if desktop-autosave-was-enabled (desktop-auto-save-enable))
1294 ;; No desktop file found.
1295 (let ((default-directory desktop-dirname))
1296 (run-hooks 'desktop-no-desktop-file-hook))
1297 (message "No desktop file.")
1298 nil)))
1300 ;; ----------------------------------------------------------------------------
1301 ;;;###autoload
1302 (defun desktop-change-dir (dirname)
1303 "Change to desktop saved in DIRNAME.
1304 Kill the desktop as specified by variables `desktop-save-mode' and
1305 `desktop-save', then clear the desktop and load the desktop file in
1306 directory DIRNAME."
1307 (interactive "DChange to directory: ")
1308 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1309 (desktop-kill)
1310 (desktop-clear)
1311 (desktop-read dirname))
1313 ;; ----------------------------------------------------------------------------
1314 ;;;###autoload
1315 (defun desktop-save-in-desktop-dir ()
1316 "Save the desktop in directory `desktop-dirname'."
1317 (interactive)
1318 (if desktop-dirname
1319 (desktop-save desktop-dirname)
1320 (call-interactively 'desktop-save))
1321 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1323 ;; ----------------------------------------------------------------------------
1324 ;; Auto-Saving.
1325 (defvar desktop-auto-save-timer nil)
1327 (defun desktop-auto-save-enable (&optional timeout)
1328 (when (and (integerp (or timeout desktop-auto-save-timeout))
1329 (> (or timeout desktop-auto-save-timeout) 0))
1330 (add-hook 'window-configuration-change-hook #'desktop-auto-save-set-timer)))
1332 (defun desktop-auto-save-disable ()
1333 (remove-hook 'window-configuration-change-hook #'desktop-auto-save-set-timer)
1334 (desktop-auto-save-cancel-timer))
1336 (defun desktop-auto-save ()
1337 "Save the desktop periodically.
1338 Called by the timer created in `desktop-auto-save-set-timer'."
1339 (when (and desktop-save-mode
1340 (integerp desktop-auto-save-timeout)
1341 (> desktop-auto-save-timeout 0)
1342 ;; Avoid desktop saving during lazy loading.
1343 (not desktop-lazy-timer)
1344 ;; Save only to own desktop file.
1345 (eq (emacs-pid) (desktop-owner))
1346 desktop-dirname)
1347 (desktop-save desktop-dirname nil t)))
1349 (defun desktop-auto-save-set-timer ()
1350 "Set the desktop auto-save timer.
1351 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1352 integer, start a new idle timer to call `desktop-auto-save' after that many
1353 seconds of idle time.
1354 This function is called from `window-configuration-change-hook'."
1355 (desktop-auto-save-cancel-timer)
1356 (when (and (integerp desktop-auto-save-timeout)
1357 (> desktop-auto-save-timeout 0))
1358 (setq desktop-auto-save-timer
1359 (run-with-idle-timer desktop-auto-save-timeout nil
1360 'desktop-auto-save))))
1362 (defun desktop-auto-save-cancel-timer ()
1363 (when desktop-auto-save-timer
1364 (cancel-timer desktop-auto-save-timer)
1365 (setq desktop-auto-save-timer nil)))
1367 ;; ----------------------------------------------------------------------------
1368 ;;;###autoload
1369 (defun desktop-revert ()
1370 "Revert to the last loaded desktop."
1371 (interactive)
1372 (unless desktop-dirname
1373 (error "Unknown desktop directory"))
1374 (unless (file-exists-p (desktop-full-file-name))
1375 (error "No desktop file found"))
1376 (desktop-clear)
1377 (desktop-read desktop-dirname))
1379 (defvar desktop-buffer-major-mode)
1380 (defvar desktop-buffer-locals)
1381 (defvar auto-insert) ; from autoinsert.el
1382 ;; ----------------------------------------------------------------------------
1383 (defun desktop-restore-file-buffer (buffer-filename
1384 _buffer-name
1385 _buffer-misc)
1386 "Restore a file buffer."
1387 (when buffer-filename
1388 (if (or (file-exists-p buffer-filename)
1389 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1390 buffer-filename)))
1391 (if desktop-missing-file-warning
1392 (y-or-n-p (concat msg " Re-create buffer? "))
1393 (message "%s" msg)
1394 nil)))
1395 (let* ((auto-insert nil) ; Disable auto insertion
1396 (coding-system-for-read
1397 (or coding-system-for-read
1398 (cdr (assq 'buffer-file-coding-system
1399 desktop-buffer-locals))))
1400 (buf (find-file-noselect buffer-filename :nowarn)))
1401 (condition-case nil
1402 (switch-to-buffer buf)
1403 (error (pop-to-buffer buf)))
1404 (and (not (eq major-mode desktop-buffer-major-mode))
1405 (functionp desktop-buffer-major-mode)
1406 (funcall desktop-buffer-major-mode))
1407 buf)
1408 nil)))
1410 (defun desktop-load-file (function)
1411 "Load the file where auto loaded FUNCTION is defined.
1412 If FUNCTION is not currently defined, guess the library that defines it
1413 and try to load that."
1414 (if (fboundp function)
1415 (autoload-do-load (symbol-function function) function)
1416 ;; Guess that foobar-mode is defined in foobar.
1417 ;; TODO rather than guessing or requiring an autoload, the desktop
1418 ;; file should record the name of the library.
1419 (let ((name (symbol-name function)))
1420 (if (string-match "\\`\\(.*\\)-mode\\'" name)
1421 (with-demoted-errors "Require error in desktop-load-file: %S"
1422 (require (intern (match-string 1 name)) nil t))))))
1424 ;; ----------------------------------------------------------------------------
1425 ;; Create a buffer, load its file, set its mode, ...;
1426 ;; called from Desktop file only.
1428 (defun desktop-create-buffer
1429 (file-version
1430 buffer-filename
1431 buffer-name
1432 buffer-majormode
1433 buffer-minormodes
1434 buffer-point
1435 buffer-mark
1436 buffer-readonly
1437 buffer-misc
1438 &optional
1439 buffer-locals
1440 compacted-vars
1441 &rest _unsupported)
1443 (setq desktop-io-file-version file-version)
1445 (let ((desktop-file-version file-version)
1446 (desktop-buffer-file-name buffer-filename)
1447 (desktop-buffer-name buffer-name)
1448 (desktop-buffer-major-mode buffer-majormode)
1449 (desktop-buffer-minor-modes buffer-minormodes)
1450 (desktop-buffer-point buffer-point)
1451 (desktop-buffer-mark buffer-mark)
1452 (desktop-buffer-read-only buffer-readonly)
1453 (desktop-buffer-misc buffer-misc)
1454 (desktop-buffer-locals buffer-locals))
1455 ;; To make desktop files with relative file names possible, we cannot
1456 ;; allow `default-directory' to change. Therefore we save current buffer.
1457 (save-current-buffer
1458 ;; Give major mode module a chance to add a handler.
1459 (desktop-load-file desktop-buffer-major-mode)
1460 (let ((buffer-list (buffer-list))
1461 (result
1462 (condition-case-unless-debug err
1463 (funcall (or (cdr (assq desktop-buffer-major-mode
1464 desktop-buffer-mode-handlers))
1465 'desktop-restore-file-buffer)
1466 desktop-buffer-file-name
1467 desktop-buffer-name
1468 desktop-buffer-misc)
1469 (error
1470 (message "Desktop: Can't load buffer %s: %s"
1471 desktop-buffer-name
1472 (error-message-string err))
1473 (when desktop-missing-file-warning (sit-for 1))
1474 nil))))
1475 (if (bufferp result)
1476 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1477 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1478 (setq result nil))
1479 ;; Restore buffer list order with new buffer at end. Don't change
1480 ;; the order for old desktop files (old desktop module behavior).
1481 (unless (< desktop-file-version 206)
1482 (dolist (buf buffer-list)
1483 (and (buffer-live-p buf)
1484 (bury-buffer buf)))
1485 (when result (bury-buffer result)))
1486 (when result
1487 (unless (or desktop-first-buffer (< desktop-file-version 206))
1488 (setq desktop-first-buffer result))
1489 (set-buffer result)
1490 (unless (equal (buffer-name) desktop-buffer-name)
1491 (rename-buffer desktop-buffer-name t))
1492 ;; minor modes
1493 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1494 (auto-fill-mode 1))
1495 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1496 (auto-fill-mode 0))
1498 (dolist (minor-mode desktop-buffer-minor-modes)
1499 ;; Give minor mode module a chance to add a handler.
1500 (desktop-load-file minor-mode)
1501 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1502 (if handler
1503 (funcall handler desktop-buffer-locals)
1504 (when (functionp minor-mode)
1505 (funcall minor-mode 1)))))))
1506 ;; Even though point and mark are non-nil when written by
1507 ;; `desktop-save', they may be modified by handlers wanting to set
1508 ;; point or mark themselves.
1509 (when desktop-buffer-point
1510 (goto-char
1511 (condition-case err
1512 ;; Evaluate point. Thus point can be something like
1513 ;; '(search-forward ...
1514 (eval desktop-buffer-point)
1515 (error (message "%s" (error-message-string err)) 1))))
1516 (when desktop-buffer-mark
1517 (if (consp desktop-buffer-mark)
1518 (progn
1519 (move-marker (mark-marker) (car desktop-buffer-mark))
1520 (if (car (cdr desktop-buffer-mark))
1521 (activate-mark 'dont-touch-tmm)))
1522 (move-marker (mark-marker) desktop-buffer-mark)))
1523 ;; Never override file system if the file really is read-only marked.
1524 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1525 (dolist (this desktop-buffer-locals)
1526 (if (consp this)
1527 ;; An entry of this form `(symbol . value)'.
1528 (progn
1529 (make-local-variable (car this))
1530 (set (car this) (cdr this)))
1531 ;; An entry of the form `symbol'.
1532 (make-local-variable this)
1533 (makunbound this)))
1534 ;; adjust `buffer-display-time' for the downtime. e.g.,
1535 ;; * if `buffer-display-time' was 8:00
1536 ;; * and emacs stopped at `desktop-file-modtime' == 11:00
1537 ;; * and we are loading the desktop file at (current-time) 12:30,
1538 ;; -> then we restore `buffer-display-time' as 9:30,
1539 ;; for the sake of `clean-buffer-list': preserving the invariant
1540 ;; "how much time the user spent in Emacs without looking at this buffer".
1541 (setq buffer-display-time
1542 (if buffer-display-time
1543 (time-add buffer-display-time
1544 (time-subtract nil desktop-file-modtime))
1545 (current-time)))
1546 (unless (< desktop-file-version 208) ; Don't misinterpret any old custom args
1547 (dolist (record compacted-vars)
1548 (let*
1549 ((var (car record))
1550 (deser-fun (nth 2 (assq var desktop-var-serdes-funs))))
1551 (if deser-fun (set var (funcall deser-fun (cadr record))))))))
1552 result))))
1554 ;; ----------------------------------------------------------------------------
1555 ;; Backward compatibility -- update parameters to 205 standards.
1556 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1557 mim pt mk ro tl fc cfs cr buffer-misc)
1558 (desktop-create-buffer 205 buffer-filename buffer-name
1559 buffer-majormode (cdr mim) pt mk ro
1560 buffer-misc
1561 (list (cons 'truncate-lines tl)
1562 (cons 'fill-column fc)
1563 (cons 'case-fold-search cfs)
1564 (cons 'case-replace cr)
1565 (cons 'overwrite-mode (car mim)))))
1567 (defun desktop-append-buffer-args (&rest args)
1568 "Append ARGS at end of `desktop-buffer-args-list'.
1569 ARGS must be an argument list for `desktop-create-buffer'."
1570 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1571 (unless desktop-lazy-timer
1572 (setq desktop-lazy-timer
1573 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1575 (defun desktop-lazy-create-buffer ()
1576 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1577 (when desktop-buffer-args-list
1578 (let* ((remaining (length desktop-buffer-args-list))
1579 (args (pop desktop-buffer-args-list))
1580 (buffer-name (nth 2 args))
1581 (msg (format "Desktop lazily opening %s (%s remaining)..."
1582 buffer-name remaining)))
1583 (when desktop-lazy-verbose
1584 (message "%s" msg))
1585 (let ((desktop-first-buffer nil)
1586 (desktop-buffer-ok-count 0)
1587 (desktop-buffer-fail-count 0))
1588 (apply #'desktop-create-buffer args)
1589 (run-hooks 'desktop-delay-hook)
1590 (setq desktop-delay-hook nil)
1591 (bury-buffer (get-buffer buffer-name))
1592 (when desktop-lazy-verbose
1593 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1595 (defun desktop-idle-create-buffers ()
1596 "Create buffers until the user does something, then stop.
1597 If there are no buffers left to create, kill the timer."
1598 (let ((repeat 1))
1599 (while (and repeat desktop-buffer-args-list)
1600 (save-window-excursion
1601 (desktop-lazy-create-buffer))
1602 (setq repeat (sit-for 0.2))
1603 (unless desktop-buffer-args-list
1604 (cancel-timer desktop-lazy-timer)
1605 (setq desktop-lazy-timer nil)
1606 (message "Lazy desktop load complete")
1607 (sit-for 3)
1608 (message "")))))
1610 (defun desktop-lazy-complete ()
1611 "Run the desktop load to completion."
1612 (interactive)
1613 (let ((desktop-lazy-verbose t))
1614 (while desktop-buffer-args-list
1615 (save-window-excursion
1616 (desktop-lazy-create-buffer)))
1617 (message "Lazy desktop load complete")))
1619 (defun desktop-lazy-abort ()
1620 "Abort lazy loading of the desktop."
1621 (interactive)
1622 (when desktop-lazy-timer
1623 (cancel-timer desktop-lazy-timer)
1624 (setq desktop-lazy-timer nil))
1625 (when desktop-buffer-args-list
1626 (setq desktop-buffer-args-list nil)
1627 (when (called-interactively-p 'interactive)
1628 (message "Lazy desktop load aborted"))))
1630 ;; ----------------------------------------------------------------------------
1631 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1632 ;; command line, we do the rest of what it takes to use desktop, but do it
1633 ;; after finishing loading the init file.
1634 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1635 ;; functions are processed after `after-init-hook'.
1636 (add-hook
1637 'after-init-hook
1638 (lambda ()
1639 (let ((key "--no-desktop"))
1640 (when (member key command-line-args)
1641 (setq command-line-args (delete key command-line-args))
1642 (desktop-save-mode 0)))
1643 (when desktop-save-mode
1644 (desktop-read)
1645 (setq inhibit-startup-screen t))))
1647 (provide 'desktop)
1649 ;;; desktop.el ends here