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