Some fixes and improvements for desktop frame restoration.
[emacs.git] / lisp / desktop.el
blob7d4ea20c210a2bbb143d7d41d05048dca8c4f824
1 ;;; desktop.el --- save partial status of Emacs when killed
3 ;; Copyright (C) 1993-1995, 1997, 2000-2013 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
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 Potorti`) for misc. tips.
127 ;; ---------------------------------------------------------------------------
128 ;; TODO:
130 ;; Save window configuration.
131 ;; Recognize more minor modes.
132 ;; Save mark rings.
134 ;;; Code:
136 (defvar desktop-file-version "206"
137 "Version number of desktop file format.
138 Written into the desktop file and used at desktop read to provide
139 backward compatibility.")
141 ;; ----------------------------------------------------------------------------
142 ;; USER OPTIONS -- settings you might want to play with.
143 ;; ----------------------------------------------------------------------------
145 (defgroup desktop nil
146 "Save status of Emacs when you exit."
147 :group 'frames)
149 ;; Maintained for backward compatibility
150 (define-obsolete-variable-alias 'desktop-enable 'desktop-save-mode "22.1")
151 ;;;###autoload
152 (define-minor-mode desktop-save-mode
153 "Toggle desktop saving (Desktop Save mode).
154 With a prefix argument ARG, enable Desktop Save mode if ARG is
155 positive, and disable it otherwise. If called from Lisp, enable
156 the mode if ARG is omitted or nil.
158 If Desktop Save mode is enabled, the state of Emacs is saved from
159 one session to another. See variable `desktop-save' and function
160 `desktop-read' for details."
161 :global t
162 :group 'desktop)
164 (defun desktop-save-mode-off ()
165 "Disable `desktop-save-mode'. Provided for use in hooks."
166 (desktop-save-mode 0))
168 (defcustom desktop-save 'ask-if-new
169 "Specifies whether the desktop should be saved when it is killed.
170 A desktop is killed when the user changes desktop or quits Emacs.
171 Possible values are:
172 t -- always save.
173 ask -- always ask.
174 ask-if-new -- ask if no desktop file exists, otherwise just save.
175 ask-if-exists -- ask if desktop file exists, otherwise don't save.
176 if-exists -- save if desktop file exists, otherwise don't save.
177 nil -- never save.
178 The desktop is never saved when `desktop-save-mode' is nil.
179 The variables `desktop-dirname' and `desktop-base-file-name'
180 determine where the desktop is saved."
181 :type
182 '(choice
183 (const :tag "Always save" t)
184 (const :tag "Always ask" ask)
185 (const :tag "Ask if desktop file is new, else do save" ask-if-new)
186 (const :tag "Ask if desktop file exists, else don't save" ask-if-exists)
187 (const :tag "Save if desktop file exists, else don't" if-exists)
188 (const :tag "Never save" nil))
189 :group 'desktop
190 :version "22.1")
192 (defcustom desktop-auto-save-timeout nil
193 "Number of seconds between auto-saves of the desktop.
194 Zero or nil means disable timer-based auto-saving."
195 :type '(choice (const :tag "Off" nil)
196 (integer :tag "Seconds"))
197 :set (lambda (symbol value)
198 (set-default symbol value)
199 (condition-case nil
200 (desktop-auto-save-set-timer)
201 (error nil)))
202 :group 'desktop
203 :version "24.4")
205 (defcustom desktop-load-locked-desktop 'ask
206 "Specifies whether the desktop should be loaded if locked.
207 Possible values are:
208 t -- load anyway.
209 nil -- don't load.
210 ask -- ask the user.
211 If the value is nil, or `ask' and the user chooses not to load the desktop,
212 the normal hook `desktop-not-loaded-hook' is run."
213 :type
214 '(choice
215 (const :tag "Load anyway" t)
216 (const :tag "Don't load" nil)
217 (const :tag "Ask the user" ask))
218 :group 'desktop
219 :version "22.2")
221 (define-obsolete-variable-alias 'desktop-basefilename
222 'desktop-base-file-name "22.1")
224 (defcustom desktop-base-file-name
225 (convert-standard-filename ".emacs.desktop")
226 "Name of file for Emacs desktop, excluding the directory part."
227 :type 'file
228 :group 'desktop)
230 (defcustom desktop-base-lock-name
231 (convert-standard-filename ".emacs.desktop.lock")
232 "Name of lock file for Emacs desktop, excluding the directory part."
233 :type 'file
234 :group 'desktop
235 :version "22.2")
237 (defcustom desktop-path (list user-emacs-directory "~")
238 "List of directories to search for the desktop file.
239 The base name of the file is specified in `desktop-base-file-name'."
240 :type '(repeat directory)
241 :group 'desktop
242 :version "23.2") ; user-emacs-directory added
244 (defcustom desktop-missing-file-warning nil
245 "If non-nil, offer to recreate the buffer of a deleted file.
246 Also pause for a moment to display message about errors signaled in
247 `desktop-buffer-mode-handlers'.
249 If nil, just print error messages in the message buffer."
250 :type 'boolean
251 :group 'desktop
252 :version "22.1")
254 (defcustom desktop-no-desktop-file-hook nil
255 "Normal hook run when `desktop-read' can't find a desktop file.
256 Run in the directory in which the desktop file was sought.
257 May be used to show a dired buffer."
258 :type 'hook
259 :group 'desktop
260 :version "22.1")
262 (defcustom desktop-not-loaded-hook nil
263 "Normal hook run when the user declines to re-use a desktop file.
264 Run in the directory in which the desktop file was found.
265 May be used to deal with accidental multiple Emacs jobs."
266 :type 'hook
267 :group 'desktop
268 :options '(desktop-save-mode-off save-buffers-kill-emacs)
269 :version "22.2")
271 (defcustom desktop-after-read-hook nil
272 "Normal hook run after a successful `desktop-read'.
273 May be used to show a buffer list."
274 :type 'hook
275 :group 'desktop
276 :options '(list-buffers)
277 :version "22.1")
279 (defcustom desktop-save-hook nil
280 "Normal hook run before the desktop is saved in a desktop file.
281 Run with the desktop buffer current with only the header present.
282 May be used to add to the desktop code or to truncate history lists,
283 for example."
284 :type 'hook
285 :group 'desktop)
287 (defcustom desktop-globals-to-save
288 '(desktop-missing-file-warning
289 tags-file-name
290 tags-table-list
291 search-ring
292 regexp-search-ring
293 register-alist
294 file-name-history)
295 "List of global variables saved by `desktop-save'.
296 An element may be variable name (a symbol) or a cons cell of the form
297 \(VAR . MAX-SIZE), which means to truncate VAR's value to at most
298 MAX-SIZE elements (if the value is a list) before saving the value.
299 Feature: Saving `kill-ring' implies saving `kill-ring-yank-pointer'."
300 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
301 :group 'desktop)
303 (defcustom desktop-globals-to-clear
304 '(kill-ring
305 kill-ring-yank-pointer
306 search-ring
307 search-ring-yank-pointer
308 regexp-search-ring
309 regexp-search-ring-yank-pointer)
310 "List of global variables that `desktop-clear' will clear.
311 An element may be variable name (a symbol) or a cons cell of the form
312 \(VAR . FORM). Symbols are set to nil and for cons cells VAR is set
313 to the value obtained by evaluating FORM."
314 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
315 :group 'desktop
316 :version "22.1")
318 (defcustom desktop-clear-preserve-buffers
319 '("\\*scratch\\*" "\\*Messages\\*" "\\*server\\*" "\\*tramp/.+\\*"
320 "\\*Warnings\\*")
321 "List of buffers that `desktop-clear' should not delete.
322 Each element is a regular expression. Buffers with a name matched by any of
323 these won't be deleted."
324 :version "23.3" ; added Warnings - bug#6336
325 :type '(repeat string)
326 :group 'desktop)
328 ;;;###autoload
329 (defcustom desktop-locals-to-save
330 '(desktop-locals-to-save ; Itself! Think it over.
331 truncate-lines
332 case-fold-search
333 case-replace
334 fill-column
335 overwrite-mode
336 change-log-default-name
337 line-number-mode
338 column-number-mode
339 size-indication-mode
340 buffer-file-coding-system
341 indent-tabs-mode
342 tab-width
343 indicate-buffer-boundaries
344 indicate-empty-lines
345 show-trailing-whitespace)
346 "List of local variables to save for each buffer.
347 The variables are saved only when they really are local. Conventional minor
348 modes are restored automatically; they should not be listed here."
349 :type '(repeat symbol)
350 :group 'desktop)
352 (defcustom desktop-buffers-not-to-save nil
353 "Regexp identifying buffers that are to be excluded from saving."
354 :type '(choice (const :tag "None" nil)
355 regexp)
356 :version "23.2" ; set to nil
357 :group 'desktop)
359 ;; Skip tramp and ange-ftp files
360 (defcustom desktop-files-not-to-save
361 "\\(^/[^/:]*:\\|(ftp)$\\)"
362 "Regexp identifying files whose buffers are to be excluded from saving."
363 :type '(choice (const :tag "None" nil)
364 regexp)
365 :group 'desktop)
367 ;; We skip TAGS files to save time (tags-file-name is saved instead).
368 (defcustom desktop-modes-not-to-save
369 '(tags-table-mode)
370 "List of major modes whose buffers should not be saved."
371 :type '(repeat symbol)
372 :group 'desktop)
374 (defcustom desktop-save-windows nil
375 "When non-nil, save window/frame configuration to desktop file."
376 :type 'boolean
377 :group 'desktop
378 :version "24.4")
380 (defcustom desktop-file-name-format 'absolute
381 "Format in which desktop file names should be saved.
382 Possible values are:
383 absolute -- Absolute file name.
384 tilde -- Relative to ~.
385 local -- Relative to directory of desktop file."
386 :type '(choice (const absolute) (const tilde) (const local))
387 :group 'desktop
388 :version "22.1")
390 (defcustom desktop-restore-eager t
391 "Number of buffers to restore immediately.
392 Remaining buffers are restored lazily (when Emacs is idle).
393 If value is t, all buffers are restored immediately."
394 :type '(choice (const t) integer)
395 :group 'desktop
396 :version "22.1")
398 (defcustom desktop-lazy-verbose t
399 "Verbose reporting of lazily created buffers."
400 :type 'boolean
401 :group 'desktop
402 :version "22.1")
404 (defcustom desktop-lazy-idle-delay 5
405 "Idle delay before starting to create buffers.
406 See `desktop-restore-eager'."
407 :type 'integer
408 :group 'desktop
409 :version "22.1")
411 ;;;###autoload
412 (defvar desktop-save-buffer nil
413 "When non-nil, save buffer status in desktop file.
414 This variable becomes buffer local when set.
416 If the value is a function, it is called by `desktop-save' with argument
417 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
418 file along with the state of the buffer for which it was called.
420 When file names are returned, they should be formatted using the call
421 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
423 Later, when `desktop-read' evaluates the desktop file, auxiliary information
424 is passed as the argument DESKTOP-BUFFER-MISC to functions in
425 `desktop-buffer-mode-handlers'.")
426 (make-variable-buffer-local 'desktop-save-buffer)
427 (make-obsolete-variable 'desktop-buffer-modes-to-save
428 'desktop-save-buffer "22.1")
429 (make-obsolete-variable 'desktop-buffer-misc-functions
430 'desktop-save-buffer "22.1")
432 ;;;###autoload
433 (defvar desktop-buffer-mode-handlers nil
434 "Alist of major mode specific functions to restore a desktop buffer.
435 Functions listed are called by `desktop-create-buffer' when `desktop-read'
436 evaluates the desktop file. List elements must have the form
438 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
440 Buffers with a major mode not specified here, are restored by the default
441 handler `desktop-restore-file-buffer'.
443 Handlers are called with argument list
445 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
447 Furthermore, they may use the following variables:
449 desktop-file-version
450 desktop-buffer-major-mode
451 desktop-buffer-minor-modes
452 desktop-buffer-point
453 desktop-buffer-mark
454 desktop-buffer-read-only
455 desktop-buffer-locals
457 If a handler returns a buffer, then the saved mode settings
458 and variable values for that buffer are copied into it.
460 Modules that define a major mode that needs a special handler should contain
461 code like
463 (defun foo-restore-desktop-buffer
465 (add-to-list 'desktop-buffer-mode-handlers
466 '(foo-mode . foo-restore-desktop-buffer))
468 Furthermore the major mode function must be autoloaded.")
470 ;;;###autoload
471 (put 'desktop-buffer-mode-handlers 'risky-local-variable t)
472 (make-obsolete-variable 'desktop-buffer-handlers
473 'desktop-buffer-mode-handlers "22.1")
475 (defcustom desktop-minor-mode-table
476 '((auto-fill-function auto-fill-mode)
477 (vc-mode nil)
478 (vc-dired-mode nil)
479 (erc-track-minor-mode nil)
480 (savehist-mode nil))
481 "Table mapping minor mode variables to minor mode functions.
482 Each entry has the form (NAME RESTORE-FUNCTION).
483 NAME is the name of the buffer-local variable indicating that the minor
484 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
485 RESTORE-FUNCTION nil means don't try to restore the minor mode.
486 Only minor modes for which the name of the buffer-local variable
487 and the name of the minor mode function are different have to be added to
488 this table. See also `desktop-minor-mode-handlers'."
489 :type 'sexp
490 :group 'desktop)
492 ;;;###autoload
493 (defvar desktop-minor-mode-handlers nil
494 "Alist of functions to restore non-standard minor modes.
495 Functions are called by `desktop-create-buffer' to restore minor modes.
496 List elements must have the form
498 (MINOR-MODE . RESTORE-FUNCTION).
500 Minor modes not specified here, are restored by the standard minor mode
501 function.
503 Handlers are called with argument list
505 (DESKTOP-BUFFER-LOCALS)
507 Furthermore, they may use the following variables:
509 desktop-file-version
510 desktop-buffer-file-name
511 desktop-buffer-name
512 desktop-buffer-major-mode
513 desktop-buffer-minor-modes
514 desktop-buffer-point
515 desktop-buffer-mark
516 desktop-buffer-read-only
517 desktop-buffer-misc
519 When a handler is called, the buffer has been created and the major mode has
520 been set, but local variables listed in desktop-buffer-locals has not yet been
521 created and set.
523 Modules that define a minor mode that needs a special handler should contain
524 code like
526 (defun foo-desktop-restore
528 (add-to-list 'desktop-minor-mode-handlers
529 '(foo-mode . foo-desktop-restore))
531 Furthermore the minor mode function must be autoloaded.
533 See also `desktop-minor-mode-table'.")
535 ;;;###autoload
536 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
538 ;; ----------------------------------------------------------------------------
539 (defvar desktop-dirname nil
540 "The directory in which the desktop file should be saved.")
542 (defun desktop-full-file-name (&optional dirname)
543 "Return the full name of the desktop file in DIRNAME.
544 DIRNAME omitted or nil means use `desktop-dirname'."
545 (expand-file-name desktop-base-file-name (or dirname desktop-dirname)))
547 (defun desktop-full-lock-name (&optional dirname)
548 "Return the full name of the desktop lock file in DIRNAME.
549 DIRNAME omitted or nil means use `desktop-dirname'."
550 (expand-file-name desktop-base-lock-name (or dirname desktop-dirname)))
552 (defconst desktop-header
553 ";; --------------------------------------------------------------------------
554 ;; Desktop File for Emacs
555 ;; --------------------------------------------------------------------------
556 " "*Header to place in Desktop file.")
558 (defvar desktop-delay-hook nil
559 "Hooks run after all buffers are loaded; intended for internal use.")
561 (defvar desktop-file-checksum nil
562 "Checksum of the last auto-saved contents of the desktop file.
563 Used to avoid writing contents unchanged between auto-saves.")
565 (defvar desktop--saved-states nil
566 "Internal use only.")
568 ;; ----------------------------------------------------------------------------
569 ;; Desktop file conflict detection
570 (defvar desktop-file-modtime nil
571 "When the desktop file was last modified to the knowledge of this Emacs.
572 Used to detect desktop file conflicts.")
574 (defun desktop-owner (&optional dirname)
575 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
576 Return nil if no desktop file found or no Emacs process is using it.
577 DIRNAME omitted or nil means use `desktop-dirname'."
578 (let (owner)
579 (and (file-exists-p (desktop-full-lock-name dirname))
580 (condition-case nil
581 (with-temp-buffer
582 (insert-file-contents-literally (desktop-full-lock-name dirname))
583 (goto-char (point-min))
584 (setq owner (read (current-buffer)))
585 (integerp owner))
586 (error nil))
587 owner)))
589 (defun desktop-claim-lock (&optional dirname)
590 "Record this Emacs process as the owner of the desktop file in DIRNAME.
591 DIRNAME omitted or nil means use `desktop-dirname'."
592 (write-region (number-to-string (emacs-pid)) nil
593 (desktop-full-lock-name dirname)))
595 (defun desktop-release-lock (&optional dirname)
596 "Remove the lock file for the desktop in DIRNAME.
597 DIRNAME omitted or nil means use `desktop-dirname'."
598 (let ((file (desktop-full-lock-name dirname)))
599 (when (file-exists-p file) (delete-file file))))
601 ;; ----------------------------------------------------------------------------
602 (defun desktop-truncate (list n)
603 "Truncate LIST to at most N elements destructively."
604 (let ((here (nthcdr (1- n) list)))
605 (when (consp here)
606 (setcdr here nil))))
608 ;; ----------------------------------------------------------------------------
609 ;;;###autoload
610 (defun desktop-clear ()
611 "Empty the Desktop.
612 This kills all buffers except for internal ones and those with names matched by
613 a regular expression in the list `desktop-clear-preserve-buffers'.
614 Furthermore, it clears the variables listed in `desktop-globals-to-clear'."
615 (interactive)
616 (desktop-lazy-abort)
617 (dolist (var desktop-globals-to-clear)
618 (if (symbolp var)
619 (eval `(setq-default ,var nil))
620 (eval `(setq-default ,(car var) ,(cdr var)))))
621 (let ((buffers (buffer-list))
622 (preserve-regexp (concat "^\\("
623 (mapconcat (lambda (regexp)
624 (concat "\\(" regexp "\\)"))
625 desktop-clear-preserve-buffers
626 "\\|")
627 "\\)$")))
628 (while buffers
629 (let ((bufname (buffer-name (car buffers))))
631 (null bufname)
632 (string-match preserve-regexp bufname)
633 ;; Don't kill buffers made for internal purposes.
634 (and (not (equal bufname "")) (eq (aref bufname 0) ?\s))
635 (kill-buffer (car buffers))))
636 (setq buffers (cdr buffers))))
637 (delete-other-windows))
639 ;; ----------------------------------------------------------------------------
640 (unless noninteractive
641 (add-hook 'kill-emacs-hook 'desktop-kill))
643 (defun desktop-kill ()
644 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
645 If the desktop should be saved and `desktop-dirname'
646 is nil, ask the user where to save the desktop."
647 (when (and desktop-save-mode
648 (let ((exists (file-exists-p (desktop-full-file-name))))
649 (or (eq desktop-save t)
650 (and exists (eq desktop-save 'if-exists))
651 ;; If it exists, but we aren't using it, we are going
652 ;; to ask for a new directory below.
653 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
654 (and
655 (or (memq desktop-save '(ask ask-if-new))
656 (and exists (eq desktop-save 'ask-if-exists)))
657 (y-or-n-p "Save desktop? ")))))
658 (unless desktop-dirname
659 (setq desktop-dirname
660 (file-name-as-directory
661 (expand-file-name
662 (read-directory-name "Directory for desktop file: " nil nil t)))))
663 (condition-case err
664 (desktop-save desktop-dirname t)
665 (file-error
666 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
667 (signal (car err) (cdr err))))))
668 ;; If we own it, we don't anymore.
669 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
671 ;; ----------------------------------------------------------------------------
672 (defun desktop-list* (&rest args)
673 (if (null (cdr args))
674 (car args)
675 (setq args (nreverse args))
676 (let ((value (cons (nth 1 args) (car args))))
677 (setq args (cdr (cdr args)))
678 (while args
679 (setq value (cons (car args) value))
680 (setq args (cdr args)))
681 value)))
683 ;; ----------------------------------------------------------------------------
684 (defun desktop-buffer-info (buffer)
685 (set-buffer buffer)
686 (list
687 ;; base name of the buffer; replaces the buffer name if managed by uniquify
688 (and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
689 ;; basic information
690 (desktop-file-name (buffer-file-name) desktop-dirname)
691 (buffer-name)
692 major-mode
693 ;; minor modes
694 (let (ret)
695 (mapc
696 #'(lambda (minor-mode)
697 (and (boundp minor-mode)
698 (symbol-value minor-mode)
699 (let* ((special (assq minor-mode desktop-minor-mode-table))
700 (value (cond (special (cadr special))
701 ((functionp minor-mode) minor-mode))))
702 (when value (add-to-list 'ret value)))))
703 (mapcar #'car minor-mode-alist))
704 ret)
705 ;; point and mark, and read-only status
706 (point)
707 (list (mark t) mark-active)
708 buffer-read-only
709 ;; auxiliary information
710 (when (functionp desktop-save-buffer)
711 (funcall desktop-save-buffer desktop-dirname))
712 ;; local variables
713 (let ((locals desktop-locals-to-save)
714 (loclist (buffer-local-variables))
715 (ll))
716 (while locals
717 (let ((here (assq (car locals) loclist)))
718 (if here
719 (setq ll (cons here ll))
720 (when (member (car locals) loclist)
721 (setq ll (cons (car locals) ll)))))
722 (setq locals (cdr locals)))
723 ll)))
725 ;; ----------------------------------------------------------------------------
726 (defun desktop--v2s (value)
727 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
728 SEXP is an sexp that when evaluated yields VALUE.
729 QUOTE may be `may' (value may be quoted),
730 `must' (value must be quoted), or nil (value must not be quoted)."
731 (cond
732 ((or (numberp value) (null value) (eq t value) (keywordp value))
733 (cons 'may value))
734 ((stringp value)
735 (let ((copy (copy-sequence value)))
736 (set-text-properties 0 (length copy) nil copy)
737 ;; Get rid of text properties because we cannot read them.
738 (cons 'may copy)))
739 ((symbolp value)
740 (cons 'must value))
741 ((vectorp value)
742 (let* ((pass1 (mapcar #'desktop--v2s value))
743 (special (assq nil pass1)))
744 (if special
745 (cons nil `(vector
746 ,@(mapcar (lambda (el)
747 (if (eq (car el) 'must)
748 `',(cdr el) (cdr el)))
749 pass1)))
750 (cons 'may `[,@(mapcar #'cdr pass1)]))))
751 ((consp value)
752 (let ((p value)
753 newlist
754 use-list*
755 anynil)
756 (while (consp p)
757 (let ((q.sexp (desktop--v2s (car p))))
758 (push q.sexp newlist))
759 (setq p (cdr p)))
760 (when p
761 (let ((last (desktop--v2s p)))
762 (setq use-list* t)
763 (push last newlist)))
764 (if (assq nil newlist)
765 (cons nil
766 `(,(if use-list* 'desktop-list* 'list)
767 ,@(mapcar (lambda (el)
768 (if (eq (car el) 'must)
769 `',(cdr el) (cdr el)))
770 (nreverse newlist))))
771 (cons 'must
772 `(,@(mapcar #'cdr
773 (nreverse (if use-list* (cdr newlist) newlist)))
774 ,@(if use-list* (cdar newlist)))))))
775 ((subrp value)
776 (cons nil `(symbol-function
777 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
778 ((markerp value)
779 (let ((pos (marker-position value))
780 (buf (buffer-name (marker-buffer value))))
781 (cons nil
782 `(let ((mk (make-marker)))
783 (add-hook 'desktop-delay-hook
784 `(lambda ()
785 (set-marker ,mk ,,pos (get-buffer ,,buf))))
786 mk))))
787 (t ; Save as text.
788 (cons 'may "Unprintable entity"))))
790 ;; ----------------------------------------------------------------------------
791 (defun desktop-value-to-string (value)
792 "Convert VALUE to a string that when read evaluates to the same value.
793 Not all types of values are supported."
794 (let* ((print-escape-newlines t)
795 (float-output-format nil)
796 (quote.sexp (desktop--v2s value))
797 (quote (car quote.sexp))
798 (txt
799 (let ((print-quoted t))
800 (prin1-to-string (cdr quote.sexp)))))
801 (if (eq quote 'must)
802 (concat "'" txt)
803 txt)))
805 ;; ----------------------------------------------------------------------------
806 (defun desktop-outvar (varspec)
807 "Output a setq statement for variable VAR to the desktop file.
808 The argument VARSPEC may be the variable name VAR (a symbol),
809 or a cons cell of the form (VAR . MAX-SIZE),
810 which means to truncate VAR's value to at most MAX-SIZE elements
811 \(if the value is a list) before saving the value."
812 (let (var size)
813 (if (consp varspec)
814 (setq var (car varspec) size (cdr varspec))
815 (setq var varspec))
816 (when (boundp var)
817 (when (and (integerp size)
818 (> size 0)
819 (listp (eval var)))
820 (desktop-truncate (eval var) size))
821 (insert "(setq "
822 (symbol-name var)
824 (desktop-value-to-string (symbol-value var))
825 ")\n"))))
827 ;; ----------------------------------------------------------------------------
828 (defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
829 "Return t if buffer should have its state saved in the desktop file.
830 FILENAME is the visited file name, BUFNAME is the buffer name, and
831 MODE is the major mode.
832 \n\(fn FILENAME BUFNAME MODE)"
833 (let ((case-fold-search nil)
834 dired-skip)
835 (and (not (and (stringp desktop-buffers-not-to-save)
836 (not filename)
837 (string-match desktop-buffers-not-to-save bufname)))
838 (not (memq mode desktop-modes-not-to-save))
839 ;; FIXME this is broken if desktop-files-not-to-save is nil.
840 (or (and filename
841 (stringp desktop-files-not-to-save)
842 (not (string-match desktop-files-not-to-save filename)))
843 (and (memq mode '(dired-mode vc-dir-mode))
844 (with-current-buffer bufname
845 (not (setq dired-skip
846 (string-match desktop-files-not-to-save
847 default-directory)))))
848 (and (null filename)
849 (null dired-skip) ; bug#5755
850 (with-current-buffer bufname desktop-save-buffer))))))
852 ;; ----------------------------------------------------------------------------
853 (defun desktop-file-name (filename dirname)
854 "Convert FILENAME to format specified in `desktop-file-name-format'.
855 DIRNAME must be the directory in which the desktop file will be saved."
856 (cond
857 ((not filename) nil)
858 ((eq desktop-file-name-format 'tilde)
859 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
860 (cond
861 ((file-name-absolute-p relative-name) relative-name)
862 ((string= "./" relative-name) "~/")
863 ((string= "." relative-name) "~")
864 (t (concat "~/" relative-name)))))
865 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
866 (t (expand-file-name filename))))
869 ;; ----------------------------------------------------------------------------
870 (defconst desktop--excluded-frame-parameters
871 '(buffer-list
872 buffer-predicate
873 buried-buffer-list
874 explicit-name
875 font-backend
876 minibuffer
877 name
878 outer-window-id
879 parent-id
880 window-id
881 window-system)
882 "Frame parameters not saved or restored.")
884 (defun desktop--filter-frame-parms (frame)
885 "Return frame parameters of FRAME.
886 Parameters in `desktop--excluded-frame-parameters' are excluded.
887 Internal use only."
888 (let (params)
889 (dolist (param (frame-parameters frame))
890 (unless (memq (car param) desktop--excluded-frame-parameters)
891 (push param params)))
892 params))
894 (defun desktop--save-windows ()
895 "Save window/frame state, as a global variable.
896 Intended to be called from `desktop-save'.
897 Internal use only."
898 (setq desktop--saved-states
899 (and desktop-save-windows
900 (mapcar (lambda (frame)
901 (cons (desktop--filter-frame-parms frame)
902 (window-state-get (frame-root-window frame) t)))
903 (cons (selected-frame)
904 (delq (selected-frame) (frame-list))))))
905 (desktop-outvar 'desktop--saved-states))
907 ;;;###autoload
908 (defun desktop-save (dirname &optional release auto-save)
909 "Save the desktop in a desktop file.
910 Parameter DIRNAME specifies where to save the desktop file.
911 Optional parameter RELEASE says whether we're done with this desktop.
912 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
913 and don't save the buffer if they are the same."
914 (interactive "DDirectory to save desktop file in: ")
915 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
916 (save-excursion
917 (let ((eager desktop-restore-eager)
918 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
919 (when
920 (or (not new-modtime) ; nothing to overwrite
921 (equal desktop-file-modtime new-modtime)
922 (yes-or-no-p (if desktop-file-modtime
923 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
924 "Desktop file is more recent than the one loaded. Save anyway? "
925 "Desktop file isn't the one loaded. Overwrite it? ")
926 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
927 (unless release (error "Desktop file conflict")))
929 ;; If we're done with it, release the lock.
930 ;; Otherwise, claim it if it's unclaimed or if we created it.
931 (if release
932 (desktop-release-lock)
933 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
935 (with-temp-buffer
936 (insert
937 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
938 desktop-header
939 ";; Created " (current-time-string) "\n"
940 ";; Desktop file format version " desktop-file-version "\n"
941 ";; Emacs version " emacs-version "\n")
942 (save-excursion (run-hooks 'desktop-save-hook))
943 (goto-char (point-max))
944 (insert "\n;; Global section:\n")
945 ;; Called here because we save the window/frame state as a global
946 ;; variable for compatibility with previous Emacsen.
947 (desktop--save-windows)
948 (mapc (function desktop-outvar) desktop-globals-to-save)
949 (when (memq 'kill-ring desktop-globals-to-save)
950 (insert
951 "(setq kill-ring-yank-pointer (nthcdr "
952 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
953 " kill-ring))\n"))
955 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
956 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
957 (let ((base (pop l)))
958 (when (apply 'desktop-save-buffer-p l)
959 (insert "("
960 (if (or (not (integerp eager))
961 (if (zerop eager)
963 (setq eager (1- eager))))
964 "desktop-create-buffer"
965 "desktop-append-buffer-args")
967 desktop-file-version)
968 ;; If there's a non-empty base name, we save it instead of the buffer name
969 (when (and base (not (string= base "")))
970 (setcar (nthcdr 1 l) base))
971 (dolist (e l)
972 (insert "\n " (desktop-value-to-string e)))
973 (insert ")\n\n"))))
975 (setq default-directory desktop-dirname)
976 ;; If auto-saving, avoid writing if nothing has changed since the last write.
977 ;; Don't check 300 characters of the header that contains the timestamp.
978 (let ((checksum (and auto-save (md5 (current-buffer)
979 (+ (point-min) 300) (point-max)
980 'emacs-mule))))
981 (unless (and auto-save (equal checksum desktop-file-checksum))
982 (let ((coding-system-for-write 'emacs-mule))
983 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
984 (setq desktop-file-checksum checksum)
985 ;; We remember when it was modified (which is presumably just now).
986 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
988 ;; ----------------------------------------------------------------------------
989 ;;;###autoload
990 (defun desktop-remove ()
991 "Delete desktop file in `desktop-dirname'.
992 This function also sets `desktop-dirname' to nil."
993 (interactive)
994 (when desktop-dirname
995 (let ((filename (desktop-full-file-name)))
996 (setq desktop-dirname nil)
997 (when (file-exists-p filename)
998 (delete-file filename)))))
1000 (defvar desktop-buffer-args-list nil
1001 "List of args for `desktop-create-buffer'.")
1003 (defvar desktop-lazy-timer nil)
1005 ;; ----------------------------------------------------------------------------
1006 (defun desktop--find-frame-in-display (frames display)
1007 (let (result)
1008 (while (and frames (not result))
1009 (if (equal display (frame-parameter (car frames) 'display))
1010 (setq result (car frames))
1011 (setq frames (cdr frames))))
1012 result))
1014 (defun desktop--make-full-frame (full display config)
1015 (let ((width (and (eq full 'fullheight) (cdr (assq 'width config))))
1016 (height (and (eq full 'fullwidth) (cdr (assq 'height config))))
1017 (params '((visibility)))
1018 frame)
1019 (when width
1020 (setq params (append `((user-size . t) (width . ,width)) params)))
1021 (when height
1022 (setq params (append `((user-size . t) (height . ,height)) params)))
1023 (setq frame (make-frame-on-display display params))
1024 (modify-frame-parameters frame config)
1025 frame))
1027 (defun desktop--restore-windows ()
1028 "Restore window/frame configuration.
1029 Internal use only."
1030 (when (and desktop-save-windows desktop--saved-states)
1031 (let ((frames (frame-list))
1032 (selected nil))
1033 (dolist (state desktop--saved-states)
1034 (condition-case err
1035 (let* ((fconfig (car state))
1036 (display (cdr (assq 'display fconfig)))
1037 (full (cdr (assq 'fullscreen fconfig)))
1038 (frame (and (not full)
1039 (desktop--find-frame-in-display frames display))))
1040 (cond (full
1041 ;; treat fullscreen/maximized frames specially
1042 (setq frame (desktop--make-full-frame full display fconfig)))
1043 (frame
1044 ;; found a frame in the right display -- reuse
1045 (setq frames (delq frame frames))
1046 (modify-frame-parameters frame fconfig))
1048 ;; no frames in the display -- make a new one
1049 (setq frame (make-frame-on-display display fconfig))))
1050 ;; restore windows
1051 (window-state-put (cdr state) (frame-root-window frame) 'safe)
1052 (unless selected (setq selected frame)))
1053 (error
1054 (message "Error restoring frame: %S" (error-message-string err)))))
1055 ;; make sure the original selected frame is visible and selected
1056 (unless (or (frame-parameter selected 'visibility) (daemonp))
1057 (modify-frame-parameters selected '((visibility . t))))
1058 (select-frame-set-input-focus selected)
1059 ;; delete any remaining frames
1060 (mapc #'delete-frame frames))))
1062 ;;;###autoload
1063 (defun desktop-read (&optional dirname)
1064 "Read and process the desktop file in directory DIRNAME.
1065 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1066 directories listed in `desktop-path'. If a desktop file is found, it
1067 is processed and `desktop-after-read-hook' is run. If no desktop file
1068 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1069 This function is a no-op when Emacs is running in batch mode.
1070 It returns t if a desktop file was loaded, nil otherwise."
1071 (interactive)
1072 (unless noninteractive
1073 (setq desktop-dirname
1074 (file-name-as-directory
1075 (expand-file-name
1077 ;; If DIRNAME is specified, use it.
1078 (and (< 0 (length dirname)) dirname)
1079 ;; Otherwise search desktop file in desktop-path.
1080 (let ((dirs desktop-path))
1081 (while (and dirs
1082 (not (file-exists-p
1083 (desktop-full-file-name (car dirs)))))
1084 (setq dirs (cdr dirs)))
1085 (and dirs (car dirs)))
1086 ;; If not found and `desktop-path' is non-nil, use its first element.
1087 (and desktop-path (car desktop-path))
1088 ;; Default: .emacs.d.
1089 user-emacs-directory))))
1090 (if (file-exists-p (desktop-full-file-name))
1091 ;; Desktop file found, but is it already in use?
1092 (let ((desktop-first-buffer nil)
1093 (desktop-buffer-ok-count 0)
1094 (desktop-buffer-fail-count 0)
1095 (owner (desktop-owner))
1096 ;; Avoid desktop saving during evaluation of desktop buffer.
1097 (desktop-save nil))
1098 (if (and owner
1099 (memq desktop-load-locked-desktop '(nil ask))
1100 (or (null desktop-load-locked-desktop)
1101 (daemonp)
1102 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1103 Using it may cause conflicts. Use it anyway? " owner)))))
1104 (let ((default-directory desktop-dirname))
1105 (setq desktop-dirname nil)
1106 (run-hooks 'desktop-not-loaded-hook)
1107 (unless desktop-dirname
1108 (message "Desktop file in use; not loaded.")))
1109 (desktop-lazy-abort)
1110 ;; Evaluate desktop buffer and remember when it was modified.
1111 (load (desktop-full-file-name) t t t)
1112 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1113 ;; If it wasn't already, mark it as in-use, to bother other
1114 ;; desktop instances.
1115 (unless owner
1116 (condition-case nil
1117 (desktop-claim-lock)
1118 (file-error (message "Couldn't record use of desktop file")
1119 (sit-for 1))))
1121 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
1122 ;; We want buffers existing prior to evaluating the desktop (and
1123 ;; not reused) to be placed at the end of the buffer list, so we
1124 ;; move them here.
1125 (mapc 'bury-buffer
1126 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
1127 (switch-to-buffer (car (buffer-list)))
1128 (run-hooks 'desktop-delay-hook)
1129 (setq desktop-delay-hook nil)
1130 (desktop--restore-windows)
1131 (run-hooks 'desktop-after-read-hook)
1132 (message "Desktop: %d buffer%s restored%s%s."
1133 desktop-buffer-ok-count
1134 (if (= 1 desktop-buffer-ok-count) "" "s")
1135 (if (< 0 desktop-buffer-fail-count)
1136 (format ", %d failed to restore" desktop-buffer-fail-count)
1138 (if desktop-buffer-args-list
1139 (format ", %d to restore lazily"
1140 (length desktop-buffer-args-list))
1141 ""))
1142 ;; Bury the *Messages* buffer to not reshow it when burying
1143 ;; the buffer we switched to above.
1144 (when (buffer-live-p (get-buffer "*Messages*"))
1145 (bury-buffer "*Messages*"))
1146 ;; Clear all windows' previous and next buffers, these have
1147 ;; been corrupted by the `switch-to-buffer' calls in
1148 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1149 ;; brute force fix and should be replaced by a more subtle
1150 ;; strategy eventually.
1151 (walk-window-tree (lambda (window)
1152 (set-window-prev-buffers window nil)
1153 (set-window-next-buffers window nil)))
1155 ;; No desktop file found.
1156 (desktop-clear)
1157 (let ((default-directory desktop-dirname))
1158 (run-hooks 'desktop-no-desktop-file-hook))
1159 (message "No desktop file.")
1160 nil)))
1162 ;; ----------------------------------------------------------------------------
1163 ;; Maintained for backward compatibility
1164 ;;;###autoload
1165 (defun desktop-load-default ()
1166 "Load the `default' start-up library manually.
1167 Also inhibit further loading of it."
1168 (declare (obsolete desktop-save-mode "22.1"))
1169 (unless inhibit-default-init ; safety check
1170 (load "default" t t)
1171 (setq inhibit-default-init t)))
1173 ;; ----------------------------------------------------------------------------
1174 ;;;###autoload
1175 (defun desktop-change-dir (dirname)
1176 "Change to desktop saved in DIRNAME.
1177 Kill the desktop as specified by variables `desktop-save-mode' and
1178 `desktop-save', then clear the desktop and load the desktop file in
1179 directory DIRNAME."
1180 (interactive "DChange to directory: ")
1181 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1182 (desktop-kill)
1183 (desktop-clear)
1184 (desktop-read dirname))
1186 ;; ----------------------------------------------------------------------------
1187 ;;;###autoload
1188 (defun desktop-save-in-desktop-dir ()
1189 "Save the desktop in directory `desktop-dirname'."
1190 (interactive)
1191 (if desktop-dirname
1192 (desktop-save desktop-dirname)
1193 (call-interactively 'desktop-save))
1194 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1196 ;; ----------------------------------------------------------------------------
1197 ;; Auto-Saving.
1198 (defvar desktop-auto-save-timer nil)
1200 (defun desktop-auto-save ()
1201 "Save the desktop periodically.
1202 Called by the timer created in `desktop-auto-save-set-timer'."
1203 (when (and desktop-save-mode
1204 (integerp desktop-auto-save-timeout)
1205 (> desktop-auto-save-timeout 0)
1206 ;; Avoid desktop saving during lazy loading.
1207 (not desktop-lazy-timer)
1208 ;; Save only to own desktop file.
1209 (eq (emacs-pid) (desktop-owner))
1210 desktop-dirname)
1211 (desktop-save desktop-dirname nil t))
1212 (desktop-auto-save-set-timer))
1214 (defun desktop-auto-save-set-timer ()
1215 "Reset the auto-save timer.
1216 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1217 integer, start a new timer to call `desktop-auto-save' in that many seconds."
1218 (when desktop-auto-save-timer
1219 (cancel-timer desktop-auto-save-timer)
1220 (setq desktop-auto-save-timer nil))
1221 (when (and (integerp desktop-auto-save-timeout)
1222 (> desktop-auto-save-timeout 0))
1223 (setq desktop-auto-save-timer
1224 (run-with-timer desktop-auto-save-timeout nil
1225 'desktop-auto-save))))
1227 ;; ----------------------------------------------------------------------------
1228 ;;;###autoload
1229 (defun desktop-revert ()
1230 "Revert to the last loaded desktop."
1231 (interactive)
1232 (unless desktop-dirname
1233 (error "Unknown desktop directory"))
1234 (unless (file-exists-p (desktop-full-file-name))
1235 (error "No desktop file found"))
1236 (desktop-clear)
1237 (desktop-read desktop-dirname))
1239 (defvar desktop-buffer-major-mode)
1240 (defvar desktop-buffer-locals)
1241 (defvar auto-insert) ; from autoinsert.el
1242 ;; ----------------------------------------------------------------------------
1243 (defun desktop-restore-file-buffer (buffer-filename
1244 _buffer-name
1245 _buffer-misc)
1246 "Restore a file buffer."
1247 (when buffer-filename
1248 (if (or (file-exists-p buffer-filename)
1249 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1250 buffer-filename)))
1251 (if desktop-missing-file-warning
1252 (y-or-n-p (concat msg " Re-create buffer? "))
1253 (message "%s" msg)
1254 nil)))
1255 (let* ((auto-insert nil) ; Disable auto insertion
1256 (coding-system-for-read
1257 (or coding-system-for-read
1258 (cdr (assq 'buffer-file-coding-system
1259 desktop-buffer-locals))))
1260 (buf (find-file-noselect buffer-filename)))
1261 (condition-case nil
1262 (switch-to-buffer buf)
1263 (error (pop-to-buffer buf)))
1264 (and (not (eq major-mode desktop-buffer-major-mode))
1265 (functionp desktop-buffer-major-mode)
1266 (funcall desktop-buffer-major-mode))
1267 buf)
1268 nil)))
1270 (defun desktop-load-file (function)
1271 "Load the file where auto loaded FUNCTION is defined."
1272 (when (fboundp function)
1273 (autoload-do-load (symbol-function function) function)))
1275 ;; ----------------------------------------------------------------------------
1276 ;; Create a buffer, load its file, set its mode, ...;
1277 ;; called from Desktop file only.
1279 ;; Just to silence the byte compiler.
1281 (defvar desktop-first-buffer) ; Dynamically bound in `desktop-read'
1283 ;; Bound locally in `desktop-read'.
1284 (defvar desktop-buffer-ok-count)
1285 (defvar desktop-buffer-fail-count)
1287 (defun desktop-create-buffer
1288 (file-version
1289 buffer-filename
1290 buffer-name
1291 buffer-majormode
1292 buffer-minormodes
1293 buffer-point
1294 buffer-mark
1295 buffer-readonly
1296 buffer-misc
1297 &optional
1298 buffer-locals)
1300 (let ((desktop-file-version file-version)
1301 (desktop-buffer-file-name buffer-filename)
1302 (desktop-buffer-name buffer-name)
1303 (desktop-buffer-major-mode buffer-majormode)
1304 (desktop-buffer-minor-modes buffer-minormodes)
1305 (desktop-buffer-point buffer-point)
1306 (desktop-buffer-mark buffer-mark)
1307 (desktop-buffer-read-only buffer-readonly)
1308 (desktop-buffer-misc buffer-misc)
1309 (desktop-buffer-locals buffer-locals))
1310 ;; To make desktop files with relative file names possible, we cannot
1311 ;; allow `default-directory' to change. Therefore we save current buffer.
1312 (save-current-buffer
1313 ;; Give major mode module a chance to add a handler.
1314 (desktop-load-file desktop-buffer-major-mode)
1315 (let ((buffer-list (buffer-list))
1316 (result
1317 (condition-case-unless-debug err
1318 (funcall (or (cdr (assq desktop-buffer-major-mode
1319 desktop-buffer-mode-handlers))
1320 'desktop-restore-file-buffer)
1321 desktop-buffer-file-name
1322 desktop-buffer-name
1323 desktop-buffer-misc)
1324 (error
1325 (message "Desktop: Can't load buffer %s: %s"
1326 desktop-buffer-name
1327 (error-message-string err))
1328 (when desktop-missing-file-warning (sit-for 1))
1329 nil))))
1330 (if (bufferp result)
1331 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1332 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1333 (setq result nil))
1334 ;; Restore buffer list order with new buffer at end. Don't change
1335 ;; the order for old desktop files (old desktop module behavior).
1336 (unless (< desktop-file-version 206)
1337 (mapc 'bury-buffer buffer-list)
1338 (when result (bury-buffer result)))
1339 (when result
1340 (unless (or desktop-first-buffer (< desktop-file-version 206))
1341 (setq desktop-first-buffer result))
1342 (set-buffer result)
1343 (unless (equal (buffer-name) desktop-buffer-name)
1344 (rename-buffer desktop-buffer-name t))
1345 ;; minor modes
1346 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1347 (auto-fill-mode 1))
1348 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1349 (auto-fill-mode 0))
1351 (dolist (minor-mode desktop-buffer-minor-modes)
1352 ;; Give minor mode module a chance to add a handler.
1353 (desktop-load-file minor-mode)
1354 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1355 (if handler
1356 (funcall handler desktop-buffer-locals)
1357 (when (functionp minor-mode)
1358 (funcall minor-mode 1)))))))
1359 ;; Even though point and mark are non-nil when written by
1360 ;; `desktop-save', they may be modified by handlers wanting to set
1361 ;; point or mark themselves.
1362 (when desktop-buffer-point
1363 (goto-char
1364 (condition-case err
1365 ;; Evaluate point. Thus point can be something like
1366 ;; '(search-forward ...
1367 (eval desktop-buffer-point)
1368 (error (message "%s" (error-message-string err)) 1))))
1369 (when desktop-buffer-mark
1370 (if (consp desktop-buffer-mark)
1371 (progn
1372 (set-mark (car desktop-buffer-mark))
1373 (setq mark-active (car (cdr desktop-buffer-mark))))
1374 (set-mark desktop-buffer-mark)))
1375 ;; Never override file system if the file really is read-only marked.
1376 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1377 (while desktop-buffer-locals
1378 (let ((this (car desktop-buffer-locals)))
1379 (if (consp this)
1380 ;; an entry of this form `(symbol . value)'
1381 (progn
1382 (make-local-variable (car this))
1383 (set (car this) (cdr this)))
1384 ;; an entry of the form `symbol'
1385 (make-local-variable this)
1386 (makunbound this)))
1387 (setq desktop-buffer-locals (cdr desktop-buffer-locals))))))))
1389 ;; ----------------------------------------------------------------------------
1390 ;; Backward compatibility -- update parameters to 205 standards.
1391 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1392 mim pt mk ro tl fc cfs cr buffer-misc)
1393 (desktop-create-buffer 205 buffer-filename buffer-name
1394 buffer-majormode (cdr mim) pt mk ro
1395 buffer-misc
1396 (list (cons 'truncate-lines tl)
1397 (cons 'fill-column fc)
1398 (cons 'case-fold-search cfs)
1399 (cons 'case-replace cr)
1400 (cons 'overwrite-mode (car mim)))))
1402 (defun desktop-append-buffer-args (&rest args)
1403 "Append ARGS at end of `desktop-buffer-args-list'.
1404 ARGS must be an argument list for `desktop-create-buffer'."
1405 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1406 (unless desktop-lazy-timer
1407 (setq desktop-lazy-timer
1408 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1410 (defun desktop-lazy-create-buffer ()
1411 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1412 (when desktop-buffer-args-list
1413 (let* ((remaining (length desktop-buffer-args-list))
1414 (args (pop desktop-buffer-args-list))
1415 (buffer-name (nth 2 args))
1416 (msg (format "Desktop lazily opening %s (%s remaining)..."
1417 buffer-name remaining)))
1418 (when desktop-lazy-verbose
1419 (message "%s" msg))
1420 (let ((desktop-first-buffer nil)
1421 (desktop-buffer-ok-count 0)
1422 (desktop-buffer-fail-count 0))
1423 (apply 'desktop-create-buffer args)
1424 (run-hooks 'desktop-delay-hook)
1425 (setq desktop-delay-hook nil)
1426 (bury-buffer (get-buffer buffer-name))
1427 (when desktop-lazy-verbose
1428 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1430 (defun desktop-idle-create-buffers ()
1431 "Create buffers until the user does something, then stop.
1432 If there are no buffers left to create, kill the timer."
1433 (let ((repeat 1))
1434 (while (and repeat desktop-buffer-args-list)
1435 (save-window-excursion
1436 (desktop-lazy-create-buffer))
1437 (setq repeat (sit-for 0.2))
1438 (unless desktop-buffer-args-list
1439 (cancel-timer desktop-lazy-timer)
1440 (setq desktop-lazy-timer nil)
1441 (message "Lazy desktop load complete")
1442 (sit-for 3)
1443 (message "")))))
1445 (defun desktop-lazy-complete ()
1446 "Run the desktop load to completion."
1447 (interactive)
1448 (let ((desktop-lazy-verbose t))
1449 (while desktop-buffer-args-list
1450 (save-window-excursion
1451 (desktop-lazy-create-buffer)))
1452 (message "Lazy desktop load complete")))
1454 (defun desktop-lazy-abort ()
1455 "Abort lazy loading of the desktop."
1456 (interactive)
1457 (when desktop-lazy-timer
1458 (cancel-timer desktop-lazy-timer)
1459 (setq desktop-lazy-timer nil))
1460 (when desktop-buffer-args-list
1461 (setq desktop-buffer-args-list nil)
1462 (when (called-interactively-p 'interactive)
1463 (message "Lazy desktop load aborted"))))
1465 ;; ----------------------------------------------------------------------------
1466 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1467 ;; command line, we do the rest of what it takes to use desktop, but do it
1468 ;; after finishing loading the init file.
1469 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1470 ;; functions are processed after `after-init-hook'.
1471 (add-hook
1472 'after-init-hook
1473 (lambda ()
1474 (let ((key "--no-desktop"))
1475 (when (member key command-line-args)
1476 (setq command-line-args (delete key command-line-args))
1477 (setq desktop-save-mode nil)))
1478 (when desktop-save-mode
1479 (desktop-read)
1480 (desktop-auto-save-set-timer)
1481 (setq inhibit-startup-screen t))))
1483 ;; So we can restore vc-dir buffers.
1484 (autoload 'vc-dir-mode "vc-dir" nil t)
1486 (provide 'desktop)
1488 ;;; desktop.el ends here