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