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