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