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