Spelling fixes.
[emacs.git] / lisp / desktop.el
blobe8fe742617e450f98d5dd9145c30cab58e79ce41
1 ;;; desktop.el --- save partial status of Emacs when killed
3 ;; Copyright (C) 1993-1995, 1997, 2000-2013 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 Potorti`) for misc. tips.
128 ;; ---------------------------------------------------------------------------
129 ;; TODO:
131 ;; Recognize more minor modes.
132 ;; Save mark rings.
134 ;;; Code:
136 (defvar desktop-file-version "206"
137 "Version number of desktop file format.
138 Written into the desktop file and used at desktop read to provide
139 backward compatibility.")
141 ;; ----------------------------------------------------------------------------
142 ;; USER OPTIONS -- settings you might want to play with.
143 ;; ----------------------------------------------------------------------------
145 (defgroup desktop nil
146 "Save status of Emacs when you exit."
147 :group 'frames)
149 ;; Maintained for backward compatibility
150 (define-obsolete-variable-alias 'desktop-enable 'desktop-save-mode "22.1")
151 ;;;###autoload
152 (define-minor-mode desktop-save-mode
153 "Toggle desktop saving (Desktop Save mode).
154 With a prefix argument ARG, enable Desktop Save mode if ARG is
155 positive, and disable it otherwise. If called from Lisp, enable
156 the mode if ARG is omitted or nil.
158 If Desktop Save mode is enabled, the state of Emacs is saved from
159 one session to another. See variable `desktop-save' and function
160 `desktop-read' for details."
161 :global t
162 :group 'desktop)
164 (defun desktop-save-mode-off ()
165 "Disable `desktop-save-mode'. Provided for use in hooks."
166 (desktop-save-mode 0))
168 (defcustom desktop-save 'ask-if-new
169 "Specifies whether the desktop should be saved when it is killed.
170 A desktop is killed when the user changes desktop or quits Emacs.
171 Possible values are:
172 t -- always save.
173 ask -- always ask.
174 ask-if-new -- ask if no desktop file exists, otherwise just save.
175 ask-if-exists -- ask if desktop file exists, otherwise don't save.
176 if-exists -- save if desktop file exists, otherwise don't save.
177 nil -- never save.
178 The desktop is never saved when `desktop-save-mode' is nil.
179 The variables `desktop-dirname' and `desktop-base-file-name'
180 determine where the desktop is saved."
181 :type
182 '(choice
183 (const :tag "Always save" t)
184 (const :tag "Always ask" ask)
185 (const :tag "Ask if desktop file is new, else do save" ask-if-new)
186 (const :tag "Ask if desktop file exists, else don't save" ask-if-exists)
187 (const :tag "Save if desktop file exists, else don't" if-exists)
188 (const :tag "Never save" nil))
189 :group 'desktop
190 :version "22.1")
192 (defcustom desktop-auto-save-timeout nil
193 "Number of seconds between auto-saves of the desktop.
194 Zero or nil means disable timer-based auto-saving."
195 :type '(choice (const :tag "Off" nil)
196 (integer :tag "Seconds"))
197 :set (lambda (symbol value)
198 (set-default symbol value)
199 (ignore-errors (desktop-auto-save-set-timer)))
200 :group 'desktop
201 :version "24.4")
203 (defcustom desktop-load-locked-desktop 'ask
204 "Specifies whether the desktop should be loaded if locked.
205 Possible values are:
206 t -- load anyway.
207 nil -- don't load.
208 ask -- ask the user.
209 If the value is nil, or `ask' and the user chooses not to load the desktop,
210 the normal hook `desktop-not-loaded-hook' is run."
211 :type
212 '(choice
213 (const :tag "Load anyway" t)
214 (const :tag "Don't load" nil)
215 (const :tag "Ask the user" ask))
216 :group 'desktop
217 :version "22.2")
219 (define-obsolete-variable-alias 'desktop-basefilename
220 'desktop-base-file-name "22.1")
222 (defcustom desktop-base-file-name
223 (convert-standard-filename ".emacs.desktop")
224 "Name of file for Emacs desktop, excluding the directory part."
225 :type 'file
226 :group 'desktop)
228 (defcustom desktop-base-lock-name
229 (convert-standard-filename ".emacs.desktop.lock")
230 "Name of lock file for Emacs desktop, excluding the directory part."
231 :type 'file
232 :group 'desktop
233 :version "22.2")
235 (defcustom desktop-path (list user-emacs-directory "~")
236 "List of directories to search for the desktop file.
237 The base name of the file is specified in `desktop-base-file-name'."
238 :type '(repeat directory)
239 :group 'desktop
240 :version "23.2") ; user-emacs-directory added
242 (defcustom desktop-missing-file-warning nil
243 "If non-nil, offer to recreate the buffer of a deleted file.
244 Also pause for a moment to display message about errors signaled in
245 `desktop-buffer-mode-handlers'.
247 If nil, just print error messages in the message buffer."
248 :type 'boolean
249 :group 'desktop
250 :version "22.1")
252 (defcustom desktop-no-desktop-file-hook nil
253 "Normal hook run when `desktop-read' can't find a desktop file.
254 Run in the directory in which the desktop file was sought.
255 May be used to show a dired buffer."
256 :type 'hook
257 :group 'desktop
258 :version "22.1")
260 (defcustom desktop-not-loaded-hook nil
261 "Normal hook run when the user declines to re-use a desktop file.
262 Run in the directory in which the desktop file was found.
263 May be used to deal with accidental multiple Emacs jobs."
264 :type 'hook
265 :group 'desktop
266 :options '(desktop-save-mode-off save-buffers-kill-emacs)
267 :version "22.2")
269 (defcustom desktop-after-read-hook nil
270 "Normal hook run after a successful `desktop-read'.
271 May be used to show a buffer list."
272 :type 'hook
273 :group 'desktop
274 :options '(list-buffers)
275 :version "22.1")
277 (defcustom desktop-save-hook nil
278 "Normal hook run before the desktop is saved in a desktop file.
279 Run with the desktop buffer current with only the header present.
280 May be used to add to the desktop code or to truncate history lists,
281 for example."
282 :type 'hook
283 :group 'desktop)
285 (defcustom desktop-globals-to-save
286 '(desktop-missing-file-warning
287 tags-file-name
288 tags-table-list
289 search-ring
290 regexp-search-ring
291 register-alist
292 file-name-history)
293 "List of global variables saved by `desktop-save'.
294 An element may be variable name (a symbol) or a cons cell of the form
295 \(VAR . MAX-SIZE), which means to truncate VAR's value to at most
296 MAX-SIZE elements (if the value is a list) before saving the value.
297 Feature: Saving `kill-ring' implies saving `kill-ring-yank-pointer'."
298 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
299 :group 'desktop)
301 (defcustom desktop-globals-to-clear
302 '(kill-ring
303 kill-ring-yank-pointer
304 search-ring
305 search-ring-yank-pointer
306 regexp-search-ring
307 regexp-search-ring-yank-pointer)
308 "List of global variables that `desktop-clear' will clear.
309 An element may be variable name (a symbol) or a cons cell of the form
310 \(VAR . FORM). Symbols are set to nil and for cons cells VAR is set
311 to the value obtained by evaluating FORM."
312 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
313 :group 'desktop
314 :version "22.1")
316 (defcustom desktop-clear-preserve-buffers
317 '("\\*scratch\\*" "\\*Messages\\*" "\\*server\\*" "\\*tramp/.+\\*"
318 "\\*Warnings\\*")
319 "List of buffers that `desktop-clear' should not delete.
320 Each element is a regular expression. Buffers with a name matched by any of
321 these won't be deleted."
322 :version "23.3" ; added Warnings - bug#6336
323 :type '(repeat string)
324 :group 'desktop)
326 ;;;###autoload
327 (defcustom desktop-locals-to-save
328 '(desktop-locals-to-save ; Itself! Think it over.
329 truncate-lines
330 case-fold-search
331 case-replace
332 fill-column
333 overwrite-mode
334 change-log-default-name
335 line-number-mode
336 column-number-mode
337 size-indication-mode
338 buffer-file-coding-system
339 indent-tabs-mode
340 tab-width
341 indicate-buffer-boundaries
342 indicate-empty-lines
343 show-trailing-whitespace)
344 "List of local variables to save for each buffer.
345 The variables are saved only when they really are local. Conventional minor
346 modes are restored automatically; they should not be listed here."
347 :type '(repeat symbol)
348 :group 'desktop)
350 (defcustom desktop-buffers-not-to-save nil
351 "Regexp identifying buffers that are to be excluded from saving."
352 :type '(choice (const :tag "None" nil)
353 regexp)
354 :version "23.2" ; set to nil
355 :group 'desktop)
357 ;; Skip tramp and ange-ftp files
358 (defcustom desktop-files-not-to-save
359 "\\(^/[^/:]*:\\|(ftp)$\\)"
360 "Regexp identifying files whose buffers are to be excluded from saving."
361 :type '(choice (const :tag "None" nil)
362 regexp)
363 :group 'desktop)
365 ;; We skip TAGS files to save time (tags-file-name is saved instead).
366 (defcustom desktop-modes-not-to-save
367 '(tags-table-mode)
368 "List of major modes whose buffers should not be saved."
369 :type '(repeat symbol)
370 :group 'desktop)
372 (defcustom desktop-restore-frames t
373 "When non-nil, save window/frame configuration to desktop file."
374 :type 'boolean
375 :group 'desktop
376 :version "24.4")
378 (defcustom desktop-restore-in-current-display nil
379 "If t, frames are restored in the current display.
380 If nil, frames are restored, if possible, in their original displays.
381 If `delete', frames on other displays are deleted instead of restored."
382 :type '(choice (const :tag "Restore in current display" t)
383 (const :tag "Restore in original display" nil)
384 (const :tag "Delete frames in other displays" 'delete))
385 :group 'desktop
386 :version "24.4")
388 (defcustom desktop-restoring-reuses-frames t
389 "If t, restoring frames reuses existing frames.
390 If nil, existing frames are deleted.
391 If `keep', existing frames are kept and not reused."
392 :type '(choice (const :tag "Reuse existing frames" t)
393 (const :tag "Delete existing frames" nil)
394 (const :tag "Keep existing frames" 'keep))
395 :group 'desktop
396 :version "24.4")
398 (defcustom desktop-file-name-format 'absolute
399 "Format in which desktop file names should be saved.
400 Possible values are:
401 absolute -- Absolute file name.
402 tilde -- Relative to ~.
403 local -- Relative to directory of desktop file."
404 :type '(choice (const absolute) (const tilde) (const local))
405 :group 'desktop
406 :version "22.1")
408 (defcustom desktop-restore-eager t
409 "Number of buffers to restore immediately.
410 Remaining buffers are restored lazily (when Emacs is idle).
411 If value is t, all buffers are restored immediately."
412 :type '(choice (const t) integer)
413 :group 'desktop
414 :version "22.1")
416 (defcustom desktop-lazy-verbose t
417 "Verbose reporting of lazily created buffers."
418 :type 'boolean
419 :group 'desktop
420 :version "22.1")
422 (defcustom desktop-lazy-idle-delay 5
423 "Idle delay before starting to create buffers.
424 See `desktop-restore-eager'."
425 :type 'integer
426 :group 'desktop
427 :version "22.1")
429 ;;;###autoload
430 (defvar-local desktop-save-buffer nil
431 "When non-nil, save buffer status in desktop file.
433 If the value is a function, it is called by `desktop-save' with argument
434 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
435 file along with the state of the buffer for which it was called.
437 When file names are returned, they should be formatted using the call
438 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
440 Later, when `desktop-read' evaluates the desktop file, auxiliary information
441 is passed as the argument DESKTOP-BUFFER-MISC to functions in
442 `desktop-buffer-mode-handlers'.")
443 (make-obsolete-variable 'desktop-buffer-modes-to-save
444 'desktop-save-buffer "22.1")
445 (make-obsolete-variable 'desktop-buffer-misc-functions
446 'desktop-save-buffer "22.1")
448 ;;;###autoload
449 (defvar desktop-buffer-mode-handlers nil
450 "Alist of major mode specific functions to restore a desktop buffer.
451 Functions listed are called by `desktop-create-buffer' when `desktop-read'
452 evaluates the desktop file. List elements must have the form
454 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
456 Buffers with a major mode not specified here, are restored by the default
457 handler `desktop-restore-file-buffer'.
459 Handlers are called with argument list
461 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
463 Furthermore, they may use the following variables:
465 desktop-file-version
466 desktop-buffer-major-mode
467 desktop-buffer-minor-modes
468 desktop-buffer-point
469 desktop-buffer-mark
470 desktop-buffer-read-only
471 desktop-buffer-locals
473 If a handler returns a buffer, then the saved mode settings
474 and variable values for that buffer are copied into it.
476 Modules that define a major mode that needs a special handler should contain
477 code like
479 (defun foo-restore-desktop-buffer
481 (add-to-list 'desktop-buffer-mode-handlers
482 '(foo-mode . foo-restore-desktop-buffer))
484 Furthermore the major mode function must be autoloaded.")
486 ;;;###autoload
487 (put 'desktop-buffer-mode-handlers 'risky-local-variable t)
488 (make-obsolete-variable 'desktop-buffer-handlers
489 'desktop-buffer-mode-handlers "22.1")
491 (defcustom desktop-minor-mode-table
492 '((auto-fill-function auto-fill-mode)
493 (vc-mode nil)
494 (vc-dired-mode nil)
495 (erc-track-minor-mode nil)
496 (savehist-mode nil))
497 "Table mapping minor mode variables to minor mode functions.
498 Each entry has the form (NAME RESTORE-FUNCTION).
499 NAME is the name of the buffer-local variable indicating that the minor
500 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
501 RESTORE-FUNCTION nil means don't try to restore the minor mode.
502 Only minor modes for which the name of the buffer-local variable
503 and the name of the minor mode function are different have to be added to
504 this table. See also `desktop-minor-mode-handlers'."
505 :type 'sexp
506 :group 'desktop)
508 ;;;###autoload
509 (defvar desktop-minor-mode-handlers nil
510 "Alist of functions to restore non-standard minor modes.
511 Functions are called by `desktop-create-buffer' to restore minor modes.
512 List elements must have the form
514 (MINOR-MODE . RESTORE-FUNCTION).
516 Minor modes not specified here, are restored by the standard minor mode
517 function.
519 Handlers are called with argument list
521 (DESKTOP-BUFFER-LOCALS)
523 Furthermore, they may use the following variables:
525 desktop-file-version
526 desktop-buffer-file-name
527 desktop-buffer-name
528 desktop-buffer-major-mode
529 desktop-buffer-minor-modes
530 desktop-buffer-point
531 desktop-buffer-mark
532 desktop-buffer-read-only
533 desktop-buffer-misc
535 When a handler is called, the buffer has been created and the major mode has
536 been set, but local variables listed in desktop-buffer-locals has not yet been
537 created and set.
539 Modules that define a minor mode that needs a special handler should contain
540 code like
542 (defun foo-desktop-restore
544 (add-to-list 'desktop-minor-mode-handlers
545 '(foo-mode . foo-desktop-restore))
547 Furthermore the minor mode function must be autoloaded.
549 See also `desktop-minor-mode-table'.")
551 ;;;###autoload
552 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
554 ;; ----------------------------------------------------------------------------
555 (defvar desktop-dirname nil
556 "The directory in which the desktop file should be saved.")
558 (defun desktop-full-file-name (&optional dirname)
559 "Return the full name of the desktop file in DIRNAME.
560 DIRNAME omitted or nil means use `desktop-dirname'."
561 (expand-file-name desktop-base-file-name (or dirname desktop-dirname)))
563 (defun desktop-full-lock-name (&optional dirname)
564 "Return the full name of the desktop lock file in DIRNAME.
565 DIRNAME omitted or nil means use `desktop-dirname'."
566 (expand-file-name desktop-base-lock-name (or dirname desktop-dirname)))
568 (defconst desktop-header
569 ";; --------------------------------------------------------------------------
570 ;; Desktop File for Emacs
571 ;; --------------------------------------------------------------------------
572 " "*Header to place in Desktop file.")
574 (defvar desktop-delay-hook nil
575 "Hooks run after all buffers are loaded; intended for internal use.")
577 (defvar desktop-file-checksum nil
578 "Checksum of the last auto-saved contents of the desktop file.
579 Used to avoid writing contents unchanged between auto-saves.")
581 (defvar desktop--saved-states nil
582 "Saved window/frame state. Internal use only.")
584 ;; ----------------------------------------------------------------------------
585 ;; Desktop file conflict detection
586 (defvar desktop-file-modtime nil
587 "When the desktop file was last modified to the knowledge of this Emacs.
588 Used to detect desktop file conflicts.")
590 (defun desktop-owner (&optional dirname)
591 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
592 Return nil if no desktop file found or no Emacs process is using it.
593 DIRNAME omitted or nil means use `desktop-dirname'."
594 (let (owner
595 (file (desktop-full-lock-name dirname)))
596 (and (file-exists-p file)
597 (ignore-errors
598 (with-temp-buffer
599 (insert-file-contents-literally file)
600 (goto-char (point-min))
601 (setq owner (read (current-buffer)))
602 (integerp owner)))
603 owner)))
605 (defun desktop-claim-lock (&optional dirname)
606 "Record this Emacs process as the owner of the desktop file in DIRNAME.
607 DIRNAME omitted or nil means use `desktop-dirname'."
608 (write-region (number-to-string (emacs-pid)) nil
609 (desktop-full-lock-name dirname)))
611 (defun desktop-release-lock (&optional dirname)
612 "Remove the lock file for the desktop in DIRNAME.
613 DIRNAME omitted or nil means use `desktop-dirname'."
614 (let ((file (desktop-full-lock-name dirname)))
615 (when (file-exists-p file) (delete-file file))))
617 ;; ----------------------------------------------------------------------------
618 (defun desktop-truncate (list n)
619 "Truncate LIST to at most N elements destructively."
620 (let ((here (nthcdr (1- n) list)))
621 (when (consp here)
622 (setcdr here nil))))
624 ;; ----------------------------------------------------------------------------
625 ;;;###autoload
626 (defun desktop-clear ()
627 "Empty the Desktop.
628 This kills all buffers except for internal ones and those with names matched by
629 a regular expression in the list `desktop-clear-preserve-buffers'.
630 Furthermore, it clears the variables listed in `desktop-globals-to-clear'."
631 (interactive)
632 (desktop-lazy-abort)
633 (dolist (var desktop-globals-to-clear)
634 (if (symbolp var)
635 (eval `(setq-default ,var nil))
636 (eval `(setq-default ,(car var) ,(cdr var)))))
637 (let ((buffers (buffer-list))
638 (preserve-regexp (concat "^\\("
639 (mapconcat (lambda (regexp)
640 (concat "\\(" regexp "\\)"))
641 desktop-clear-preserve-buffers
642 "\\|")
643 "\\)$")))
644 (while buffers
645 (let ((bufname (buffer-name (car buffers))))
647 (null bufname)
648 (string-match-p preserve-regexp bufname)
649 ;; Don't kill buffers made for internal purposes.
650 (and (not (equal bufname "")) (eq (aref bufname 0) ?\s))
651 (kill-buffer (car buffers))))
652 (setq buffers (cdr buffers))))
653 (delete-other-windows))
655 ;; ----------------------------------------------------------------------------
656 (unless noninteractive
657 (add-hook 'kill-emacs-hook 'desktop-kill))
659 (defun desktop-kill ()
660 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
661 If the desktop should be saved and `desktop-dirname'
662 is nil, ask the user where to save the desktop."
663 (when (and desktop-save-mode
664 (let ((exists (file-exists-p (desktop-full-file-name))))
665 (or (eq desktop-save t)
666 (and exists (eq desktop-save 'if-exists))
667 ;; If it exists, but we aren't using it, we are going
668 ;; to ask for a new directory below.
669 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
670 (and
671 (or (memq desktop-save '(ask ask-if-new))
672 (and exists (eq desktop-save 'ask-if-exists)))
673 (y-or-n-p "Save desktop? ")))))
674 (unless desktop-dirname
675 (setq desktop-dirname
676 (file-name-as-directory
677 (expand-file-name
678 (read-directory-name "Directory for desktop file: " nil nil t)))))
679 (condition-case err
680 (desktop-save desktop-dirname t)
681 (file-error
682 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
683 (signal (car err) (cdr err))))))
684 ;; If we own it, we don't anymore.
685 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
687 ;; ----------------------------------------------------------------------------
688 (defun desktop-list* (&rest args)
689 (if (null (cdr args))
690 (car args)
691 (setq args (nreverse args))
692 (let ((value (cons (nth 1 args) (car args))))
693 (setq args (cdr (cdr args)))
694 (while args
695 (setq value (cons (car args) value))
696 (setq args (cdr args)))
697 value)))
699 ;; ----------------------------------------------------------------------------
700 (defun desktop-buffer-info (buffer)
701 (set-buffer buffer)
702 (list
703 ;; base name of the buffer; replaces the buffer name if managed by uniquify
704 (and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
705 ;; basic information
706 (desktop-file-name (buffer-file-name) desktop-dirname)
707 (buffer-name)
708 major-mode
709 ;; minor modes
710 (let (ret)
711 (mapc
712 #'(lambda (minor-mode)
713 (and (boundp minor-mode)
714 (symbol-value minor-mode)
715 (let* ((special (assq minor-mode desktop-minor-mode-table))
716 (value (cond (special (cadr special))
717 ((functionp minor-mode) minor-mode))))
718 (when value (add-to-list 'ret value)))))
719 (mapcar #'car minor-mode-alist))
720 ret)
721 ;; point and mark, and read-only status
722 (point)
723 (list (mark t) mark-active)
724 buffer-read-only
725 ;; auxiliary information
726 (when (functionp desktop-save-buffer)
727 (funcall desktop-save-buffer desktop-dirname))
728 ;; local variables
729 (let ((locals desktop-locals-to-save)
730 (loclist (buffer-local-variables))
731 (ll))
732 (while locals
733 (let ((here (assq (car locals) loclist)))
734 (if here
735 (setq ll (cons here ll))
736 (when (member (car locals) loclist)
737 (setq ll (cons (car locals) ll)))))
738 (setq locals (cdr locals)))
739 ll)))
741 ;; ----------------------------------------------------------------------------
742 (defun desktop--v2s (value)
743 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
744 SEXP is an sexp that when evaluated yields VALUE.
745 QUOTE may be `may' (value may be quoted),
746 `must' (value must be quoted), or nil (value must not be quoted)."
747 (cond
748 ((or (numberp value) (null value) (eq t value) (keywordp value))
749 (cons 'may value))
750 ((stringp value)
751 (let ((copy (copy-sequence value)))
752 (set-text-properties 0 (length copy) nil copy)
753 ;; Get rid of text properties because we cannot read them.
754 (cons 'may copy)))
755 ((symbolp value)
756 (cons 'must value))
757 ((vectorp value)
758 (let* ((pass1 (mapcar #'desktop--v2s value))
759 (special (assq nil pass1)))
760 (if special
761 (cons nil `(vector
762 ,@(mapcar (lambda (el)
763 (if (eq (car el) 'must)
764 `',(cdr el) (cdr el)))
765 pass1)))
766 (cons 'may `[,@(mapcar #'cdr pass1)]))))
767 ((consp value)
768 (let ((p value)
769 newlist
770 use-list*)
771 (while (consp p)
772 (let ((q.sexp (desktop--v2s (car p))))
773 (push q.sexp newlist))
774 (setq p (cdr p)))
775 (when p
776 (let ((last (desktop--v2s p)))
777 (setq use-list* t)
778 (push last newlist)))
779 (if (assq nil newlist)
780 (cons nil
781 `(,(if use-list* 'desktop-list* 'list)
782 ,@(mapcar (lambda (el)
783 (if (eq (car el) 'must)
784 `',(cdr el) (cdr el)))
785 (nreverse newlist))))
786 (cons 'must
787 `(,@(mapcar #'cdr
788 (nreverse (if use-list* (cdr newlist) newlist)))
789 ,@(if use-list* (cdar newlist)))))))
790 ((subrp value)
791 (cons nil `(symbol-function
792 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
793 ((markerp value)
794 (let ((pos (marker-position value))
795 (buf (buffer-name (marker-buffer value))))
796 (cons nil
797 `(let ((mk (make-marker)))
798 (add-hook 'desktop-delay-hook
799 `(lambda ()
800 (set-marker ,mk ,,pos (get-buffer ,,buf))))
801 mk))))
802 (t ; Save as text.
803 (cons 'may "Unprintable entity"))))
805 ;; ----------------------------------------------------------------------------
806 (defun desktop-value-to-string (value)
807 "Convert VALUE to a string that when read evaluates to the same value.
808 Not all types of values are supported."
809 (let* ((print-escape-newlines t)
810 (float-output-format nil)
811 (quote.sexp (desktop--v2s value))
812 (quote (car quote.sexp))
813 (txt
814 (let ((print-quoted t))
815 (prin1-to-string (cdr quote.sexp)))))
816 (if (eq quote 'must)
817 (concat "'" txt)
818 txt)))
820 ;; ----------------------------------------------------------------------------
821 (defun desktop-outvar (varspec)
822 "Output a setq statement for variable VAR to the desktop file.
823 The argument VARSPEC may be the variable name VAR (a symbol),
824 or a cons cell of the form (VAR . MAX-SIZE),
825 which means to truncate VAR's value to at most MAX-SIZE elements
826 \(if the value is a list) before saving the value."
827 (let (var size)
828 (if (consp varspec)
829 (setq var (car varspec) size (cdr varspec))
830 (setq var varspec))
831 (when (boundp var)
832 (when (and (integerp size)
833 (> size 0)
834 (listp (eval var)))
835 (desktop-truncate (eval var) size))
836 (insert "(setq "
837 (symbol-name var)
839 (desktop-value-to-string (symbol-value var))
840 ")\n"))))
842 ;; ----------------------------------------------------------------------------
843 (defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
844 "Return t if buffer should have its state saved in the desktop file.
845 FILENAME is the visited file name, BUFNAME is the buffer name, and
846 MODE is the major mode.
847 \n\(fn FILENAME BUFNAME MODE)"
848 (let ((case-fold-search nil)
849 dired-skip)
850 (and (not (and (stringp desktop-buffers-not-to-save)
851 (not filename)
852 (string-match-p desktop-buffers-not-to-save bufname)))
853 (not (memq mode desktop-modes-not-to-save))
854 ;; FIXME this is broken if desktop-files-not-to-save is nil.
855 (or (and filename
856 (stringp desktop-files-not-to-save)
857 (not (string-match-p desktop-files-not-to-save filename)))
858 (and (memq mode '(dired-mode vc-dir-mode))
859 (with-current-buffer bufname
860 (not (setq dired-skip
861 (string-match-p desktop-files-not-to-save
862 default-directory)))))
863 (and (null filename)
864 (null dired-skip) ; bug#5755
865 (with-current-buffer bufname desktop-save-buffer))))))
867 ;; ----------------------------------------------------------------------------
868 (defun desktop-file-name (filename dirname)
869 "Convert FILENAME to format specified in `desktop-file-name-format'.
870 DIRNAME must be the directory in which the desktop file will be saved."
871 (cond
872 ((not filename) nil)
873 ((eq desktop-file-name-format 'tilde)
874 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
875 (cond
876 ((file-name-absolute-p relative-name) relative-name)
877 ((string= "./" relative-name) "~/")
878 ((string= "." relative-name) "~")
879 (t (concat "~/" relative-name)))))
880 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
881 (t (expand-file-name filename))))
884 ;; ----------------------------------------------------------------------------
885 (defvar desktop-filter-parameters-alist
886 '((background-color . desktop--filter-*-color)
887 (buffer-list . t)
888 (buffer-predicate . t)
889 (buried-buffer-list . t)
890 (desktop-font . desktop--filter-restore-desktop-parm)
891 (desktop-fullscreen . desktop--filter-restore-desktop-parm)
892 (desktop-height . desktop--filter-restore-desktop-parm)
893 (desktop-width . desktop--filter-restore-desktop-parm)
894 (font . desktop--filter-save-desktop-parm)
895 (font-backend . t)
896 (foreground-color . desktop--filter-*-color)
897 (fullscreen . desktop--filter-save-desktop-parm)
898 (height . desktop--filter-save-desktop-parm)
899 (left . desktop--filter-iconified-position)
900 (minibuffer . desktop--filter-minibuffer)
901 (name . t)
902 (outer-window-id . t)
903 (parent-id . t)
904 (top . desktop--filter-iconified-position)
905 (tty . desktop--filter-tty*)
906 (tty-type . desktop--filter-tty*)
907 (width . desktop--filter-save-desktop-parm)
908 (window-id . t)
909 (window-system . t))
910 "Alist of frame parameters and filtering functions.
912 Each element is a cons (PARAM . FILTER), where PARAM is a parameter
913 name (a symbol identifying a frame parameter), and FILTER can be t
914 \(meaning the parameter is removed from the parameter list on saving
915 and restoring), or a function that will be called with three args:
917 CURRENT a cons (PARAM . VALUE), where PARAM is the one being
918 filtered and VALUE is its current value
919 PARAMETERS the complete alist of parameters being filtered
920 SAVING non-nil if filtering before saving state, nil otherwise
922 The FILTER function must return:
923 nil CURRENT is removed from the list
924 t CURRENT is left as is
925 (PARAM' . VALUE') replace CURRENT with this
927 Frame parameters not on this list are passed intact.")
929 (defvar desktop--target-display nil
930 "Either (minibuffer . VALUE) or nil.
931 This refers to the current frame config being processed inside
932 `frame--restore-frames' and its auxiliary functions (like filtering).
933 If nil, there is no need to change the display.
934 If non-nil, display parameter to use when creating the frame.
935 Internal use only.")
937 (defun desktop-switch-to-gui-p (parameters)
938 "True when switching to a graphic display.
939 Return t if PARAMETERS describes a text-only terminal and
940 the target is a graphic display; otherwise return nil.
941 Only meaningful when called from a filtering function in
942 `desktop-filter-parameters-alist'."
943 (and desktop--target-display ; we're switching
944 (null (cdr (assq 'display parameters))) ; from a tty
945 (cdr desktop--target-display))) ; to a GUI display
947 (defun desktop-switch-to-tty-p (parameters)
948 "True when switching to a text-only terminal.
949 Return t if PARAMETERS describes a graphic display and
950 the target is a text-only terminal; otherwise return nil.
951 Only meaningful when called from a filtering function in
952 `desktop-filter-parameters-alist'."
953 (and desktop--target-display ; we're switching
954 (cdr (assq 'display parameters)) ; from a GUI display
955 (null (cdr desktop--target-display)))) ; to a tty
957 (defun desktop--filter-tty* (_current parameters saving)
958 ;; Remove tty and tty-type parameters when switching
959 ;; to a GUI frame.
960 (or saving
961 (not (desktop-switch-to-gui-p parameters))))
963 (defun desktop--filter-*-color (current parameters saving)
964 ;; Remove (foreground|background)-color parameters
965 ;; when switching to a GUI frame if they denote an
966 ;; "unspecified" color.
967 (or saving
968 (not (desktop-switch-to-gui-p parameters))
969 (not (stringp (cdr current)))
970 (not (string-match-p "^unspecified-[fb]g$" (cdr current)))))
972 (defun desktop--filter-minibuffer (current _parameters saving)
973 ;; When minibuffer is a window, save it as minibuffer . t
974 (or (not saving)
975 (if (windowp (cdr current))
976 '(minibuffer . t)
977 t)))
979 (defun desktop--filter-restore-desktop-parm (current parameters saving)
980 ;; When switching to a GUI frame, convert desktop-XXX parameter to XXX
981 (or saving
982 (not (desktop-switch-to-gui-p parameters))
983 (let ((val (cdr current)))
984 (if (eq val :desktop-processed)
986 (cons (intern (substring (symbol-name (car current))
987 8)) ;; (length "desktop-")
988 val)))))
990 (defun desktop--filter-save-desktop-parm (current parameters saving)
991 ;; When switching to a tty frame, save parameter XXX as desktop-XXX so it
992 ;; can be restored in a subsequent GUI session, unless it already exists.
993 (cond (saving t)
994 ((desktop-switch-to-tty-p parameters)
995 (let ((sym (intern (format "desktop-%s" (car current)))))
996 (if (assq sym parameters)
998 (cons sym (cdr current)))))
999 ((desktop-switch-to-gui-p parameters)
1000 (let* ((dtp (assq (intern (format "desktop-%s" (car current)))
1001 parameters))
1002 (val (cdr dtp)))
1003 (if (eq val :desktop-processed)
1005 (setcdr dtp :desktop-processed)
1006 (cons (car current) val))))
1007 (t t)))
1009 (defun desktop--filter-iconified-position (_current parameters saving)
1010 ;; When saving an iconified frame, top & left are meaningless,
1011 ;; so remove them to allow restoring to a default position.
1012 (not (and saving (eq (cdr (assq 'visibility parameters)) 'icon))))
1014 (defun desktop-restore-in-original-display-p ()
1015 "True if saved frames' displays should be honored."
1016 (cond ((daemonp) t)
1017 ((eq system-type 'windows-nt) nil)
1018 (t (null desktop-restore-in-current-display))))
1020 (defun desktop--filter-frame-parms (parameters saving)
1021 "Filter frame parameters and return filtered list.
1022 PARAMETERS is a parameter alist as returned by `frame-parameters'.
1023 If SAVING is non-nil, filtering is happening before saving frame state;
1024 otherwise, filtering is being done before restoring frame state.
1025 Parameters are filtered according to the setting of
1026 `desktop-filter-parameters-alist' (which see).
1027 Internal use only."
1028 (let ((filtered nil))
1029 (dolist (param parameters)
1030 (let ((filter (cdr (assq (car param) desktop-filter-parameters-alist)))
1031 this)
1032 (cond (;; no filter: pass param
1033 (null filter)
1034 (push param filtered))
1035 (;; filter = t; skip param
1036 (eq filter t))
1037 (;; filter func returns nil: skip param
1038 (null (setq this (funcall filter param parameters saving))))
1039 (;; filter func returns t: pass param
1040 (eq this t)
1041 (push param filtered))
1042 (;; filter func returns a new param: use it
1044 (push this filtered)))))
1045 ;; Set the display parameter after filtering, so that filter functions
1046 ;; have access to its original value.
1047 (when desktop--target-display
1048 (let ((display (assq 'display filtered)))
1049 (if display
1050 (setcdr display (cdr desktop--target-display))
1051 (push desktop--target-display filtered))))
1052 filtered))
1054 (defun desktop--save-minibuffer-frames ()
1055 ;; Adds a desktop-mini parameter to frames
1056 ;; desktop-mini is a list (MINIBUFFER NUMBER DEFAULT?) where
1057 ;; MINIBUFFER t if the frame (including minibuffer-only) owns a minibuffer
1058 ;; NUMBER if MINIBUFFER = t, an ID for the frame; if nil, the ID of
1059 ;; the frame containing the minibuffer used by this frame
1060 ;; DEFAULT? if t, this frame is the value of default-minibuffer-frame
1061 ;; FIXME: What happens with multi-terminal sessions?
1062 (let ((frames (frame-list))
1063 (count 0))
1064 ;; Reset desktop-mini for all frames
1065 (dolist (frame frames)
1066 (set-frame-parameter frame 'desktop-mini nil))
1067 ;; Number all frames with its own minibuffer
1068 (dolist (frame (minibuffer-frame-list))
1069 (set-frame-parameter frame 'desktop-mini
1070 (list t
1071 (setq count (1+ count))
1072 (eq frame default-minibuffer-frame))))
1073 ;; Now link minibufferless frames with their minibuffer frames
1074 (dolist (frame frames)
1075 (unless (frame-parameter frame 'desktop-mini)
1076 (let* ((mb-frame (window-frame (minibuffer-window frame)))
1077 (this (cadr (frame-parameter mb-frame 'desktop-mini))))
1078 (set-frame-parameter frame 'desktop-mini (list nil this nil)))))))
1080 (defun desktop--save-frames ()
1081 "Save window/frame state, as a global variable.
1082 Intended to be called from `desktop-save'.
1083 Internal use only."
1084 (setq desktop--saved-states
1085 (and desktop-restore-frames
1086 (progn
1087 (desktop--save-minibuffer-frames)
1088 (mapcar (lambda (frame)
1089 (cons (desktop--filter-frame-parms (frame-parameters frame) t)
1090 (window-state-get (frame-root-window frame) t)))
1091 (frame-list)))))
1092 (unless (memq 'desktop--saved-states desktop-globals-to-save)
1093 (desktop-outvar 'desktop--saved-states)))
1095 ;;;###autoload
1096 (defun desktop-save (dirname &optional release auto-save)
1097 "Save the desktop in a desktop file.
1098 Parameter DIRNAME specifies where to save the desktop file.
1099 Optional parameter RELEASE says whether we're done with this desktop.
1100 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
1101 and don't save the buffer if they are the same."
1102 (interactive "DDirectory to save desktop file in: ")
1103 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
1104 (save-excursion
1105 (let ((eager desktop-restore-eager)
1106 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
1107 (when
1108 (or (not new-modtime) ; nothing to overwrite
1109 (equal desktop-file-modtime new-modtime)
1110 (yes-or-no-p (if desktop-file-modtime
1111 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
1112 "Desktop file is more recent than the one loaded. Save anyway? "
1113 "Desktop file isn't the one loaded. Overwrite it? ")
1114 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
1115 (unless release (error "Desktop file conflict")))
1117 ;; If we're done with it, release the lock.
1118 ;; Otherwise, claim it if it's unclaimed or if we created it.
1119 (if release
1120 (desktop-release-lock)
1121 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
1123 (with-temp-buffer
1124 (insert
1125 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
1126 desktop-header
1127 ";; Created " (current-time-string) "\n"
1128 ";; Desktop file format version " desktop-file-version "\n"
1129 ";; Emacs version " emacs-version "\n")
1130 (save-excursion (run-hooks 'desktop-save-hook))
1131 (goto-char (point-max))
1132 (insert "\n;; Global section:\n")
1133 ;; Called here because we save the window/frame state as a global
1134 ;; variable for compatibility with previous Emacsen.
1135 (desktop--save-frames)
1136 (mapc (function desktop-outvar) desktop-globals-to-save)
1137 (when (memq 'kill-ring desktop-globals-to-save)
1138 (insert
1139 "(setq kill-ring-yank-pointer (nthcdr "
1140 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
1141 " kill-ring))\n"))
1143 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
1144 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
1145 (let ((base (pop l)))
1146 (when (apply 'desktop-save-buffer-p l)
1147 (insert "("
1148 (if (or (not (integerp eager))
1149 (if (zerop eager)
1151 (setq eager (1- eager))))
1152 "desktop-create-buffer"
1153 "desktop-append-buffer-args")
1155 desktop-file-version)
1156 ;; If there's a non-empty base name, we save it instead of the buffer name
1157 (when (and base (not (string= base "")))
1158 (setcar (nthcdr 1 l) base))
1159 (dolist (e l)
1160 (insert "\n " (desktop-value-to-string e)))
1161 (insert ")\n\n"))))
1163 (setq default-directory desktop-dirname)
1164 ;; If auto-saving, avoid writing if nothing has changed since the last write.
1165 ;; Don't check 300 characters of the header that contains the timestamp.
1166 (let ((checksum (and auto-save (md5 (current-buffer)
1167 (+ (point-min) 300) (point-max)
1168 'emacs-mule))))
1169 (unless (and auto-save (equal checksum desktop-file-checksum))
1170 (let ((coding-system-for-write 'emacs-mule))
1171 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
1172 (setq desktop-file-checksum checksum)
1173 ;; We remember when it was modified (which is presumably just now).
1174 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
1176 ;; ----------------------------------------------------------------------------
1177 ;;;###autoload
1178 (defun desktop-remove ()
1179 "Delete desktop file in `desktop-dirname'.
1180 This function also sets `desktop-dirname' to nil."
1181 (interactive)
1182 (when desktop-dirname
1183 (let ((filename (desktop-full-file-name)))
1184 (setq desktop-dirname nil)
1185 (when (file-exists-p filename)
1186 (delete-file filename)))))
1188 (defvar desktop-buffer-args-list nil
1189 "List of args for `desktop-create-buffer'.")
1191 (defvar desktop-lazy-timer nil)
1193 ;; ----------------------------------------------------------------------------
1194 (defvar desktop--reuse-list nil
1195 "Internal use only.")
1197 (defun desktop--find-frame (predicate display &rest args)
1198 "Find a suitable frame in `desktop--reuse-list'.
1199 Look through frames whose display property matches DISPLAY and
1200 return the first one for which (PREDICATE frame ARGS) returns t.
1201 If PREDICATE is nil, it is always satisfied. Internal use only.
1202 This is an auxiliary function for `desktop--select-frame'."
1203 (catch :found
1204 (dolist (frame desktop--reuse-list)
1205 (when (and (equal (frame-parameter frame 'display) display)
1206 (or (null predicate)
1207 (apply predicate frame args)))
1208 (throw :found frame)))
1209 nil))
1211 (defun desktop--select-frame (display frame-cfg)
1212 "Look for an existing frame to reuse.
1213 DISPLAY is the display where the frame will be shown, and FRAME-CFG
1214 is the parameter list of the frame being restored. Internal use only."
1215 (if (eq desktop-restoring-reuses-frames t)
1216 (let ((frame nil)
1217 mini)
1218 ;; There are no fancy heuristics there. We could implement some
1219 ;; based on frame size and/or position, etc., but it is not clear
1220 ;; that any "gain" (in the sense of reduced flickering, etc.) is
1221 ;; worth the added complexity. In fact, the code below mainly
1222 ;; tries to work nicely when M-x desktop-read is used after a desktop
1223 ;; session has already been loaded. The other main use case, which
1224 ;; is the initial desktop-read upon starting Emacs, should usually
1225 ;; only have one, or very few, frame(s) to reuse.
1226 (cond (;; When the target is tty, every existing frame is reusable.
1227 (null display)
1228 (setq frame (desktop--find-frame nil display)))
1229 (;; If the frame has its own minibuffer, let's see whether
1230 ;; that frame has already been loaded (which can happen after
1231 ;; M-x desktop-read).
1232 (car (setq mini (cdr (assq 'desktop-mini frame-cfg))))
1233 (setq frame (or (desktop--find-frame
1234 (lambda (f m)
1235 (equal (frame-parameter f 'desktop-mini) m))
1236 display mini))))
1237 (;; For minibufferless frames, check whether they already exist,
1238 ;; and that they are linked to the right minibuffer frame.
1239 mini
1240 (setq frame (desktop--find-frame
1241 (lambda (f n)
1242 (let ((m (frame-parameter f 'desktop-mini)))
1243 (and m
1244 (null (car m))
1245 (= (cadr m) n)
1246 (equal (cadr (frame-parameter
1247 (window-frame (minibuffer-window f))
1248 'desktop-mini))
1249 n))))
1250 display (cadr mini))))
1251 (;; Default to just finding a frame in the same display.
1253 (setq frame (desktop--find-frame nil display))))
1254 ;; If found, remove from the list.
1255 (when frame
1256 (setq desktop--reuse-list (delq frame desktop--reuse-list)))
1257 frame)
1258 nil))
1260 (defun desktop--make-frame (frame-cfg window-cfg)
1261 "Set up a frame according to its saved state.
1262 That means either creating a new frame or reusing an existing one.
1263 FRAME-CFG is the parameter list of the new frame; WINDOW-CFG is
1264 its window state. Internal use only."
1265 (let* ((fullscreen (cdr (assq 'fullscreen frame-cfg)))
1266 (lines (assq 'tool-bar-lines frame-cfg))
1267 (filtered-cfg (desktop--filter-frame-parms frame-cfg nil))
1268 (display (cdr (assq 'display filtered-cfg))) ;; post-filtering
1269 alt-cfg frame)
1271 ;; This works around bug#14795 (or feature#14795, if not a bug :-)
1272 (setq filtered-cfg (assq-delete-all 'tool-bar-lines filtered-cfg))
1273 (push '(tool-bar-lines . 0) filtered-cfg)
1275 (when fullscreen
1276 ;; Currently Emacs has the limitation that it does not record the size
1277 ;; and position of a frame before maximizing it, so we cannot save &
1278 ;; restore that info. Instead, when restoring, we resort to creating
1279 ;; invisible "fullscreen" frames of default size and then maximizing them
1280 ;; (and making them visible) which at least is somewhat user-friendly
1281 ;; when these frames are later de-maximized.
1282 (let ((width (and (eq fullscreen 'fullheight) (cdr (assq 'width filtered-cfg))))
1283 (height (and (eq fullscreen 'fullwidth) (cdr (assq 'height filtered-cfg))))
1284 (visible (assq 'visibility filtered-cfg)))
1285 (dolist (parameter '(visibility fullscreen width height))
1286 (setq filtered-cfg (assq-delete-all parameter filtered-cfg)))
1287 (when width
1288 (setq filtered-cfg (append `((user-size . t) (width . ,width))
1289 filtered-cfg)))
1290 (when height
1291 (setq filtered-cfg (append `((user-size . t) (height . ,height))
1292 filtered-cfg)))
1293 ;; These are parameters to apply after creating/setting the frame.
1294 (push visible alt-cfg)
1295 (push (cons 'fullscreen fullscreen) alt-cfg)))
1297 ;; Time to select or create a frame an apply the big bunch of parameters
1298 (if (setq frame (desktop--select-frame display filtered-cfg))
1299 (modify-frame-parameters frame filtered-cfg)
1300 (setq frame (make-frame-on-display display filtered-cfg)))
1302 ;; Let's give the finishing touches (visibility, tool-bar, maximization).
1303 (when lines (push lines alt-cfg))
1304 (when alt-cfg (modify-frame-parameters frame alt-cfg))
1305 ;; Now restore window state.
1306 (window-state-put window-cfg (frame-root-window frame) 'safe)
1307 frame))
1309 (defun desktop--sort-states (state1 state2)
1310 ;; Order: default minibuffer frame
1311 ;; other frames with minibuffer, ascending ID
1312 ;; minibufferless frames, ascending ID
1313 (let ((dm1 (cdr (assq 'desktop-mini (car state1))))
1314 (dm2 (cdr (assq 'desktop-mini (car state2)))))
1315 (cond ((nth 2 dm1) t)
1316 ((nth 2 dm2) nil)
1317 ((null (car dm2)) t)
1318 ((null (car dm1)) nil)
1319 (t (< (cadr dm1) (cadr dm2))))))
1321 (defun desktop--restore-frames ()
1322 "Restore window/frame configuration.
1323 Internal use only."
1324 (when (and desktop-restore-frames desktop--saved-states)
1325 (let* ((frame-mb-map nil) ;; Alist of frames with their own minibuffer
1326 (visible nil)
1327 (delete-saved (eq desktop-restore-in-current-display 'delete))
1328 (forcing (not (desktop-restore-in-original-display-p)))
1329 (target (and forcing (cons 'display (frame-parameter nil 'display)))))
1331 ;; Sorting saved states allows us to easily restore minibuffer-owning frames
1332 ;; before minibufferless ones.
1333 (setq desktop--saved-states (sort desktop--saved-states #'desktop--sort-states))
1334 ;; Potentially all existing frames are reusable. Later we will decide which ones
1335 ;; to reuse, and how to deal with any leftover.
1336 (setq desktop--reuse-list (frame-list))
1338 (dolist (state desktop--saved-states)
1339 (condition-case err
1340 (let* ((frame-cfg (car state))
1341 (window-cfg (cdr state))
1342 (d-mini (cdr (assq 'desktop-mini frame-cfg)))
1343 num frame to-tty)
1344 ;; Only set target if forcing displays and the target display is different.
1345 (if (or (not forcing)
1346 (equal target (or (assq 'display frame-cfg) '(display . nil))))
1347 (setq desktop--target-display nil)
1348 (setq desktop--target-display target
1349 to-tty (null (cdr target))))
1350 ;; Time to restore frames and set up their minibuffers as they were.
1351 ;; We only skip a frame (thus deleting it) if either:
1352 ;; - we're switching displays, and the user chose the option to delete, or
1353 ;; - we're switching to tty, and the frame to restore is minibuffer-only.
1354 (unless (and desktop--target-display
1355 (or delete-saved
1356 (and to-tty
1357 (eq (cdr (assq 'minibuffer frame-cfg)) 'only))))
1359 ;; Restore minibuffers. Some of this stuff could be done in a filter
1360 ;; function, but it would be messy because restoring minibuffers affects
1361 ;; global state; it's best to do it here than add a bunch of global
1362 ;; variables to pass info back-and-forth to/from the filter function.
1363 (cond
1364 ((null d-mini)) ;; No desktop-mini. Process as normal frame.
1365 (to-tty) ;; Ignore minibuffer stuff and process as normal frame.
1366 ((car d-mini) ;; Frame has its own minibuffer (or it is minibuffer-only).
1367 (setq num (cadr d-mini))
1368 (when (eq (cdr (assq 'minibuffer frame-cfg)) 'only)
1369 (setq frame-cfg (append '((tool-bar-lines . 0) (menu-bar-lines . 0))
1370 frame-cfg))))
1371 (t ;; Frame depends on other frame's minibuffer window.
1372 (let ((mb-frame (cdr (assq (cadr d-mini) frame-mb-map))))
1373 (unless (frame-live-p mb-frame)
1374 (error "Minibuffer frame %s not found" (cadr d-mini)))
1375 (let ((mb-param (assq 'minibuffer frame-cfg))
1376 (mb-window (minibuffer-window mb-frame)))
1377 (unless (and (window-live-p mb-window)
1378 (window-minibuffer-p mb-window))
1379 (error "Not a minibuffer window %s" mb-window))
1380 (if mb-param
1381 (setcdr mb-param mb-window)
1382 (push (cons 'minibuffer mb-window) frame-cfg))))))
1383 ;; OK, we're ready at last to create (or reuse) a frame and
1384 ;; restore the window config.
1385 (setq frame (desktop--make-frame frame-cfg window-cfg))
1386 ;; Set default-minibuffer if required.
1387 (when (nth 2 d-mini) (setq default-minibuffer-frame frame))
1388 ;; Store frame/NUM to assign to minibufferless frames.
1389 (when num (push (cons num frame) frame-mb-map))
1390 ;; Try to locate at least one visible frame.
1391 (when (and (not visible) (frame-visible-p frame))
1392 (setq visible frame))))
1393 (error
1394 (delay-warning 'desktop (error-message-string err) :error))))
1396 ;; Delete remaining frames, but do not fail if some resist being deleted.
1397 (unless (eq desktop-restoring-reuses-frames 'keep)
1398 (dolist (frame desktop--reuse-list)
1399 (ignore-errors (delete-frame frame))))
1400 (setq desktop--reuse-list nil)
1401 ;; Make sure there's at least one visible frame, and select it.
1402 (unless (or visible (daemonp))
1403 (setq visible (if (frame-live-p default-minibuffer-frame)
1404 default-minibuffer-frame
1405 (car (frame-list))))
1406 (make-frame-visible visible)
1407 (select-frame-set-input-focus visible)))))
1409 ;;;###autoload
1410 (defun desktop-read (&optional dirname)
1411 "Read and process the desktop file in directory DIRNAME.
1412 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1413 directories listed in `desktop-path'. If a desktop file is found, it
1414 is processed and `desktop-after-read-hook' is run. If no desktop file
1415 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1416 This function is a no-op when Emacs is running in batch mode.
1417 It returns t if a desktop file was loaded, nil otherwise."
1418 (interactive)
1419 (unless noninteractive
1420 (setq desktop-dirname
1421 (file-name-as-directory
1422 (expand-file-name
1424 ;; If DIRNAME is specified, use it.
1425 (and (< 0 (length dirname)) dirname)
1426 ;; Otherwise search desktop file in desktop-path.
1427 (let ((dirs desktop-path))
1428 (while (and dirs
1429 (not (file-exists-p
1430 (desktop-full-file-name (car dirs)))))
1431 (setq dirs (cdr dirs)))
1432 (and dirs (car dirs)))
1433 ;; If not found and `desktop-path' is non-nil, use its first element.
1434 (and desktop-path (car desktop-path))
1435 ;; Default: .emacs.d.
1436 user-emacs-directory))))
1437 (if (file-exists-p (desktop-full-file-name))
1438 ;; Desktop file found, but is it already in use?
1439 (let ((desktop-first-buffer nil)
1440 (desktop-buffer-ok-count 0)
1441 (desktop-buffer-fail-count 0)
1442 (owner (desktop-owner))
1443 ;; Avoid desktop saving during evaluation of desktop buffer.
1444 (desktop-save nil))
1445 (if (and owner
1446 (memq desktop-load-locked-desktop '(nil ask))
1447 (or (null desktop-load-locked-desktop)
1448 (daemonp)
1449 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1450 Using it may cause conflicts. Use it anyway? " owner)))))
1451 (let ((default-directory desktop-dirname))
1452 (setq desktop-dirname nil)
1453 (run-hooks 'desktop-not-loaded-hook)
1454 (unless desktop-dirname
1455 (message "Desktop file in use; not loaded.")))
1456 (desktop-lazy-abort)
1457 ;; Evaluate desktop buffer and remember when it was modified.
1458 (load (desktop-full-file-name) t t t)
1459 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1460 ;; If it wasn't already, mark it as in-use, to bother other
1461 ;; desktop instances.
1462 (unless owner
1463 (condition-case nil
1464 (desktop-claim-lock)
1465 (file-error (message "Couldn't record use of desktop file")
1466 (sit-for 1))))
1468 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1469 ;; We want buffers existing prior to evaluating the desktop (and
1470 ;; not reused) to be placed at the end of the buffer list, so we
1471 ;; move them here.
1472 (mapc 'bury-buffer
1473 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1474 (switch-to-buffer (car (buffer-list)))
1475 (run-hooks 'desktop-delay-hook)
1476 (setq desktop-delay-hook nil)
1477 (desktop--restore-frames)
1478 (run-hooks 'desktop-after-read-hook)
1479 (message "Desktop: %d buffer%s restored%s%s."
1480 desktop-buffer-ok-count
1481 (if (= 1 desktop-buffer-ok-count) "" "s")
1482 (if (< 0 desktop-buffer-fail-count)
1483 (format ", %d failed to restore" desktop-buffer-fail-count)
1485 (if desktop-buffer-args-list
1486 (format ", %d to restore lazily"
1487 (length desktop-buffer-args-list))
1488 ""))
1489 ;; Bury the *Messages* buffer to not reshow it when burying
1490 ;; the buffer we switched to above.
1491 (when (buffer-live-p (get-buffer "*Messages*"))
1492 (bury-buffer "*Messages*"))
1493 ;; Clear all windows' previous and next buffers, these have
1494 ;; been corrupted by the `switch-to-buffer' calls in
1495 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1496 ;; brute force fix and should be replaced by a more subtle
1497 ;; strategy eventually.
1498 (walk-window-tree (lambda (window)
1499 (set-window-prev-buffers window nil)
1500 (set-window-next-buffers window nil)))
1502 ;; No desktop file found.
1503 (desktop-clear)
1504 (let ((default-directory desktop-dirname))
1505 (run-hooks 'desktop-no-desktop-file-hook))
1506 (message "No desktop file.")
1507 nil)))
1509 ;; ----------------------------------------------------------------------------
1510 ;; Maintained for backward compatibility
1511 ;;;###autoload
1512 (defun desktop-load-default ()
1513 "Load the `default' start-up library manually.
1514 Also inhibit further loading of it."
1515 (declare (obsolete desktop-save-mode "22.1"))
1516 (unless inhibit-default-init ; safety check
1517 (load "default" t t)
1518 (setq inhibit-default-init t)))
1520 ;; ----------------------------------------------------------------------------
1521 ;;;###autoload
1522 (defun desktop-change-dir (dirname)
1523 "Change to desktop saved in DIRNAME.
1524 Kill the desktop as specified by variables `desktop-save-mode' and
1525 `desktop-save', then clear the desktop and load the desktop file in
1526 directory DIRNAME."
1527 (interactive "DChange to directory: ")
1528 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1529 (desktop-kill)
1530 (desktop-clear)
1531 (desktop-read dirname))
1533 ;; ----------------------------------------------------------------------------
1534 ;;;###autoload
1535 (defun desktop-save-in-desktop-dir ()
1536 "Save the desktop in directory `desktop-dirname'."
1537 (interactive)
1538 (if desktop-dirname
1539 (desktop-save desktop-dirname)
1540 (call-interactively 'desktop-save))
1541 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1543 ;; ----------------------------------------------------------------------------
1544 ;; Auto-Saving.
1545 (defvar desktop-auto-save-timer nil)
1547 (defun desktop-auto-save ()
1548 "Save the desktop periodically.
1549 Called by the timer created in `desktop-auto-save-set-timer'."
1550 (when (and desktop-save-mode
1551 (integerp desktop-auto-save-timeout)
1552 (> desktop-auto-save-timeout 0)
1553 ;; Avoid desktop saving during lazy loading.
1554 (not desktop-lazy-timer)
1555 ;; Save only to own desktop file.
1556 (eq (emacs-pid) (desktop-owner))
1557 desktop-dirname)
1558 (desktop-save desktop-dirname nil t))
1559 (desktop-auto-save-set-timer))
1561 (defun desktop-auto-save-set-timer ()
1562 "Reset the auto-save timer.
1563 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1564 integer, start a new timer to call `desktop-auto-save' in that many seconds."
1565 (when desktop-auto-save-timer
1566 (cancel-timer desktop-auto-save-timer)
1567 (setq desktop-auto-save-timer nil))
1568 (when (and (integerp desktop-auto-save-timeout)
1569 (> desktop-auto-save-timeout 0))
1570 (setq desktop-auto-save-timer
1571 (run-with-timer desktop-auto-save-timeout nil
1572 'desktop-auto-save))))
1574 ;; ----------------------------------------------------------------------------
1575 ;;;###autoload
1576 (defun desktop-revert ()
1577 "Revert to the last loaded desktop."
1578 (interactive)
1579 (unless desktop-dirname
1580 (error "Unknown desktop directory"))
1581 (unless (file-exists-p (desktop-full-file-name))
1582 (error "No desktop file found"))
1583 (desktop-clear)
1584 (desktop-read desktop-dirname))
1586 (defvar desktop-buffer-major-mode)
1587 (defvar desktop-buffer-locals)
1588 (defvar auto-insert) ; from autoinsert.el
1589 ;; ----------------------------------------------------------------------------
1590 (defun desktop-restore-file-buffer (buffer-filename
1591 _buffer-name
1592 _buffer-misc)
1593 "Restore a file buffer."
1594 (when buffer-filename
1595 (if (or (file-exists-p buffer-filename)
1596 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1597 buffer-filename)))
1598 (if desktop-missing-file-warning
1599 (y-or-n-p (concat msg " Re-create buffer? "))
1600 (message "%s" msg)
1601 nil)))
1602 (let* ((auto-insert nil) ; Disable auto insertion
1603 (coding-system-for-read
1604 (or coding-system-for-read
1605 (cdr (assq 'buffer-file-coding-system
1606 desktop-buffer-locals))))
1607 (buf (find-file-noselect buffer-filename)))
1608 (condition-case nil
1609 (switch-to-buffer buf)
1610 (error (pop-to-buffer buf)))
1611 (and (not (eq major-mode desktop-buffer-major-mode))
1612 (functionp desktop-buffer-major-mode)
1613 (funcall desktop-buffer-major-mode))
1614 buf)
1615 nil)))
1617 (defun desktop-load-file (function)
1618 "Load the file where auto loaded FUNCTION is defined."
1619 (when (fboundp function)
1620 (autoload-do-load (symbol-function function) function)))
1622 ;; ----------------------------------------------------------------------------
1623 ;; Create a buffer, load its file, set its mode, ...;
1624 ;; called from Desktop file only.
1626 ;; Just to silence the byte compiler.
1628 (defvar desktop-first-buffer) ; Dynamically bound in `desktop-read'
1630 ;; Bound locally in `desktop-read'.
1631 (defvar desktop-buffer-ok-count)
1632 (defvar desktop-buffer-fail-count)
1634 (defun desktop-create-buffer
1635 (file-version
1636 buffer-filename
1637 buffer-name
1638 buffer-majormode
1639 buffer-minormodes
1640 buffer-point
1641 buffer-mark
1642 buffer-readonly
1643 buffer-misc
1644 &optional
1645 buffer-locals)
1647 (let ((desktop-file-version file-version)
1648 (desktop-buffer-file-name buffer-filename)
1649 (desktop-buffer-name buffer-name)
1650 (desktop-buffer-major-mode buffer-majormode)
1651 (desktop-buffer-minor-modes buffer-minormodes)
1652 (desktop-buffer-point buffer-point)
1653 (desktop-buffer-mark buffer-mark)
1654 (desktop-buffer-read-only buffer-readonly)
1655 (desktop-buffer-misc buffer-misc)
1656 (desktop-buffer-locals buffer-locals))
1657 ;; To make desktop files with relative file names possible, we cannot
1658 ;; allow `default-directory' to change. Therefore we save current buffer.
1659 (save-current-buffer
1660 ;; Give major mode module a chance to add a handler.
1661 (desktop-load-file desktop-buffer-major-mode)
1662 (let ((buffer-list (buffer-list))
1663 (result
1664 (condition-case-unless-debug err
1665 (funcall (or (cdr (assq desktop-buffer-major-mode
1666 desktop-buffer-mode-handlers))
1667 'desktop-restore-file-buffer)
1668 desktop-buffer-file-name
1669 desktop-buffer-name
1670 desktop-buffer-misc)
1671 (error
1672 (message "Desktop: Can't load buffer %s: %s"
1673 desktop-buffer-name
1674 (error-message-string err))
1675 (when desktop-missing-file-warning (sit-for 1))
1676 nil))))
1677 (if (bufferp result)
1678 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1679 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1680 (setq result nil))
1681 ;; Restore buffer list order with new buffer at end. Don't change
1682 ;; the order for old desktop files (old desktop module behavior).
1683 (unless (< desktop-file-version 206)
1684 (mapc 'bury-buffer buffer-list)
1685 (when result (bury-buffer result)))
1686 (when result
1687 (unless (or desktop-first-buffer (< desktop-file-version 206))
1688 (setq desktop-first-buffer result))
1689 (set-buffer result)
1690 (unless (equal (buffer-name) desktop-buffer-name)
1691 (rename-buffer desktop-buffer-name t))
1692 ;; minor modes
1693 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1694 (auto-fill-mode 1))
1695 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1696 (auto-fill-mode 0))
1698 (dolist (minor-mode desktop-buffer-minor-modes)
1699 ;; Give minor mode module a chance to add a handler.
1700 (desktop-load-file minor-mode)
1701 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1702 (if handler
1703 (funcall handler desktop-buffer-locals)
1704 (when (functionp minor-mode)
1705 (funcall minor-mode 1)))))))
1706 ;; Even though point and mark are non-nil when written by
1707 ;; `desktop-save', they may be modified by handlers wanting to set
1708 ;; point or mark themselves.
1709 (when desktop-buffer-point
1710 (goto-char
1711 (condition-case err
1712 ;; Evaluate point. Thus point can be something like
1713 ;; '(search-forward ...
1714 (eval desktop-buffer-point)
1715 (error (message "%s" (error-message-string err)) 1))))
1716 (when desktop-buffer-mark
1717 (if (consp desktop-buffer-mark)
1718 (progn
1719 (set-mark (car desktop-buffer-mark))
1720 (setq mark-active (car (cdr desktop-buffer-mark))))
1721 (set-mark desktop-buffer-mark)))
1722 ;; Never override file system if the file really is read-only marked.
1723 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1724 (while desktop-buffer-locals
1725 (let ((this (car desktop-buffer-locals)))
1726 (if (consp this)
1727 ;; an entry of this form `(symbol . value)'
1728 (progn
1729 (make-local-variable (car this))
1730 (set (car this) (cdr this)))
1731 ;; an entry of the form `symbol'
1732 (make-local-variable this)
1733 (makunbound this)))
1734 (setq desktop-buffer-locals (cdr desktop-buffer-locals))))))))
1736 ;; ----------------------------------------------------------------------------
1737 ;; Backward compatibility -- update parameters to 205 standards.
1738 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1739 mim pt mk ro tl fc cfs cr buffer-misc)
1740 (desktop-create-buffer 205 buffer-filename buffer-name
1741 buffer-majormode (cdr mim) pt mk ro
1742 buffer-misc
1743 (list (cons 'truncate-lines tl)
1744 (cons 'fill-column fc)
1745 (cons 'case-fold-search cfs)
1746 (cons 'case-replace cr)
1747 (cons 'overwrite-mode (car mim)))))
1749 (defun desktop-append-buffer-args (&rest args)
1750 "Append ARGS at end of `desktop-buffer-args-list'.
1751 ARGS must be an argument list for `desktop-create-buffer'."
1752 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1753 (unless desktop-lazy-timer
1754 (setq desktop-lazy-timer
1755 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1757 (defun desktop-lazy-create-buffer ()
1758 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1759 (when desktop-buffer-args-list
1760 (let* ((remaining (length desktop-buffer-args-list))
1761 (args (pop desktop-buffer-args-list))
1762 (buffer-name (nth 2 args))
1763 (msg (format "Desktop lazily opening %s (%s remaining)..."
1764 buffer-name remaining)))
1765 (when desktop-lazy-verbose
1766 (message "%s" msg))
1767 (let ((desktop-first-buffer nil)
1768 (desktop-buffer-ok-count 0)
1769 (desktop-buffer-fail-count 0))
1770 (apply 'desktop-create-buffer args)
1771 (run-hooks 'desktop-delay-hook)
1772 (setq desktop-delay-hook nil)
1773 (bury-buffer (get-buffer buffer-name))
1774 (when desktop-lazy-verbose
1775 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1777 (defun desktop-idle-create-buffers ()
1778 "Create buffers until the user does something, then stop.
1779 If there are no buffers left to create, kill the timer."
1780 (let ((repeat 1))
1781 (while (and repeat desktop-buffer-args-list)
1782 (save-window-excursion
1783 (desktop-lazy-create-buffer))
1784 (setq repeat (sit-for 0.2))
1785 (unless desktop-buffer-args-list
1786 (cancel-timer desktop-lazy-timer)
1787 (setq desktop-lazy-timer nil)
1788 (message "Lazy desktop load complete")
1789 (sit-for 3)
1790 (message "")))))
1792 (defun desktop-lazy-complete ()
1793 "Run the desktop load to completion."
1794 (interactive)
1795 (let ((desktop-lazy-verbose t))
1796 (while desktop-buffer-args-list
1797 (save-window-excursion
1798 (desktop-lazy-create-buffer)))
1799 (message "Lazy desktop load complete")))
1801 (defun desktop-lazy-abort ()
1802 "Abort lazy loading of the desktop."
1803 (interactive)
1804 (when desktop-lazy-timer
1805 (cancel-timer desktop-lazy-timer)
1806 (setq desktop-lazy-timer nil))
1807 (when desktop-buffer-args-list
1808 (setq desktop-buffer-args-list nil)
1809 (when (called-interactively-p 'interactive)
1810 (message "Lazy desktop load aborted"))))
1812 ;; ----------------------------------------------------------------------------
1813 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1814 ;; command line, we do the rest of what it takes to use desktop, but do it
1815 ;; after finishing loading the init file.
1816 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1817 ;; functions are processed after `after-init-hook'.
1818 (add-hook
1819 'after-init-hook
1820 (lambda ()
1821 (let ((key "--no-desktop"))
1822 (when (member key command-line-args)
1823 (setq command-line-args (delete key command-line-args))
1824 (setq desktop-save-mode nil)))
1825 (when desktop-save-mode
1826 (desktop-read)
1827 (desktop-auto-save-set-timer)
1828 (setq inhibit-startup-screen t))))
1830 ;; So we can restore vc-dir buffers.
1831 (autoload 'vc-dir-mode "vc-dir" nil t)
1833 (provide 'desktop)
1835 ;;; desktop.el ends here