lisp/finder.el (finder-unload-function): New function.
[emacs.git] / lisp / desktop.el
blob69c17015030793be9469c350ed2b5b11b6e06421
1 ;;; desktop.el --- save partial status of Emacs when killed -*- lexical-binding: t -*-
3 ;; Copyright (C) 1993-1995, 1997, 2000-2014 Free Software Foundation, Inc.
5 ;; Author: Morten Welinder <terra@diku.dk>
6 ;; Keywords: convenience
7 ;; Favorite-brand-of-beer: None, I hate beer.
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
24 ;;; Commentary:
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
37 ;; To use this, use customize to turn on desktop-save-mode or add the
38 ;; following line somewhere in your init file:
40 ;; (desktop-save-mode 1)
42 ;; For further usage information, look at the section
43 ;; (info "(emacs)Saving Emacs Sessions") in the GNU Emacs Manual.
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.
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
58 ;; (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
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
66 ;; (MINOR-MODE . RESTORE-FUNCTION).
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
73 ;; (defun foo-restore-desktop-buffer
74 ;; ...
75 ;; (add-to-list 'desktop-buffer-mode-handlers
76 ;; '(foo-mode . foo-restore-desktop-buffer))
78 ;; or
80 ;; (defun bar-desktop-restore
81 ;; ...
82 ;; (add-to-list 'desktop-minor-mode-handlers
83 ;; '(bar-mode . bar-desktop-restore))
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.
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
104 ;; (NAME RESTORE-FUNCTION)
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 ;; ---------------------------------------------------------------------------
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.
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.
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:
130 ;; Recognize more minor modes.
131 ;; Save mark rings.
133 ;;; Code:
135 (require 'cl-lib)
136 (require 'frameset)
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.")
143 ;; ----------------------------------------------------------------------------
144 ;; USER OPTIONS -- settings you might want to play with.
145 ;; ----------------------------------------------------------------------------
147 (defgroup desktop nil
148 "Save status of Emacs when you exit."
149 :group 'frames)
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.
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.
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'.
168 Once a desktop file exists, Emacs will auto-save it according to the
169 option `desktop-auto-save-timeout'.
171 To see all the options you can set, browse the `desktop' customization group.
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)))
180 (defun desktop-save-mode-off ()
181 "Disable `desktop-save-mode'. Provided for use in hooks."
182 (desktop-save-mode 0))
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")
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")
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")
236 (define-obsolete-variable-alias 'desktop-basefilename
237 'desktop-base-file-name "22.1")
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)
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")
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
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'.
264 If nil, just print error messages in the message buffer."
265 :type 'boolean
266 :group 'desktop
267 :version "22.1")
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")
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")
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")
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)
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)
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")
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)
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)
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)
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)
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)
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")
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")
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")
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")
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")
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")
445 (defcustom desktop-lazy-verbose t
446 "Verbose reporting of lazily created buffers."
447 :type 'boolean
448 :group 'desktop
449 :version "22.1")
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")
458 ;;;###autoload
459 (defvar-local desktop-save-buffer nil
460 "When non-nil, save buffer status in desktop file.
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.
466 When file names are returned, they should be formatted using the call
467 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
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")
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
483 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
485 Buffers with a major mode not specified here, are restored by the default
486 handler `desktop-restore-file-buffer'.
488 Handlers are called with argument list
490 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
492 Furthermore, they may use the following variables:
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
502 If a handler returns a buffer, then the saved mode settings
503 and variable values for that buffer are copied into it.
505 Modules that define a major mode that needs a special handler should contain
506 code like
508 (defun foo-restore-desktop-buffer
510 (add-to-list 'desktop-buffer-mode-handlers
511 '(foo-mode . foo-restore-desktop-buffer))
513 Furthermore the major mode function must be autoloaded.")
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")
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)
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
543 (MINOR-MODE . RESTORE-FUNCTION).
545 Minor modes not specified here, are restored by the standard minor mode
546 function.
548 Handlers are called with argument list
550 (DESKTOP-BUFFER-LOCALS)
552 Furthermore, they may use the following variables:
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
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.
568 Modules that define a minor mode that needs a special handler should contain
569 code like
571 (defun foo-desktop-restore
573 (add-to-list 'desktop-minor-mode-handlers
574 '(foo-mode . foo-desktop-restore))
576 Furthermore the minor mode function must be autoloaded.
578 See also `desktop-minor-mode-table'.")
580 ;;;###autoload
581 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
583 ;; ----------------------------------------------------------------------------
584 (defvar desktop-dirname nil
585 "The directory in which the desktop file should be saved.")
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)))
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)))
597 (defconst desktop-header
598 ";; --------------------------------------------------------------------------
599 ;; Desktop File for Emacs
600 ;; --------------------------------------------------------------------------
601 " "*Header to place in Desktop file.")
603 (defvar desktop-delay-hook nil
604 "Hooks run after all buffers are loaded; intended for internal use.")
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.")
610 (defvar desktop-saved-frameset nil
611 "Saved state of all frames.
612 Only valid during frame saving & restoring; intended for internal use.")
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.")
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)))
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)))
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))))
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))))
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))))))))
697 ;; ----------------------------------------------------------------------------
698 (unless noninteractive
699 (add-hook 'kill-emacs-hook 'desktop-kill))
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)))
729 ;; ----------------------------------------------------------------------------
730 (defun desktop-list* (&rest args)
731 (and args (apply #'cl-list* args)))
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)))
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"))))
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)))
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)
871 (desktop-value-to-string (symbol-value var))
872 ")\n"))))
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 (no-regexp-to-check (not (stringp desktop-files-not-to-save)))
882 dired-skip)
883 (and (or filename
884 (not (stringp desktop-buffers-not-to-save))
885 (not (string-match-p desktop-buffers-not-to-save bufname)))
886 (not (memq mode desktop-modes-not-to-save))
887 (or (and filename
888 (or no-regexp-to-check
889 (not (string-match-p desktop-files-not-to-save filename))))
890 (and (memq mode '(dired-mode vc-dir-mode))
891 (or no-regexp-to-check
892 (not (setq dired-skip
893 (with-current-buffer bufname
894 (string-match-p desktop-files-not-to-save
895 default-directory))))))
896 (and (null filename)
897 (null dired-skip) ; bug#5755
898 (with-current-buffer bufname desktop-save-buffer)))
899 t)))
901 ;; ----------------------------------------------------------------------------
902 (defun desktop-file-name (filename dirname)
903 "Convert FILENAME to format specified in `desktop-file-name-format'.
904 DIRNAME must be the directory in which the desktop file will be saved."
905 (cond
906 ((not filename) nil)
907 ((eq desktop-file-name-format 'tilde)
908 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
909 (cond
910 ((file-name-absolute-p relative-name) relative-name)
911 ((string= "./" relative-name) "~/")
912 ((string= "." relative-name) "~")
913 (t (concat "~/" relative-name)))))
914 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
915 (t (expand-file-name filename))))
918 ;; ----------------------------------------------------------------------------
919 (defun desktop--check-dont-save (frame)
920 (not (frame-parameter frame 'desktop-dont-save)))
922 (defconst desktop--app-id `(desktop . ,desktop-file-version))
924 (defun desktop-save-frameset ()
925 "Save the state of existing frames in `desktop-saved-frameset'.
926 Frames with a non-nil `desktop-dont-save' parameter are not saved."
927 (setq desktop-saved-frameset
928 (and desktop-restore-frames
929 (frameset-save nil
930 :app desktop--app-id
931 :name (concat user-login-name "@" system-name)
932 :predicate #'desktop--check-dont-save))))
934 ;;;###autoload
935 (defun desktop-save (dirname &optional release auto-save)
936 "Save the desktop in a desktop file.
937 Parameter DIRNAME specifies where to save the desktop file.
938 Optional parameter RELEASE says whether we're done with this desktop.
939 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
940 and don't save the buffer if they are the same."
941 (interactive (list
942 ;; Or should we just use (car desktop-path)?
943 (let ((default (if (member "." desktop-path)
944 default-directory
945 user-emacs-directory)))
946 (read-directory-name "Directory to save desktop file in: "
947 default default t))))
948 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
949 (save-excursion
950 (let ((eager desktop-restore-eager)
951 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
952 (when
953 (or (not new-modtime) ; nothing to overwrite
954 (equal desktop-file-modtime new-modtime)
955 (yes-or-no-p (if desktop-file-modtime
956 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
957 "Desktop file is more recent than the one loaded. Save anyway? "
958 "Desktop file isn't the one loaded. Overwrite it? ")
959 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
960 (unless release (error "Desktop file conflict")))
962 ;; If we're done with it, release the lock.
963 ;; Otherwise, claim it if it's unclaimed or if we created it.
964 (if release
965 (desktop-release-lock)
966 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
968 (with-temp-buffer
969 (insert
970 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
971 desktop-header
972 ";; Created " (current-time-string) "\n"
973 ";; Desktop file format version " desktop-file-version "\n"
974 ";; Emacs version " emacs-version "\n")
975 (save-excursion (run-hooks 'desktop-save-hook))
976 (goto-char (point-max))
977 (insert "\n;; Global section:\n")
978 ;; Called here because we save the window/frame state as a global
979 ;; variable for compatibility with previous Emacsen.
980 (desktop-save-frameset)
981 (unless (memq 'desktop-saved-frameset desktop-globals-to-save)
982 (desktop-outvar 'desktop-saved-frameset))
983 (mapc (function desktop-outvar) desktop-globals-to-save)
984 (setq desktop-saved-frameset nil) ; after saving desktop-globals-to-save
985 (when (memq 'kill-ring desktop-globals-to-save)
986 (insert
987 "(setq kill-ring-yank-pointer (nthcdr "
988 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
989 " kill-ring))\n"))
991 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
992 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
993 (let ((base (pop l)))
994 (when (apply 'desktop-save-buffer-p l)
995 (insert "("
996 (if (or (not (integerp eager))
997 (if (zerop eager)
999 (setq eager (1- eager))))
1000 "desktop-create-buffer"
1001 "desktop-append-buffer-args")
1003 desktop-file-version)
1004 ;; If there's a non-empty base name, we save it instead of the buffer name
1005 (when (and base (not (string= base "")))
1006 (setcar (nthcdr 1 l) base))
1007 (dolist (e l)
1008 (insert "\n " (desktop-value-to-string e)))
1009 (insert ")\n\n"))))
1011 (setq default-directory desktop-dirname)
1012 ;; When auto-saving, avoid writing if nothing has changed since the last write.
1013 (let* ((beg (and auto-save
1014 (save-excursion
1015 (goto-char (point-min))
1016 ;; Don't check the header with changing timestamp
1017 (and (search-forward "Global section" nil t)
1018 ;; Also skip the timestamp in desktop-saved-frameset
1019 ;; if it's saved in the first non-header line
1020 (search-forward "desktop-saved-frameset"
1021 (line-beginning-position 3) t)
1022 ;; This is saved after the timestamp
1023 (search-forward (format "%S" desktop--app-id) nil t))
1024 (point))))
1025 (checksum (and beg (md5 (current-buffer) beg (point-max) 'emacs-mule))))
1026 (unless (and checksum (equal checksum desktop-file-checksum))
1027 (let ((coding-system-for-write 'emacs-mule))
1028 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
1029 (setq desktop-file-checksum checksum)
1030 ;; We remember when it was modified (which is presumably just now).
1031 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
1033 ;; ----------------------------------------------------------------------------
1034 ;;;###autoload
1035 (defun desktop-remove ()
1036 "Delete desktop file in `desktop-dirname'.
1037 This function also sets `desktop-dirname' to nil."
1038 (interactive)
1039 (when desktop-dirname
1040 (let ((filename (desktop-full-file-name)))
1041 (setq desktop-dirname nil)
1042 (when (file-exists-p filename)
1043 (delete-file filename)))))
1045 (defvar desktop-buffer-args-list nil
1046 "List of args for `desktop-create-buffer'.")
1048 (defvar desktop-lazy-timer nil)
1050 ;; ----------------------------------------------------------------------------
1051 (defun desktop-restoring-frameset-p ()
1052 "True if calling `desktop-restore-frameset' will actually restore it."
1053 (and desktop-restore-frames desktop-saved-frameset t))
1055 (defun desktop-restore-frameset ()
1056 "Restore the state of a set of frames.
1057 This function depends on the value of `desktop-saved-frameset'
1058 being set (usually, by reading it from the desktop)."
1059 (when (desktop-restoring-frameset-p)
1060 (frameset-restore desktop-saved-frameset
1061 :reuse-frames desktop-restore-reuses-frames
1062 :force-display desktop-restore-in-current-display
1063 :force-onscreen desktop-restore-forces-onscreen)))
1065 ;; Just to silence the byte compiler.
1066 ;; Dynamically bound in `desktop-read'.
1067 (defvar desktop-first-buffer)
1068 (defvar desktop-buffer-ok-count)
1069 (defvar desktop-buffer-fail-count)
1071 ;; FIXME Interactively, this should have the option to prompt for dirname.
1072 ;;;###autoload
1073 (defun desktop-read (&optional dirname)
1074 "Read and process the desktop file in directory DIRNAME.
1075 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1076 directories listed in `desktop-path'. If a desktop file is found, it
1077 is processed and `desktop-after-read-hook' is run. If no desktop file
1078 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1079 This function is a no-op when Emacs is running in batch mode.
1080 It returns t if a desktop file was loaded, nil otherwise."
1081 (interactive)
1082 (unless noninteractive
1083 (setq desktop-dirname
1084 (file-name-as-directory
1085 (expand-file-name
1087 ;; If DIRNAME is specified, use it.
1088 (and (< 0 (length dirname)) dirname)
1089 ;; Otherwise search desktop file in desktop-path.
1090 (let ((dirs desktop-path))
1091 (while (and dirs
1092 (not (file-exists-p
1093 (desktop-full-file-name (car dirs)))))
1094 (setq dirs (cdr dirs)))
1095 (and dirs (car dirs)))
1096 ;; If not found and `desktop-path' is non-nil, use its first element.
1097 (and desktop-path (car desktop-path))
1098 ;; Default: .emacs.d.
1099 user-emacs-directory))))
1100 (if (file-exists-p (desktop-full-file-name))
1101 ;; Desktop file found, but is it already in use?
1102 (let ((desktop-first-buffer nil)
1103 (desktop-buffer-ok-count 0)
1104 (desktop-buffer-fail-count 0)
1105 (owner (desktop-owner))
1106 ;; Avoid desktop saving during evaluation of desktop buffer.
1107 (desktop-save nil))
1108 (if (and owner
1109 (memq desktop-load-locked-desktop '(nil ask))
1110 (or (null desktop-load-locked-desktop)
1111 (daemonp)
1112 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1113 Using it may cause conflicts. Use it anyway? " owner)))))
1114 (let ((default-directory desktop-dirname))
1115 (setq desktop-dirname nil)
1116 (run-hooks 'desktop-not-loaded-hook)
1117 (unless desktop-dirname
1118 (message "Desktop file in use; not loaded.")))
1119 (desktop-lazy-abort)
1120 ;; Evaluate desktop buffer and remember when it was modified.
1121 (load (desktop-full-file-name) t t t)
1122 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1123 ;; If it wasn't already, mark it as in-use, to bother other
1124 ;; desktop instances.
1125 (unless (eq (emacs-pid) owner)
1126 (condition-case nil
1127 (desktop-claim-lock)
1128 (file-error (message "Couldn't record use of desktop file")
1129 (sit-for 1))))
1131 (unless (desktop-restoring-frameset-p)
1132 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1133 ;; We want buffers existing prior to evaluating the desktop (and
1134 ;; not reused) to be placed at the end of the buffer list, so we
1135 ;; move them here.
1136 (mapc 'bury-buffer
1137 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1138 (switch-to-buffer (car (buffer-list))))
1139 (run-hooks 'desktop-delay-hook)
1140 (setq desktop-delay-hook nil)
1141 (desktop-restore-frameset)
1142 (run-hooks 'desktop-after-read-hook)
1143 (message "Desktop: %s%d buffer%s restored%s%s."
1144 (if desktop-saved-frameset
1145 (let ((fn (length (frameset-states desktop-saved-frameset))))
1146 (format "%d frame%s, "
1147 fn (if (= fn 1) "" "s")))
1149 desktop-buffer-ok-count
1150 (if (= 1 desktop-buffer-ok-count) "" "s")
1151 (if (< 0 desktop-buffer-fail-count)
1152 (format ", %d failed to restore" desktop-buffer-fail-count)
1154 (if desktop-buffer-args-list
1155 (format ", %d to restore lazily"
1156 (length desktop-buffer-args-list))
1157 ""))
1158 (unless (desktop-restoring-frameset-p)
1159 ;; Bury the *Messages* buffer to not reshow it when burying
1160 ;; the buffer we switched to above.
1161 (when (buffer-live-p (get-buffer "*Messages*"))
1162 (bury-buffer "*Messages*"))
1163 ;; Clear all windows' previous and next buffers, these have
1164 ;; been corrupted by the `switch-to-buffer' calls in
1165 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1166 ;; brute force fix and should be replaced by a more subtle
1167 ;; strategy eventually.
1168 (walk-window-tree (lambda (window)
1169 (set-window-prev-buffers window nil)
1170 (set-window-next-buffers window nil))))
1171 (setq desktop-saved-frameset nil)
1173 ;; No desktop file found.
1174 (desktop-clear)
1175 (let ((default-directory desktop-dirname))
1176 (run-hooks 'desktop-no-desktop-file-hook))
1177 (message "No desktop file.")
1178 nil)))
1180 ;; ----------------------------------------------------------------------------
1181 ;; Maintained for backward compatibility
1182 ;;;###autoload
1183 (defun desktop-load-default ()
1184 "Load the `default' start-up library manually.
1185 Also inhibit further loading of it."
1186 (declare (obsolete desktop-save-mode "22.1"))
1187 (unless inhibit-default-init ; safety check
1188 (load "default" t t)
1189 (setq inhibit-default-init t)))
1191 ;; ----------------------------------------------------------------------------
1192 ;;;###autoload
1193 (defun desktop-change-dir (dirname)
1194 "Change to desktop saved in DIRNAME.
1195 Kill the desktop as specified by variables `desktop-save-mode' and
1196 `desktop-save', then clear the desktop and load the desktop file in
1197 directory DIRNAME."
1198 (interactive "DChange to directory: ")
1199 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1200 (desktop-kill)
1201 (desktop-clear)
1202 (desktop-read dirname))
1204 ;; ----------------------------------------------------------------------------
1205 ;;;###autoload
1206 (defun desktop-save-in-desktop-dir ()
1207 "Save the desktop in directory `desktop-dirname'."
1208 (interactive)
1209 (if desktop-dirname
1210 (desktop-save desktop-dirname)
1211 (call-interactively 'desktop-save))
1212 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1214 ;; ----------------------------------------------------------------------------
1215 ;; Auto-Saving.
1216 (defvar desktop-auto-save-timer nil)
1218 (defun desktop-auto-save ()
1219 "Save the desktop periodically.
1220 Called by the timer created in `desktop-auto-save-set-timer'."
1221 (when (and desktop-save-mode
1222 (integerp desktop-auto-save-timeout)
1223 (> desktop-auto-save-timeout 0)
1224 ;; Avoid desktop saving during lazy loading.
1225 (not desktop-lazy-timer)
1226 ;; Save only to own desktop file.
1227 (eq (emacs-pid) (desktop-owner))
1228 desktop-dirname)
1229 (desktop-save desktop-dirname nil t)))
1231 (defun desktop-auto-save-set-timer ()
1232 "Set the auto-save timer.
1233 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1234 integer, start a new idle timer to call `desktop-auto-save' repeatedly
1235 after that many seconds of idle time."
1236 (desktop-auto-save-cancel-timer)
1237 (when (and (integerp desktop-auto-save-timeout)
1238 (> desktop-auto-save-timeout 0))
1239 (setq desktop-auto-save-timer
1240 (run-with-idle-timer desktop-auto-save-timeout t
1241 'desktop-auto-save))))
1243 (defun desktop-auto-save-cancel-timer ()
1244 (when desktop-auto-save-timer
1245 (cancel-timer desktop-auto-save-timer)
1246 (setq desktop-auto-save-timer nil)))
1248 ;; ----------------------------------------------------------------------------
1249 ;;;###autoload
1250 (defun desktop-revert ()
1251 "Revert to the last loaded desktop."
1252 (interactive)
1253 (unless desktop-dirname
1254 (error "Unknown desktop directory"))
1255 (unless (file-exists-p (desktop-full-file-name))
1256 (error "No desktop file found"))
1257 (desktop-clear)
1258 (desktop-read desktop-dirname))
1260 (defvar desktop-buffer-major-mode)
1261 (defvar desktop-buffer-locals)
1262 (defvar auto-insert) ; from autoinsert.el
1263 ;; ----------------------------------------------------------------------------
1264 (defun desktop-restore-file-buffer (buffer-filename
1265 _buffer-name
1266 _buffer-misc)
1267 "Restore a file buffer."
1268 (when buffer-filename
1269 (if (or (file-exists-p buffer-filename)
1270 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1271 buffer-filename)))
1272 (if desktop-missing-file-warning
1273 (y-or-n-p (concat msg " Re-create buffer? "))
1274 (message "%s" msg)
1275 nil)))
1276 (let* ((auto-insert nil) ; Disable auto insertion
1277 (coding-system-for-read
1278 (or coding-system-for-read
1279 (cdr (assq 'buffer-file-coding-system
1280 desktop-buffer-locals))))
1281 (buf (find-file-noselect buffer-filename)))
1282 (condition-case nil
1283 (switch-to-buffer buf)
1284 (error (pop-to-buffer buf)))
1285 (and (not (eq major-mode desktop-buffer-major-mode))
1286 (functionp desktop-buffer-major-mode)
1287 (funcall desktop-buffer-major-mode))
1288 buf)
1289 nil)))
1291 (defun desktop-load-file (function)
1292 "Load the file where auto loaded FUNCTION is defined."
1293 (when (fboundp function)
1294 (autoload-do-load (symbol-function function) function)))
1296 ;; ----------------------------------------------------------------------------
1297 ;; Create a buffer, load its file, set its mode, ...;
1298 ;; called from Desktop file only.
1300 (defun desktop-create-buffer
1301 (file-version
1302 buffer-filename
1303 buffer-name
1304 buffer-majormode
1305 buffer-minormodes
1306 buffer-point
1307 buffer-mark
1308 buffer-readonly
1309 buffer-misc
1310 &optional
1311 buffer-locals)
1313 (let ((desktop-file-version file-version)
1314 (desktop-buffer-file-name buffer-filename)
1315 (desktop-buffer-name buffer-name)
1316 (desktop-buffer-major-mode buffer-majormode)
1317 (desktop-buffer-minor-modes buffer-minormodes)
1318 (desktop-buffer-point buffer-point)
1319 (desktop-buffer-mark buffer-mark)
1320 (desktop-buffer-read-only buffer-readonly)
1321 (desktop-buffer-misc buffer-misc)
1322 (desktop-buffer-locals buffer-locals))
1323 ;; To make desktop files with relative file names possible, we cannot
1324 ;; allow `default-directory' to change. Therefore we save current buffer.
1325 (save-current-buffer
1326 ;; Give major mode module a chance to add a handler.
1327 (desktop-load-file desktop-buffer-major-mode)
1328 (let ((buffer-list (buffer-list))
1329 (result
1330 (condition-case-unless-debug err
1331 (funcall (or (cdr (assq desktop-buffer-major-mode
1332 desktop-buffer-mode-handlers))
1333 'desktop-restore-file-buffer)
1334 desktop-buffer-file-name
1335 desktop-buffer-name
1336 desktop-buffer-misc)
1337 (error
1338 (message "Desktop: Can't load buffer %s: %s"
1339 desktop-buffer-name
1340 (error-message-string err))
1341 (when desktop-missing-file-warning (sit-for 1))
1342 nil))))
1343 (if (bufferp result)
1344 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1345 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1346 (setq result nil))
1347 ;; Restore buffer list order with new buffer at end. Don't change
1348 ;; the order for old desktop files (old desktop module behavior).
1349 (unless (< desktop-file-version 206)
1350 (mapc 'bury-buffer buffer-list)
1351 (when result (bury-buffer result)))
1352 (when result
1353 (unless (or desktop-first-buffer (< desktop-file-version 206))
1354 (setq desktop-first-buffer result))
1355 (set-buffer result)
1356 (unless (equal (buffer-name) desktop-buffer-name)
1357 (rename-buffer desktop-buffer-name t))
1358 ;; minor modes
1359 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1360 (auto-fill-mode 1))
1361 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1362 (auto-fill-mode 0))
1364 (dolist (minor-mode desktop-buffer-minor-modes)
1365 ;; Give minor mode module a chance to add a handler.
1366 (desktop-load-file minor-mode)
1367 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1368 (if handler
1369 (funcall handler desktop-buffer-locals)
1370 (when (functionp minor-mode)
1371 (funcall minor-mode 1)))))))
1372 ;; Even though point and mark are non-nil when written by
1373 ;; `desktop-save', they may be modified by handlers wanting to set
1374 ;; point or mark themselves.
1375 (when desktop-buffer-point
1376 (goto-char
1377 (condition-case err
1378 ;; Evaluate point. Thus point can be something like
1379 ;; '(search-forward ...
1380 (eval desktop-buffer-point)
1381 (error (message "%s" (error-message-string err)) 1))))
1382 (when desktop-buffer-mark
1383 (if (consp desktop-buffer-mark)
1384 (progn
1385 (set-mark (car desktop-buffer-mark))
1386 (setq mark-active (car (cdr desktop-buffer-mark))))
1387 (set-mark desktop-buffer-mark)))
1388 ;; Never override file system if the file really is read-only marked.
1389 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1390 (dolist (this desktop-buffer-locals)
1391 (if (consp this)
1392 ;; an entry of this form `(symbol . value)'
1393 (progn
1394 (make-local-variable (car this))
1395 (set (car this) (cdr this)))
1396 ;; an entry of the form `symbol'
1397 (make-local-variable this)
1398 (makunbound this))))))))
1400 ;; ----------------------------------------------------------------------------
1401 ;; Backward compatibility -- update parameters to 205 standards.
1402 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1403 mim pt mk ro tl fc cfs cr buffer-misc)
1404 (desktop-create-buffer 205 buffer-filename buffer-name
1405 buffer-majormode (cdr mim) pt mk ro
1406 buffer-misc
1407 (list (cons 'truncate-lines tl)
1408 (cons 'fill-column fc)
1409 (cons 'case-fold-search cfs)
1410 (cons 'case-replace cr)
1411 (cons 'overwrite-mode (car mim)))))
1413 (defun desktop-append-buffer-args (&rest args)
1414 "Append ARGS at end of `desktop-buffer-args-list'.
1415 ARGS must be an argument list for `desktop-create-buffer'."
1416 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1417 (unless desktop-lazy-timer
1418 (setq desktop-lazy-timer
1419 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1421 (defun desktop-lazy-create-buffer ()
1422 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1423 (when desktop-buffer-args-list
1424 (let* ((remaining (length desktop-buffer-args-list))
1425 (args (pop desktop-buffer-args-list))
1426 (buffer-name (nth 2 args))
1427 (msg (format "Desktop lazily opening %s (%s remaining)..."
1428 buffer-name remaining)))
1429 (when desktop-lazy-verbose
1430 (message "%s" msg))
1431 (let ((desktop-first-buffer nil)
1432 (desktop-buffer-ok-count 0)
1433 (desktop-buffer-fail-count 0))
1434 (apply 'desktop-create-buffer args)
1435 (run-hooks 'desktop-delay-hook)
1436 (setq desktop-delay-hook nil)
1437 (bury-buffer (get-buffer buffer-name))
1438 (when desktop-lazy-verbose
1439 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1441 (defun desktop-idle-create-buffers ()
1442 "Create buffers until the user does something, then stop.
1443 If there are no buffers left to create, kill the timer."
1444 (let ((repeat 1))
1445 (while (and repeat desktop-buffer-args-list)
1446 (save-window-excursion
1447 (desktop-lazy-create-buffer))
1448 (setq repeat (sit-for 0.2))
1449 (unless desktop-buffer-args-list
1450 (cancel-timer desktop-lazy-timer)
1451 (setq desktop-lazy-timer nil)
1452 (message "Lazy desktop load complete")
1453 (sit-for 3)
1454 (message "")))))
1456 (defun desktop-lazy-complete ()
1457 "Run the desktop load to completion."
1458 (interactive)
1459 (let ((desktop-lazy-verbose t))
1460 (while desktop-buffer-args-list
1461 (save-window-excursion
1462 (desktop-lazy-create-buffer)))
1463 (message "Lazy desktop load complete")))
1465 (defun desktop-lazy-abort ()
1466 "Abort lazy loading of the desktop."
1467 (interactive)
1468 (when desktop-lazy-timer
1469 (cancel-timer desktop-lazy-timer)
1470 (setq desktop-lazy-timer nil))
1471 (when desktop-buffer-args-list
1472 (setq desktop-buffer-args-list nil)
1473 (when (called-interactively-p 'interactive)
1474 (message "Lazy desktop load aborted"))))
1476 ;; ----------------------------------------------------------------------------
1477 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1478 ;; command line, we do the rest of what it takes to use desktop, but do it
1479 ;; after finishing loading the init file.
1480 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1481 ;; functions are processed after `after-init-hook'.
1482 (add-hook
1483 'after-init-hook
1484 (lambda ()
1485 (let ((key "--no-desktop"))
1486 (when (member key command-line-args)
1487 (setq command-line-args (delete key command-line-args))
1488 (desktop-save-mode 0)))
1489 (when desktop-save-mode
1490 (desktop-read)
1491 (setq inhibit-startup-screen t))))
1493 ;; So we can restore vc-dir buffers.
1494 (autoload 'vc-dir-mode "vc-dir" nil t)
1496 (provide 'desktop)
1498 ;;; desktop.el ends here
1500 ;; Local Variables:
1501 ;; coding: utf-8
1502 ;; End: