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