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