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