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