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