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