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