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