*** empty log message ***
[emacs.git] / lisp / desktop.el
blobf56e2204e78b90e88933f2c5da664727b72bd443
1 ;;; desktop.el --- save partial status of Emacs when killed
3 ;; Copyright (C) 1993, 1994, 1995, 1997, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006 Free Software Foundation, Inc.
6 ;; Author: Morten Welinder <terra@diku.dk>
7 ;; Maintainter: Lars Hansen <larsh@soem.dk>
8 ;; Keywords: convenience
9 ;; Favourite-brand-of-beer: None, I hate beer.
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
28 ;;; Commentary:
30 ;; Save the Desktop, i.e.,
31 ;; - some global variables
32 ;; - the list of buffers with associated files. For each buffer also
33 ;; - the major mode
34 ;; - the default directory
35 ;; - the point
36 ;; - the mark & mark-active
37 ;; - buffer-read-only
38 ;; - some local variables
40 ;; To use this, use customize to turn on desktop-save-mode or add the
41 ;; following line somewhere in your .emacs file:
43 ;; (desktop-save-mode 1)
45 ;; For further usage information, look at the section
46 ;; "Saving Emacs Sessions" in the GNU Emacs Manual.
48 ;; When the desktop module is loaded, the function `desktop-kill' is
49 ;; added to the `kill-emacs-hook'. This function is responsible for
50 ;; saving the desktop when Emacs is killed. Furthermore an anonymous
51 ;; function is added to the `after-init-hook'. This function is
52 ;; responsible for loading the desktop when Emacs is started.
54 ;; Special handling.
55 ;; -----------------
56 ;; Variables `desktop-buffer-mode-handlers' and `desktop-minor-mode-handlers'
57 ;; are supplied to handle special major and minor modes respectively.
58 ;; `desktop-buffer-mode-handlers' is an alist of major mode specific functions
59 ;; to restore a desktop buffer. Elements must have the form
61 ;; (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
63 ;; Functions listed are called by `desktop-create-buffer' when `desktop-read'
64 ;; evaluates the desktop file. Buffers with a major mode not specified here,
65 ;; are restored by the default handler `desktop-restore-file-buffer'.
66 ;; `desktop-minor-mode-handlers' is an alist of functions to restore
67 ;; non-standard minor modes. Elements must have the form
69 ;; (MINOR-MODE . RESTORE-FUNCTION).
71 ;; Functions are called by `desktop-create-buffer' to restore minor modes.
72 ;; Minor modes not specified here, are restored by the standard minor mode
73 ;; function. If you write a module that defines a major or minor mode that
74 ;; needs a special handler, then place code like
76 ;; (defun foo-restore-desktop-buffer
77 ;; ...
78 ;; (add-to-list 'desktop-buffer-mode-handlers
79 ;; '(foo-mode . foo-restore-desktop-buffer))
81 ;; or
83 ;; (defun bar-desktop-restore
84 ;; ...
85 ;; (add-to-list 'desktop-minor-mode-handlers
86 ;; '(bar-mode . bar-desktop-restore))
88 ;; in the module itself, and make shure that the mode function is
89 ;; autoloaded. See the docstrings of `desktop-buffer-mode-handlers' and
90 ;; `desktop-minor-mode-handlers' for more info.
92 ;; Minor modes.
93 ;; ------------
94 ;; Conventional minor modes (see node "Minor Mode Conventions" in the elisp
95 ;; manual) are handled in the following way:
96 ;; When `desktop-save' saves the state of a buffer to the desktop file, it
97 ;; saves as `desktop-minor-modes' the list of names of those variables in
98 ;; `minor-mode-alist' that have a non-nil value.
99 ;; When `desktop-create' restores the buffer, each of the symbols in
100 ;; `desktop-minor-modes' is called as function with parameter 1.
101 ;; The variables `desktop-minor-mode-table' and `desktop-minor-mode-handlers'
102 ;; are used to handle non-conventional minor modes. `desktop-save' uses
103 ;; `desktop-minor-mode-table' to map minor mode variables to minor mode
104 ;; functions before writing `desktop-minor-modes'. If a minor mode has a
105 ;; variable name that is different form its function name, an entry
107 ;; (NAME RESTORE-FUNCTION)
109 ;; should be added to `desktop-minor-mode-table'. If a minor mode should not
110 ;; be restored, RESTORE-FUNCTION should be set to nil. `desktop-create' uses
111 ;; `desktop-minor-mode-handlers' to lookup minor modes that needs a restore
112 ;; function different from the usual minor mode function.
113 ;; ---------------------------------------------------------------------------
115 ;; By the way: don't use desktop.el to customize Emacs -- the file .emacs
116 ;; in your home directory is used for that. Saving global default values
117 ;; for buffers is an example of misuse.
119 ;; PLEASE NOTE: The kill ring can be saved as specified by the variable
120 ;; `desktop-globals-to-save' (by default it isn't). This may result in saving
121 ;; things you did not mean to keep. Use M-x desktop-clear RET.
123 ;; Thanks to hetrick@phys.uva.nl (Jim Hetrick) for useful ideas.
124 ;; avk@rtsg.mot.com (Andrew V. Klein) for a dired tip.
125 ;; chris@tecc.co.uk (Chris Boucher) for a mark tip.
126 ;; f89-kam@nada.kth.se (Klas Mellbourn) for a mh-e tip.
127 ;; kifer@sbkifer.cs.sunysb.edu (M. Kifer) for a bug hunt.
128 ;; treese@lcs.mit.edu (Win Treese) for ange-ftp tips.
129 ;; pot@cnuce.cnr.it (Francesco Potorti`) for misc. tips.
130 ;; ---------------------------------------------------------------------------
131 ;; TODO:
133 ;; Save window configuration.
134 ;; Recognize more minor modes.
135 ;; Save mark rings.
137 ;;; Code:
139 (defvar desktop-file-version "206"
140 "Version number of desktop file format.
141 Written into the desktop file and used at desktop read to provide
142 backward compatibility.")
144 ;; ----------------------------------------------------------------------------
145 ;; USER OPTIONS -- settings you might want to play with.
146 ;; ----------------------------------------------------------------------------
148 (defgroup desktop nil
149 "Save status of Emacs when you exit."
150 :group 'frames)
152 ;;;###autoload
153 (define-minor-mode desktop-save-mode
154 "Toggle desktop saving mode.
155 With numeric ARG, turn desktop saving on if ARG is positive, off
156 otherwise. See variable `desktop-save' for a description of when the
157 desktop is saved."
158 :global t
159 :group 'desktop)
161 ;; Maintained for backward compatibility
162 (define-obsolete-variable-alias 'desktop-enable
163 'desktop-save-mode "22.1")
165 (defcustom desktop-save 'ask-if-new
166 "*Specifies whether the desktop should be saved when it is killed.
167 A desktop is killed when the user changes desktop or quits Emacs.
168 Possible values are:
169 t -- always save.
170 ask -- always ask.
171 ask-if-new -- ask if no desktop file exists, otherwise just save.
172 ask-if-exists -- ask if desktop file exists, otherwise don't save.
173 if-exists -- save if desktop file exists, otherwise don't save.
174 nil -- never save.
175 The desktop is never saved when `desktop-save-mode' is nil.
176 The variables `desktop-dirname' and `desktop-base-file-name'
177 determine where the desktop is saved."
178 :type '(choice
179 (const :tag "Always save" t)
180 (const :tag "Always ask" ask)
181 (const :tag "Ask if desktop file is new, else do save" ask-if-new)
182 (const :tag "Ask if desktop file exists, else don't save" ask-if-exists)
183 (const :tag "Save if desktop file exists, else don't" if-exists)
184 (const :tag "Never save" nil))
185 :group 'desktop
186 :version "22.1")
188 (defcustom desktop-base-file-name
189 (convert-standard-filename ".emacs.desktop")
190 "Name of file for Emacs desktop, excluding the directory part."
191 :type 'file
192 :group 'desktop)
193 (define-obsolete-variable-alias 'desktop-basefilename
194 'desktop-base-file-name "22.1")
196 (defcustom desktop-path '("." "~")
197 "List of directories to search for the desktop file.
198 The base name of the file is specified in `desktop-base-file-name'."
199 :type '(repeat directory)
200 :group 'desktop
201 :version "22.1")
203 (defcustom desktop-missing-file-warning nil
204 "*If non-nil then `desktop-read' asks if a non-existent file should be recreated.
205 Also pause for a moment to display message about errors signaled in
206 `desktop-buffer-mode-handlers'.
208 If nil, just print error messages in the message buffer."
209 :type 'boolean
210 :group 'desktop
211 :version "22.1")
213 (defcustom desktop-no-desktop-file-hook nil
214 "Normal hook run when `desktop-read' can't find a desktop file.
215 May be used to show a dired buffer."
216 :type 'hook
217 :group 'desktop
218 :version "22.1")
220 (defcustom desktop-after-read-hook nil
221 "Normal hook run after a successful `desktop-read'.
222 May be used to show a buffer list."
223 :type 'hook
224 :group 'desktop
225 :version "22.1")
227 (defcustom desktop-save-hook nil
228 "Normal hook run before the desktop is saved in a desktop file.
229 This is useful for truncating history lists, for example."
230 :type 'hook
231 :group 'desktop)
233 (defcustom desktop-globals-to-save
234 '(desktop-missing-file-warning
235 tags-file-name
236 tags-table-list
237 search-ring
238 regexp-search-ring
239 register-alist)
240 "List of global variables saved by `desktop-save'.
241 An element may be variable name (a symbol) or a cons cell of the form
242 \(VAR . MAX-SIZE), which means to truncate VAR's value to at most
243 MAX-SIZE elements (if the value is a list) before saving the value.
244 Feature: Saving `kill-ring' implies saving `kill-ring-yank-pointer'."
245 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
246 :group 'desktop)
248 (defcustom desktop-globals-to-clear
249 '(kill-ring
250 kill-ring-yank-pointer
251 search-ring
252 search-ring-yank-pointer
253 regexp-search-ring
254 regexp-search-ring-yank-pointer)
255 "List of global variables that `desktop-clear' will clear.
256 An element may be variable name (a symbol) or a cons cell of the form
257 \(VAR . FORM). Symbols are set to nil and for cons cells VAR is set
258 to the value obtained by evaluating FORM."
259 :type '(repeat (restricted-sexp :match-alternatives (symbolp consp)))
260 :group 'desktop
261 :version "22.1")
263 (defcustom desktop-clear-preserve-buffers
264 '("\\*scratch\\*" "\\*Messages\\*" "\\*server\\*" "\\*tramp/.+\\*")
265 "*List of buffers that `desktop-clear' should not delete.
266 Each element is a regular expression. Buffers with a name matched by any of
267 these won't be deleted."
268 :type '(repeat string)
269 :group 'desktop)
271 ;;;###autoload
272 (defcustom desktop-locals-to-save
273 '(desktop-locals-to-save ; Itself! Think it over.
274 truncate-lines
275 case-fold-search
276 case-replace
277 fill-column
278 overwrite-mode
279 change-log-default-name
280 line-number-mode
281 column-number-mode
282 size-indication-mode
283 buffer-file-coding-system
284 indent-tabs-mode
285 indicate-buffer-boundaries
286 indicate-empty-lines
287 show-trailing-whitespace)
288 "List of local variables to save for each buffer.
289 The variables are saved only when they really are local. Conventional minor
290 modes are restored automatically; they should not be listed here."
291 :type '(repeat symbol)
292 :group 'desktop)
294 ;; We skip .log files because they are normally temporary.
295 ;; (ftp) files because they require passwords and whatnot.
296 (defcustom desktop-buffers-not-to-save
297 "\\(^nn\\.a[0-9]+\\|\\.log\\|(ftp)\\)$"
298 "Regexp identifying buffers that are to be excluded from saving."
299 :type 'regexp
300 :group 'desktop)
302 ;; Skip tramp and ange-ftp files
303 (defcustom desktop-files-not-to-save
304 "^/[^/:]*:"
305 "Regexp identifying files whose buffers are to be excluded from saving."
306 :type 'regexp
307 :group 'desktop)
309 ;; We skip TAGS files to save time (tags-file-name is saved instead).
310 (defcustom desktop-modes-not-to-save
311 '(tags-table-mode)
312 "List of major modes whose buffers should not be saved."
313 :type '(repeat symbol)
314 :group 'desktop)
316 (defcustom desktop-file-name-format 'absolute
317 "*Format in which desktop file names should be saved.
318 Possible values are:
319 absolute -- Absolute file name.
320 tilde -- Relative to ~.
321 local -- Relative to directory of desktop file."
322 :type '(choice (const absolute) (const tilde) (const local))
323 :group 'desktop
324 :version "22.1")
326 (defcustom desktop-restore-eager t
327 "Number of buffers to restore immediately.
328 Remaining buffers are restored lazily (when Emacs is idle).
329 If value is t, all buffers are restored immediately."
330 :type '(choice (const t) integer)
331 :group 'desktop
332 :version "22.1")
334 (defcustom desktop-lazy-verbose t
335 "Verbose reporting of lazily created buffers."
336 :type 'boolean
337 :group 'desktop
338 :version "22.1")
340 (defcustom desktop-lazy-idle-delay 5
341 "Idle delay before starting to create buffers.
342 See `desktop-restore-eager'."
343 :type 'integer
344 :group 'desktop
345 :version "22.1")
347 ;;;###autoload
348 (defvar desktop-save-buffer nil
349 "When non-nil, save buffer status in desktop file.
350 This variable becomes buffer local when set.
352 If the value is a function, it is called by `desktop-save' with argument
353 DESKTOP-DIRNAME to obtain auxiliary information to save in the desktop
354 file along with the state of the buffer for which it was called.
356 When file names are returned, they should be formatted using the call
357 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
359 Later, when `desktop-read' evaluates the desktop file, auxiliary information
360 is passed as the argument DESKTOP-BUFFER-MISC to functions in
361 `desktop-buffer-mode-handlers'.")
362 (make-variable-buffer-local 'desktop-save-buffer)
363 (make-obsolete-variable 'desktop-buffer-modes-to-save
364 'desktop-save-buffer "22.1")
365 (make-obsolete-variable 'desktop-buffer-misc-functions
366 'desktop-save-buffer "22.1")
368 ;;;###autoload
369 (defvar desktop-buffer-mode-handlers
371 "Alist of major mode specific functions to restore a desktop buffer.
372 Functions listed are called by `desktop-create-buffer' when `desktop-read'
373 evaluates the desktop file. List elements must have the form
375 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
377 Buffers with a major mode not specified here, are restored by the default
378 handler `desktop-restore-file-buffer'.
380 Handlers are called with argument list
382 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
384 Furthermore, they may use the following variables:
386 desktop-file-version
387 desktop-buffer-major-mode
388 desktop-buffer-minor-modes
389 desktop-buffer-point
390 desktop-buffer-mark
391 desktop-buffer-read-only
392 desktop-buffer-locals
394 If a handler returns a buffer, then the saved mode settings
395 and variable values for that buffer are copied into it.
397 Modules that define a major mode that needs a special handler should contain
398 code like
400 (defun foo-restore-desktop-buffer
402 (add-to-list 'desktop-buffer-mode-handlers
403 '(foo-mode . foo-restore-desktop-buffer))
405 Furthermore the major mode function must be autoloaded.")
407 ;;;###autoload
408 (put 'desktop-buffer-mode-handlers 'risky-local-variable t)
409 (make-obsolete-variable 'desktop-buffer-handlers
410 'desktop-buffer-mode-handlers "22.1")
412 (defcustom desktop-minor-mode-table
413 '((auto-fill-function auto-fill-mode)
414 (vc-mode nil)
415 (vc-dired-mode nil))
416 "Table mapping minor mode variables to minor mode functions.
417 Each entry has the form (NAME RESTORE-FUNCTION).
418 NAME is the name of the buffer-local variable indicating that the minor
419 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
420 called. RESTORE-FUNCTION nil means don't try to restore the minor mode.
421 Only minor modes for which the name of the buffer-local variable
422 and the name of the minor mode function are different have to be added to
423 this table. See also `desktop-minor-mode-handlers'."
424 :type 'sexp
425 :group 'desktop)
427 ;;;###autoload
428 (defvar desktop-minor-mode-handlers
430 "Alist of functions to restore non-standard minor modes.
431 Functions are called by `desktop-create-buffer' to restore minor modes.
432 List elements must have the form
434 (MINOR-MODE . RESTORE-FUNCTION).
436 Minor modes not specified here, are restored by the standard minor mode
437 function.
439 Handlers are called with argument list
441 (DESKTOP-BUFFER-LOCALS)
443 Furthermore, they may use the following variables:
445 desktop-file-version
446 desktop-buffer-file-name
447 desktop-buffer-name
448 desktop-buffer-major-mode
449 desktop-buffer-minor-modes
450 desktop-buffer-point
451 desktop-buffer-mark
452 desktop-buffer-read-only
453 desktop-buffer-misc
455 When a handler is called, the buffer has been created and the major mode has
456 been set, but local variables listed in desktop-buffer-locals has not yet been
457 created and set.
459 Modules that define a minor mode that needs a special handler should contain
460 code like
462 (defun foo-desktop-restore
464 (add-to-list 'desktop-minor-mode-handlers
465 '(foo-mode . foo-desktop-restore))
467 Furthermore the minor mode function must be autoloaded.
469 See also `desktop-minor-mode-table'.")
471 ;;;###autoload
472 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
474 ;; ----------------------------------------------------------------------------
475 (defvar desktop-dirname nil
476 "The directory in which the desktop file should be saved.")
478 (defconst desktop-header
479 ";; --------------------------------------------------------------------------
480 ;; Desktop File for Emacs
481 ;; --------------------------------------------------------------------------
482 " "*Header to place in Desktop file.")
484 (defvar desktop-delay-hook nil
485 "Hooks run after all buffers are loaded; intended for internal use.")
487 ;; ----------------------------------------------------------------------------
488 (defun desktop-truncate (list n)
489 "Truncate LIST to at most N elements destructively."
490 (let ((here (nthcdr (1- n) list)))
491 (if (consp here)
492 (setcdr here nil))))
494 ;; ----------------------------------------------------------------------------
495 (defun desktop-clear ()
496 "Empty the Desktop.
497 This kills all buffers except for internal ones and those with names matched by
498 a regular expression in the list `desktop-clear-preserve-buffers'.
499 Furthermore, it clears the variables listed in `desktop-globals-to-clear'."
500 (interactive)
501 (desktop-lazy-abort)
502 (dolist (var desktop-globals-to-clear)
503 (if (symbolp var)
504 (eval `(setq-default ,var nil))
505 (eval `(setq-default ,(car var) ,(cdr var)))))
506 (let ((buffers (buffer-list))
507 (preserve-regexp (concat "^\\("
508 (mapconcat (lambda (regexp)
509 (concat "\\(" regexp "\\)"))
510 desktop-clear-preserve-buffers
511 "\\|")
512 "\\)$")))
513 (while buffers
514 (let ((bufname (buffer-name (car buffers))))
516 (null bufname)
517 (string-match preserve-regexp bufname)
518 ;; Don't kill buffers made for internal purposes.
519 (and (not (equal bufname "")) (eq (aref bufname 0) ?\s))
520 (kill-buffer (car buffers))))
521 (setq buffers (cdr buffers))))
522 (delete-other-windows))
524 ;; ----------------------------------------------------------------------------
525 (add-hook 'kill-emacs-hook 'desktop-kill)
527 (defun desktop-kill ()
528 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
529 If the desktop should be saved and `desktop-dirname'
530 is nil, ask the user where to save the desktop."
531 (when
532 (and
533 desktop-save-mode
534 (let ((exists (file-exists-p (expand-file-name desktop-base-file-name desktop-dirname))))
536 (eq desktop-save t)
537 (and exists (memq desktop-save '(ask-if-new if-exists)))
538 (and
540 (memq desktop-save '(ask ask-if-new))
541 (and exists (eq desktop-save 'ask-if-exists)))
542 (y-or-n-p "Save desktop? ")))))
543 (unless desktop-dirname
544 (setq desktop-dirname
545 (file-name-as-directory
546 (expand-file-name
547 (call-interactively
548 (lambda (dir) (interactive "DDirectory for desktop file: ") dir))))))
549 (condition-case err
550 (desktop-save desktop-dirname)
551 (file-error
552 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
553 (signal (car err) (cdr err)))))))
555 ;; ----------------------------------------------------------------------------
556 (defun desktop-list* (&rest args)
557 (if (null (cdr args))
558 (car args)
559 (setq args (nreverse args))
560 (let ((value (cons (nth 1 args) (car args))))
561 (setq args (cdr (cdr args)))
562 (while args
563 (setq value (cons (car args) value))
564 (setq args (cdr args)))
565 value)))
567 ;; ----------------------------------------------------------------------------
568 (defun desktop-internal-v2s (value)
569 "Convert VALUE to a pair (QUOTE . TXT); (eval (read TXT)) gives VALUE.
570 TXT is a string that when read and evaluated yields value.
571 QUOTE may be `may' (value may be quoted),
572 `must' (values must be quoted), or nil (value may not be quoted)."
573 (cond
574 ((or (numberp value) (null value) (eq t value) (keywordp value))
575 (cons 'may (prin1-to-string value)))
576 ((stringp value)
577 (let ((copy (copy-sequence value)))
578 (set-text-properties 0 (length copy) nil copy)
579 ;; Get rid of text properties because we cannot read them
580 (cons 'may (prin1-to-string copy))))
581 ((symbolp value)
582 (cons 'must (prin1-to-string value)))
583 ((vectorp value)
584 (let* ((special nil)
585 (pass1 (mapcar
586 (lambda (el)
587 (let ((res (desktop-internal-v2s el)))
588 (if (null (car res))
589 (setq special t))
590 res))
591 value)))
592 (if special
593 (cons nil (concat "(vector "
594 (mapconcat (lambda (el)
595 (if (eq (car el) 'must)
596 (concat "'" (cdr el))
597 (cdr el)))
598 pass1
599 " ")
600 ")"))
601 (cons 'may (concat "[" (mapconcat 'cdr pass1 " ") "]")))))
602 ((consp value)
603 (let ((p value)
604 newlist
605 use-list*
606 anynil)
607 (while (consp p)
608 (let ((q.txt (desktop-internal-v2s (car p))))
609 (or anynil (setq anynil (null (car q.txt))))
610 (setq newlist (cons q.txt newlist)))
611 (setq p (cdr p)))
612 (if p
613 (let ((last (desktop-internal-v2s p))
614 (el (car newlist)))
615 (or anynil (setq anynil (null (car last))))
616 (or anynil
617 (setq newlist (cons '(must . ".") newlist)))
618 (setq use-list* t)
619 (setq newlist (cons last newlist))))
620 (setq newlist (nreverse newlist))
621 (if anynil
622 (cons nil
623 (concat (if use-list* "(desktop-list* " "(list ")
624 (mapconcat (lambda (el)
625 (if (eq (car el) 'must)
626 (concat "'" (cdr el))
627 (cdr el)))
628 newlist
629 " ")
630 ")"))
631 (cons 'must
632 (concat "(" (mapconcat 'cdr newlist " ") ")")))))
633 ((subrp value)
634 (cons nil (concat "(symbol-function '"
635 (substring (prin1-to-string value) 7 -1)
636 ")")))
637 ((markerp value)
638 (let ((pos (prin1-to-string (marker-position value)))
639 (buf (prin1-to-string (buffer-name (marker-buffer value)))))
640 (cons nil (concat "(let ((mk (make-marker)))"
641 " (add-hook 'desktop-delay-hook"
642 " (list 'lambda '() (list 'set-marker mk "
643 pos " (get-buffer " buf ")))) mk)"))))
644 (t ; save as text
645 (cons 'may "\"Unprintable entity\""))))
647 ;; ----------------------------------------------------------------------------
648 (defun desktop-value-to-string (value)
649 "Convert VALUE to a string that when read evaluates to the same value.
650 Not all types of values are supported."
651 (let* ((print-escape-newlines t)
652 (float-output-format nil)
653 (quote.txt (desktop-internal-v2s value))
654 (quote (car quote.txt))
655 (txt (cdr quote.txt)))
656 (if (eq quote 'must)
657 (concat "'" txt)
658 txt)))
660 ;; ----------------------------------------------------------------------------
661 (defun desktop-outvar (varspec)
662 "Output a setq statement for variable VAR to the desktop file.
663 The argument VARSPEC may be the variable name VAR (a symbol),
664 or a cons cell of the form (VAR . MAX-SIZE),
665 which means to truncate VAR's value to at most MAX-SIZE elements
666 \(if the value is a list) before saving the value."
667 (let (var size)
668 (if (consp varspec)
669 (setq var (car varspec) size (cdr varspec))
670 (setq var varspec))
671 (if (boundp var)
672 (progn
673 (if (and (integerp size)
674 (> size 0)
675 (listp (eval var)))
676 (desktop-truncate (eval var) size))
677 (insert "(setq "
678 (symbol-name var)
680 (desktop-value-to-string (symbol-value var))
681 ")\n")))))
683 ;; ----------------------------------------------------------------------------
684 (defun desktop-save-buffer-p (filename bufname mode &rest dummy)
685 "Return t if buffer should have its state saved in the desktop file.
686 FILENAME is the visited file name, BUFNAME is the buffer name, and
687 MODE is the major mode.
688 \n\(fn FILENAME BUFNAME MODE)"
689 (let ((case-fold-search nil))
690 (and (not (string-match desktop-buffers-not-to-save bufname))
691 (not (memq mode desktop-modes-not-to-save))
692 (or (and filename
693 (not (string-match desktop-files-not-to-save filename)))
694 (and (eq mode 'dired-mode)
695 (with-current-buffer bufname
696 (not (string-match desktop-files-not-to-save
697 default-directory))))
698 (and (null filename)
699 (with-current-buffer bufname desktop-save-buffer))))))
701 ;; ----------------------------------------------------------------------------
702 (defun desktop-file-name (filename dirname)
703 "Convert FILENAME to format specified in `desktop-file-name-format'.
704 DIRNAME must be the directory in which the desktop file will be saved."
705 (cond
706 ((not filename) nil)
707 ((eq desktop-file-name-format 'tilde)
708 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
709 (cond
710 ((file-name-absolute-p relative-name) relative-name)
711 ((string= "./" relative-name) "~/")
712 ((string= "." relative-name) "~")
713 (t (concat "~/" relative-name)))))
714 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
715 (t (expand-file-name filename))))
717 ;; ----------------------------------------------------------------------------
718 (defun desktop-save (dirname)
719 "Save the desktop in a desktop file.
720 Parameter DIRNAME specifies where to save the desktop file.
721 See also `desktop-base-file-name'."
722 (interactive "DDirectory to save desktop file in: ")
723 (run-hooks 'desktop-save-hook)
724 (setq dirname (file-name-as-directory (expand-file-name dirname)))
725 (save-excursion
726 (let ((filename (expand-file-name desktop-base-file-name dirname))
727 (info
728 (mapcar
729 #'(lambda (b)
730 (set-buffer b)
731 (list
732 (desktop-file-name (buffer-file-name) dirname)
733 (buffer-name)
734 major-mode
735 ;; minor modes
736 (let (ret)
737 (mapc
738 #'(lambda (minor-mode)
739 (and
740 (boundp minor-mode)
741 (symbol-value minor-mode)
742 (let* ((special (assq minor-mode desktop-minor-mode-table))
743 (value (cond (special (cadr special))
744 ((functionp minor-mode) minor-mode))))
745 (when value (add-to-list 'ret value)))))
746 (mapcar #'car minor-mode-alist))
747 ret)
748 (point)
749 (list (mark t) mark-active)
750 buffer-read-only
751 ;; Auxiliary information
752 (when (functionp desktop-save-buffer)
753 (funcall desktop-save-buffer dirname))
754 (let ((locals desktop-locals-to-save)
755 (loclist (buffer-local-variables))
756 (ll))
757 (while locals
758 (let ((here (assq (car locals) loclist)))
759 (if here
760 (setq ll (cons here ll))
761 (when (member (car locals) loclist)
762 (setq ll (cons (car locals) ll)))))
763 (setq locals (cdr locals)))
764 ll)))
765 (buffer-list)))
766 (eager desktop-restore-eager)
767 (buf (get-buffer-create "*desktop*")))
768 (set-buffer buf)
769 (erase-buffer)
771 (insert
772 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
773 desktop-header
774 ";; Created " (current-time-string) "\n"
775 ";; Desktop file format version " desktop-file-version "\n"
776 ";; Emacs version " emacs-version "\n\n"
777 ";; Global section:\n")
778 (mapc (function desktop-outvar) desktop-globals-to-save)
779 (if (memq 'kill-ring desktop-globals-to-save)
780 (insert
781 "(setq kill-ring-yank-pointer (nthcdr "
782 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
783 " kill-ring))\n"))
785 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
786 (mapc #'(lambda (l)
787 (when (apply 'desktop-save-buffer-p l)
788 (insert "("
789 (if (or (not (integerp eager))
790 (unless (zerop eager)
791 (setq eager (1- eager))
793 "desktop-create-buffer"
794 "desktop-append-buffer-args")
796 desktop-file-version)
797 (mapc #'(lambda (e)
798 (insert "\n " (desktop-value-to-string e)))
800 (insert ")\n\n")))
801 info)
802 (setq default-directory dirname)
803 (let ((coding-system-for-write 'emacs-mule))
804 (write-region (point-min) (point-max) filename nil 'nomessage))))
805 (setq desktop-dirname dirname))
807 ;; ----------------------------------------------------------------------------
808 (defun desktop-remove ()
809 "Delete desktop file in `desktop-dirname'.
810 This function also sets `desktop-dirname' to nil."
811 (interactive)
812 (when desktop-dirname
813 (let ((filename (expand-file-name desktop-base-file-name desktop-dirname)))
814 (setq desktop-dirname nil)
815 (when (file-exists-p filename)
816 (delete-file filename)))))
818 (defvar desktop-buffer-args-list nil
819 "List of args for `desktop-create-buffer'.")
821 (defvar desktop-lazy-timer nil)
823 ;; ----------------------------------------------------------------------------
824 ;;;###autoload
825 (defun desktop-read (&optional dirname)
826 "Read and process the desktop file in directory DIRNAME.
827 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
828 directories listed in `desktop-path'. If a desktop file is found, it
829 is processed and `desktop-after-read-hook' is run. If no desktop file
830 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
831 This function is a no-op when Emacs is running in batch mode.
832 It returns t if a desktop file was loaded, nil otherwise."
833 (interactive)
834 (unless noninteractive
835 (setq desktop-dirname
836 (file-name-as-directory
837 (expand-file-name
839 ;; If DIRNAME is specified, use it.
840 (and (< 0 (length dirname)) dirname)
841 ;; Otherwise search desktop file in desktop-path.
842 (let ((dirs desktop-path))
843 (while
844 (and
845 dirs
846 (not
847 (file-exists-p (expand-file-name desktop-base-file-name (car dirs)))))
848 (setq dirs (cdr dirs)))
849 (and dirs (car dirs)))
850 ;; If not found and `desktop-path' is non-nil, use its first element.
851 (and desktop-path (car desktop-path))
852 ;; Default: Home directory.
853 "~"))))
854 (if (file-exists-p (expand-file-name desktop-base-file-name desktop-dirname))
855 ;; Desktop file found, process it.
856 (let ((desktop-first-buffer nil)
857 (desktop-buffer-ok-count 0)
858 (desktop-buffer-fail-count 0))
859 (setq desktop-lazy-timer nil)
860 ;; Evaluate desktop buffer.
861 (load (expand-file-name desktop-base-file-name desktop-dirname) t t t)
862 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
863 ;; We want buffers existing prior to evaluating the desktop (and not reused)
864 ;; to be placed at the end of the buffer list, so we move them here.
865 (mapc 'bury-buffer
866 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
867 (switch-to-buffer (car (buffer-list)))
868 (run-hooks 'desktop-delay-hook)
869 (setq desktop-delay-hook nil)
870 (run-hooks 'desktop-after-read-hook)
871 (message "Desktop: %d buffer%s restored%s%s."
872 desktop-buffer-ok-count
873 (if (= 1 desktop-buffer-ok-count) "" "s")
874 (if (< 0 desktop-buffer-fail-count)
875 (format ", %d failed to restore" desktop-buffer-fail-count)
877 (if desktop-buffer-args-list
878 (format ", %d to restore lazily"
879 (length desktop-buffer-args-list))
880 ""))
882 ;; No desktop file found.
883 (desktop-clear)
884 (let ((default-directory desktop-dirname))
885 (run-hooks 'desktop-no-desktop-file-hook))
886 (message "No desktop file.")
887 nil)))
889 ;; ----------------------------------------------------------------------------
890 ;; Maintained for backward compatibility
891 ;;;###autoload
892 (defun desktop-load-default ()
893 "Load the `default' start-up library manually.
894 Also inhibit further loading of it."
895 (unless inhibit-default-init ; safety check
896 (load "default" t t)
897 (setq inhibit-default-init t)))
898 (make-obsolete 'desktop-load-default
899 'desktop-save-mode "22.1")
901 ;; ----------------------------------------------------------------------------
902 ;;;###autoload
903 (defun desktop-change-dir (dirname)
904 "Change to desktop saved in DIRNAME.
905 Kill the desktop as specified by variables `desktop-save-mode' and
906 `desktop-save', then clear the desktop and load the desktop file in
907 directory DIRNAME."
908 (interactive "DChange to directory: ")
909 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
910 (desktop-kill)
911 (desktop-clear)
912 (desktop-read dirname))
914 ;; ----------------------------------------------------------------------------
915 ;;;###autoload
916 (defun desktop-save-in-desktop-dir ()
917 "Save the desktop in directory `desktop-dirname'."
918 (interactive)
919 (if desktop-dirname
920 (desktop-save desktop-dirname)
921 (call-interactively 'desktop-save))
922 (message "Desktop saved in %s" desktop-dirname))
924 ;; ----------------------------------------------------------------------------
925 ;;;###autoload
926 (defun desktop-revert ()
927 "Revert to the last loaded desktop."
928 (interactive)
929 (unless desktop-dirname
930 (error "Unknown desktop directory"))
931 (unless (file-exists-p (expand-file-name desktop-base-file-name desktop-dirname))
932 (error "No desktop file found"))
933 (desktop-clear)
934 (desktop-read desktop-dirname))
936 ;; ----------------------------------------------------------------------------
937 (defun desktop-restore-file-buffer (desktop-buffer-file-name
938 desktop-buffer-name
939 desktop-buffer-misc)
940 "Restore a file buffer."
941 (eval-when-compile ; Just to silence the byte compiler
942 (defvar desktop-buffer-major-mode)
943 (defvar desktop-buffer-locals))
944 (if desktop-buffer-file-name
945 (if (or (file-exists-p desktop-buffer-file-name)
946 (let ((msg (format "Desktop: File \"%s\" no longer exists."
947 desktop-buffer-file-name)))
948 (if desktop-missing-file-warning
949 (y-or-n-p (concat msg " Re-create? "))
950 (message "%s" msg)
951 nil)))
952 (let* ((auto-insert nil) ; Disable auto insertion
953 (coding-system-for-read
954 (or coding-system-for-read
955 (cdr (assq 'buffer-file-coding-system
956 desktop-buffer-locals))))
957 (buf (find-file-noselect desktop-buffer-file-name)))
958 (condition-case nil
959 (switch-to-buffer buf)
960 (error (pop-to-buffer buf)))
961 (and (not (eq major-mode desktop-buffer-major-mode))
962 (functionp desktop-buffer-major-mode)
963 (funcall desktop-buffer-major-mode))
964 buf)
965 nil)))
967 (defun desktop-load-file (function)
968 "Load the file where auto loaded FUNCTION is defined."
969 (when function
970 (let ((fcell (and (fboundp function) (symbol-function function))))
971 (when (and (listp fcell)
972 (eq 'autoload (car fcell)))
973 (load (cadr fcell))))))
975 ;; ----------------------------------------------------------------------------
976 ;; Create a buffer, load its file, set its mode, ...;
977 ;; called from Desktop file only.
979 ;; Just to silence the byte compiler.
980 (eval-when-compile
981 (defvar desktop-first-buffer)) ; Dynamically bound in `desktop-read'
983 (defun desktop-create-buffer
984 (desktop-file-version
985 desktop-buffer-file-name
986 desktop-buffer-name
987 desktop-buffer-major-mode
988 desktop-buffer-minor-modes
989 desktop-buffer-point
990 desktop-buffer-mark
991 desktop-buffer-read-only
992 desktop-buffer-misc
993 &optional
994 desktop-buffer-locals)
995 ;; Just to silence the byte compiler. Bound locally in `desktop-read'.
996 (eval-when-compile
997 (defvar desktop-buffer-ok-count)
998 (defvar desktop-buffer-fail-count))
999 ;; To make desktop files with relative file names possible, we cannot
1000 ;; allow `default-directory' to change. Therefore we save current buffer.
1001 (save-current-buffer
1002 ;; Give major mode module a chance to add a handler.
1003 (desktop-load-file desktop-buffer-major-mode)
1004 (let ((buffer-list (buffer-list))
1005 (result
1006 (condition-case err
1007 (funcall (or (cdr (assq desktop-buffer-major-mode
1008 desktop-buffer-mode-handlers))
1009 'desktop-restore-file-buffer)
1010 desktop-buffer-file-name
1011 desktop-buffer-name
1012 desktop-buffer-misc)
1013 (error
1014 (message "Desktop: Can't load buffer %s: %s"
1015 desktop-buffer-name
1016 (error-message-string err))
1017 (when desktop-missing-file-warning (sit-for 1))
1018 nil))))
1019 (if (bufferp result)
1020 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1021 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1022 (setq result nil))
1023 ;; Restore buffer list order with new buffer at end. Don't change
1024 ;; the order for old desktop files (old desktop module behaviour).
1025 (unless (< desktop-file-version 206)
1026 (mapc 'bury-buffer buffer-list)
1027 (when result (bury-buffer result)))
1028 (when result
1029 (unless (or desktop-first-buffer (< desktop-file-version 206))
1030 (setq desktop-first-buffer result))
1031 (set-buffer result)
1032 (unless (equal (buffer-name) desktop-buffer-name)
1033 (rename-buffer desktop-buffer-name))
1034 ;; minor modes
1035 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1036 (auto-fill-mode 1))
1037 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1038 (auto-fill-mode 0))
1040 (mapc #'(lambda (minor-mode)
1041 ;; Give minor mode module a chance to add a handler.
1042 (desktop-load-file minor-mode)
1043 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1044 (if handler
1045 (funcall handler desktop-buffer-locals)
1046 (when (functionp minor-mode)
1047 (funcall minor-mode 1)))))
1048 desktop-buffer-minor-modes)))
1049 ;; Even though point and mark are non-nil when written by `desktop-save',
1050 ;; they may be modified by handlers wanting to set point or mark themselves.
1051 (when desktop-buffer-point
1052 (goto-char
1053 (condition-case err
1054 ;; Evaluate point. Thus point can be something like '(search-forward ...
1055 (eval desktop-buffer-point)
1056 (error (message "%s" (error-message-string err)) 1))))
1057 (when desktop-buffer-mark
1058 (if (consp desktop-buffer-mark)
1059 (progn
1060 (set-mark (car desktop-buffer-mark))
1061 (setq mark-active (car (cdr desktop-buffer-mark))))
1062 (set-mark desktop-buffer-mark)))
1063 ;; Never override file system if the file really is read-only marked.
1064 (if desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1065 (while desktop-buffer-locals
1066 (let ((this (car desktop-buffer-locals)))
1067 (if (consp this)
1068 ;; an entry of this form `(symbol . value)'
1069 (progn
1070 (make-local-variable (car this))
1071 (set (car this) (cdr this)))
1072 ;; an entry of the form `symbol'
1073 (make-local-variable this)
1074 (makunbound this)))
1075 (setq desktop-buffer-locals (cdr desktop-buffer-locals)))))))
1077 ;; ----------------------------------------------------------------------------
1078 ;; Backward compatibility -- update parameters to 205 standards.
1079 (defun desktop-buffer (desktop-buffer-file-name desktop-buffer-name
1080 desktop-buffer-major-mode
1081 mim pt mk ro tl fc cfs cr desktop-buffer-misc)
1082 (desktop-create-buffer 205 desktop-buffer-file-name desktop-buffer-name
1083 desktop-buffer-major-mode (cdr mim) pt mk ro
1084 desktop-buffer-misc
1085 (list (cons 'truncate-lines tl)
1086 (cons 'fill-column fc)
1087 (cons 'case-fold-search cfs)
1088 (cons 'case-replace cr)
1089 (cons 'overwrite-mode (car mim)))))
1091 (defun desktop-append-buffer-args (&rest args)
1092 "Append ARGS at end of `desktop-buffer-args-list'.
1093 ARGS must be an argument list for `desktop-create-buffer'."
1094 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1095 (unless desktop-lazy-timer
1096 (setq desktop-lazy-timer
1097 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1099 (defun desktop-lazy-create-buffer ()
1100 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1101 (when desktop-buffer-args-list
1102 (let* ((remaining (length desktop-buffer-args-list))
1103 (args (pop desktop-buffer-args-list))
1104 (buffer-name (nth 2 args))
1105 (msg (format "Desktop lazily opening %s (%s remaining)..."
1106 buffer-name remaining)))
1107 (when desktop-lazy-verbose
1108 (message "%s" msg))
1109 (let ((desktop-first-buffer nil)
1110 (desktop-buffer-ok-count 0)
1111 (desktop-buffer-fail-count 0))
1112 (apply 'desktop-create-buffer args)
1113 (run-hooks 'desktop-delay-hook)
1114 (setq desktop-delay-hook nil)
1115 (bury-buffer (get-buffer buffer-name))
1116 (when desktop-lazy-verbose
1117 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1119 (defun desktop-idle-create-buffers ()
1120 "Create buffers until the user does something, then stop.
1121 If there are no buffers left to create, kill the timer."
1122 (let ((repeat 1))
1123 (while (and repeat desktop-buffer-args-list)
1124 (save-window-excursion
1125 (desktop-lazy-create-buffer))
1126 (setq repeat (sit-for 0.2))
1127 (unless desktop-buffer-args-list
1128 (cancel-timer desktop-lazy-timer)
1129 (setq desktop-lazy-timer nil)
1130 (message "Lazy desktop load complete")
1131 (sit-for 3)
1132 (message "")))))
1134 (defun desktop-lazy-complete ()
1135 "Run the desktop load to completion."
1136 (interactive)
1137 (let ((desktop-lazy-verbose t))
1138 (while desktop-buffer-args-list
1139 (save-window-excursion
1140 (desktop-lazy-create-buffer)))
1141 (message "Lazy desktop load complete")))
1143 (defun desktop-lazy-abort ()
1144 "Abort lazy loading of the desktop."
1145 (interactive)
1146 (when desktop-lazy-timer
1147 (cancel-timer desktop-lazy-timer)
1148 (setq desktop-lazy-timer nil))
1149 (when desktop-buffer-args-list
1150 (setq desktop-buffer-args-list nil)
1151 (when (interactive-p)
1152 (message "Lazy desktop load aborted"))))
1154 ;; ----------------------------------------------------------------------------
1155 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1156 ;; command line, we do the rest of what it takes to use desktop, but do it
1157 ;; after finishing loading the init file.
1158 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1159 ;; functions are processed after `after-init-hook'.
1160 (add-hook
1161 'after-init-hook
1162 '(lambda ()
1163 (let ((key "--no-desktop"))
1164 (when (member key command-line-args)
1165 (setq command-line-args (delete key command-line-args))
1166 (setq desktop-save-mode nil)))
1167 (when desktop-save-mode (desktop-read))))
1169 (provide 'desktop)
1171 ;;; arch-tag: 221907c3-1771-4fd3-9c2e-c6f700c6ede9
1172 ;;; desktop.el ends here