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