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