lisp/desktop.el: Make some frame-restoring functions public.
[bpt/emacs.git] / lisp / desktop.el
1 ;;; desktop.el --- save partial status of Emacs when killed
2
3 ;; Copyright (C) 1993-1995, 1997, 2000-2013 Free Software Foundation,
4 ;; Inc.
5
6 ;; Author: Morten Welinder <terra@diku.dk>
7 ;; Keywords: convenience
8 ;; Favorite-brand-of-beer: None, I hate beer.
9
10 ;; This file is part of GNU Emacs.
11
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.
16
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.
21
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/>.
24
25 ;;; Commentary:
26
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
37
38 ;; To use this, use customize to turn on desktop-save-mode or add the
39 ;; following line somewhere in your init file:
40 ;;
41 ;; (desktop-save-mode 1)
42 ;;
43 ;; For further usage information, look at the section
44 ;; (info "(emacs)Saving Emacs Sessions") in the GNU Emacs Manual.
45
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.
51
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
58 ;;
59 ;; (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
60 ;;
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
66 ;;
67 ;; (MINOR-MODE . RESTORE-FUNCTION).
68 ;;
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
73
74 ;; (defun foo-restore-desktop-buffer
75 ;; ...
76 ;; (add-to-list 'desktop-buffer-mode-handlers
77 ;; '(foo-mode . foo-restore-desktop-buffer))
78
79 ;; or
80
81 ;; (defun bar-desktop-restore
82 ;; ...
83 ;; (add-to-list 'desktop-minor-mode-handlers
84 ;; '(bar-mode . bar-desktop-restore))
85
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.
89
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
104
105 ;; (NAME RESTORE-FUNCTION)
106
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 ;; ---------------------------------------------------------------------------
112
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.
116
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.
120
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:
130 ;;
131 ;; Recognize more minor modes.
132 ;; Save mark rings.
133
134 ;;; Code:
135
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.")
140
141 ;; ----------------------------------------------------------------------------
142 ;; USER OPTIONS -- settings you might want to play with.
143 ;; ----------------------------------------------------------------------------
144
145 (defgroup desktop nil
146 "Save status of Emacs when you exit."
147 :group 'frames)
148
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.
157
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)
163
164 (defun desktop-save-mode-off ()
165 "Disable `desktop-save-mode'. Provided for use in hooks."
166 (desktop-save-mode 0))
167
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")
191
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")
202
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")
218
219 (define-obsolete-variable-alias 'desktop-basefilename
220 'desktop-base-file-name "22.1")
221
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)
227
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")
234
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
241
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'.
246
247 If nil, just print error messages in the message buffer."
248 :type 'boolean
249 :group 'desktop
250 :version "22.1")
251
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")
259
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")
268
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")
276
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)
284
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)
300
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")
315
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)
325
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)
349
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)
356
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)
364
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)
371
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")
377
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")
387
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")
397
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")
407
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")
415
416 (defcustom desktop-lazy-verbose t
417 "Verbose reporting of lazily created buffers."
418 :type 'boolean
419 :group 'desktop
420 :version "22.1")
421
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")
428
429 ;;;###autoload
430 (defvar-local desktop-save-buffer nil
431 "When non-nil, save buffer status in desktop file.
432
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.
436
437 When file names are returned, they should be formatted using the call
438 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
439
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")
447
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
453
454 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
455
456 Buffers with a major mode not specified here, are restored by the default
457 handler `desktop-restore-file-buffer'.
458
459 Handlers are called with argument list
460
461 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
462
463 Furthermore, they may use the following variables:
464
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
472
473 If a handler returns a buffer, then the saved mode settings
474 and variable values for that buffer are copied into it.
475
476 Modules that define a major mode that needs a special handler should contain
477 code like
478
479 (defun foo-restore-desktop-buffer
480 ...
481 (add-to-list 'desktop-buffer-mode-handlers
482 '(foo-mode . foo-restore-desktop-buffer))
483
484 Furthermore the major mode function must be autoloaded.")
485
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")
490
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)
507
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
513
514 (MINOR-MODE . RESTORE-FUNCTION).
515
516 Minor modes not specified here, are restored by the standard minor mode
517 function.
518
519 Handlers are called with argument list
520
521 (DESKTOP-BUFFER-LOCALS)
522
523 Furthermore, they may use the following variables:
524
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
534
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.
538
539 Modules that define a minor mode that needs a special handler should contain
540 code like
541
542 (defun foo-desktop-restore
543 ...
544 (add-to-list 'desktop-minor-mode-handlers
545 '(foo-mode . foo-desktop-restore))
546
547 Furthermore the minor mode function must be autoloaded.
548
549 See also `desktop-minor-mode-table'.")
550
551 ;;;###autoload
552 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
553
554 ;; ----------------------------------------------------------------------------
555 (defvar desktop-dirname nil
556 "The directory in which the desktop file should be saved.")
557
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)))
562
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)))
567
568 (defconst desktop-header
569 ";; --------------------------------------------------------------------------
570 ;; Desktop File for Emacs
571 ;; --------------------------------------------------------------------------
572 " "*Header to place in Desktop file.")
573
574 (defvar desktop-delay-hook nil
575 "Hooks run after all buffers are loaded; intended for internal use.")
576
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.")
580
581 (defvar desktop-saved-frame-states nil
582 "Saved state of all frames.
583 Only valid during frame saving & restoring; intended for internal use.")
584
585 ;; ----------------------------------------------------------------------------
586 ;; Desktop file conflict detection
587 (defvar desktop-file-modtime nil
588 "When the desktop file was last modified to the knowledge of this Emacs.
589 Used to detect desktop file conflicts.")
590
591 (defun desktop-owner (&optional dirname)
592 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
593 Return nil if no desktop file found or no Emacs process is using it.
594 DIRNAME omitted or nil means use `desktop-dirname'."
595 (let (owner
596 (file (desktop-full-lock-name dirname)))
597 (and (file-exists-p file)
598 (ignore-errors
599 (with-temp-buffer
600 (insert-file-contents-literally file)
601 (goto-char (point-min))
602 (setq owner (read (current-buffer)))
603 (integerp owner)))
604 owner)))
605
606 (defun desktop-claim-lock (&optional dirname)
607 "Record this Emacs process as the owner of the desktop file in DIRNAME.
608 DIRNAME omitted or nil means use `desktop-dirname'."
609 (write-region (number-to-string (emacs-pid)) nil
610 (desktop-full-lock-name dirname)))
611
612 (defun desktop-release-lock (&optional dirname)
613 "Remove the lock file for the desktop in DIRNAME.
614 DIRNAME omitted or nil means use `desktop-dirname'."
615 (let ((file (desktop-full-lock-name dirname)))
616 (when (file-exists-p file) (delete-file file))))
617
618 ;; ----------------------------------------------------------------------------
619 (defun desktop-truncate (list n)
620 "Truncate LIST to at most N elements destructively."
621 (let ((here (nthcdr (1- n) list)))
622 (when (consp here)
623 (setcdr here nil))))
624
625 ;; ----------------------------------------------------------------------------
626 ;;;###autoload
627 (defun desktop-clear ()
628 "Empty the Desktop.
629 This kills all buffers except for internal ones and those with names matched by
630 a regular expression in the list `desktop-clear-preserve-buffers'.
631 Furthermore, it clears the variables listed in `desktop-globals-to-clear'."
632 (interactive)
633 (desktop-lazy-abort)
634 (dolist (var desktop-globals-to-clear)
635 (if (symbolp var)
636 (eval `(setq-default ,var nil))
637 (eval `(setq-default ,(car var) ,(cdr var)))))
638 (let ((buffers (buffer-list))
639 (preserve-regexp (concat "^\\("
640 (mapconcat (lambda (regexp)
641 (concat "\\(" regexp "\\)"))
642 desktop-clear-preserve-buffers
643 "\\|")
644 "\\)$")))
645 (while buffers
646 (let ((bufname (buffer-name (car buffers))))
647 (or
648 (null bufname)
649 (string-match-p preserve-regexp bufname)
650 ;; Don't kill buffers made for internal purposes.
651 (and (not (equal bufname "")) (eq (aref bufname 0) ?\s))
652 (kill-buffer (car buffers))))
653 (setq buffers (cdr buffers))))
654 (delete-other-windows))
655
656 ;; ----------------------------------------------------------------------------
657 (unless noninteractive
658 (add-hook 'kill-emacs-hook 'desktop-kill))
659
660 (defun desktop-kill ()
661 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
662 If the desktop should be saved and `desktop-dirname'
663 is nil, ask the user where to save the desktop."
664 (when (and desktop-save-mode
665 (let ((exists (file-exists-p (desktop-full-file-name))))
666 (or (eq desktop-save t)
667 (and exists (eq desktop-save 'if-exists))
668 ;; If it exists, but we aren't using it, we are going
669 ;; to ask for a new directory below.
670 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
671 (and
672 (or (memq desktop-save '(ask ask-if-new))
673 (and exists (eq desktop-save 'ask-if-exists)))
674 (y-or-n-p "Save desktop? ")))))
675 (unless desktop-dirname
676 (setq desktop-dirname
677 (file-name-as-directory
678 (expand-file-name
679 (read-directory-name "Directory for desktop file: " nil nil t)))))
680 (condition-case err
681 (desktop-save desktop-dirname t)
682 (file-error
683 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
684 (signal (car err) (cdr err))))))
685 ;; If we own it, we don't anymore.
686 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
687
688 ;; ----------------------------------------------------------------------------
689 (defun desktop-list* (&rest args)
690 (if (null (cdr args))
691 (car args)
692 (setq args (nreverse args))
693 (let ((value (cons (nth 1 args) (car args))))
694 (setq args (cdr (cdr args)))
695 (while args
696 (setq value (cons (car args) value))
697 (setq args (cdr args)))
698 value)))
699
700 ;; ----------------------------------------------------------------------------
701 (defun desktop-buffer-info (buffer)
702 (set-buffer buffer)
703 (list
704 ;; base name of the buffer; replaces the buffer name if managed by uniquify
705 (and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
706 ;; basic information
707 (desktop-file-name (buffer-file-name) desktop-dirname)
708 (buffer-name)
709 major-mode
710 ;; minor modes
711 (let (ret)
712 (mapc
713 #'(lambda (minor-mode)
714 (and (boundp minor-mode)
715 (symbol-value minor-mode)
716 (let* ((special (assq minor-mode desktop-minor-mode-table))
717 (value (cond (special (cadr special))
718 ((functionp minor-mode) minor-mode))))
719 (when value (add-to-list 'ret value)))))
720 (mapcar #'car minor-mode-alist))
721 ret)
722 ;; point and mark, and read-only status
723 (point)
724 (list (mark t) mark-active)
725 buffer-read-only
726 ;; auxiliary information
727 (when (functionp desktop-save-buffer)
728 (funcall desktop-save-buffer desktop-dirname))
729 ;; local variables
730 (let ((locals desktop-locals-to-save)
731 (loclist (buffer-local-variables))
732 (ll))
733 (while locals
734 (let ((here (assq (car locals) loclist)))
735 (if here
736 (setq ll (cons here ll))
737 (when (member (car locals) loclist)
738 (setq ll (cons (car locals) ll)))))
739 (setq locals (cdr locals)))
740 ll)))
741
742 ;; ----------------------------------------------------------------------------
743 (defun desktop--v2s (value)
744 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
745 SEXP is an sexp that when evaluated yields VALUE.
746 QUOTE may be `may' (value may be quoted),
747 `must' (value must be quoted), or nil (value must not be quoted)."
748 (cond
749 ((or (numberp value) (null value) (eq t value) (keywordp value))
750 (cons 'may value))
751 ((stringp value)
752 (let ((copy (copy-sequence value)))
753 (set-text-properties 0 (length copy) nil copy)
754 ;; Get rid of text properties because we cannot read them.
755 (cons 'may copy)))
756 ((symbolp value)
757 (cons 'must value))
758 ((vectorp value)
759 (let* ((pass1 (mapcar #'desktop--v2s value))
760 (special (assq nil pass1)))
761 (if special
762 (cons nil `(vector
763 ,@(mapcar (lambda (el)
764 (if (eq (car el) 'must)
765 `',(cdr el) (cdr el)))
766 pass1)))
767 (cons 'may `[,@(mapcar #'cdr pass1)]))))
768 ((consp value)
769 (let ((p value)
770 newlist
771 use-list*)
772 (while (consp p)
773 (let ((q.sexp (desktop--v2s (car p))))
774 (push q.sexp newlist))
775 (setq p (cdr p)))
776 (when p
777 (let ((last (desktop--v2s p)))
778 (setq use-list* t)
779 (push last newlist)))
780 (if (assq nil newlist)
781 (cons nil
782 `(,(if use-list* 'desktop-list* 'list)
783 ,@(mapcar (lambda (el)
784 (if (eq (car el) 'must)
785 `',(cdr el) (cdr el)))
786 (nreverse newlist))))
787 (cons 'must
788 `(,@(mapcar #'cdr
789 (nreverse (if use-list* (cdr newlist) newlist)))
790 ,@(if use-list* (cdar newlist)))))))
791 ((subrp value)
792 (cons nil `(symbol-function
793 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
794 ((markerp value)
795 (let ((pos (marker-position value))
796 (buf (buffer-name (marker-buffer value))))
797 (cons nil
798 `(let ((mk (make-marker)))
799 (add-hook 'desktop-delay-hook
800 `(lambda ()
801 (set-marker ,mk ,,pos (get-buffer ,,buf))))
802 mk))))
803 (t ; Save as text.
804 (cons 'may "Unprintable entity"))))
805
806 ;; ----------------------------------------------------------------------------
807 (defun desktop-value-to-string (value)
808 "Convert VALUE to a string that when read evaluates to the same value.
809 Not all types of values are supported."
810 (let* ((print-escape-newlines t)
811 (float-output-format nil)
812 (quote.sexp (desktop--v2s value))
813 (quote (car quote.sexp))
814 (txt
815 (let ((print-quoted t))
816 (prin1-to-string (cdr quote.sexp)))))
817 (if (eq quote 'must)
818 (concat "'" txt)
819 txt)))
820
821 ;; ----------------------------------------------------------------------------
822 (defun desktop-outvar (varspec)
823 "Output a setq statement for variable VAR to the desktop file.
824 The argument VARSPEC may be the variable name VAR (a symbol),
825 or a cons cell of the form (VAR . MAX-SIZE),
826 which means to truncate VAR's value to at most MAX-SIZE elements
827 \(if the value is a list) before saving the value."
828 (let (var size)
829 (if (consp varspec)
830 (setq var (car varspec) size (cdr varspec))
831 (setq var varspec))
832 (when (boundp var)
833 (when (and (integerp size)
834 (> size 0)
835 (listp (eval var)))
836 (desktop-truncate (eval var) size))
837 (insert "(setq "
838 (symbol-name var)
839 " "
840 (desktop-value-to-string (symbol-value var))
841 ")\n"))))
842
843 ;; ----------------------------------------------------------------------------
844 (defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
845 "Return t if buffer should have its state saved in the desktop file.
846 FILENAME is the visited file name, BUFNAME is the buffer name, and
847 MODE is the major mode.
848 \n\(fn FILENAME BUFNAME MODE)"
849 (let ((case-fold-search nil)
850 dired-skip)
851 (and (not (and (stringp desktop-buffers-not-to-save)
852 (not filename)
853 (string-match-p desktop-buffers-not-to-save bufname)))
854 (not (memq mode desktop-modes-not-to-save))
855 ;; FIXME this is broken if desktop-files-not-to-save is nil.
856 (or (and filename
857 (stringp desktop-files-not-to-save)
858 (not (string-match-p desktop-files-not-to-save filename)))
859 (and (memq mode '(dired-mode vc-dir-mode))
860 (with-current-buffer bufname
861 (not (setq dired-skip
862 (string-match-p desktop-files-not-to-save
863 default-directory)))))
864 (and (null filename)
865 (null dired-skip) ; bug#5755
866 (with-current-buffer bufname desktop-save-buffer))))))
867
868 ;; ----------------------------------------------------------------------------
869 (defun desktop-file-name (filename dirname)
870 "Convert FILENAME to format specified in `desktop-file-name-format'.
871 DIRNAME must be the directory in which the desktop file will be saved."
872 (cond
873 ((not filename) nil)
874 ((eq desktop-file-name-format 'tilde)
875 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
876 (cond
877 ((file-name-absolute-p relative-name) relative-name)
878 ((string= "./" relative-name) "~/")
879 ((string= "." relative-name) "~")
880 (t (concat "~/" relative-name)))))
881 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
882 (t (expand-file-name filename))))
883
884
885 ;; ----------------------------------------------------------------------------
886 (defvar desktop-filter-parameters-alist
887 '((background-color . desktop--filter-*-color)
888 (buffer-list . t)
889 (buffer-predicate . t)
890 (buried-buffer-list . t)
891 (desktop-font . desktop--filter-restore-desktop-parm)
892 (desktop-fullscreen . desktop--filter-restore-desktop-parm)
893 (desktop-height . desktop--filter-restore-desktop-parm)
894 (desktop-width . desktop--filter-restore-desktop-parm)
895 (font . desktop--filter-save-desktop-parm)
896 (font-backend . t)
897 (foreground-color . desktop--filter-*-color)
898 (fullscreen . desktop--filter-save-desktop-parm)
899 (height . desktop--filter-save-desktop-parm)
900 (left . desktop--filter-iconified-position)
901 (minibuffer . desktop--filter-minibuffer)
902 (name . t)
903 (outer-window-id . t)
904 (parent-id . t)
905 (top . desktop--filter-iconified-position)
906 (tty . desktop--filter-tty*)
907 (tty-type . desktop--filter-tty*)
908 (width . desktop--filter-save-desktop-parm)
909 (window-id . t)
910 (window-system . t))
911 "Alist of frame parameters and filtering functions.
912
913 Each element is a cons (PARAM . FILTER), where PARAM is a parameter
914 name (a symbol identifying a frame parameter), and FILTER can be t
915 \(meaning the parameter is removed from the parameter list on saving
916 and restoring), or a function that will be called with three args:
917
918 CURRENT a cons (PARAM . VALUE), where PARAM is the one being
919 filtered and VALUE is its current value
920 PARAMETERS the complete alist of parameters being filtered
921 SAVING non-nil if filtering before saving state, nil otherwise
922
923 The FILTER function must return:
924 nil CURRENT is removed from the list
925 t CURRENT is left as is
926 (PARAM' . VALUE') replace CURRENT with this
927
928 Frame parameters not on this list are passed intact.")
929
930 (defvar desktop--target-display nil
931 "Either (minibuffer . VALUE) or nil.
932 This refers to the current frame config being processed inside
933 `frame--restore-frames' and its auxiliary functions (like filtering).
934 If nil, there is no need to change the display.
935 If non-nil, display parameter to use when creating the frame.
936 Internal use only.")
937
938 (defun desktop-switch-to-gui-p (parameters)
939 "True when switching to a graphic display.
940 Return t if PARAMETERS describes a text-only terminal and
941 the target is a graphic display; otherwise return nil.
942 Only meaningful when called from a filtering function in
943 `desktop-filter-parameters-alist'."
944 (and desktop--target-display ; we're switching
945 (null (cdr (assq 'display parameters))) ; from a tty
946 (cdr desktop--target-display))) ; to a GUI display
947
948 (defun desktop-switch-to-tty-p (parameters)
949 "True when switching to a text-only terminal.
950 Return t if PARAMETERS describes a graphic display and
951 the target is a text-only terminal; otherwise return nil.
952 Only meaningful when called from a filtering function in
953 `desktop-filter-parameters-alist'."
954 (and desktop--target-display ; we're switching
955 (cdr (assq 'display parameters)) ; from a GUI display
956 (null (cdr desktop--target-display)))) ; to a tty
957
958 (defun desktop--filter-tty* (_current parameters saving)
959 ;; Remove tty and tty-type parameters when switching
960 ;; to a GUI frame.
961 (or saving
962 (not (desktop-switch-to-gui-p parameters))))
963
964 (defun desktop--filter-*-color (current parameters saving)
965 ;; Remove (foreground|background)-color parameters
966 ;; when switching to a GUI frame if they denote an
967 ;; "unspecified" color.
968 (or saving
969 (not (desktop-switch-to-gui-p parameters))
970 (not (stringp (cdr current)))
971 (not (string-match-p "^unspecified-[fb]g$" (cdr current)))))
972
973 (defun desktop--filter-minibuffer (current _parameters saving)
974 ;; When minibuffer is a window, save it as minibuffer . t
975 (or (not saving)
976 (if (windowp (cdr current))
977 '(minibuffer . t)
978 t)))
979
980 (defun desktop--filter-restore-desktop-parm (current parameters saving)
981 ;; When switching to a GUI frame, convert desktop-XXX parameter to XXX
982 (or saving
983 (not (desktop-switch-to-gui-p parameters))
984 (let ((val (cdr current)))
985 (if (eq val :desktop-processed)
986 nil
987 (cons (intern (substring (symbol-name (car current))
988 8)) ;; (length "desktop-")
989 val)))))
990
991 (defun desktop--filter-save-desktop-parm (current parameters saving)
992 ;; When switching to a tty frame, save parameter XXX as desktop-XXX so it
993 ;; can be restored in a subsequent GUI session, unless it already exists.
994 (cond (saving t)
995 ((desktop-switch-to-tty-p parameters)
996 (let ((sym (intern (format "desktop-%s" (car current)))))
997 (if (assq sym parameters)
998 nil
999 (cons sym (cdr current)))))
1000 ((desktop-switch-to-gui-p parameters)
1001 (let* ((dtp (assq (intern (format "desktop-%s" (car current)))
1002 parameters))
1003 (val (cdr dtp)))
1004 (if (eq val :desktop-processed)
1005 nil
1006 (setcdr dtp :desktop-processed)
1007 (cons (car current) val))))
1008 (t t)))
1009
1010 (defun desktop--filter-iconified-position (_current parameters saving)
1011 ;; When saving an iconified frame, top & left are meaningless,
1012 ;; so remove them to allow restoring to a default position.
1013 (not (and saving (eq (cdr (assq 'visibility parameters)) 'icon))))
1014
1015 (defun desktop-restore-in-original-display-p ()
1016 "True if saved frames' displays should be honored."
1017 (cond ((daemonp) t)
1018 ((eq system-type 'windows-nt) nil)
1019 (t (null desktop-restore-in-current-display))))
1020
1021 (defun desktop--filter-frame-parms (parameters saving)
1022 "Filter frame parameters and return filtered list.
1023 PARAMETERS is a parameter alist as returned by `frame-parameters'.
1024 If SAVING is non-nil, filtering is happening before saving frame state;
1025 otherwise, filtering is being done before restoring frame state.
1026 Parameters are filtered according to the setting of
1027 `desktop-filter-parameters-alist' (which see).
1028 Internal use only."
1029 (let ((filtered nil))
1030 (dolist (param parameters)
1031 (let ((filter (cdr (assq (car param) desktop-filter-parameters-alist)))
1032 this)
1033 (cond (;; no filter: pass param
1034 (null filter)
1035 (push param filtered))
1036 (;; filter = t; skip param
1037 (eq filter t))
1038 (;; filter func returns nil: skip param
1039 (null (setq this (funcall filter param parameters saving))))
1040 (;; filter func returns t: pass param
1041 (eq this t)
1042 (push param filtered))
1043 (;; filter func returns a new param: use it
1044 t
1045 (push this filtered)))))
1046 ;; Set the display parameter after filtering, so that filter functions
1047 ;; have access to its original value.
1048 (when desktop--target-display
1049 (let ((display (assq 'display filtered)))
1050 (if display
1051 (setcdr display (cdr desktop--target-display))
1052 (push desktop--target-display filtered))))
1053 filtered))
1054
1055 (defun desktop--save-minibuffer-frames ()
1056 ;; Adds a desktop-mini parameter to frames
1057 ;; desktop-mini is a list (MINIBUFFER NUMBER DEFAULT?) where
1058 ;; MINIBUFFER t if the frame (including minibuffer-only) owns a minibuffer
1059 ;; NUMBER if MINIBUFFER = t, an ID for the frame; if nil, the ID of
1060 ;; the frame containing the minibuffer used by this frame
1061 ;; DEFAULT? if t, this frame is the value of default-minibuffer-frame
1062 ;; FIXME: What happens with multi-terminal sessions?
1063 (let ((frames (frame-list))
1064 (count 0))
1065 ;; Reset desktop-mini for all frames
1066 (dolist (frame frames)
1067 (set-frame-parameter frame 'desktop-mini nil))
1068 ;; Number all frames with its own minibuffer
1069 (dolist (frame (minibuffer-frame-list))
1070 (set-frame-parameter frame 'desktop-mini
1071 (list t
1072 (setq count (1+ count))
1073 (eq frame default-minibuffer-frame))))
1074 ;; Now link minibufferless frames with their minibuffer frames
1075 (dolist (frame frames)
1076 (unless (frame-parameter frame 'desktop-mini)
1077 (let* ((mb-frame (window-frame (minibuffer-window frame)))
1078 (this (cadr (frame-parameter mb-frame 'desktop-mini))))
1079 (set-frame-parameter frame 'desktop-mini (list nil this nil)))))))
1080
1081 (defun desktop-save-frames ()
1082 "Save frame state in `desktop-saved-frame-states'."
1083 (setq desktop-saved-frame-states
1084 (and desktop-restore-frames
1085 (progn
1086 (desktop--save-minibuffer-frames)
1087 (mapcar (lambda (frame)
1088 (cons (desktop--filter-frame-parms (frame-parameters frame) t)
1089 (window-state-get (frame-root-window frame) t)))
1090 (frame-list))))))
1091
1092 ;;;###autoload
1093 (defun desktop-save (dirname &optional release auto-save)
1094 "Save the desktop in a desktop file.
1095 Parameter DIRNAME specifies where to save the desktop file.
1096 Optional parameter RELEASE says whether we're done with this desktop.
1097 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
1098 and don't save the buffer if they are the same."
1099 (interactive "DDirectory to save desktop file in: ")
1100 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
1101 (save-excursion
1102 (let ((eager desktop-restore-eager)
1103 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
1104 (when
1105 (or (not new-modtime) ; nothing to overwrite
1106 (equal desktop-file-modtime new-modtime)
1107 (yes-or-no-p (if desktop-file-modtime
1108 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
1109 "Desktop file is more recent than the one loaded. Save anyway? "
1110 "Desktop file isn't the one loaded. Overwrite it? ")
1111 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
1112 (unless release (error "Desktop file conflict")))
1113
1114 ;; If we're done with it, release the lock.
1115 ;; Otherwise, claim it if it's unclaimed or if we created it.
1116 (if release
1117 (desktop-release-lock)
1118 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
1119
1120 (with-temp-buffer
1121 (insert
1122 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
1123 desktop-header
1124 ";; Created " (current-time-string) "\n"
1125 ";; Desktop file format version " desktop-file-version "\n"
1126 ";; Emacs version " emacs-version "\n")
1127 (save-excursion (run-hooks 'desktop-save-hook))
1128 (goto-char (point-max))
1129 (insert "\n;; Global section:\n")
1130 ;; Called here because we save the window/frame state as a global
1131 ;; variable for compatibility with previous Emacsen.
1132 (desktop-save-frames)
1133 (unless (memq 'desktop-saved-frame-states desktop-globals-to-save)
1134 (desktop-outvar 'desktop-saved-frame-states))
1135 (mapc (function desktop-outvar) desktop-globals-to-save)
1136 (setq desktop-saved-frame-states nil) ; after saving 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"))
1142
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)
1150 nil
1151 (setq eager (1- eager))))
1152 "desktop-create-buffer"
1153 "desktop-append-buffer-args")
1154 " "
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"))))
1162
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)))))))))))
1175
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)))))
1187
1188 (defvar desktop-buffer-args-list nil
1189 "List of args for `desktop-create-buffer'.")
1190
1191 (defvar desktop-lazy-timer nil)
1192
1193 ;; ----------------------------------------------------------------------------
1194 (defvar desktop--reuse-list nil
1195 "Internal use only.")
1196
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))
1210
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.
1252 t
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))
1259
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)
1270
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)
1274
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)))
1296
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)))
1301
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))
1308
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))))))
1320
1321 (defun desktop-restoring-frames-p ()
1322 "True if calling `desktop-restore-frames' will actually restore frames."
1323 (and desktop-restore-frames desktop-saved-frame-states))
1324
1325 (defun desktop-restore-frames ()
1326 "Restore window/frame configuration.
1327 This function depends on the value of `desktop-saved-frame-states'
1328 being set (usually, by reading it from the desktop)."
1329 (when (desktop-restoring-frames-p)
1330 (let* ((frame-mb-map nil) ;; Alist of frames with their own minibuffer
1331 (visible nil)
1332 (delete-saved (eq desktop-restore-in-current-display 'delete))
1333 (forcing (not (desktop-restore-in-original-display-p)))
1334 (target (and forcing (cons 'display (frame-parameter nil 'display)))))
1335
1336 ;; Sorting saved states allows us to easily restore minibuffer-owning frames
1337 ;; before minibufferless ones.
1338 (setq desktop-saved-frame-states (sort desktop-saved-frame-states
1339 #'desktop--sort-states))
1340 ;; Potentially all existing frames are reusable. Later we will decide which ones
1341 ;; to reuse, and how to deal with any leftover.
1342 (setq desktop--reuse-list (frame-list))
1343
1344 (dolist (state desktop-saved-frame-states)
1345 (condition-case err
1346 (let* ((frame-cfg (car state))
1347 (window-cfg (cdr state))
1348 (d-mini (cdr (assq 'desktop-mini frame-cfg)))
1349 num frame to-tty)
1350 ;; Only set target if forcing displays and the target display is different.
1351 (if (or (not forcing)
1352 (equal target (or (assq 'display frame-cfg) '(display . nil))))
1353 (setq desktop--target-display nil)
1354 (setq desktop--target-display target
1355 to-tty (null (cdr target))))
1356 ;; Time to restore frames and set up their minibuffers as they were.
1357 ;; We only skip a frame (thus deleting it) if either:
1358 ;; - we're switching displays, and the user chose the option to delete, or
1359 ;; - we're switching to tty, and the frame to restore is minibuffer-only.
1360 (unless (and desktop--target-display
1361 (or delete-saved
1362 (and to-tty
1363 (eq (cdr (assq 'minibuffer frame-cfg)) 'only))))
1364
1365 ;; Restore minibuffers. Some of this stuff could be done in a filter
1366 ;; function, but it would be messy because restoring minibuffers affects
1367 ;; global state; it's best to do it here than add a bunch of global
1368 ;; variables to pass info back-and-forth to/from the filter function.
1369 (cond
1370 ((null d-mini)) ;; No desktop-mini. Process as normal frame.
1371 (to-tty) ;; Ignore minibuffer stuff and process as normal frame.
1372 ((car d-mini) ;; Frame has its own minibuffer (or it is minibuffer-only).
1373 (setq num (cadr d-mini))
1374 (when (eq (cdr (assq 'minibuffer frame-cfg)) 'only)
1375 (setq frame-cfg (append '((tool-bar-lines . 0) (menu-bar-lines . 0))
1376 frame-cfg))))
1377 (t ;; Frame depends on other frame's minibuffer window.
1378 (let ((mb-frame (cdr (assq (cadr d-mini) frame-mb-map))))
1379 (unless (frame-live-p mb-frame)
1380 (error "Minibuffer frame %s not found" (cadr d-mini)))
1381 (let ((mb-param (assq 'minibuffer frame-cfg))
1382 (mb-window (minibuffer-window mb-frame)))
1383 (unless (and (window-live-p mb-window)
1384 (window-minibuffer-p mb-window))
1385 (error "Not a minibuffer window %s" mb-window))
1386 (if mb-param
1387 (setcdr mb-param mb-window)
1388 (push (cons 'minibuffer mb-window) frame-cfg))))))
1389 ;; OK, we're ready at last to create (or reuse) a frame and
1390 ;; restore the window config.
1391 (setq frame (desktop--make-frame frame-cfg window-cfg))
1392 ;; Set default-minibuffer if required.
1393 (when (nth 2 d-mini) (setq default-minibuffer-frame frame))
1394 ;; Store frame/NUM to assign to minibufferless frames.
1395 (when num (push (cons num frame) frame-mb-map))
1396 ;; Try to locate at least one visible frame.
1397 (when (and (not visible) (frame-visible-p frame))
1398 (setq visible frame))))
1399 (error
1400 (delay-warning 'desktop (error-message-string err) :error))))
1401
1402 ;; Delete remaining frames, but do not fail if some resist being deleted.
1403 (unless (eq desktop-restoring-reuses-frames 'keep)
1404 (dolist (frame desktop--reuse-list)
1405 (ignore-errors (delete-frame frame))))
1406 (setq desktop--reuse-list nil)
1407 ;; Make sure there's at least one visible frame, and select it.
1408 (unless (or visible (daemonp))
1409 (setq visible (if (frame-live-p default-minibuffer-frame)
1410 default-minibuffer-frame
1411 (car (frame-list))))
1412 (make-frame-visible visible)
1413 (select-frame-set-input-focus visible)))))
1414
1415 ;;;###autoload
1416 (defun desktop-read (&optional dirname)
1417 "Read and process the desktop file in directory DIRNAME.
1418 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1419 directories listed in `desktop-path'. If a desktop file is found, it
1420 is processed and `desktop-after-read-hook' is run. If no desktop file
1421 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1422 This function is a no-op when Emacs is running in batch mode.
1423 It returns t if a desktop file was loaded, nil otherwise."
1424 (interactive)
1425 (unless noninteractive
1426 (setq desktop-dirname
1427 (file-name-as-directory
1428 (expand-file-name
1429 (or
1430 ;; If DIRNAME is specified, use it.
1431 (and (< 0 (length dirname)) dirname)
1432 ;; Otherwise search desktop file in desktop-path.
1433 (let ((dirs desktop-path))
1434 (while (and dirs
1435 (not (file-exists-p
1436 (desktop-full-file-name (car dirs)))))
1437 (setq dirs (cdr dirs)))
1438 (and dirs (car dirs)))
1439 ;; If not found and `desktop-path' is non-nil, use its first element.
1440 (and desktop-path (car desktop-path))
1441 ;; Default: .emacs.d.
1442 user-emacs-directory))))
1443 (if (file-exists-p (desktop-full-file-name))
1444 ;; Desktop file found, but is it already in use?
1445 (let ((desktop-first-buffer nil)
1446 (desktop-buffer-ok-count 0)
1447 (desktop-buffer-fail-count 0)
1448 (owner (desktop-owner))
1449 ;; Avoid desktop saving during evaluation of desktop buffer.
1450 (desktop-save nil))
1451 (if (and owner
1452 (memq desktop-load-locked-desktop '(nil ask))
1453 (or (null desktop-load-locked-desktop)
1454 (daemonp)
1455 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1456 Using it may cause conflicts. Use it anyway? " owner)))))
1457 (let ((default-directory desktop-dirname))
1458 (setq desktop-dirname nil)
1459 (run-hooks 'desktop-not-loaded-hook)
1460 (unless desktop-dirname
1461 (message "Desktop file in use; not loaded.")))
1462 (desktop-lazy-abort)
1463 ;; Evaluate desktop buffer and remember when it was modified.
1464 (load (desktop-full-file-name) t t t)
1465 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1466 ;; If it wasn't already, mark it as in-use, to bother other
1467 ;; desktop instances.
1468 (unless owner
1469 (condition-case nil
1470 (desktop-claim-lock)
1471 (file-error (message "Couldn't record use of desktop file")
1472 (sit-for 1))))
1473
1474 (unless (desktop-restoring-frames-p)
1475 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1476 ;; We want buffers existing prior to evaluating the desktop (and
1477 ;; not reused) to be placed at the end of the buffer list, so we
1478 ;; move them here.
1479 (mapc 'bury-buffer
1480 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1481 (switch-to-buffer (car (buffer-list))))
1482 (run-hooks 'desktop-delay-hook)
1483 (setq desktop-delay-hook nil)
1484 (desktop-restore-frames)
1485 (run-hooks 'desktop-after-read-hook)
1486 (message "Desktop: %d buffer%s restored%s%s."
1487 desktop-buffer-ok-count
1488 (if (= 1 desktop-buffer-ok-count) "" "s")
1489 (if (< 0 desktop-buffer-fail-count)
1490 (format ", %d failed to restore" desktop-buffer-fail-count)
1491 "")
1492 (if desktop-buffer-args-list
1493 (format ", %d to restore lazily"
1494 (length desktop-buffer-args-list))
1495 ""))
1496 (unless (desktop-restoring-frames-p)
1497 ;; Bury the *Messages* buffer to not reshow it when burying
1498 ;; the buffer we switched to above.
1499 (when (buffer-live-p (get-buffer "*Messages*"))
1500 (bury-buffer "*Messages*"))
1501 ;; Clear all windows' previous and next buffers, these have
1502 ;; been corrupted by the `switch-to-buffer' calls in
1503 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1504 ;; brute force fix and should be replaced by a more subtle
1505 ;; strategy eventually.
1506 (walk-window-tree (lambda (window)
1507 (set-window-prev-buffers window nil)
1508 (set-window-next-buffers window nil))))
1509 t))
1510 ;; No desktop file found.
1511 (desktop-clear)
1512 (let ((default-directory desktop-dirname))
1513 (run-hooks 'desktop-no-desktop-file-hook))
1514 (message "No desktop file.")
1515 nil)))
1516
1517 ;; ----------------------------------------------------------------------------
1518 ;; Maintained for backward compatibility
1519 ;;;###autoload
1520 (defun desktop-load-default ()
1521 "Load the `default' start-up library manually.
1522 Also inhibit further loading of it."
1523 (declare (obsolete desktop-save-mode "22.1"))
1524 (unless inhibit-default-init ; safety check
1525 (load "default" t t)
1526 (setq inhibit-default-init t)))
1527
1528 ;; ----------------------------------------------------------------------------
1529 ;;;###autoload
1530 (defun desktop-change-dir (dirname)
1531 "Change to desktop saved in DIRNAME.
1532 Kill the desktop as specified by variables `desktop-save-mode' and
1533 `desktop-save', then clear the desktop and load the desktop file in
1534 directory DIRNAME."
1535 (interactive "DChange to directory: ")
1536 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1537 (desktop-kill)
1538 (desktop-clear)
1539 (desktop-read dirname))
1540
1541 ;; ----------------------------------------------------------------------------
1542 ;;;###autoload
1543 (defun desktop-save-in-desktop-dir ()
1544 "Save the desktop in directory `desktop-dirname'."
1545 (interactive)
1546 (if desktop-dirname
1547 (desktop-save desktop-dirname)
1548 (call-interactively 'desktop-save))
1549 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1550
1551 ;; ----------------------------------------------------------------------------
1552 ;; Auto-Saving.
1553 (defvar desktop-auto-save-timer nil)
1554
1555 (defun desktop-auto-save ()
1556 "Save the desktop periodically.
1557 Called by the timer created in `desktop-auto-save-set-timer'."
1558 (when (and desktop-save-mode
1559 (integerp desktop-auto-save-timeout)
1560 (> desktop-auto-save-timeout 0)
1561 ;; Avoid desktop saving during lazy loading.
1562 (not desktop-lazy-timer)
1563 ;; Save only to own desktop file.
1564 (eq (emacs-pid) (desktop-owner))
1565 desktop-dirname)
1566 (desktop-save desktop-dirname nil t))
1567 (desktop-auto-save-set-timer))
1568
1569 (defun desktop-auto-save-set-timer ()
1570 "Reset the auto-save timer.
1571 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1572 integer, start a new timer to call `desktop-auto-save' in that many seconds."
1573 (when desktop-auto-save-timer
1574 (cancel-timer desktop-auto-save-timer)
1575 (setq desktop-auto-save-timer nil))
1576 (when (and (integerp desktop-auto-save-timeout)
1577 (> desktop-auto-save-timeout 0))
1578 (setq desktop-auto-save-timer
1579 (run-with-timer desktop-auto-save-timeout nil
1580 'desktop-auto-save))))
1581
1582 ;; ----------------------------------------------------------------------------
1583 ;;;###autoload
1584 (defun desktop-revert ()
1585 "Revert to the last loaded desktop."
1586 (interactive)
1587 (unless desktop-dirname
1588 (error "Unknown desktop directory"))
1589 (unless (file-exists-p (desktop-full-file-name))
1590 (error "No desktop file found"))
1591 (desktop-clear)
1592 (desktop-read desktop-dirname))
1593
1594 (defvar desktop-buffer-major-mode)
1595 (defvar desktop-buffer-locals)
1596 (defvar auto-insert) ; from autoinsert.el
1597 ;; ----------------------------------------------------------------------------
1598 (defun desktop-restore-file-buffer (buffer-filename
1599 _buffer-name
1600 _buffer-misc)
1601 "Restore a file buffer."
1602 (when buffer-filename
1603 (if (or (file-exists-p buffer-filename)
1604 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1605 buffer-filename)))
1606 (if desktop-missing-file-warning
1607 (y-or-n-p (concat msg " Re-create buffer? "))
1608 (message "%s" msg)
1609 nil)))
1610 (let* ((auto-insert nil) ; Disable auto insertion
1611 (coding-system-for-read
1612 (or coding-system-for-read
1613 (cdr (assq 'buffer-file-coding-system
1614 desktop-buffer-locals))))
1615 (buf (find-file-noselect buffer-filename)))
1616 (condition-case nil
1617 (switch-to-buffer buf)
1618 (error (pop-to-buffer buf)))
1619 (and (not (eq major-mode desktop-buffer-major-mode))
1620 (functionp desktop-buffer-major-mode)
1621 (funcall desktop-buffer-major-mode))
1622 buf)
1623 nil)))
1624
1625 (defun desktop-load-file (function)
1626 "Load the file where auto loaded FUNCTION is defined."
1627 (when (fboundp function)
1628 (autoload-do-load (symbol-function function) function)))
1629
1630 ;; ----------------------------------------------------------------------------
1631 ;; Create a buffer, load its file, set its mode, ...;
1632 ;; called from Desktop file only.
1633
1634 ;; Just to silence the byte compiler.
1635
1636 (defvar desktop-first-buffer) ; Dynamically bound in `desktop-read'
1637
1638 ;; Bound locally in `desktop-read'.
1639 (defvar desktop-buffer-ok-count)
1640 (defvar desktop-buffer-fail-count)
1641
1642 (defun desktop-create-buffer
1643 (file-version
1644 buffer-filename
1645 buffer-name
1646 buffer-majormode
1647 buffer-minormodes
1648 buffer-point
1649 buffer-mark
1650 buffer-readonly
1651 buffer-misc
1652 &optional
1653 buffer-locals)
1654
1655 (let ((desktop-file-version file-version)
1656 (desktop-buffer-file-name buffer-filename)
1657 (desktop-buffer-name buffer-name)
1658 (desktop-buffer-major-mode buffer-majormode)
1659 (desktop-buffer-minor-modes buffer-minormodes)
1660 (desktop-buffer-point buffer-point)
1661 (desktop-buffer-mark buffer-mark)
1662 (desktop-buffer-read-only buffer-readonly)
1663 (desktop-buffer-misc buffer-misc)
1664 (desktop-buffer-locals buffer-locals))
1665 ;; To make desktop files with relative file names possible, we cannot
1666 ;; allow `default-directory' to change. Therefore we save current buffer.
1667 (save-current-buffer
1668 ;; Give major mode module a chance to add a handler.
1669 (desktop-load-file desktop-buffer-major-mode)
1670 (let ((buffer-list (buffer-list))
1671 (result
1672 (condition-case-unless-debug err
1673 (funcall (or (cdr (assq desktop-buffer-major-mode
1674 desktop-buffer-mode-handlers))
1675 'desktop-restore-file-buffer)
1676 desktop-buffer-file-name
1677 desktop-buffer-name
1678 desktop-buffer-misc)
1679 (error
1680 (message "Desktop: Can't load buffer %s: %s"
1681 desktop-buffer-name
1682 (error-message-string err))
1683 (when desktop-missing-file-warning (sit-for 1))
1684 nil))))
1685 (if (bufferp result)
1686 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1687 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1688 (setq result nil))
1689 ;; Restore buffer list order with new buffer at end. Don't change
1690 ;; the order for old desktop files (old desktop module behavior).
1691 (unless (< desktop-file-version 206)
1692 (mapc 'bury-buffer buffer-list)
1693 (when result (bury-buffer result)))
1694 (when result
1695 (unless (or desktop-first-buffer (< desktop-file-version 206))
1696 (setq desktop-first-buffer result))
1697 (set-buffer result)
1698 (unless (equal (buffer-name) desktop-buffer-name)
1699 (rename-buffer desktop-buffer-name t))
1700 ;; minor modes
1701 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1702 (auto-fill-mode 1))
1703 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1704 (auto-fill-mode 0))
1705 (t
1706 (dolist (minor-mode desktop-buffer-minor-modes)
1707 ;; Give minor mode module a chance to add a handler.
1708 (desktop-load-file minor-mode)
1709 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1710 (if handler
1711 (funcall handler desktop-buffer-locals)
1712 (when (functionp minor-mode)
1713 (funcall minor-mode 1)))))))
1714 ;; Even though point and mark are non-nil when written by
1715 ;; `desktop-save', they may be modified by handlers wanting to set
1716 ;; point or mark themselves.
1717 (when desktop-buffer-point
1718 (goto-char
1719 (condition-case err
1720 ;; Evaluate point. Thus point can be something like
1721 ;; '(search-forward ...
1722 (eval desktop-buffer-point)
1723 (error (message "%s" (error-message-string err)) 1))))
1724 (when desktop-buffer-mark
1725 (if (consp desktop-buffer-mark)
1726 (progn
1727 (set-mark (car desktop-buffer-mark))
1728 (setq mark-active (car (cdr desktop-buffer-mark))))
1729 (set-mark desktop-buffer-mark)))
1730 ;; Never override file system if the file really is read-only marked.
1731 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1732 (while desktop-buffer-locals
1733 (let ((this (car desktop-buffer-locals)))
1734 (if (consp this)
1735 ;; an entry of this form `(symbol . value)'
1736 (progn
1737 (make-local-variable (car this))
1738 (set (car this) (cdr this)))
1739 ;; an entry of the form `symbol'
1740 (make-local-variable this)
1741 (makunbound this)))
1742 (setq desktop-buffer-locals (cdr desktop-buffer-locals))))))))
1743
1744 ;; ----------------------------------------------------------------------------
1745 ;; Backward compatibility -- update parameters to 205 standards.
1746 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1747 mim pt mk ro tl fc cfs cr buffer-misc)
1748 (desktop-create-buffer 205 buffer-filename buffer-name
1749 buffer-majormode (cdr mim) pt mk ro
1750 buffer-misc
1751 (list (cons 'truncate-lines tl)
1752 (cons 'fill-column fc)
1753 (cons 'case-fold-search cfs)
1754 (cons 'case-replace cr)
1755 (cons 'overwrite-mode (car mim)))))
1756
1757 (defun desktop-append-buffer-args (&rest args)
1758 "Append ARGS at end of `desktop-buffer-args-list'.
1759 ARGS must be an argument list for `desktop-create-buffer'."
1760 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1761 (unless desktop-lazy-timer
1762 (setq desktop-lazy-timer
1763 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1764
1765 (defun desktop-lazy-create-buffer ()
1766 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1767 (when desktop-buffer-args-list
1768 (let* ((remaining (length desktop-buffer-args-list))
1769 (args (pop desktop-buffer-args-list))
1770 (buffer-name (nth 2 args))
1771 (msg (format "Desktop lazily opening %s (%s remaining)..."
1772 buffer-name remaining)))
1773 (when desktop-lazy-verbose
1774 (message "%s" msg))
1775 (let ((desktop-first-buffer nil)
1776 (desktop-buffer-ok-count 0)
1777 (desktop-buffer-fail-count 0))
1778 (apply 'desktop-create-buffer args)
1779 (run-hooks 'desktop-delay-hook)
1780 (setq desktop-delay-hook nil)
1781 (bury-buffer (get-buffer buffer-name))
1782 (when desktop-lazy-verbose
1783 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1784
1785 (defun desktop-idle-create-buffers ()
1786 "Create buffers until the user does something, then stop.
1787 If there are no buffers left to create, kill the timer."
1788 (let ((repeat 1))
1789 (while (and repeat desktop-buffer-args-list)
1790 (save-window-excursion
1791 (desktop-lazy-create-buffer))
1792 (setq repeat (sit-for 0.2))
1793 (unless desktop-buffer-args-list
1794 (cancel-timer desktop-lazy-timer)
1795 (setq desktop-lazy-timer nil)
1796 (message "Lazy desktop load complete")
1797 (sit-for 3)
1798 (message "")))))
1799
1800 (defun desktop-lazy-complete ()
1801 "Run the desktop load to completion."
1802 (interactive)
1803 (let ((desktop-lazy-verbose t))
1804 (while desktop-buffer-args-list
1805 (save-window-excursion
1806 (desktop-lazy-create-buffer)))
1807 (message "Lazy desktop load complete")))
1808
1809 (defun desktop-lazy-abort ()
1810 "Abort lazy loading of the desktop."
1811 (interactive)
1812 (when desktop-lazy-timer
1813 (cancel-timer desktop-lazy-timer)
1814 (setq desktop-lazy-timer nil))
1815 (when desktop-buffer-args-list
1816 (setq desktop-buffer-args-list nil)
1817 (when (called-interactively-p 'interactive)
1818 (message "Lazy desktop load aborted"))))
1819
1820 ;; ----------------------------------------------------------------------------
1821 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1822 ;; command line, we do the rest of what it takes to use desktop, but do it
1823 ;; after finishing loading the init file.
1824 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1825 ;; functions are processed after `after-init-hook'.
1826 (add-hook
1827 'after-init-hook
1828 (lambda ()
1829 (let ((key "--no-desktop"))
1830 (when (member key command-line-args)
1831 (setq command-line-args (delete key command-line-args))
1832 (setq desktop-save-mode nil)))
1833 (when desktop-save-mode
1834 (desktop-read)
1835 (desktop-auto-save-set-timer)
1836 (setq inhibit-startup-screen t))))
1837
1838 ;; So we can restore vc-dir buffers.
1839 (autoload 'vc-dir-mode "vc-dir" nil t)
1840
1841 (provide 'desktop)
1842
1843 ;;; desktop.el ends here