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