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