* lisp/mail/footnote.el (footnote-align-to-fn-text): New config var
[emacs.git] / lisp / desktop.el
blob5257c609dde3b19c1d3c062f48936219bd3151a0
1 ;;; desktop.el --- save partial status of Emacs when killed -*- lexical-binding: t -*-
3 ;; Copyright (C) 1993-1995, 1997, 2000-2017 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 :type '(choice (const :tag "None" nil)
398 regexp)
399 :group 'desktop)
401 ;; We skip TAGS files to save time (tags-file-name is saved instead).
402 (defcustom desktop-modes-not-to-save
403 '(tags-table-mode)
404 "List of major modes whose buffers should not be saved."
405 :type '(repeat symbol)
406 :group 'desktop)
408 (defcustom desktop-restore-frames t
409 "When non-nil, save and restore the frame and window configuration.
410 See related options `desktop-restore-reuses-frames',
411 `desktop-restore-in-current-display', and `desktop-restore-forces-onscreen'."
412 :type 'boolean
413 :group 'desktop
414 :version "24.4")
416 (defcustom desktop-restore-in-current-display t
417 "Controls how restoring of frames treats displays.
418 If t, restores frames into the current display.
419 If nil, restores frames into their original displays (if possible).
420 If `delete', deletes frames on other displays instead of restoring them."
421 :type '(choice (const :tag "Restore in current display" t)
422 (const :tag "Restore in original display" nil)
423 (const :tag "Delete frames in other displays" delete))
424 :group 'desktop
425 :version "24.4")
427 (defcustom desktop-restore-forces-onscreen t
428 "If t, restores frames that are fully offscreen onscreen instead.
429 If `all', also restores frames that are partially offscreen onscreen.
431 Note that checking of frame boundaries is only approximate.
432 It can fail to reliably detect frames whose onscreen/offscreen state
433 depends on a few pixels, especially near the right / bottom borders
434 of the screen."
435 :type '(choice (const :tag "Only fully offscreen frames" t)
436 (const :tag "Also partially offscreen frames" all)
437 (const :tag "Do not force frames onscreen" nil))
438 :group 'desktop
439 :version "24.4")
441 (defcustom desktop-restore-reuses-frames t
442 "If t, restoring frames reuses existing frames.
443 If nil, deletes existing frames.
444 If `keep', keeps existing frames and does not reuse them."
445 :type '(choice (const :tag "Reuse existing frames" t)
446 (const :tag "Delete existing frames" nil)
447 (const :tag "Keep existing frames" :keep))
448 :group 'desktop
449 :version "24.4")
451 (defcustom desktop-file-name-format 'absolute
452 "Format in which desktop file names should be saved.
453 Possible values are:
454 absolute -- Absolute file name.
455 tilde -- Relative to ~.
456 local -- Relative to directory of desktop file."
457 :type '(choice (const absolute) (const tilde) (const local))
458 :group 'desktop
459 :version "22.1")
461 (defcustom desktop-restore-eager t
462 "Number of buffers to restore immediately.
463 Remaining buffers are restored lazily (when Emacs is idle).
464 If value is t, all buffers are restored immediately."
465 :type '(choice (const t) integer)
466 :group 'desktop
467 :version "22.1")
469 (defcustom desktop-lazy-verbose t
470 "Verbose reporting of lazily created buffers."
471 :type 'boolean
472 :group 'desktop
473 :version "22.1")
475 (defcustom desktop-lazy-idle-delay 5
476 "Idle delay before starting to create buffers.
477 See `desktop-restore-eager'."
478 :type 'integer
479 :group 'desktop
480 :version "22.1")
482 ;;;###autoload
483 (defvar-local desktop-save-buffer nil
484 "When non-nil, save buffer status in desktop file.
486 If the value is a function, it is called by `desktop-save' with argument
487 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
488 file along with the state of the buffer for which it was called.
490 When file names are returned, they should be formatted using the call
491 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
493 Later, when `desktop-read' evaluates the desktop file, auxiliary information
494 is passed as the argument DESKTOP-BUFFER-MISC to functions in
495 `desktop-buffer-mode-handlers'.")
496 (make-obsolete-variable 'desktop-buffer-modes-to-save
497 'desktop-save-buffer "22.1")
498 (make-obsolete-variable 'desktop-buffer-misc-functions
499 'desktop-save-buffer "22.1")
501 ;;;###autoload
502 (defvar desktop-buffer-mode-handlers nil
503 "Alist of major mode specific functions to restore a desktop buffer.
504 Functions listed are called by `desktop-create-buffer' when `desktop-read'
505 evaluates the desktop file. List elements must have the form
507 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
509 Buffers with a major mode not specified here, are restored by the default
510 handler `desktop-restore-file-buffer'.
512 Handlers are called with argument list
514 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
516 Furthermore, they may use the following variables:
518 `desktop-file-version'
519 `desktop-buffer-major-mode'
520 `desktop-buffer-minor-modes'
521 `desktop-buffer-point'
522 `desktop-buffer-mark'
523 `desktop-buffer-read-only'
524 `desktop-buffer-locals'
526 If a handler returns a buffer, then the saved mode settings
527 and variable values for that buffer are copied into it.
529 Modules that define a major mode that needs a special handler should contain
530 code like
532 (defun foo-restore-desktop-buffer
534 (add-to-list \\='desktop-buffer-mode-handlers
535 \\='(foo-mode . foo-restore-desktop-buffer))
537 The major mode function must either be autoloaded, or of the form
538 \"foobar-mode\" and defined in library \"foobar\", so that desktop
539 can guess how to load the mode's definition.")
541 ;;;###autoload
542 (put 'desktop-buffer-mode-handlers 'risky-local-variable t)
543 (make-obsolete-variable 'desktop-buffer-handlers
544 'desktop-buffer-mode-handlers "22.1")
546 (defcustom desktop-minor-mode-table
547 '((auto-fill-function auto-fill-mode)
548 (defining-kbd-macro nil)
549 (isearch-mode nil)
550 (vc-mode nil)
551 (vc-dired-mode nil)
552 (erc-track-minor-mode nil)
553 (savehist-mode nil))
554 "Table mapping minor mode variables to minor mode functions.
555 Each entry has the form (NAME RESTORE-FUNCTION).
556 NAME is the name of the buffer-local variable indicating that the minor
557 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
558 RESTORE-FUNCTION nil means don't try to restore the minor mode.
559 Only minor modes for which the name of the buffer-local variable
560 and the name of the minor mode function are different have to be added to
561 this table. See also `desktop-minor-mode-handlers'."
562 :type '(alist :key-type (symbol :tag "Minor mode")
563 :value-type (list :tag "Restore function"
564 (choice (const nil) function)))
565 :group 'desktop)
567 ;;;###autoload
568 (defvar desktop-minor-mode-handlers nil
569 "Alist of functions to restore non-standard minor modes.
570 Functions are called by `desktop-create-buffer' to restore minor modes.
571 List elements must have the form
573 (MINOR-MODE . RESTORE-FUNCTION).
575 Minor modes not specified here, are restored by the standard minor mode
576 function.
578 Handlers are called with argument list
580 (DESKTOP-BUFFER-LOCALS)
582 Furthermore, they may use the following variables:
584 `desktop-file-version'
585 `desktop-buffer-file-name'
586 `desktop-buffer-name'
587 `desktop-buffer-major-mode'
588 `desktop-buffer-minor-modes'
589 `desktop-buffer-point'
590 `desktop-buffer-mark'
591 `desktop-buffer-read-only'
592 `desktop-buffer-misc'
594 When a handler is called, the buffer has been created and the major mode has
595 been set, but local variables listed in desktop-buffer-locals has not yet been
596 created and set.
598 Modules that define a minor mode that needs a special handler should contain
599 code like
601 (defun foo-desktop-restore
603 (add-to-list \\='desktop-minor-mode-handlers
604 \\='(foo-mode . foo-desktop-restore))
606 The minor mode function must either be autoloaded, or of the form
607 \"foobar-mode\" and defined in library \"foobar\", so that desktop
608 can guess how to load the mode's definition.
610 See also `desktop-minor-mode-table'.")
612 ;;;###autoload
613 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
615 ;; ----------------------------------------------------------------------------
616 (defvar desktop-dirname nil
617 "The directory in which the desktop file should be saved.")
619 (defun desktop-full-file-name (&optional dirname)
620 "Return the full name of the desktop file in DIRNAME.
621 DIRNAME omitted or nil means use `desktop-dirname'."
622 (expand-file-name desktop-base-file-name (or dirname desktop-dirname)))
624 (defun desktop-full-lock-name (&optional dirname)
625 "Return the full name of the desktop lock file in DIRNAME.
626 DIRNAME omitted or nil means use `desktop-dirname'."
627 (expand-file-name desktop-base-lock-name (or dirname desktop-dirname)))
629 (defconst desktop-header
630 ";; --------------------------------------------------------------------------
631 ;; Desktop File for Emacs
632 ;; --------------------------------------------------------------------------
633 " "*Header to place in Desktop file.")
635 (defvar desktop-delay-hook nil
636 "Hooks run after all buffers are loaded; intended for internal use.")
638 (defvar desktop-file-checksum nil
639 "Checksum of the last auto-saved contents of the desktop file.
640 Used to avoid writing contents unchanged between auto-saves.")
642 (defvar desktop-saved-frameset nil
643 "Saved state of all frames.
644 Only valid during frame saving & restoring; intended for internal use.")
646 ;; ----------------------------------------------------------------------------
647 ;; Desktop file conflict detection
648 (defvar desktop-file-modtime nil
649 "When the desktop file was last modified to the knowledge of this Emacs.
650 Used to detect desktop file conflicts.")
652 (defvar desktop-var-serdes-funs
653 (list (list
654 'mark-ring
655 (lambda (mr)
656 (mapcar #'marker-position mr))
657 (lambda (mr)
658 (mapcar #'copy-marker mr))))
659 "Table of serialization/deserialization functions for variables.
660 Each record is a list of form: (var serializer deserializer).
661 These records can be freely reordered, deleted, or new ones added.
662 However, for compatibility, don't modify the functions for existing records.")
664 (defun desktop-owner (&optional dirname)
665 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
666 Return nil if no desktop file found or no Emacs process is using it.
667 DIRNAME omitted or nil means use `desktop-dirname'."
668 (let (owner
669 (file (desktop-full-lock-name dirname)))
670 (and (file-exists-p file)
671 (ignore-errors
672 (with-temp-buffer
673 (insert-file-contents-literally file)
674 (goto-char (point-min))
675 (setq owner (read (current-buffer)))
676 (integerp owner)))
677 owner)))
679 (defun desktop-claim-lock (&optional dirname)
680 "Record this Emacs process as the owner of the desktop file in DIRNAME.
681 DIRNAME omitted or nil means use `desktop-dirname'."
682 (write-region (number-to-string (emacs-pid)) nil
683 (desktop-full-lock-name dirname)))
685 (defun desktop-release-lock (&optional dirname)
686 "Remove the lock file for the desktop in DIRNAME.
687 DIRNAME omitted or nil means use `desktop-dirname'."
688 (let ((file (desktop-full-lock-name dirname)))
689 (when (file-exists-p file) (delete-file file))))
691 ;; ----------------------------------------------------------------------------
692 (defun desktop-truncate (list n)
693 "Truncate LIST to at most N elements destructively."
694 (let ((here (nthcdr (1- n) list)))
695 (when (consp here)
696 (setcdr here nil))))
698 ;; ----------------------------------------------------------------------------
699 ;;;###autoload
700 (defun desktop-clear ()
701 "Empty the Desktop.
702 This kills all buffers except for internal ones and those with names matched by
703 a regular expression in the list `desktop-clear-preserve-buffers'.
704 Furthermore, it clears the variables listed in `desktop-globals-to-clear'.
705 When called interactively and `desktop-restore-frames' is non-nil, it also
706 deletes all frames except the selected one (and its minibuffer frame,
707 if different)."
708 (interactive)
709 (desktop-lazy-abort)
710 (setq desktop-io-file-version nil)
711 (dolist (var desktop-globals-to-clear)
712 (if (symbolp var)
713 (set-default var nil)
714 (set-default var (eval (cdr var)))))
715 (let ((preserve-regexp (concat "^\\("
716 (mapconcat (lambda (regexp)
717 (concat "\\(" regexp "\\)"))
718 desktop-clear-preserve-buffers
719 "\\|")
720 "\\)$")))
721 (dolist (buffer (buffer-list))
722 (let ((bufname (buffer-name buffer)))
723 (unless (or (eq (aref bufname 0) ?\s) ;; Don't kill internal buffers
724 (string-match-p preserve-regexp bufname))
725 (kill-buffer buffer)))))
726 (delete-other-windows)
727 (when (and desktop-restore-frames
728 ;; Non-interactive calls to desktop-clear happen before desktop-read
729 ;; which already takes care of frame restoration and deletion.
730 (called-interactively-p 'any))
731 (let* ((this (selected-frame))
732 (mini (window-frame (minibuffer-window this)))) ; in case they differ
733 (dolist (frame (sort (frame-list) #'frameset-minibufferless-first-p))
734 (condition-case err
735 (unless (or (eq frame this)
736 (eq frame mini)
737 ;; Don't delete daemon's initial frame, or
738 ;; we'll never be able to close the last
739 ;; client's frame (Bug#26912).
740 (if (daemonp) (not (frame-parameter frame 'client)))
741 (frame-parameter frame 'desktop-dont-clear))
742 (delete-frame frame))
743 (error
744 (delay-warning 'desktop (error-message-string err))))))))
746 ;; ----------------------------------------------------------------------------
747 (unless noninteractive
748 (add-hook 'kill-emacs-hook 'desktop-kill))
750 (defun desktop-kill ()
751 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
752 If the desktop should be saved and `desktop-dirname'
753 is nil, ask the user where to save the desktop."
754 (when (and desktop-save-mode
755 (let ((exists (file-exists-p (desktop-full-file-name))))
756 (or (eq desktop-save t)
757 (and exists (eq desktop-save 'if-exists))
758 ;; If it exists, but we aren't using it, we are going
759 ;; to ask for a new directory below.
760 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
761 (and
762 (or (memq desktop-save '(ask ask-if-new))
763 (and exists (eq desktop-save 'ask-if-exists)))
764 (y-or-n-p "Save desktop? ")))))
765 (unless desktop-dirname
766 (setq desktop-dirname
767 (file-name-as-directory
768 (expand-file-name
769 (read-directory-name "Directory for desktop file: " nil nil t)))))
770 (condition-case err
771 (desktop-save desktop-dirname t)
772 (file-error
773 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
774 (signal (car err) (cdr err))))))
775 ;; If we own it, we don't anymore.
776 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
778 ;; ----------------------------------------------------------------------------
779 (defun desktop-list* (&rest args)
780 (and args (apply #'cl-list* args)))
782 ;; ----------------------------------------------------------------------------
783 (defun desktop-buffer-info (buffer)
784 "Return information describing BUFFER.
785 This function is not pure, as BUFFER is made current with
786 `set-buffer'.
788 Returns a list of all the necessary information to recreate the
789 buffer, which is (in order):
791 `uniquify-buffer-base-name';
792 `buffer-file-name';
793 `buffer-name';
794 `major-mode';
795 list of minor-modes,;
796 `point';
797 `mark';
798 `buffer-read-only';
799 auxiliary information given by `desktop-save-buffer';
800 local variables;
801 auxiliary information given by `desktop-var-serdes-funs'."
802 (set-buffer buffer)
804 ;; base name of the buffer; replaces the buffer name if managed by uniquify
805 ,(and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
806 ;; basic information
807 ,(desktop-file-name (buffer-file-name) desktop-dirname)
808 ,(buffer-name)
809 ,major-mode
810 ;; minor modes
811 ,(let (ret)
812 (dolist (minor-mode (mapcar #'car minor-mode-alist) ret)
813 (and (boundp minor-mode)
814 (symbol-value minor-mode)
815 (let* ((special (assq minor-mode desktop-minor-mode-table))
816 (value (cond (special (cadr special))
817 ((functionp minor-mode) minor-mode))))
818 (when value (cl-pushnew value ret))))))
819 ;; point and mark, and read-only status
820 ,(point)
821 ,(list (mark t) mark-active)
822 ,buffer-read-only
823 ;; auxiliary information
824 ,(when (functionp desktop-save-buffer)
825 (funcall desktop-save-buffer desktop-dirname))
826 ;; local variables
827 ,(let ((loclist (buffer-local-variables))
828 (ll nil))
829 (dolist (local desktop-locals-to-save)
830 (let ((here (assq local loclist)))
831 (cond (here
832 (push here ll))
833 ((member local loclist)
834 (push local ll)))))
836 ,@(when (>= desktop-io-file-version 208)
837 (list
838 (mapcar (lambda (record)
839 (let ((var (car record)))
840 (list var
841 (funcall (cadr record) (symbol-value var)))))
842 desktop-var-serdes-funs)))))
844 ;; ----------------------------------------------------------------------------
845 (defun desktop--v2s (value)
846 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
847 SEXP is an sexp that when evaluated yields VALUE.
848 QUOTE may be `may' (value may be quoted),
849 `must' (value must be quoted), or nil (value must not be quoted)."
850 (cond
851 ((or (numberp value) (null value) (eq t value) (keywordp value))
852 (cons 'may value))
853 ((stringp value)
854 (let ((copy (copy-sequence value)))
855 (set-text-properties 0 (length copy) nil copy)
856 ;; Get rid of text properties because we cannot read them.
857 (cons 'may copy)))
858 ((symbolp value)
859 (cons 'must value))
860 ((vectorp value)
861 (let* ((pass1 (mapcar #'desktop--v2s value))
862 (special (assq nil pass1)))
863 (if special
864 (cons nil `(vector
865 ,@(mapcar (lambda (el)
866 (if (eq (car el) 'must)
867 `',(cdr el) (cdr el)))
868 pass1)))
869 (cons 'may `[,@(mapcar #'cdr pass1)]))))
870 ((consp value)
871 (let ((p value)
872 newlist
873 use-list*)
874 (while (consp p)
875 (let ((q.sexp (desktop--v2s (car p))))
876 (push q.sexp newlist))
877 (setq p (cdr p)))
878 (when p
879 (let ((last (desktop--v2s p)))
880 (setq use-list* t)
881 (push last newlist)))
882 (if (assq nil newlist)
883 (cons nil
884 `(,(if use-list* 'desktop-list* 'list)
885 ,@(mapcar (lambda (el)
886 (if (eq (car el) 'must)
887 `',(cdr el) (cdr el)))
888 (nreverse newlist))))
889 (cons 'must
890 `(,@(mapcar #'cdr
891 (nreverse (if use-list* (cdr newlist) newlist)))
892 ,@(if use-list* (cdar newlist)))))))
893 ((subrp value)
894 (cons nil `(symbol-function
895 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
896 ((markerp value)
897 (let ((pos (marker-position value))
898 (buf (buffer-name (marker-buffer value))))
899 (cons nil
900 `(let ((mk (make-marker)))
901 (add-hook 'desktop-delay-hook
902 `(lambda ()
903 (set-marker ,mk ,,pos (get-buffer ,,buf))))
904 mk))))
905 (t ; Save as text.
906 (cons 'may "Unprintable entity"))))
908 ;; ----------------------------------------------------------------------------
909 (defun desktop-value-to-string (value)
910 "Convert VALUE to a string that when read evaluates to the same value.
911 Not all types of values are supported."
912 (let* ((print-escape-newlines t)
913 (print-length nil)
914 (print-level nil)
915 (float-output-format nil)
916 (quote.sexp (desktop--v2s value))
917 (quote (car quote.sexp))
918 (print-quoted t)
919 (txt (prin1-to-string (cdr quote.sexp))))
920 (if (eq quote 'must)
921 (concat "'" txt)
922 txt)))
924 ;; ----------------------------------------------------------------------------
925 (defun desktop-outvar (varspec)
926 "Output a setq statement for variable VAR to the desktop file.
927 The argument VARSPEC may be the variable name VAR (a symbol),
928 or a cons cell of the form (VAR . MAX-SIZE),
929 which means to truncate VAR's value to at most MAX-SIZE elements
930 \(if the value is a list) before saving the value."
931 (let (var size)
932 (if (consp varspec)
933 (setq var (car varspec) size (cdr varspec))
934 (setq var varspec))
935 (when (boundp var)
936 (when (and (integerp size)
937 (> size 0)
938 (listp (eval var)))
939 (desktop-truncate (eval var) size))
940 (insert "(setq "
941 (symbol-name var)
943 (desktop-value-to-string (symbol-value var))
944 ")\n"))))
946 ;; ----------------------------------------------------------------------------
947 (defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
948 "Return t if buffer should have its state saved in the desktop file.
949 FILENAME is the visited file name, BUFNAME is the buffer name, and
950 MODE is the major mode.
951 \n\(fn FILENAME BUFNAME MODE)"
952 (let ((case-fold-search nil)
953 (no-regexp-to-check (not (stringp desktop-files-not-to-save)))
954 dired-skip)
955 (and (or filename
956 (not (stringp desktop-buffers-not-to-save))
957 (not (string-match-p desktop-buffers-not-to-save bufname)))
958 (not (memq mode desktop-modes-not-to-save))
959 (or (and filename
960 (or no-regexp-to-check
961 (not (string-match-p desktop-files-not-to-save filename))))
962 (and (memq mode '(dired-mode vc-dir-mode))
963 (or no-regexp-to-check
964 (not (setq dired-skip
965 (with-current-buffer bufname
966 (string-match-p desktop-files-not-to-save
967 default-directory))))))
968 (and (null filename)
969 (null dired-skip) ; bug#5755
970 (with-current-buffer bufname desktop-save-buffer)))
971 t)))
973 ;; ----------------------------------------------------------------------------
974 (defun desktop-file-name (filename dirname)
975 "Convert FILENAME to format specified in `desktop-file-name-format'.
976 DIRNAME must be the directory in which the desktop file will be saved."
977 (cond
978 ((not filename) nil)
979 ((eq desktop-file-name-format 'tilde)
980 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
981 (cond
982 ((file-name-absolute-p relative-name) relative-name)
983 ((string= "./" relative-name) "~/")
984 ((string= "." relative-name) "~")
985 (t (concat "~/" relative-name)))))
986 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
987 (t (expand-file-name filename))))
990 ;; ----------------------------------------------------------------------------
991 (defun desktop--check-dont-save (frame)
992 (not (frame-parameter frame 'desktop-dont-save)))
994 (defconst desktop--app-id `(desktop . ,desktop-file-version))
996 (defun desktop-save-frameset ()
997 "Save the state of existing frames in `desktop-saved-frameset'.
998 Frames with a non-nil `desktop-dont-save' parameter are not saved."
999 (setq desktop-saved-frameset
1000 (and desktop-restore-frames
1001 (frameset-save nil
1002 :app desktop--app-id
1003 :name (concat user-login-name "@" (system-name))
1004 :predicate #'desktop--check-dont-save))))
1006 ;;;###autoload
1007 (defun desktop-save (dirname &optional release only-if-changed version)
1008 "Save the desktop in a desktop file.
1009 Parameter DIRNAME specifies where to save the desktop file.
1010 Optional parameter RELEASE says whether we're done with this
1011 desktop. If ONLY-IF-CHANGED is non-nil, compare the current
1012 desktop information to that in the desktop file, and if the
1013 desktop information has not changed since it was last saved then
1014 do not rewrite the file.
1016 This function can save the desktop in either format version
1017 208 (which only Emacs 25.1 and later can read) or version
1018 206 (which is readable by any Emacs from version 22.1 onwards).
1019 By default, it will use the same format the desktop file had when
1020 it was last saved, or version 208 when writing a fresh desktop
1021 file.
1023 To upgrade a version 206 file to version 208, call this command
1024 explicitly with a bare prefix argument: C-u M-x desktop-save.
1025 You are recommended to do this once you have firmly upgraded to
1026 Emacs 25.1 (or later). To downgrade a version 208 file to version
1027 206, use a double command prefix: C-u C-u M-x desktop-save.
1028 Confirmation will be requested in either case. In a non-interactive
1029 call, VERSION can be given as an integer, either 206 or 208, which
1030 will be accepted as the format version in which to save the file
1031 without further confirmation."
1032 (interactive (list
1033 ;; Or should we just use (car desktop-path)?
1034 (let ((default (if (member "." desktop-path)
1035 default-directory
1036 user-emacs-directory)))
1037 (read-directory-name "Directory to save desktop file in: "
1038 default default t))
1041 current-prefix-arg))
1042 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
1043 (save-excursion
1044 (let ((eager desktop-restore-eager)
1045 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
1046 (when
1047 (or (not new-modtime) ; nothing to overwrite
1048 (equal desktop-file-modtime new-modtime)
1049 (yes-or-no-p (if desktop-file-modtime
1050 (if (time-less-p desktop-file-modtime
1051 new-modtime)
1052 "Desktop file is more recent than the one loaded. Save anyway? "
1053 "Desktop file isn't the one loaded. Overwrite it? ")
1054 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
1055 (unless release (error "Desktop file conflict")))
1057 ;; If we're done with it, release the lock.
1058 ;; Otherwise, claim it if it's unclaimed or if we created it.
1059 (if release
1060 (desktop-release-lock)
1061 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
1063 ;; What format are we going to write the file in?
1064 (setq desktop-io-file-version
1065 (cond
1066 ((equal version '(4))
1067 (if (or (eq desktop-io-file-version 208)
1068 (yes-or-no-p "Save desktop file in format 208 \
1069 \(Readable by Emacs 25.1 and later only)? "))
1071 (or desktop-io-file-version desktop-native-file-version)))
1072 ((equal version '(16))
1073 (if (or (eq desktop-io-file-version 206)
1074 (yes-or-no-p "Save desktop file in format 206 \
1075 \(Readable by all Emacs versions since 22.1)? "))
1077 (or desktop-io-file-version desktop-native-file-version)))
1078 ((memq version '(206 208))
1079 version)
1080 ((null desktop-io-file-version) ; As yet, no desktop file exists.
1081 desktop-native-file-version)
1083 desktop-io-file-version)))
1085 (with-temp-buffer
1086 (insert
1087 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
1088 desktop-header
1089 ";; Created " (current-time-string) "\n"
1090 ";; Desktop file format version " (format "%d" desktop-io-file-version) "\n"
1091 ";; Emacs version " emacs-version "\n")
1092 (save-excursion (run-hooks 'desktop-save-hook))
1093 (goto-char (point-max))
1094 (insert "\n;; Global section:\n")
1095 ;; Called here because we save the window/frame state as a global
1096 ;; variable for compatibility with previous Emacsen.
1097 (desktop-save-frameset)
1098 (unless (memq 'desktop-saved-frameset desktop-globals-to-save)
1099 (desktop-outvar 'desktop-saved-frameset))
1100 (mapc (function desktop-outvar) desktop-globals-to-save)
1101 (setq desktop-saved-frameset nil) ; after saving desktop-globals-to-save
1102 (when (memq 'kill-ring desktop-globals-to-save)
1103 (insert
1104 "(setq kill-ring-yank-pointer (nthcdr "
1105 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
1106 " kill-ring))\n"))
1108 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
1109 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
1110 (let ((base (pop l)))
1111 (when (apply 'desktop-save-buffer-p l)
1112 (insert "("
1113 (if (or (not (integerp eager))
1114 (if (zerop eager)
1116 (setq eager (1- eager))))
1117 "desktop-create-buffer"
1118 "desktop-append-buffer-args")
1120 (format "%d" desktop-io-file-version))
1121 ;; If there's a non-empty base name, we save it instead of the buffer name
1122 (when (and base (not (string= base "")))
1123 (setcar (nthcdr 1 l) base))
1124 (dolist (e l)
1125 (insert "\n " (desktop-value-to-string e)))
1126 (insert ")\n\n"))))
1128 (setq default-directory desktop-dirname)
1129 ;; When auto-saving, avoid writing if nothing has changed since the last write.
1130 (let* ((beg (and only-if-changed
1131 (save-excursion
1132 (goto-char (point-min))
1133 ;; Don't check the header with changing timestamp
1134 (and (search-forward "Global section" nil t)
1135 ;; Also skip the timestamp in desktop-saved-frameset
1136 ;; if it's saved in the first non-header line
1137 (search-forward "desktop-saved-frameset"
1138 (line-beginning-position 3) t)
1139 ;; This is saved after the timestamp
1140 (search-forward (format "%S" desktop--app-id) nil t))
1141 (point))))
1142 (checksum (and beg (md5 (current-buffer) beg (point-max) 'emacs-mule))))
1143 (unless (and checksum (equal checksum desktop-file-checksum))
1144 (let ((coding-system-for-write 'emacs-mule))
1145 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
1146 (setq desktop-file-checksum checksum)
1147 ;; We remember when it was modified (which is presumably just now).
1148 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
1150 ;; ----------------------------------------------------------------------------
1151 ;;;###autoload
1152 (defun desktop-remove ()
1153 "Delete desktop file in `desktop-dirname'.
1154 This function also sets `desktop-dirname' to nil."
1155 (interactive)
1156 (when desktop-dirname
1157 (let ((filename (desktop-full-file-name)))
1158 (setq desktop-dirname nil)
1159 (when (file-exists-p filename)
1160 (delete-file filename)))))
1162 (defvar desktop-buffer-args-list nil
1163 "List of args for `desktop-create-buffer'.")
1165 (defvar desktop-lazy-timer nil)
1167 ;; ----------------------------------------------------------------------------
1168 (defun desktop-restoring-frameset-p ()
1169 "True if calling `desktop-restore-frameset' will actually restore it."
1170 (and desktop-restore-frames desktop-saved-frameset (display-graphic-p) t))
1172 (defun desktop-restore-frameset ()
1173 "Restore the state of a set of frames.
1174 This function depends on the value of `desktop-saved-frameset'
1175 being set (usually, by reading it from the desktop)."
1176 (when (desktop-restoring-frameset-p)
1177 (frameset-restore desktop-saved-frameset
1178 :reuse-frames (eq desktop-restore-reuses-frames t)
1179 :cleanup-frames (not (eq desktop-restore-reuses-frames 'keep))
1180 :force-display desktop-restore-in-current-display
1181 :force-onscreen desktop-restore-forces-onscreen)))
1183 ;; Just to silence the byte compiler.
1184 ;; Dynamically bound in `desktop-read'.
1185 (defvar desktop-first-buffer)
1186 (defvar desktop-buffer-ok-count)
1187 (defvar desktop-buffer-fail-count)
1189 ;; FIXME Interactively, this should have the option to prompt for dirname.
1190 ;;;###autoload
1191 (defun desktop-read (&optional dirname)
1192 "Read and process the desktop file in directory DIRNAME.
1193 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1194 directories listed in `desktop-path'. If a desktop file is found, it
1195 is processed and `desktop-after-read-hook' is run. If no desktop file
1196 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1197 This function is a no-op when Emacs is running in batch mode.
1198 It returns t if a desktop file was loaded, nil otherwise."
1199 (interactive)
1200 (unless noninteractive
1201 (setq desktop-dirname
1202 (file-name-as-directory
1203 (expand-file-name
1205 ;; If DIRNAME is specified, use it.
1206 (and (< 0 (length dirname)) dirname)
1207 ;; Otherwise search desktop file in desktop-path.
1208 (let ((dirs desktop-path))
1209 (while (and dirs
1210 (not (file-exists-p
1211 (desktop-full-file-name (car dirs)))))
1212 (setq dirs (cdr dirs)))
1213 (and dirs (car dirs)))
1214 ;; If not found and `desktop-path' is non-nil, use its first element.
1215 (and desktop-path (car desktop-path))
1216 ;; Default: .emacs.d.
1217 user-emacs-directory))))
1218 (if (file-exists-p (desktop-full-file-name))
1219 ;; Desktop file found, but is it already in use?
1220 (let ((desktop-first-buffer nil)
1221 (desktop-buffer-ok-count 0)
1222 (desktop-buffer-fail-count 0)
1223 (owner (desktop-owner))
1224 ;; Avoid desktop saving during evaluation of desktop buffer.
1225 (desktop-save nil)
1226 (desktop-autosave-was-enabled))
1227 (if (and owner
1228 (memq desktop-load-locked-desktop '(nil ask))
1229 (or (null desktop-load-locked-desktop)
1230 (daemonp)
1231 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1232 Using it may cause conflicts. Use it anyway? " owner)))))
1233 (let ((default-directory desktop-dirname))
1234 (setq desktop-dirname nil)
1235 (run-hooks 'desktop-not-loaded-hook)
1236 (unless desktop-dirname
1237 (message "Desktop file in use; not loaded.")))
1238 (desktop-lazy-abort)
1239 ;; Temporarily disable the autosave that will leave it
1240 ;; disabled when loading the desktop fails with errors,
1241 ;; thus not overwriting the desktop with broken contents.
1242 (setq desktop-autosave-was-enabled
1243 (memq 'desktop-auto-save-set-timer
1244 ;; Use the toplevel value of the hook, in case some
1245 ;; feature makes window-configuration-change-hook
1246 ;; buffer-local, and puts there stuff which
1247 ;; doesn't include our timer.
1248 (default-toplevel-value
1249 'window-configuration-change-hook)))
1250 (desktop-auto-save-disable)
1251 ;; Evaluate desktop buffer and remember when it was modified.
1252 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1253 (load (desktop-full-file-name) t t t)
1254 ;; If it wasn't already, mark it as in-use, to bother other
1255 ;; desktop instances.
1256 (unless (eq (emacs-pid) owner)
1257 (condition-case nil
1258 (desktop-claim-lock)
1259 (file-error (message "Couldn't record use of desktop file")
1260 (sit-for 1))))
1262 (unless (desktop-restoring-frameset-p)
1263 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1264 ;; We want buffers existing prior to evaluating the desktop (and
1265 ;; not reused) to be placed at the end of the buffer list, so we
1266 ;; move them here.
1267 (mapc 'bury-buffer
1268 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1269 (switch-to-buffer (car (buffer-list))))
1270 (run-hooks 'desktop-delay-hook)
1271 (setq desktop-delay-hook nil)
1272 (desktop-restore-frameset)
1273 (run-hooks 'desktop-after-read-hook)
1274 (message "Desktop: %s%d buffer%s restored%s%s."
1275 (if desktop-saved-frameset
1276 (let ((fn (length (frameset-states desktop-saved-frameset))))
1277 (format "%d frame%s, "
1278 fn (if (= fn 1) "" "s")))
1280 desktop-buffer-ok-count
1281 (if (= 1 desktop-buffer-ok-count) "" "s")
1282 (if (< 0 desktop-buffer-fail-count)
1283 (format ", %d failed to restore" desktop-buffer-fail-count)
1285 (if desktop-buffer-args-list
1286 (format ", %d to restore lazily"
1287 (length desktop-buffer-args-list))
1288 ""))
1289 (unless (desktop-restoring-frameset-p)
1290 ;; Bury the *Messages* buffer to not reshow it when burying
1291 ;; the buffer we switched to above.
1292 (when (buffer-live-p (get-buffer "*Messages*"))
1293 (bury-buffer "*Messages*"))
1294 ;; Clear all windows' previous and next buffers, these have
1295 ;; been corrupted by the `switch-to-buffer' calls in
1296 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1297 ;; brute force fix and should be replaced by a more subtle
1298 ;; strategy eventually.
1299 (walk-window-tree (lambda (window)
1300 (set-window-prev-buffers window nil)
1301 (set-window-next-buffers window nil))))
1302 (setq desktop-saved-frameset nil)
1303 (if desktop-autosave-was-enabled (desktop-auto-save-enable))
1305 ;; No desktop file found.
1306 (let ((default-directory desktop-dirname))
1307 (run-hooks 'desktop-no-desktop-file-hook))
1308 (message "No desktop file.")
1309 nil)))
1311 ;; ----------------------------------------------------------------------------
1312 ;; Maintained for backward compatibility
1313 ;;;###autoload
1314 (defun desktop-load-default ()
1315 "Load the `default' start-up library manually.
1316 Also inhibit further loading of it."
1317 (declare (obsolete desktop-save-mode "22.1"))
1318 (unless inhibit-default-init ; safety check
1319 (load "default" t t)
1320 (setq inhibit-default-init t)))
1322 ;; ----------------------------------------------------------------------------
1323 ;;;###autoload
1324 (defun desktop-change-dir (dirname)
1325 "Change to desktop saved in DIRNAME.
1326 Kill the desktop as specified by variables `desktop-save-mode' and
1327 `desktop-save', then clear the desktop and load the desktop file in
1328 directory DIRNAME."
1329 (interactive "DChange to directory: ")
1330 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1331 (desktop-kill)
1332 (desktop-clear)
1333 (desktop-read dirname))
1335 ;; ----------------------------------------------------------------------------
1336 ;;;###autoload
1337 (defun desktop-save-in-desktop-dir ()
1338 "Save the desktop in directory `desktop-dirname'."
1339 (interactive)
1340 (if desktop-dirname
1341 (desktop-save desktop-dirname)
1342 (call-interactively 'desktop-save))
1343 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1345 ;; ----------------------------------------------------------------------------
1346 ;; Auto-Saving.
1347 (defvar desktop-auto-save-timer nil)
1349 (defun desktop-auto-save-enable (&optional timeout)
1350 (when (and (integerp (or timeout desktop-auto-save-timeout))
1351 (> (or timeout desktop-auto-save-timeout) 0))
1352 (add-hook 'window-configuration-change-hook 'desktop-auto-save-set-timer)))
1354 (defun desktop-auto-save-disable ()
1355 (remove-hook 'window-configuration-change-hook 'desktop-auto-save-set-timer)
1356 (desktop-auto-save-cancel-timer))
1358 (defun desktop-auto-save ()
1359 "Save the desktop periodically.
1360 Called by the timer created in `desktop-auto-save-set-timer'."
1361 (when (and desktop-save-mode
1362 (integerp desktop-auto-save-timeout)
1363 (> desktop-auto-save-timeout 0)
1364 ;; Avoid desktop saving during lazy loading.
1365 (not desktop-lazy-timer)
1366 ;; Save only to own desktop file.
1367 (eq (emacs-pid) (desktop-owner))
1368 desktop-dirname)
1369 (desktop-save desktop-dirname nil t)))
1371 (defun desktop-auto-save-set-timer ()
1372 "Set the desktop auto-save timer.
1373 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1374 integer, start a new idle timer to call `desktop-auto-save' after that many
1375 seconds of idle time.
1376 This function is called from `window-configuration-change-hook'."
1377 (desktop-auto-save-cancel-timer)
1378 (when (and (integerp desktop-auto-save-timeout)
1379 (> desktop-auto-save-timeout 0))
1380 (setq desktop-auto-save-timer
1381 (run-with-idle-timer desktop-auto-save-timeout nil
1382 'desktop-auto-save))))
1384 (defun desktop-auto-save-cancel-timer ()
1385 (when desktop-auto-save-timer
1386 (cancel-timer desktop-auto-save-timer)
1387 (setq desktop-auto-save-timer nil)))
1389 ;; ----------------------------------------------------------------------------
1390 ;;;###autoload
1391 (defun desktop-revert ()
1392 "Revert to the last loaded desktop."
1393 (interactive)
1394 (unless desktop-dirname
1395 (error "Unknown desktop directory"))
1396 (unless (file-exists-p (desktop-full-file-name))
1397 (error "No desktop file found"))
1398 (desktop-clear)
1399 (desktop-read desktop-dirname))
1401 (defvar desktop-buffer-major-mode)
1402 (defvar desktop-buffer-locals)
1403 (defvar auto-insert) ; from autoinsert.el
1404 ;; ----------------------------------------------------------------------------
1405 (defun desktop-restore-file-buffer (buffer-filename
1406 _buffer-name
1407 _buffer-misc)
1408 "Restore a file buffer."
1409 (when buffer-filename
1410 (if (or (file-exists-p buffer-filename)
1411 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1412 buffer-filename)))
1413 (if desktop-missing-file-warning
1414 (y-or-n-p (concat msg " Re-create buffer? "))
1415 (message "%s" msg)
1416 nil)))
1417 (let* ((auto-insert nil) ; Disable auto insertion
1418 (coding-system-for-read
1419 (or coding-system-for-read
1420 (cdr (assq 'buffer-file-coding-system
1421 desktop-buffer-locals))))
1422 (buf (find-file-noselect buffer-filename :nowarn)))
1423 (condition-case nil
1424 (switch-to-buffer buf)
1425 (error (pop-to-buffer buf)))
1426 (and (not (eq major-mode desktop-buffer-major-mode))
1427 (functionp desktop-buffer-major-mode)
1428 (funcall desktop-buffer-major-mode))
1429 buf)
1430 nil)))
1432 (defun desktop-load-file (function)
1433 "Load the file where auto loaded FUNCTION is defined.
1434 If FUNCTION is not currently defined, guess the library that defines it
1435 and try to load that."
1436 (if (fboundp function)
1437 (autoload-do-load (symbol-function function) function)
1438 ;; Guess that foobar-mode is defined in foobar.
1439 ;; TODO rather than guessing or requiring an autoload, the desktop
1440 ;; file should record the name of the library.
1441 (let ((name (symbol-name function)))
1442 (if (string-match "\\`\\(.*\\)-mode\\'" name)
1443 (with-demoted-errors "Require error in desktop-load-file: %S"
1444 (require (intern (match-string 1 name)) nil t))))))
1446 ;; ----------------------------------------------------------------------------
1447 ;; Create a buffer, load its file, set its mode, ...;
1448 ;; called from Desktop file only.
1450 (defun desktop-create-buffer
1451 (file-version
1452 buffer-filename
1453 buffer-name
1454 buffer-majormode
1455 buffer-minormodes
1456 buffer-point
1457 buffer-mark
1458 buffer-readonly
1459 buffer-misc
1460 &optional
1461 buffer-locals
1462 compacted-vars
1463 &rest _unsupported)
1465 (setq desktop-io-file-version file-version)
1467 (let ((desktop-file-version file-version)
1468 (desktop-buffer-file-name buffer-filename)
1469 (desktop-buffer-name buffer-name)
1470 (desktop-buffer-major-mode buffer-majormode)
1471 (desktop-buffer-minor-modes buffer-minormodes)
1472 (desktop-buffer-point buffer-point)
1473 (desktop-buffer-mark buffer-mark)
1474 (desktop-buffer-read-only buffer-readonly)
1475 (desktop-buffer-misc buffer-misc)
1476 (desktop-buffer-locals buffer-locals))
1477 ;; To make desktop files with relative file names possible, we cannot
1478 ;; allow `default-directory' to change. Therefore we save current buffer.
1479 (save-current-buffer
1480 ;; Give major mode module a chance to add a handler.
1481 (desktop-load-file desktop-buffer-major-mode)
1482 (let ((buffer-list (buffer-list))
1483 (result
1484 (condition-case-unless-debug err
1485 (funcall (or (cdr (assq desktop-buffer-major-mode
1486 desktop-buffer-mode-handlers))
1487 'desktop-restore-file-buffer)
1488 desktop-buffer-file-name
1489 desktop-buffer-name
1490 desktop-buffer-misc)
1491 (error
1492 (message "Desktop: Can't load buffer %s: %s"
1493 desktop-buffer-name
1494 (error-message-string err))
1495 (when desktop-missing-file-warning (sit-for 1))
1496 nil))))
1497 (if (bufferp result)
1498 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1499 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1500 (setq result nil))
1501 ;; Restore buffer list order with new buffer at end. Don't change
1502 ;; the order for old desktop files (old desktop module behavior).
1503 (unless (< desktop-file-version 206)
1504 (dolist (buf buffer-list)
1505 (and (buffer-live-p buf)
1506 (bury-buffer buf)))
1507 (when result (bury-buffer result)))
1508 (when result
1509 (unless (or desktop-first-buffer (< desktop-file-version 206))
1510 (setq desktop-first-buffer result))
1511 (set-buffer result)
1512 (unless (equal (buffer-name) desktop-buffer-name)
1513 (rename-buffer desktop-buffer-name t))
1514 ;; minor modes
1515 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1516 (auto-fill-mode 1))
1517 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1518 (auto-fill-mode 0))
1520 (dolist (minor-mode desktop-buffer-minor-modes)
1521 ;; Give minor mode module a chance to add a handler.
1522 (desktop-load-file minor-mode)
1523 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1524 (if handler
1525 (funcall handler desktop-buffer-locals)
1526 (when (functionp minor-mode)
1527 (funcall minor-mode 1)))))))
1528 ;; Even though point and mark are non-nil when written by
1529 ;; `desktop-save', they may be modified by handlers wanting to set
1530 ;; point or mark themselves.
1531 (when desktop-buffer-point
1532 (goto-char
1533 (condition-case err
1534 ;; Evaluate point. Thus point can be something like
1535 ;; '(search-forward ...
1536 (eval desktop-buffer-point)
1537 (error (message "%s" (error-message-string err)) 1))))
1538 (when desktop-buffer-mark
1539 (if (consp desktop-buffer-mark)
1540 (progn
1541 (move-marker (mark-marker) (car desktop-buffer-mark))
1542 (if (car (cdr desktop-buffer-mark))
1543 (activate-mark 'dont-touch-tmm)))
1544 (move-marker (mark-marker) desktop-buffer-mark)))
1545 ;; Never override file system if the file really is read-only marked.
1546 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1547 (dolist (this desktop-buffer-locals)
1548 (if (consp this)
1549 ;; An entry of this form `(symbol . value)'.
1550 (progn
1551 (make-local-variable (car this))
1552 (set (car this) (cdr this)))
1553 ;; An entry of the form `symbol'.
1554 (make-local-variable this)
1555 (makunbound this)))
1556 ;; adjust `buffer-display-time' for the downtime. e.g.,
1557 ;; * if `buffer-display-time' was 8:00
1558 ;; * and emacs stopped at `desktop-file-modtime' == 11:00
1559 ;; * and we are loading the desktop file at (current-time) 12:30,
1560 ;; -> then we restore `buffer-display-time' as 9:30,
1561 ;; for the sake of `clean-buffer-list': preserving the invariant
1562 ;; "how much time the user spent in Emacs without looking at this buffer".
1563 (setq buffer-display-time
1564 (if buffer-display-time
1565 (time-add buffer-display-time
1566 (time-subtract nil desktop-file-modtime))
1567 (current-time)))
1568 (unless (< desktop-file-version 208) ; Don't misinterpret any old custom args
1569 (dolist (record compacted-vars)
1570 (let*
1571 ((var (car record))
1572 (deser-fun (nth 2 (assq var desktop-var-serdes-funs))))
1573 (if deser-fun (set var (funcall deser-fun (cadr record))))))))
1574 result))))
1576 ;; ----------------------------------------------------------------------------
1577 ;; Backward compatibility -- update parameters to 205 standards.
1578 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1579 mim pt mk ro tl fc cfs cr buffer-misc)
1580 (desktop-create-buffer 205 buffer-filename buffer-name
1581 buffer-majormode (cdr mim) pt mk ro
1582 buffer-misc
1583 (list (cons 'truncate-lines tl)
1584 (cons 'fill-column fc)
1585 (cons 'case-fold-search cfs)
1586 (cons 'case-replace cr)
1587 (cons 'overwrite-mode (car mim)))))
1589 (defun desktop-append-buffer-args (&rest args)
1590 "Append ARGS at end of `desktop-buffer-args-list'.
1591 ARGS must be an argument list for `desktop-create-buffer'."
1592 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1593 (unless desktop-lazy-timer
1594 (setq desktop-lazy-timer
1595 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1597 (defun desktop-lazy-create-buffer ()
1598 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1599 (when desktop-buffer-args-list
1600 (let* ((remaining (length desktop-buffer-args-list))
1601 (args (pop desktop-buffer-args-list))
1602 (buffer-name (nth 2 args))
1603 (msg (format "Desktop lazily opening %s (%s remaining)..."
1604 buffer-name remaining)))
1605 (when desktop-lazy-verbose
1606 (message "%s" msg))
1607 (let ((desktop-first-buffer nil)
1608 (desktop-buffer-ok-count 0)
1609 (desktop-buffer-fail-count 0))
1610 (apply 'desktop-create-buffer args)
1611 (run-hooks 'desktop-delay-hook)
1612 (setq desktop-delay-hook nil)
1613 (bury-buffer (get-buffer buffer-name))
1614 (when desktop-lazy-verbose
1615 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1617 (defun desktop-idle-create-buffers ()
1618 "Create buffers until the user does something, then stop.
1619 If there are no buffers left to create, kill the timer."
1620 (let ((repeat 1))
1621 (while (and repeat desktop-buffer-args-list)
1622 (save-window-excursion
1623 (desktop-lazy-create-buffer))
1624 (setq repeat (sit-for 0.2))
1625 (unless desktop-buffer-args-list
1626 (cancel-timer desktop-lazy-timer)
1627 (setq desktop-lazy-timer nil)
1628 (message "Lazy desktop load complete")
1629 (sit-for 3)
1630 (message "")))))
1632 (defun desktop-lazy-complete ()
1633 "Run the desktop load to completion."
1634 (interactive)
1635 (let ((desktop-lazy-verbose t))
1636 (while desktop-buffer-args-list
1637 (save-window-excursion
1638 (desktop-lazy-create-buffer)))
1639 (message "Lazy desktop load complete")))
1641 (defun desktop-lazy-abort ()
1642 "Abort lazy loading of the desktop."
1643 (interactive)
1644 (when desktop-lazy-timer
1645 (cancel-timer desktop-lazy-timer)
1646 (setq desktop-lazy-timer nil))
1647 (when desktop-buffer-args-list
1648 (setq desktop-buffer-args-list nil)
1649 (when (called-interactively-p 'interactive)
1650 (message "Lazy desktop load aborted"))))
1652 ;; ----------------------------------------------------------------------------
1653 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1654 ;; command line, we do the rest of what it takes to use desktop, but do it
1655 ;; after finishing loading the init file.
1656 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1657 ;; functions are processed after `after-init-hook'.
1658 (add-hook
1659 'after-init-hook
1660 (lambda ()
1661 (let ((key "--no-desktop"))
1662 (when (member key command-line-args)
1663 (setq command-line-args (delete key command-line-args))
1664 (desktop-save-mode 0)))
1665 (when desktop-save-mode
1666 (desktop-read)
1667 (setq inhibit-startup-screen t))))
1669 (provide 'desktop)
1671 ;;; desktop.el ends here