src/emacs.c (Fkill_emacs): Expand Vauto_save_list_file_name before unlinking it.
[emacs.git] / lisp / desktop.el
blob2f4c2a8589c2d25ac47491ce35808dd53ad6bd5e
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-restore-frames 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-restore-in-current-display nil
381 "When non-nil, frames are restored in the current display.
382 Otherwise they are restored, if possible, in their original displays."
383 :type 'boolean
384 :group 'desktop
385 :version "24.4")
387 (defcustom desktop-file-name-format 'absolute
388 "Format in which desktop file names should be saved.
389 Possible values are:
390 absolute -- Absolute file name.
391 tilde -- Relative to ~.
392 local -- Relative to directory of desktop file."
393 :type '(choice (const absolute) (const tilde) (const local))
394 :group 'desktop
395 :version "22.1")
397 (defcustom desktop-restore-eager t
398 "Number of buffers to restore immediately.
399 Remaining buffers are restored lazily (when Emacs is idle).
400 If value is t, all buffers are restored immediately."
401 :type '(choice (const t) integer)
402 :group 'desktop
403 :version "22.1")
405 (defcustom desktop-lazy-verbose t
406 "Verbose reporting of lazily created buffers."
407 :type 'boolean
408 :group 'desktop
409 :version "22.1")
411 (defcustom desktop-lazy-idle-delay 5
412 "Idle delay before starting to create buffers.
413 See `desktop-restore-eager'."
414 :type 'integer
415 :group 'desktop
416 :version "22.1")
418 ;;;###autoload
419 (defvar desktop-save-buffer nil
420 "When non-nil, save buffer status in desktop file.
421 This variable becomes buffer local when set.
423 If the value is a function, it is called by `desktop-save' with argument
424 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
425 file along with the state of the buffer for which it was called.
427 When file names are returned, they should be formatted using the call
428 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
430 Later, when `desktop-read' evaluates the desktop file, auxiliary information
431 is passed as the argument DESKTOP-BUFFER-MISC to functions in
432 `desktop-buffer-mode-handlers'.")
433 (make-variable-buffer-local 'desktop-save-buffer)
434 (make-obsolete-variable 'desktop-buffer-modes-to-save
435 'desktop-save-buffer "22.1")
436 (make-obsolete-variable 'desktop-buffer-misc-functions
437 'desktop-save-buffer "22.1")
439 ;;;###autoload
440 (defvar desktop-buffer-mode-handlers nil
441 "Alist of major mode specific functions to restore a desktop buffer.
442 Functions listed are called by `desktop-create-buffer' when `desktop-read'
443 evaluates the desktop file. List elements must have the form
445 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
447 Buffers with a major mode not specified here, are restored by the default
448 handler `desktop-restore-file-buffer'.
450 Handlers are called with argument list
452 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
454 Furthermore, they may use the following variables:
456 desktop-file-version
457 desktop-buffer-major-mode
458 desktop-buffer-minor-modes
459 desktop-buffer-point
460 desktop-buffer-mark
461 desktop-buffer-read-only
462 desktop-buffer-locals
464 If a handler returns a buffer, then the saved mode settings
465 and variable values for that buffer are copied into it.
467 Modules that define a major mode that needs a special handler should contain
468 code like
470 (defun foo-restore-desktop-buffer
472 (add-to-list 'desktop-buffer-mode-handlers
473 '(foo-mode . foo-restore-desktop-buffer))
475 Furthermore the major mode function must be autoloaded.")
477 ;;;###autoload
478 (put 'desktop-buffer-mode-handlers 'risky-local-variable t)
479 (make-obsolete-variable 'desktop-buffer-handlers
480 'desktop-buffer-mode-handlers "22.1")
482 (defcustom desktop-minor-mode-table
483 '((auto-fill-function auto-fill-mode)
484 (vc-mode nil)
485 (vc-dired-mode nil)
486 (erc-track-minor-mode nil)
487 (savehist-mode nil))
488 "Table mapping minor mode variables to minor mode functions.
489 Each entry has the form (NAME RESTORE-FUNCTION).
490 NAME is the name of the buffer-local variable indicating that the minor
491 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
492 RESTORE-FUNCTION nil means don't try to restore the minor mode.
493 Only minor modes for which the name of the buffer-local variable
494 and the name of the minor mode function are different have to be added to
495 this table. See also `desktop-minor-mode-handlers'."
496 :type 'sexp
497 :group 'desktop)
499 ;;;###autoload
500 (defvar desktop-minor-mode-handlers nil
501 "Alist of functions to restore non-standard minor modes.
502 Functions are called by `desktop-create-buffer' to restore minor modes.
503 List elements must have the form
505 (MINOR-MODE . RESTORE-FUNCTION).
507 Minor modes not specified here, are restored by the standard minor mode
508 function.
510 Handlers are called with argument list
512 (DESKTOP-BUFFER-LOCALS)
514 Furthermore, they may use the following variables:
516 desktop-file-version
517 desktop-buffer-file-name
518 desktop-buffer-name
519 desktop-buffer-major-mode
520 desktop-buffer-minor-modes
521 desktop-buffer-point
522 desktop-buffer-mark
523 desktop-buffer-read-only
524 desktop-buffer-misc
526 When a handler is called, the buffer has been created and the major mode has
527 been set, but local variables listed in desktop-buffer-locals has not yet been
528 created and set.
530 Modules that define a minor mode that needs a special handler should contain
531 code like
533 (defun foo-desktop-restore
535 (add-to-list 'desktop-minor-mode-handlers
536 '(foo-mode . foo-desktop-restore))
538 Furthermore the minor mode function must be autoloaded.
540 See also `desktop-minor-mode-table'.")
542 ;;;###autoload
543 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
545 ;; ----------------------------------------------------------------------------
546 (defvar desktop-dirname nil
547 "The directory in which the desktop file should be saved.")
549 (defun desktop-full-file-name (&optional dirname)
550 "Return the full name of the desktop file in DIRNAME.
551 DIRNAME omitted or nil means use `desktop-dirname'."
552 (expand-file-name desktop-base-file-name (or dirname desktop-dirname)))
554 (defun desktop-full-lock-name (&optional dirname)
555 "Return the full name of the desktop lock file in DIRNAME.
556 DIRNAME omitted or nil means use `desktop-dirname'."
557 (expand-file-name desktop-base-lock-name (or dirname desktop-dirname)))
559 (defconst desktop-header
560 ";; --------------------------------------------------------------------------
561 ;; Desktop File for Emacs
562 ;; --------------------------------------------------------------------------
563 " "*Header to place in Desktop file.")
565 (defvar desktop-delay-hook nil
566 "Hooks run after all buffers are loaded; intended for internal use.")
568 (defvar desktop-file-checksum nil
569 "Checksum of the last auto-saved contents of the desktop file.
570 Used to avoid writing contents unchanged between auto-saves.")
572 (defvar desktop--saved-states nil
573 "Internal use only.")
575 ;; ----------------------------------------------------------------------------
576 ;; Desktop file conflict detection
577 (defvar desktop-file-modtime nil
578 "When the desktop file was last modified to the knowledge of this Emacs.
579 Used to detect desktop file conflicts.")
581 (defun desktop-owner (&optional dirname)
582 "Return the PID of the Emacs process that owns the desktop file in DIRNAME.
583 Return nil if no desktop file found or no Emacs process is using it.
584 DIRNAME omitted or nil means use `desktop-dirname'."
585 (let (owner)
586 (and (file-exists-p (desktop-full-lock-name dirname))
587 (condition-case nil
588 (with-temp-buffer
589 (insert-file-contents-literally (desktop-full-lock-name dirname))
590 (goto-char (point-min))
591 (setq owner (read (current-buffer)))
592 (integerp owner))
593 (error nil))
594 owner)))
596 (defun desktop-claim-lock (&optional dirname)
597 "Record this Emacs process as the owner of the desktop file in DIRNAME.
598 DIRNAME omitted or nil means use `desktop-dirname'."
599 (write-region (number-to-string (emacs-pid)) nil
600 (desktop-full-lock-name dirname)))
602 (defun desktop-release-lock (&optional dirname)
603 "Remove the lock file for the desktop in DIRNAME.
604 DIRNAME omitted or nil means use `desktop-dirname'."
605 (let ((file (desktop-full-lock-name dirname)))
606 (when (file-exists-p file) (delete-file file))))
608 ;; ----------------------------------------------------------------------------
609 (defun desktop-truncate (list n)
610 "Truncate LIST to at most N elements destructively."
611 (let ((here (nthcdr (1- n) list)))
612 (when (consp here)
613 (setcdr here nil))))
615 ;; ----------------------------------------------------------------------------
616 ;;;###autoload
617 (defun desktop-clear ()
618 "Empty the Desktop.
619 This kills all buffers except for internal ones and those with names matched by
620 a regular expression in the list `desktop-clear-preserve-buffers'.
621 Furthermore, it clears the variables listed in `desktop-globals-to-clear'."
622 (interactive)
623 (desktop-lazy-abort)
624 (dolist (var desktop-globals-to-clear)
625 (if (symbolp var)
626 (eval `(setq-default ,var nil))
627 (eval `(setq-default ,(car var) ,(cdr var)))))
628 (let ((buffers (buffer-list))
629 (preserve-regexp (concat "^\\("
630 (mapconcat (lambda (regexp)
631 (concat "\\(" regexp "\\)"))
632 desktop-clear-preserve-buffers
633 "\\|")
634 "\\)$")))
635 (while buffers
636 (let ((bufname (buffer-name (car buffers))))
638 (null bufname)
639 (string-match preserve-regexp bufname)
640 ;; Don't kill buffers made for internal purposes.
641 (and (not (equal bufname "")) (eq (aref bufname 0) ?\s))
642 (kill-buffer (car buffers))))
643 (setq buffers (cdr buffers))))
644 (delete-other-windows))
646 ;; ----------------------------------------------------------------------------
647 (unless noninteractive
648 (add-hook 'kill-emacs-hook 'desktop-kill))
650 (defun desktop-kill ()
651 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
652 If the desktop should be saved and `desktop-dirname'
653 is nil, ask the user where to save the desktop."
654 (when (and desktop-save-mode
655 (let ((exists (file-exists-p (desktop-full-file-name))))
656 (or (eq desktop-save t)
657 (and exists (eq desktop-save 'if-exists))
658 ;; If it exists, but we aren't using it, we are going
659 ;; to ask for a new directory below.
660 (and exists desktop-dirname (eq desktop-save 'ask-if-new))
661 (and
662 (or (memq desktop-save '(ask ask-if-new))
663 (and exists (eq desktop-save 'ask-if-exists)))
664 (y-or-n-p "Save desktop? ")))))
665 (unless desktop-dirname
666 (setq desktop-dirname
667 (file-name-as-directory
668 (expand-file-name
669 (read-directory-name "Directory for desktop file: " nil nil t)))))
670 (condition-case err
671 (desktop-save desktop-dirname t)
672 (file-error
673 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
674 (signal (car err) (cdr err))))))
675 ;; If we own it, we don't anymore.
676 (when (eq (emacs-pid) (desktop-owner)) (desktop-release-lock)))
678 ;; ----------------------------------------------------------------------------
679 (defun desktop-list* (&rest args)
680 (if (null (cdr args))
681 (car args)
682 (setq args (nreverse args))
683 (let ((value (cons (nth 1 args) (car args))))
684 (setq args (cdr (cdr args)))
685 (while args
686 (setq value (cons (car args) value))
687 (setq args (cdr args)))
688 value)))
690 ;; ----------------------------------------------------------------------------
691 (defun desktop-buffer-info (buffer)
692 (set-buffer buffer)
693 (list
694 ;; base name of the buffer; replaces the buffer name if managed by uniquify
695 (and (fboundp 'uniquify-buffer-base-name) (uniquify-buffer-base-name))
696 ;; basic information
697 (desktop-file-name (buffer-file-name) desktop-dirname)
698 (buffer-name)
699 major-mode
700 ;; minor modes
701 (let (ret)
702 (mapc
703 #'(lambda (minor-mode)
704 (and (boundp minor-mode)
705 (symbol-value minor-mode)
706 (let* ((special (assq minor-mode desktop-minor-mode-table))
707 (value (cond (special (cadr special))
708 ((functionp minor-mode) minor-mode))))
709 (when value (add-to-list 'ret value)))))
710 (mapcar #'car minor-mode-alist))
711 ret)
712 ;; point and mark, and read-only status
713 (point)
714 (list (mark t) mark-active)
715 buffer-read-only
716 ;; auxiliary information
717 (when (functionp desktop-save-buffer)
718 (funcall desktop-save-buffer desktop-dirname))
719 ;; local variables
720 (let ((locals desktop-locals-to-save)
721 (loclist (buffer-local-variables))
722 (ll))
723 (while locals
724 (let ((here (assq (car locals) loclist)))
725 (if here
726 (setq ll (cons here ll))
727 (when (member (car locals) loclist)
728 (setq ll (cons (car locals) ll)))))
729 (setq locals (cdr locals)))
730 ll)))
732 ;; ----------------------------------------------------------------------------
733 (defun desktop--v2s (value)
734 "Convert VALUE to a pair (QUOTE . SEXP); (eval SEXP) gives VALUE.
735 SEXP is an sexp that when evaluated yields VALUE.
736 QUOTE may be `may' (value may be quoted),
737 `must' (value must be quoted), or nil (value must not be quoted)."
738 (cond
739 ((or (numberp value) (null value) (eq t value) (keywordp value))
740 (cons 'may value))
741 ((stringp value)
742 (let ((copy (copy-sequence value)))
743 (set-text-properties 0 (length copy) nil copy)
744 ;; Get rid of text properties because we cannot read them.
745 (cons 'may copy)))
746 ((symbolp value)
747 (cons 'must value))
748 ((vectorp value)
749 (let* ((pass1 (mapcar #'desktop--v2s value))
750 (special (assq nil pass1)))
751 (if special
752 (cons nil `(vector
753 ,@(mapcar (lambda (el)
754 (if (eq (car el) 'must)
755 `',(cdr el) (cdr el)))
756 pass1)))
757 (cons 'may `[,@(mapcar #'cdr pass1)]))))
758 ((consp value)
759 (let ((p value)
760 newlist
761 use-list*
762 anynil)
763 (while (consp p)
764 (let ((q.sexp (desktop--v2s (car p))))
765 (push q.sexp newlist))
766 (setq p (cdr p)))
767 (when p
768 (let ((last (desktop--v2s p)))
769 (setq use-list* t)
770 (push last newlist)))
771 (if (assq nil newlist)
772 (cons nil
773 `(,(if use-list* 'desktop-list* 'list)
774 ,@(mapcar (lambda (el)
775 (if (eq (car el) 'must)
776 `',(cdr el) (cdr el)))
777 (nreverse newlist))))
778 (cons 'must
779 `(,@(mapcar #'cdr
780 (nreverse (if use-list* (cdr newlist) newlist)))
781 ,@(if use-list* (cdar newlist)))))))
782 ((subrp value)
783 (cons nil `(symbol-function
784 ',(intern-soft (substring (prin1-to-string value) 7 -1)))))
785 ((markerp value)
786 (let ((pos (marker-position value))
787 (buf (buffer-name (marker-buffer value))))
788 (cons nil
789 `(let ((mk (make-marker)))
790 (add-hook 'desktop-delay-hook
791 `(lambda ()
792 (set-marker ,mk ,,pos (get-buffer ,,buf))))
793 mk))))
794 (t ; Save as text.
795 (cons 'may "Unprintable entity"))))
797 ;; ----------------------------------------------------------------------------
798 (defun desktop-value-to-string (value)
799 "Convert VALUE to a string that when read evaluates to the same value.
800 Not all types of values are supported."
801 (let* ((print-escape-newlines t)
802 (float-output-format nil)
803 (quote.sexp (desktop--v2s value))
804 (quote (car quote.sexp))
805 (txt
806 (let ((print-quoted t))
807 (prin1-to-string (cdr quote.sexp)))))
808 (if (eq quote 'must)
809 (concat "'" txt)
810 txt)))
812 ;; ----------------------------------------------------------------------------
813 (defun desktop-outvar (varspec)
814 "Output a setq statement for variable VAR to the desktop file.
815 The argument VARSPEC may be the variable name VAR (a symbol),
816 or a cons cell of the form (VAR . MAX-SIZE),
817 which means to truncate VAR's value to at most MAX-SIZE elements
818 \(if the value is a list) before saving the value."
819 (let (var size)
820 (if (consp varspec)
821 (setq var (car varspec) size (cdr varspec))
822 (setq var varspec))
823 (when (boundp var)
824 (when (and (integerp size)
825 (> size 0)
826 (listp (eval var)))
827 (desktop-truncate (eval var) size))
828 (insert "(setq "
829 (symbol-name var)
831 (desktop-value-to-string (symbol-value var))
832 ")\n"))))
834 ;; ----------------------------------------------------------------------------
835 (defun desktop-save-buffer-p (filename bufname mode &rest _dummy)
836 "Return t if buffer should have its state saved in the desktop file.
837 FILENAME is the visited file name, BUFNAME is the buffer name, and
838 MODE is the major mode.
839 \n\(fn FILENAME BUFNAME MODE)"
840 (let ((case-fold-search nil)
841 dired-skip)
842 (and (not (and (stringp desktop-buffers-not-to-save)
843 (not filename)
844 (string-match desktop-buffers-not-to-save bufname)))
845 (not (memq mode desktop-modes-not-to-save))
846 ;; FIXME this is broken if desktop-files-not-to-save is nil.
847 (or (and filename
848 (stringp desktop-files-not-to-save)
849 (not (string-match desktop-files-not-to-save filename)))
850 (and (memq mode '(dired-mode vc-dir-mode))
851 (with-current-buffer bufname
852 (not (setq dired-skip
853 (string-match desktop-files-not-to-save
854 default-directory)))))
855 (and (null filename)
856 (null dired-skip) ; bug#5755
857 (with-current-buffer bufname desktop-save-buffer))))))
859 ;; ----------------------------------------------------------------------------
860 (defun desktop-file-name (filename dirname)
861 "Convert FILENAME to format specified in `desktop-file-name-format'.
862 DIRNAME must be the directory in which the desktop file will be saved."
863 (cond
864 ((not filename) nil)
865 ((eq desktop-file-name-format 'tilde)
866 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
867 (cond
868 ((file-name-absolute-p relative-name) relative-name)
869 ((string= "./" relative-name) "~/")
870 ((string= "." relative-name) "~")
871 (t (concat "~/" relative-name)))))
872 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
873 (t (expand-file-name filename))))
876 ;; ----------------------------------------------------------------------------
877 (defconst desktop--excluded-frame-parameters
878 '(buffer-list
879 buffer-predicate
880 buried-buffer-list
881 explicit-name
882 font
883 font-backend
884 minibuffer
885 name
886 outer-window-id
887 parent-id
888 window-id
889 window-system)
890 "Frame parameters not saved or restored.")
892 (defun desktop--filter-frame-parms (frame)
893 "Return frame parameters of FRAME.
894 Parameters in `desktop--excluded-frame-parameters' are excluded.
895 Internal use only."
896 (let (params)
897 (dolist (param (frame-parameters frame))
898 (unless (memq (car param) desktop--excluded-frame-parameters)
899 (push param params)))
900 params))
902 (defun desktop--save-frames ()
903 "Save window/frame state, as a global variable.
904 Intended to be called from `desktop-save'.
905 Internal use only."
906 (setq desktop--saved-states
907 (and desktop-restore-frames
908 (mapcar (lambda (frame)
909 (cons (desktop--filter-frame-parms frame)
910 (window-state-get (frame-root-window frame) t)))
911 (cons (selected-frame)
912 (delq (selected-frame) (frame-list))))))
913 (desktop-outvar 'desktop--saved-states))
915 ;;;###autoload
916 (defun desktop-save (dirname &optional release auto-save)
917 "Save the desktop in a desktop file.
918 Parameter DIRNAME specifies where to save the desktop file.
919 Optional parameter RELEASE says whether we're done with this desktop.
920 If AUTO-SAVE is non-nil, compare the saved contents to the one last saved,
921 and don't save the buffer if they are the same."
922 (interactive "DDirectory to save desktop file in: ")
923 (setq desktop-dirname (file-name-as-directory (expand-file-name dirname)))
924 (save-excursion
925 (let ((eager desktop-restore-eager)
926 (new-modtime (nth 5 (file-attributes (desktop-full-file-name)))))
927 (when
928 (or (not new-modtime) ; nothing to overwrite
929 (equal desktop-file-modtime new-modtime)
930 (yes-or-no-p (if desktop-file-modtime
931 (if (> (float-time new-modtime) (float-time desktop-file-modtime))
932 "Desktop file is more recent than the one loaded. Save anyway? "
933 "Desktop file isn't the one loaded. Overwrite it? ")
934 "Current desktop was not loaded from a file. Overwrite this desktop file? "))
935 (unless release (error "Desktop file conflict")))
937 ;; If we're done with it, release the lock.
938 ;; Otherwise, claim it if it's unclaimed or if we created it.
939 (if release
940 (desktop-release-lock)
941 (unless (and new-modtime (desktop-owner)) (desktop-claim-lock)))
943 (with-temp-buffer
944 (insert
945 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
946 desktop-header
947 ";; Created " (current-time-string) "\n"
948 ";; Desktop file format version " desktop-file-version "\n"
949 ";; Emacs version " emacs-version "\n")
950 (save-excursion (run-hooks 'desktop-save-hook))
951 (goto-char (point-max))
952 (insert "\n;; Global section:\n")
953 ;; Called here because we save the window/frame state as a global
954 ;; variable for compatibility with previous Emacsen.
955 (desktop--save-frames)
956 (mapc (function desktop-outvar) desktop-globals-to-save)
957 (when (memq 'kill-ring desktop-globals-to-save)
958 (insert
959 "(setq kill-ring-yank-pointer (nthcdr "
960 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
961 " kill-ring))\n"))
963 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
964 (dolist (l (mapcar 'desktop-buffer-info (buffer-list)))
965 (let ((base (pop l)))
966 (when (apply 'desktop-save-buffer-p l)
967 (insert "("
968 (if (or (not (integerp eager))
969 (if (zerop eager)
971 (setq eager (1- eager))))
972 "desktop-create-buffer"
973 "desktop-append-buffer-args")
975 desktop-file-version)
976 ;; If there's a non-empty base name, we save it instead of the buffer name
977 (when (and base (not (string= base "")))
978 (setcar (nthcdr 1 l) base))
979 (dolist (e l)
980 (insert "\n " (desktop-value-to-string e)))
981 (insert ")\n\n"))))
983 (setq default-directory desktop-dirname)
984 ;; If auto-saving, avoid writing if nothing has changed since the last write.
985 ;; Don't check 300 characters of the header that contains the timestamp.
986 (let ((checksum (and auto-save (md5 (current-buffer)
987 (+ (point-min) 300) (point-max)
988 'emacs-mule))))
989 (unless (and auto-save (equal checksum desktop-file-checksum))
990 (let ((coding-system-for-write 'emacs-mule))
991 (write-region (point-min) (point-max) (desktop-full-file-name) nil 'nomessage))
992 (setq desktop-file-checksum checksum)
993 ;; We remember when it was modified (which is presumably just now).
994 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name)))))))))))
996 ;; ----------------------------------------------------------------------------
997 ;;;###autoload
998 (defun desktop-remove ()
999 "Delete desktop file in `desktop-dirname'.
1000 This function also sets `desktop-dirname' to nil."
1001 (interactive)
1002 (when desktop-dirname
1003 (let ((filename (desktop-full-file-name)))
1004 (setq desktop-dirname nil)
1005 (when (file-exists-p filename)
1006 (delete-file filename)))))
1008 (defvar desktop-buffer-args-list nil
1009 "List of args for `desktop-create-buffer'.")
1011 (defvar desktop-lazy-timer nil)
1013 ;; ----------------------------------------------------------------------------
1014 (defun desktop--restore-in-this-display-p ()
1015 (or desktop-restore-in-current-display
1016 (and (eq system-type 'windows-nt) (not (display-graphic-p)))))
1018 (defun desktop--find-frame-in-display (frames display)
1019 (let (result)
1020 (while (and frames (not result))
1021 (if (equal display (frame-parameter (car frames) 'display))
1022 (setq result (car frames))
1023 (setq frames (cdr frames))))
1024 result))
1026 (defun desktop--make-full-frame (full display config)
1027 (let ((width (and (eq full 'fullheight) (cdr (assq 'width config))))
1028 (height (and (eq full 'fullwidth) (cdr (assq 'height config))))
1029 (params '((visibility)))
1030 frame)
1031 (when width
1032 (setq params (append `((user-size . t) (width . ,width)) params)
1033 config (assq-delete-all 'height config)))
1034 (when height
1035 (setq params (append `((user-size . t) (height . ,height)) params)
1036 config (assq-delete-all 'width config)))
1037 (setq frame (make-frame-on-display display params))
1038 (modify-frame-parameters frame config)
1039 frame))
1041 (defun desktop--restore-frames ()
1042 "Restore window/frame configuration.
1043 Internal use only."
1044 (when (and desktop-restore-frames desktop--saved-states)
1045 (let ((frames (frame-list))
1046 (current (frame-parameter nil 'display))
1047 (selected nil))
1048 (dolist (state desktop--saved-states)
1049 (condition-case err
1050 (let* ((config (car state))
1051 (display (if (desktop--restore-in-this-display-p)
1052 (setcdr (assq 'display config) current)
1053 (cdr (assq 'display config))))
1054 (full (cdr (assq 'fullscreen config)))
1055 (frame (and (not full)
1056 (desktop--find-frame-in-display frames display))))
1057 (cond (full
1058 ;; treat fullscreen/maximized frames specially
1059 (setq frame (desktop--make-full-frame full display config)))
1060 (frame
1061 ;; found a frame in the right display -- reuse
1062 (setq frames (delq frame frames))
1063 (modify-frame-parameters frame config))
1065 ;; no frames in the display -- make a new one
1066 (setq frame (make-frame-on-display display config))))
1067 ;; restore windows
1068 (window-state-put (cdr state) (frame-root-window frame) 'safe)
1069 (unless selected (setq selected frame)))
1070 (error
1071 (message "Error restoring frame: %S" (error-message-string err)))))
1072 (when selected
1073 ;; make sure the original selected frame is visible and selected
1074 (unless (or (frame-parameter selected 'visibility) (daemonp))
1075 (modify-frame-parameters selected '((visibility . t))))
1076 (select-frame-set-input-focus selected)
1077 ;; delete any remaining frames
1078 (mapc #'delete-frame frames)))))
1080 ;;;###autoload
1081 (defun desktop-read (&optional dirname)
1082 "Read and process the desktop file in directory DIRNAME.
1083 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
1084 directories listed in `desktop-path'. If a desktop file is found, it
1085 is processed and `desktop-after-read-hook' is run. If no desktop file
1086 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
1087 This function is a no-op when Emacs is running in batch mode.
1088 It returns t if a desktop file was loaded, nil otherwise."
1089 (interactive)
1090 (unless noninteractive
1091 (setq desktop-dirname
1092 (file-name-as-directory
1093 (expand-file-name
1095 ;; If DIRNAME is specified, use it.
1096 (and (< 0 (length dirname)) dirname)
1097 ;; Otherwise search desktop file in desktop-path.
1098 (let ((dirs desktop-path))
1099 (while (and dirs
1100 (not (file-exists-p
1101 (desktop-full-file-name (car dirs)))))
1102 (setq dirs (cdr dirs)))
1103 (and dirs (car dirs)))
1104 ;; If not found and `desktop-path' is non-nil, use its first element.
1105 (and desktop-path (car desktop-path))
1106 ;; Default: .emacs.d.
1107 user-emacs-directory))))
1108 (if (file-exists-p (desktop-full-file-name))
1109 ;; Desktop file found, but is it already in use?
1110 (let ((desktop-first-buffer nil)
1111 (desktop-buffer-ok-count 0)
1112 (desktop-buffer-fail-count 0)
1113 (owner (desktop-owner))
1114 ;; Avoid desktop saving during evaluation of desktop buffer.
1115 (desktop-save nil))
1116 (if (and owner
1117 (memq desktop-load-locked-desktop '(nil ask))
1118 (or (null desktop-load-locked-desktop)
1119 (daemonp)
1120 (not (y-or-n-p (format "Warning: desktop file appears to be in use by PID %s.\n\
1121 Using it may cause conflicts. Use it anyway? " owner)))))
1122 (let ((default-directory desktop-dirname))
1123 (setq desktop-dirname nil)
1124 (run-hooks 'desktop-not-loaded-hook)
1125 (unless desktop-dirname
1126 (message "Desktop file in use; not loaded.")))
1127 (desktop-lazy-abort)
1128 ;; Evaluate desktop buffer and remember when it was modified.
1129 (load (desktop-full-file-name) t t t)
1130 (setq desktop-file-modtime (nth 5 (file-attributes (desktop-full-file-name))))
1131 ;; If it wasn't already, mark it as in-use, to bother other
1132 ;; desktop instances.
1133 (unless owner
1134 (condition-case nil
1135 (desktop-claim-lock)
1136 (file-error (message "Couldn't record use of desktop file")
1137 (sit-for 1))))
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-frames)
1149 (run-hooks 'desktop-after-read-hook)
1150 (message "Desktop: %d buffer%s restored%s%s."
1151 desktop-buffer-ok-count
1152 (if (= 1 desktop-buffer-ok-count) "" "s")
1153 (if (< 0 desktop-buffer-fail-count)
1154 (format ", %d failed to restore" desktop-buffer-fail-count)
1156 (if desktop-buffer-args-list
1157 (format ", %d to restore lazily"
1158 (length desktop-buffer-args-list))
1159 ""))
1160 ;; Bury the *Messages* buffer to not reshow it when burying
1161 ;; the buffer we switched to above.
1162 (when (buffer-live-p (get-buffer "*Messages*"))
1163 (bury-buffer "*Messages*"))
1164 ;; Clear all windows' previous and next buffers, these have
1165 ;; been corrupted by the `switch-to-buffer' calls in
1166 ;; `desktop-restore-file-buffer' (bug#11556). This is a
1167 ;; brute force fix and should be replaced by a more subtle
1168 ;; strategy eventually.
1169 (walk-window-tree (lambda (window)
1170 (set-window-prev-buffers window nil)
1171 (set-window-next-buffers window nil)))
1173 ;; No desktop file found.
1174 (desktop-clear)
1175 (let ((default-directory desktop-dirname))
1176 (run-hooks 'desktop-no-desktop-file-hook))
1177 (message "No desktop file.")
1178 nil)))
1180 ;; ----------------------------------------------------------------------------
1181 ;; Maintained for backward compatibility
1182 ;;;###autoload
1183 (defun desktop-load-default ()
1184 "Load the `default' start-up library manually.
1185 Also inhibit further loading of it."
1186 (declare (obsolete desktop-save-mode "22.1"))
1187 (unless inhibit-default-init ; safety check
1188 (load "default" t t)
1189 (setq inhibit-default-init t)))
1191 ;; ----------------------------------------------------------------------------
1192 ;;;###autoload
1193 (defun desktop-change-dir (dirname)
1194 "Change to desktop saved in DIRNAME.
1195 Kill the desktop as specified by variables `desktop-save-mode' and
1196 `desktop-save', then clear the desktop and load the desktop file in
1197 directory DIRNAME."
1198 (interactive "DChange to directory: ")
1199 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
1200 (desktop-kill)
1201 (desktop-clear)
1202 (desktop-read dirname))
1204 ;; ----------------------------------------------------------------------------
1205 ;;;###autoload
1206 (defun desktop-save-in-desktop-dir ()
1207 "Save the desktop in directory `desktop-dirname'."
1208 (interactive)
1209 (if desktop-dirname
1210 (desktop-save desktop-dirname)
1211 (call-interactively 'desktop-save))
1212 (message "Desktop saved in %s" (abbreviate-file-name desktop-dirname)))
1214 ;; ----------------------------------------------------------------------------
1215 ;; Auto-Saving.
1216 (defvar desktop-auto-save-timer nil)
1218 (defun desktop-auto-save ()
1219 "Save the desktop periodically.
1220 Called by the timer created in `desktop-auto-save-set-timer'."
1221 (when (and desktop-save-mode
1222 (integerp desktop-auto-save-timeout)
1223 (> desktop-auto-save-timeout 0)
1224 ;; Avoid desktop saving during lazy loading.
1225 (not desktop-lazy-timer)
1226 ;; Save only to own desktop file.
1227 (eq (emacs-pid) (desktop-owner))
1228 desktop-dirname)
1229 (desktop-save desktop-dirname nil t))
1230 (desktop-auto-save-set-timer))
1232 (defun desktop-auto-save-set-timer ()
1233 "Reset the auto-save timer.
1234 Cancel any previous timer. When `desktop-auto-save-timeout' is a positive
1235 integer, start a new timer to call `desktop-auto-save' in that many seconds."
1236 (when desktop-auto-save-timer
1237 (cancel-timer desktop-auto-save-timer)
1238 (setq desktop-auto-save-timer nil))
1239 (when (and (integerp desktop-auto-save-timeout)
1240 (> desktop-auto-save-timeout 0))
1241 (setq desktop-auto-save-timer
1242 (run-with-timer desktop-auto-save-timeout nil
1243 'desktop-auto-save))))
1245 ;; ----------------------------------------------------------------------------
1246 ;;;###autoload
1247 (defun desktop-revert ()
1248 "Revert to the last loaded desktop."
1249 (interactive)
1250 (unless desktop-dirname
1251 (error "Unknown desktop directory"))
1252 (unless (file-exists-p (desktop-full-file-name))
1253 (error "No desktop file found"))
1254 (desktop-clear)
1255 (desktop-read desktop-dirname))
1257 (defvar desktop-buffer-major-mode)
1258 (defvar desktop-buffer-locals)
1259 (defvar auto-insert) ; from autoinsert.el
1260 ;; ----------------------------------------------------------------------------
1261 (defun desktop-restore-file-buffer (buffer-filename
1262 _buffer-name
1263 _buffer-misc)
1264 "Restore a file buffer."
1265 (when buffer-filename
1266 (if (or (file-exists-p buffer-filename)
1267 (let ((msg (format "Desktop: File \"%s\" no longer exists."
1268 buffer-filename)))
1269 (if desktop-missing-file-warning
1270 (y-or-n-p (concat msg " Re-create buffer? "))
1271 (message "%s" msg)
1272 nil)))
1273 (let* ((auto-insert nil) ; Disable auto insertion
1274 (coding-system-for-read
1275 (or coding-system-for-read
1276 (cdr (assq 'buffer-file-coding-system
1277 desktop-buffer-locals))))
1278 (buf (find-file-noselect buffer-filename)))
1279 (condition-case nil
1280 (switch-to-buffer buf)
1281 (error (pop-to-buffer buf)))
1282 (and (not (eq major-mode desktop-buffer-major-mode))
1283 (functionp desktop-buffer-major-mode)
1284 (funcall desktop-buffer-major-mode))
1285 buf)
1286 nil)))
1288 (defun desktop-load-file (function)
1289 "Load the file where auto loaded FUNCTION is defined."
1290 (when (fboundp function)
1291 (autoload-do-load (symbol-function function) function)))
1293 ;; ----------------------------------------------------------------------------
1294 ;; Create a buffer, load its file, set its mode, ...;
1295 ;; called from Desktop file only.
1297 ;; Just to silence the byte compiler.
1299 (defvar desktop-first-buffer) ; Dynamically bound in `desktop-read'
1301 ;; Bound locally in `desktop-read'.
1302 (defvar desktop-buffer-ok-count)
1303 (defvar desktop-buffer-fail-count)
1305 (defun desktop-create-buffer
1306 (file-version
1307 buffer-filename
1308 buffer-name
1309 buffer-majormode
1310 buffer-minormodes
1311 buffer-point
1312 buffer-mark
1313 buffer-readonly
1314 buffer-misc
1315 &optional
1316 buffer-locals)
1318 (let ((desktop-file-version file-version)
1319 (desktop-buffer-file-name buffer-filename)
1320 (desktop-buffer-name buffer-name)
1321 (desktop-buffer-major-mode buffer-majormode)
1322 (desktop-buffer-minor-modes buffer-minormodes)
1323 (desktop-buffer-point buffer-point)
1324 (desktop-buffer-mark buffer-mark)
1325 (desktop-buffer-read-only buffer-readonly)
1326 (desktop-buffer-misc buffer-misc)
1327 (desktop-buffer-locals buffer-locals))
1328 ;; To make desktop files with relative file names possible, we cannot
1329 ;; allow `default-directory' to change. Therefore we save current buffer.
1330 (save-current-buffer
1331 ;; Give major mode module a chance to add a handler.
1332 (desktop-load-file desktop-buffer-major-mode)
1333 (let ((buffer-list (buffer-list))
1334 (result
1335 (condition-case-unless-debug err
1336 (funcall (or (cdr (assq desktop-buffer-major-mode
1337 desktop-buffer-mode-handlers))
1338 'desktop-restore-file-buffer)
1339 desktop-buffer-file-name
1340 desktop-buffer-name
1341 desktop-buffer-misc)
1342 (error
1343 (message "Desktop: Can't load buffer %s: %s"
1344 desktop-buffer-name
1345 (error-message-string err))
1346 (when desktop-missing-file-warning (sit-for 1))
1347 nil))))
1348 (if (bufferp result)
1349 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1350 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1351 (setq result nil))
1352 ;; Restore buffer list order with new buffer at end. Don't change
1353 ;; the order for old desktop files (old desktop module behavior).
1354 (unless (< desktop-file-version 206)
1355 (mapc 'bury-buffer buffer-list)
1356 (when result (bury-buffer result)))
1357 (when result
1358 (unless (or desktop-first-buffer (< desktop-file-version 206))
1359 (setq desktop-first-buffer result))
1360 (set-buffer result)
1361 (unless (equal (buffer-name) desktop-buffer-name)
1362 (rename-buffer desktop-buffer-name t))
1363 ;; minor modes
1364 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1365 (auto-fill-mode 1))
1366 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1367 (auto-fill-mode 0))
1369 (dolist (minor-mode desktop-buffer-minor-modes)
1370 ;; Give minor mode module a chance to add a handler.
1371 (desktop-load-file minor-mode)
1372 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1373 (if handler
1374 (funcall handler desktop-buffer-locals)
1375 (when (functionp minor-mode)
1376 (funcall minor-mode 1)))))))
1377 ;; Even though point and mark are non-nil when written by
1378 ;; `desktop-save', they may be modified by handlers wanting to set
1379 ;; point or mark themselves.
1380 (when desktop-buffer-point
1381 (goto-char
1382 (condition-case err
1383 ;; Evaluate point. Thus point can be something like
1384 ;; '(search-forward ...
1385 (eval desktop-buffer-point)
1386 (error (message "%s" (error-message-string err)) 1))))
1387 (when desktop-buffer-mark
1388 (if (consp desktop-buffer-mark)
1389 (progn
1390 (set-mark (car desktop-buffer-mark))
1391 (setq mark-active (car (cdr desktop-buffer-mark))))
1392 (set-mark desktop-buffer-mark)))
1393 ;; Never override file system if the file really is read-only marked.
1394 (when desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1395 (while desktop-buffer-locals
1396 (let ((this (car desktop-buffer-locals)))
1397 (if (consp this)
1398 ;; an entry of this form `(symbol . value)'
1399 (progn
1400 (make-local-variable (car this))
1401 (set (car this) (cdr this)))
1402 ;; an entry of the form `symbol'
1403 (make-local-variable this)
1404 (makunbound this)))
1405 (setq desktop-buffer-locals (cdr desktop-buffer-locals))))))))
1407 ;; ----------------------------------------------------------------------------
1408 ;; Backward compatibility -- update parameters to 205 standards.
1409 (defun desktop-buffer (buffer-filename buffer-name buffer-majormode
1410 mim pt mk ro tl fc cfs cr buffer-misc)
1411 (desktop-create-buffer 205 buffer-filename buffer-name
1412 buffer-majormode (cdr mim) pt mk ro
1413 buffer-misc
1414 (list (cons 'truncate-lines tl)
1415 (cons 'fill-column fc)
1416 (cons 'case-fold-search cfs)
1417 (cons 'case-replace cr)
1418 (cons 'overwrite-mode (car mim)))))
1420 (defun desktop-append-buffer-args (&rest args)
1421 "Append ARGS at end of `desktop-buffer-args-list'.
1422 ARGS must be an argument list for `desktop-create-buffer'."
1423 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1424 (unless desktop-lazy-timer
1425 (setq desktop-lazy-timer
1426 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1428 (defun desktop-lazy-create-buffer ()
1429 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1430 (when desktop-buffer-args-list
1431 (let* ((remaining (length desktop-buffer-args-list))
1432 (args (pop desktop-buffer-args-list))
1433 (buffer-name (nth 2 args))
1434 (msg (format "Desktop lazily opening %s (%s remaining)..."
1435 buffer-name remaining)))
1436 (when desktop-lazy-verbose
1437 (message "%s" msg))
1438 (let ((desktop-first-buffer nil)
1439 (desktop-buffer-ok-count 0)
1440 (desktop-buffer-fail-count 0))
1441 (apply 'desktop-create-buffer args)
1442 (run-hooks 'desktop-delay-hook)
1443 (setq desktop-delay-hook nil)
1444 (bury-buffer (get-buffer buffer-name))
1445 (when desktop-lazy-verbose
1446 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1448 (defun desktop-idle-create-buffers ()
1449 "Create buffers until the user does something, then stop.
1450 If there are no buffers left to create, kill the timer."
1451 (let ((repeat 1))
1452 (while (and repeat desktop-buffer-args-list)
1453 (save-window-excursion
1454 (desktop-lazy-create-buffer))
1455 (setq repeat (sit-for 0.2))
1456 (unless desktop-buffer-args-list
1457 (cancel-timer desktop-lazy-timer)
1458 (setq desktop-lazy-timer nil)
1459 (message "Lazy desktop load complete")
1460 (sit-for 3)
1461 (message "")))))
1463 (defun desktop-lazy-complete ()
1464 "Run the desktop load to completion."
1465 (interactive)
1466 (let ((desktop-lazy-verbose t))
1467 (while desktop-buffer-args-list
1468 (save-window-excursion
1469 (desktop-lazy-create-buffer)))
1470 (message "Lazy desktop load complete")))
1472 (defun desktop-lazy-abort ()
1473 "Abort lazy loading of the desktop."
1474 (interactive)
1475 (when desktop-lazy-timer
1476 (cancel-timer desktop-lazy-timer)
1477 (setq desktop-lazy-timer nil))
1478 (when desktop-buffer-args-list
1479 (setq desktop-buffer-args-list nil)
1480 (when (called-interactively-p 'interactive)
1481 (message "Lazy desktop load aborted"))))
1483 ;; ----------------------------------------------------------------------------
1484 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1485 ;; command line, we do the rest of what it takes to use desktop, but do it
1486 ;; after finishing loading the init file.
1487 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1488 ;; functions are processed after `after-init-hook'.
1489 (add-hook
1490 'after-init-hook
1491 (lambda ()
1492 (let ((key "--no-desktop"))
1493 (when (member key command-line-args)
1494 (setq command-line-args (delete key command-line-args))
1495 (setq desktop-save-mode nil)))
1496 (when desktop-save-mode
1497 (desktop-read)
1498 (desktop-auto-save-set-timer)
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