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