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