(vc-svn-registered): Catch all errors.
[bpt/emacs.git] / lisp / desktop.el
1 ;;; desktop.el --- save partial status of Emacs when killed
2
3 ;; Copyright (C) 1993, 1994, 1995, 1997, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005 Free Software Foundation, Inc.
5
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.
10
11 ;; This file is part of GNU Emacs.
12
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.
17
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.
22
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.
27
28 ;;; Commentary:
29
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
39
40 ;; To use this, use customize to turn on desktop-save-mode or add the
41 ;; following line somewhere in your .emacs file:
42 ;;
43 ;; (desktop-save-mode 1)
44 ;;
45 ;; For further usage information, look at the section
46 ;; "Saving Emacs Sessions" in the GNU Emacs Manual.
47
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.
53
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
60 ;;
61 ;; (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
62 ;;
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
68 ;;
69 ;; (MINOR-MODE . RESTORE-FUNCTION).
70 ;;
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
75
76 ;; (defun foo-restore-desktop-buffer
77 ;; ...
78 ;; (add-to-list 'desktop-buffer-mode-handlers
79 ;; '(foo-mode . foo-restore-desktop-buffer))
80
81 ;; or
82
83 ;; (defun bar-desktop-restore
84 ;; ...
85 ;; (add-to-list 'desktop-minor-mode-handlers
86 ;; '(bar-mode . bar-desktop-restore))
87
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.
91
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
106
107 ;; (NAME RESTORE-FUNCTION)
108
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 ;; ---------------------------------------------------------------------------
114
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.
118
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.
122
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:
132 ;;
133 ;; Save window configuration.
134 ;; Recognize more minor modes.
135 ;; Save mark rings.
136
137 ;;; Code:
138
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.")
143
144 ;; ----------------------------------------------------------------------------
145 ;; USER OPTIONS -- settings you might want to play with.
146 ;; ----------------------------------------------------------------------------
147
148 (defgroup desktop nil
149 "Save status of Emacs when you exit."
150 :group 'frames)
151
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)
160
161 ;; Maintained for backward compatibility
162 (define-obsolete-variable-alias 'desktop-enable
163 'desktop-save-mode "22.1")
164
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")
187
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")
195
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")
202
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'.
207
208 If nil, just print error messages in the message buffer."
209 :type 'boolean
210 :group 'desktop
211 :version "22.1")
212
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")
219
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")
226
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)
232
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)
247
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")
262
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)
270
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)
293
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)
301
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)
308
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)
315
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")
325
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")
333
334 (defcustom desktop-lazy-verbose t
335 "Verbose reporting of lazily created buffers."
336 :type 'boolean
337 :group 'desktop
338 :version "22.1")
339
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")
346
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.
351
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.
355
356 When file names are returned, they should be formatted using the call
357 \"(desktop-file-name FILE-NAME DESKTOP-DIRNAME)\".
358
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")
367
368 ;;;###autoload
369 (defvar desktop-buffer-mode-handlers
370 nil
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
374
375 (MAJOR-MODE . RESTORE-BUFFER-FUNCTION).
376
377 Buffers with a major mode not specified here, are restored by the default
378 handler `desktop-restore-file-buffer'.
379
380 Handlers are called with argument list
381
382 (DESKTOP-BUFFER-FILE-NAME DESKTOP-BUFFER-NAME DESKTOP-BUFFER-MISC)
383
384 Furthermore, they may use the following variables:
385
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
393
394 If a handler returns a buffer, then the saved mode settings
395 and variable values for that buffer are copied into it.
396
397 Modules that define a major mode that needs a special handler should contain
398 code like
399
400 (defun foo-restore-desktop-buffer
401 ...
402 (add-to-list 'desktop-buffer-mode-handlers
403 '(foo-mode . foo-restore-desktop-buffer))
404
405 Furthermore the major mode function must be autoloaded.")
406
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")
411
412 (defcustom desktop-minor-mode-table
413 '((auto-fill-function auto-fill-mode)
414 (vc-mode nil))
415 "Table mapping minor mode variables to minor mode functions.
416 Each entry has the form (NAME RESTORE-FUNCTION).
417 NAME is the name of the buffer-local variable indicating that the minor
418 mode is active. RESTORE-FUNCTION is the function to activate the minor mode.
419 called. RESTORE-FUNCTION nil means don't try to restore the minor mode.
420 Only minor modes for which the name of the buffer-local variable
421 and the name of the minor mode function are different have to be added to
422 this table. See also `desktop-minor-mode-handlers'."
423 :type 'sexp
424 :group 'desktop)
425
426 ;;;###autoload
427 (defvar desktop-minor-mode-handlers
428 nil
429 "Alist of functions to restore non-standard minor modes.
430 Functions are called by `desktop-create-buffer' to restore minor modes.
431 List elements must have the form
432
433 (MINOR-MODE . RESTORE-FUNCTION).
434
435 Minor modes not specified here, are restored by the standard minor mode
436 function.
437
438 Handlers are called with argument list
439
440 (DESKTOP-BUFFER-LOCALS)
441
442 Furthermore, they may use the following variables:
443
444 desktop-file-version
445 desktop-buffer-file-name
446 desktop-buffer-name
447 desktop-buffer-major-mode
448 desktop-buffer-minor-modes
449 desktop-buffer-point
450 desktop-buffer-mark
451 desktop-buffer-read-only
452 desktop-buffer-misc
453
454 When a handler is called, the buffer has been created and the major mode has
455 been set, but local variables listed in desktop-buffer-locals has not yet been
456 created and set.
457
458 Modules that define a minor mode that needs a special handler should contain
459 code like
460
461 (defun foo-desktop-restore
462 ...
463 (add-to-list 'desktop-minor-mode-handlers
464 '(foo-mode . foo-desktop-restore))
465
466 Furthermore the minor mode function must be autoloaded.
467
468 See also `desktop-minor-mode-table'.")
469
470 ;;;###autoload
471 (put 'desktop-minor-mode-handlers 'risky-local-variable t)
472
473 ;; ----------------------------------------------------------------------------
474 (defvar desktop-dirname nil
475 "The directory in which the desktop file should be saved.")
476
477 (defconst desktop-header
478 ";; --------------------------------------------------------------------------
479 ;; Desktop File for Emacs
480 ;; --------------------------------------------------------------------------
481 " "*Header to place in Desktop file.")
482
483 (defvar desktop-delay-hook nil
484 "Hooks run after all buffers are loaded; intended for internal use.")
485
486 ;; ----------------------------------------------------------------------------
487 (defun desktop-truncate (list n)
488 "Truncate LIST to at most N elements destructively."
489 (let ((here (nthcdr (1- n) list)))
490 (if (consp here)
491 (setcdr here nil))))
492
493 ;; ----------------------------------------------------------------------------
494 (defun desktop-clear ()
495 "Empty the Desktop.
496 This kills all buffers except for internal ones and those with names matched by
497 a regular expression in the list `desktop-clear-preserve-buffers'.
498 Furthermore, it clears the variables listed in `desktop-globals-to-clear'."
499 (interactive)
500 (desktop-lazy-abort)
501 (dolist (var desktop-globals-to-clear)
502 (if (symbolp var)
503 (eval `(setq-default ,var nil))
504 (eval `(setq-default ,(car var) ,(cdr var)))))
505 (let ((buffers (buffer-list))
506 (preserve-regexp (concat "^\\("
507 (mapconcat (lambda (regexp)
508 (concat "\\(" regexp "\\)"))
509 desktop-clear-preserve-buffers
510 "\\|")
511 "\\)$")))
512 (while buffers
513 (let ((bufname (buffer-name (car buffers))))
514 (or
515 (null bufname)
516 (string-match preserve-regexp bufname)
517 ;; Don't kill buffers made for internal purposes.
518 (and (not (equal bufname "")) (eq (aref bufname 0) ?\s))
519 (kill-buffer (car buffers))))
520 (setq buffers (cdr buffers))))
521 (delete-other-windows))
522
523 ;; ----------------------------------------------------------------------------
524 (add-hook 'kill-emacs-hook 'desktop-kill)
525
526 (defun desktop-kill ()
527 "If `desktop-save-mode' is non-nil, do what `desktop-save' says to do.
528 If the desktop should be saved and `desktop-dirname'
529 is nil, ask the user where to save the desktop."
530 (when
531 (and
532 desktop-save-mode
533 (let ((exists (file-exists-p (expand-file-name desktop-base-file-name desktop-dirname))))
534 (or
535 (eq desktop-save t)
536 (and exists (memq desktop-save '(ask-if-new if-exists)))
537 (and
538 (or
539 (memq desktop-save '(ask ask-if-new))
540 (and exists (eq desktop-save 'ask-if-exists)))
541 (y-or-n-p "Save desktop? ")))))
542 (unless desktop-dirname
543 (setq desktop-dirname
544 (file-name-as-directory
545 (expand-file-name
546 (call-interactively
547 (lambda (dir) (interactive "DDirectory for desktop file: ") dir))))))
548 (condition-case err
549 (desktop-save desktop-dirname)
550 (file-error
551 (unless (yes-or-no-p "Error while saving the desktop. Ignore? ")
552 (signal (car err) (cdr err)))))))
553
554 ;; ----------------------------------------------------------------------------
555 (defun desktop-list* (&rest args)
556 (if (null (cdr args))
557 (car args)
558 (setq args (nreverse args))
559 (let ((value (cons (nth 1 args) (car args))))
560 (setq args (cdr (cdr args)))
561 (while args
562 (setq value (cons (car args) value))
563 (setq args (cdr args)))
564 value)))
565
566 ;; ----------------------------------------------------------------------------
567 (defun desktop-internal-v2s (value)
568 "Convert VALUE to a pair (QUOTE . TXT); (eval (read TXT)) gives VALUE.
569 TXT is a string that when read and evaluated yields value.
570 QUOTE may be `may' (value may be quoted),
571 `must' (values must be quoted), or nil (value may not be quoted)."
572 (cond
573 ((or (numberp value) (null value) (eq t value) (keywordp value))
574 (cons 'may (prin1-to-string value)))
575 ((stringp value)
576 (let ((copy (copy-sequence value)))
577 (set-text-properties 0 (length copy) nil copy)
578 ;; Get rid of text properties because we cannot read them
579 (cons 'may (prin1-to-string copy))))
580 ((symbolp value)
581 (cons 'must (prin1-to-string value)))
582 ((vectorp value)
583 (let* ((special nil)
584 (pass1 (mapcar
585 (lambda (el)
586 (let ((res (desktop-internal-v2s el)))
587 (if (null (car res))
588 (setq special t))
589 res))
590 value)))
591 (if special
592 (cons nil (concat "(vector "
593 (mapconcat (lambda (el)
594 (if (eq (car el) 'must)
595 (concat "'" (cdr el))
596 (cdr el)))
597 pass1
598 " ")
599 ")"))
600 (cons 'may (concat "[" (mapconcat 'cdr pass1 " ") "]")))))
601 ((consp value)
602 (let ((p value)
603 newlist
604 use-list*
605 anynil)
606 (while (consp p)
607 (let ((q.txt (desktop-internal-v2s (car p))))
608 (or anynil (setq anynil (null (car q.txt))))
609 (setq newlist (cons q.txt newlist)))
610 (setq p (cdr p)))
611 (if p
612 (let ((last (desktop-internal-v2s p))
613 (el (car newlist)))
614 (or anynil (setq anynil (null (car last))))
615 (or anynil
616 (setq newlist (cons '(must . ".") newlist)))
617 (setq use-list* t)
618 (setq newlist (cons last newlist))))
619 (setq newlist (nreverse newlist))
620 (if anynil
621 (cons nil
622 (concat (if use-list* "(desktop-list* " "(list ")
623 (mapconcat (lambda (el)
624 (if (eq (car el) 'must)
625 (concat "'" (cdr el))
626 (cdr el)))
627 newlist
628 " ")
629 ")"))
630 (cons 'must
631 (concat "(" (mapconcat 'cdr newlist " ") ")")))))
632 ((subrp value)
633 (cons nil (concat "(symbol-function '"
634 (substring (prin1-to-string value) 7 -1)
635 ")")))
636 ((markerp value)
637 (let ((pos (prin1-to-string (marker-position value)))
638 (buf (prin1-to-string (buffer-name (marker-buffer value)))))
639 (cons nil (concat "(let ((mk (make-marker)))"
640 " (add-hook 'desktop-delay-hook"
641 " (list 'lambda '() (list 'set-marker mk "
642 pos " (get-buffer " buf ")))) mk)"))))
643 (t ; save as text
644 (cons 'may "\"Unprintable entity\""))))
645
646 ;; ----------------------------------------------------------------------------
647 (defun desktop-value-to-string (value)
648 "Convert VALUE to a string that when read evaluates to the same value.
649 Not all types of values are supported."
650 (let* ((print-escape-newlines t)
651 (float-output-format nil)
652 (quote.txt (desktop-internal-v2s value))
653 (quote (car quote.txt))
654 (txt (cdr quote.txt)))
655 (if (eq quote 'must)
656 (concat "'" txt)
657 txt)))
658
659 ;; ----------------------------------------------------------------------------
660 (defun desktop-outvar (varspec)
661 "Output a setq statement for variable VAR to the desktop file.
662 The argument VARSPEC may be the variable name VAR (a symbol),
663 or a cons cell of the form (VAR . MAX-SIZE),
664 which means to truncate VAR's value to at most MAX-SIZE elements
665 \(if the value is a list) before saving the value."
666 (let (var size)
667 (if (consp varspec)
668 (setq var (car varspec) size (cdr varspec))
669 (setq var varspec))
670 (if (boundp var)
671 (progn
672 (if (and (integerp size)
673 (> size 0)
674 (listp (eval var)))
675 (desktop-truncate (eval var) size))
676 (insert "(setq "
677 (symbol-name var)
678 " "
679 (desktop-value-to-string (symbol-value var))
680 ")\n")))))
681
682 ;; ----------------------------------------------------------------------------
683 (defun desktop-save-buffer-p (filename bufname mode &rest dummy)
684 "Return t if buffer should have its state saved in the desktop file.
685 FILENAME is the visited file name, BUFNAME is the buffer name, and
686 MODE is the major mode."
687 (let ((case-fold-search nil))
688 (and (not (string-match desktop-buffers-not-to-save bufname))
689 (not (memq mode desktop-modes-not-to-save))
690 (or (and filename
691 (not (string-match desktop-files-not-to-save filename)))
692 (and (eq mode 'dired-mode)
693 (with-current-buffer bufname
694 (not (string-match desktop-files-not-to-save
695 default-directory))))
696 (and (null filename)
697 (with-current-buffer bufname desktop-save-buffer))))))
698
699 ;; ----------------------------------------------------------------------------
700 (defun desktop-file-name (filename dirname)
701 "Convert FILENAME to format specified in `desktop-file-name-format'.
702 DIRNAME must be the directory in which the desktop file will be saved."
703 (cond
704 ((not filename) nil)
705 ((eq desktop-file-name-format 'tilde)
706 (let ((relative-name (file-relative-name (expand-file-name filename) "~")))
707 (cond
708 ((file-name-absolute-p relative-name) relative-name)
709 ((string= "./" relative-name) "~/")
710 ((string= "." relative-name) "~")
711 (t (concat "~/" relative-name)))))
712 ((eq desktop-file-name-format 'local) (file-relative-name filename dirname))
713 (t (expand-file-name filename))))
714
715 ;; ----------------------------------------------------------------------------
716 (defun desktop-save (dirname)
717 "Save the desktop in a desktop file.
718 Parameter DIRNAME specifies where to save the desktop file.
719 See also `desktop-base-file-name'."
720 (interactive "DDirectory to save desktop file in: ")
721 (run-hooks 'desktop-save-hook)
722 (setq dirname (file-name-as-directory (expand-file-name dirname)))
723 (save-excursion
724 (let ((filename (expand-file-name desktop-base-file-name dirname))
725 (info
726 (mapcar
727 #'(lambda (b)
728 (set-buffer b)
729 (list
730 (desktop-file-name (buffer-file-name) dirname)
731 (buffer-name)
732 major-mode
733 ;; minor modes
734 (let (ret)
735 (mapc
736 #'(lambda (minor-mode)
737 (and
738 (boundp minor-mode)
739 (symbol-value minor-mode)
740 (let* ((special (assq minor-mode desktop-minor-mode-table))
741 (value (cond (special (cadr special))
742 ((functionp minor-mode) minor-mode))))
743 (when value (add-to-list 'ret value)))))
744 (mapcar #'car minor-mode-alist))
745 ret)
746 (point)
747 (list (mark t) mark-active)
748 buffer-read-only
749 ;; Auxiliary information
750 (when (functionp desktop-save-buffer)
751 (funcall desktop-save-buffer dirname))
752 (let ((locals desktop-locals-to-save)
753 (loclist (buffer-local-variables))
754 (ll))
755 (while locals
756 (let ((here (assq (car locals) loclist)))
757 (if here
758 (setq ll (cons here ll))
759 (when (member (car locals) loclist)
760 (setq ll (cons (car locals) ll)))))
761 (setq locals (cdr locals)))
762 ll)))
763 (buffer-list)))
764 (eager desktop-restore-eager)
765 (buf (get-buffer-create "*desktop*")))
766 (set-buffer buf)
767 (erase-buffer)
768
769 (insert
770 ";; -*- mode: emacs-lisp; coding: emacs-mule; -*-\n"
771 desktop-header
772 ";; Created " (current-time-string) "\n"
773 ";; Desktop file format version " desktop-file-version "\n"
774 ";; Emacs version " emacs-version "\n\n"
775 ";; Global section:\n")
776 (mapc (function desktop-outvar) desktop-globals-to-save)
777 (if (memq 'kill-ring desktop-globals-to-save)
778 (insert
779 "(setq kill-ring-yank-pointer (nthcdr "
780 (int-to-string (- (length kill-ring) (length kill-ring-yank-pointer)))
781 " kill-ring))\n"))
782
783 (insert "\n;; Buffer section -- buffers listed in same order as in buffer list:\n")
784 (mapc #'(lambda (l)
785 (when (apply 'desktop-save-buffer-p l)
786 (insert "("
787 (if (or (not (integerp eager))
788 (unless (zerop eager)
789 (setq eager (1- eager))
790 t))
791 "desktop-create-buffer"
792 "desktop-append-buffer-args")
793 " "
794 desktop-file-version)
795 (mapc #'(lambda (e)
796 (insert "\n " (desktop-value-to-string e)))
797 l)
798 (insert ")\n\n")))
799 info)
800 (setq default-directory dirname)
801 (let ((coding-system-for-write 'emacs-mule))
802 (write-region (point-min) (point-max) filename nil 'nomessage))))
803 (setq desktop-dirname dirname))
804
805 ;; ----------------------------------------------------------------------------
806 (defun desktop-remove ()
807 "Delete desktop file in `desktop-dirname'.
808 This function also sets `desktop-dirname' to nil."
809 (interactive)
810 (when desktop-dirname
811 (let ((filename (expand-file-name desktop-base-file-name desktop-dirname)))
812 (setq desktop-dirname nil)
813 (when (file-exists-p filename)
814 (delete-file filename)))))
815
816 (defvar desktop-buffer-args-list nil
817 "List of args for `desktop-create-buffer'.")
818
819 (defvar desktop-lazy-timer nil)
820
821 ;; ----------------------------------------------------------------------------
822 ;;;###autoload
823 (defun desktop-read (&optional dirname)
824 "Read and process the desktop file in directory DIRNAME.
825 Look for a desktop file in DIRNAME, or if DIRNAME is omitted, look in
826 directories listed in `desktop-path'. If a desktop file is found, it
827 is processed and `desktop-after-read-hook' is run. If no desktop file
828 is found, clear the desktop and run `desktop-no-desktop-file-hook'.
829 This function is a no-op when Emacs is running in batch mode.
830 It returns t if a desktop file was loaded, nil otherwise."
831 (interactive)
832 (unless noninteractive
833 (setq desktop-dirname
834 (file-name-as-directory
835 (expand-file-name
836 (or
837 ;; If DIRNAME is specified, use it.
838 (and (< 0 (length dirname)) dirname)
839 ;; Otherwise search desktop file in desktop-path.
840 (let ((dirs desktop-path))
841 (while
842 (and
843 dirs
844 (not
845 (file-exists-p (expand-file-name desktop-base-file-name (car dirs)))))
846 (setq dirs (cdr dirs)))
847 (and dirs (car dirs)))
848 ;; If not found and `desktop-path' is non-nil, use its first element.
849 (and desktop-path (car desktop-path))
850 ;; Default: Home directory.
851 "~"))))
852 (if (file-exists-p (expand-file-name desktop-base-file-name desktop-dirname))
853 ;; Desktop file found, process it.
854 (let ((desktop-first-buffer nil)
855 (desktop-buffer-ok-count 0)
856 (desktop-buffer-fail-count 0))
857 (setq desktop-lazy-timer nil)
858 ;; Evaluate desktop buffer.
859 (load (expand-file-name desktop-base-file-name desktop-dirname) t t t)
860 ;; `desktop-create-buffer' puts buffers at end of the buffer list.
861 ;; We want buffers existing prior to evaluating the desktop (and not reused)
862 ;; to be placed at the end of the buffer list, so we move them here.
863 (mapc 'bury-buffer
864 (nreverse (cdr (memq desktop-first-buffer (nreverse (buffer-list))))))
865 (switch-to-buffer (car (buffer-list)))
866 (run-hooks 'desktop-delay-hook)
867 (setq desktop-delay-hook nil)
868 (run-hooks 'desktop-after-read-hook)
869 (message "Desktop: %d buffer%s restored%s%s."
870 desktop-buffer-ok-count
871 (if (= 1 desktop-buffer-ok-count) "" "s")
872 (if (< 0 desktop-buffer-fail-count)
873 (format ", %d failed to restore" desktop-buffer-fail-count)
874 "")
875 (if desktop-buffer-args-list
876 (format ", %d to restore lazily"
877 (length desktop-buffer-args-list))
878 ""))
879 t)
880 ;; No desktop file found.
881 (desktop-clear)
882 (let ((default-directory desktop-dirname))
883 (run-hooks 'desktop-no-desktop-file-hook))
884 (message "No desktop file.")
885 nil)))
886
887 ;; ----------------------------------------------------------------------------
888 ;; Maintained for backward compatibility
889 ;;;###autoload
890 (defun desktop-load-default ()
891 "Load the `default' start-up library manually.
892 Also inhibit further loading of it."
893 (unless inhibit-default-init ; safety check
894 (load "default" t t)
895 (setq inhibit-default-init t)))
896 (make-obsolete 'desktop-load-default
897 'desktop-save-mode "22.1")
898
899 ;; ----------------------------------------------------------------------------
900 ;;;###autoload
901 (defun desktop-change-dir (dirname)
902 "Change to desktop saved in DIRNAME.
903 Kill the desktop as specified by variables `desktop-save-mode' and
904 `desktop-save', then clear the desktop and load the desktop file in
905 directory DIRNAME."
906 (interactive "DChange to directory: ")
907 (setq dirname (file-name-as-directory (expand-file-name dirname desktop-dirname)))
908 (desktop-kill)
909 (desktop-clear)
910 (desktop-read dirname))
911
912 ;; ----------------------------------------------------------------------------
913 ;;;###autoload
914 (defun desktop-save-in-desktop-dir ()
915 "Save the desktop in directory `desktop-dirname'."
916 (interactive)
917 (if desktop-dirname
918 (desktop-save desktop-dirname)
919 (call-interactively 'desktop-save))
920 (message "Desktop saved in %s" desktop-dirname))
921
922 ;; ----------------------------------------------------------------------------
923 ;;;###autoload
924 (defun desktop-revert ()
925 "Revert to the last loaded desktop."
926 (interactive)
927 (unless desktop-dirname
928 (error "Unknown desktop directory"))
929 (unless (file-exists-p (expand-file-name desktop-base-file-name desktop-dirname))
930 (error "No desktop file found"))
931 (desktop-clear)
932 (desktop-read desktop-dirname))
933
934 ;; ----------------------------------------------------------------------------
935 (defun desktop-restore-file-buffer (desktop-buffer-file-name
936 desktop-buffer-name
937 desktop-buffer-misc)
938 "Restore a file buffer."
939 (eval-when-compile ; Just to silence the byte compiler
940 (defvar desktop-buffer-major-mode)
941 (defvar desktop-buffer-locals))
942 (if desktop-buffer-file-name
943 (if (or (file-exists-p desktop-buffer-file-name)
944 (let ((msg (format "Desktop: File \"%s\" no longer exists."
945 desktop-buffer-file-name)))
946 (if desktop-missing-file-warning
947 (y-or-n-p (concat msg " Re-create? "))
948 (message "%s" msg)
949 nil)))
950 (let* ((auto-insert nil) ; Disable auto insertion
951 (coding-system-for-read
952 (or coding-system-for-read
953 (cdr (assq 'buffer-file-coding-system
954 desktop-buffer-locals))))
955 (buf (find-file-noselect desktop-buffer-file-name)))
956 (condition-case nil
957 (switch-to-buffer buf)
958 (error (pop-to-buffer buf)))
959 (and (not (eq major-mode desktop-buffer-major-mode))
960 (functionp desktop-buffer-major-mode)
961 (funcall desktop-buffer-major-mode))
962 buf)
963 nil)))
964
965 (defun desktop-load-file (function)
966 "Load the file where auto loaded FUNCTION is defined."
967 (when function
968 (let ((fcell (symbol-function function)))
969 (when (and (listp fcell)
970 (eq 'autoload (car fcell)))
971 (load (cadr fcell))))))
972
973 ;; ----------------------------------------------------------------------------
974 ;; Create a buffer, load its file, set its mode, ...;
975 ;; called from Desktop file only.
976
977 ;; Just to silence the byte compiler.
978 (eval-when-compile
979 (defvar desktop-first-buffer)) ; Dynamically bound in `desktop-read'
980
981 (defun desktop-create-buffer
982 (desktop-file-version
983 desktop-buffer-file-name
984 desktop-buffer-name
985 desktop-buffer-major-mode
986 desktop-buffer-minor-modes
987 desktop-buffer-point
988 desktop-buffer-mark
989 desktop-buffer-read-only
990 desktop-buffer-misc
991 &optional
992 desktop-buffer-locals)
993 ;; Just to silence the byte compiler. Bound locally in `desktop-read'.
994 (eval-when-compile
995 (defvar desktop-buffer-ok-count)
996 (defvar desktop-buffer-fail-count))
997 ;; To make desktop files with relative file names possible, we cannot
998 ;; allow `default-directory' to change. Therefore we save current buffer.
999 (save-current-buffer
1000 ;; Give major mode module a chance to add a handler.
1001 (desktop-load-file desktop-buffer-major-mode)
1002 (let ((buffer-list (buffer-list))
1003 (result
1004 (condition-case err
1005 (funcall (or (cdr (assq desktop-buffer-major-mode
1006 desktop-buffer-mode-handlers))
1007 'desktop-restore-file-buffer)
1008 desktop-buffer-file-name
1009 desktop-buffer-name
1010 desktop-buffer-misc)
1011 (error
1012 (message "Desktop: Can't load buffer %s: %s"
1013 desktop-buffer-name
1014 (error-message-string err))
1015 (when desktop-missing-file-warning (sit-for 1))
1016 nil))))
1017 (if (bufferp result)
1018 (setq desktop-buffer-ok-count (1+ desktop-buffer-ok-count))
1019 (setq desktop-buffer-fail-count (1+ desktop-buffer-fail-count))
1020 (setq result nil))
1021 ;; Restore buffer list order with new buffer at end. Don't change
1022 ;; the order for old desktop files (old desktop module behaviour).
1023 (unless (< desktop-file-version 206)
1024 (mapc 'bury-buffer buffer-list)
1025 (when result (bury-buffer result)))
1026 (when result
1027 (unless (or desktop-first-buffer (< desktop-file-version 206))
1028 (setq desktop-first-buffer result))
1029 (set-buffer result)
1030 (unless (equal (buffer-name) desktop-buffer-name)
1031 (rename-buffer desktop-buffer-name))
1032 ;; minor modes
1033 (cond ((equal '(t) desktop-buffer-minor-modes) ; backwards compatible
1034 (auto-fill-mode 1))
1035 ((equal '(nil) desktop-buffer-minor-modes) ; backwards compatible
1036 (auto-fill-mode 0))
1037 (t
1038 (mapc #'(lambda (minor-mode)
1039 ;; Give minor mode module a chance to add a handler.
1040 (desktop-load-file minor-mode)
1041 (let ((handler (cdr (assq minor-mode desktop-minor-mode-handlers))))
1042 (if handler
1043 (funcall handler desktop-buffer-locals)
1044 (when (functionp minor-mode)
1045 (funcall minor-mode 1)))))
1046 desktop-buffer-minor-modes)))
1047 ;; Even though point and mark are non-nil when written by `desktop-save',
1048 ;; they may be modified by handlers wanting to set point or mark themselves.
1049 (when desktop-buffer-point
1050 (goto-char
1051 (condition-case err
1052 ;; Evaluate point. Thus point can be something like '(search-forward ...
1053 (eval desktop-buffer-point)
1054 (error (message "%s" (error-message-string err)) 1))))
1055 (when desktop-buffer-mark
1056 (if (consp desktop-buffer-mark)
1057 (progn
1058 (set-mark (car desktop-buffer-mark))
1059 (setq mark-active (car (cdr desktop-buffer-mark))))
1060 (set-mark desktop-buffer-mark)))
1061 ;; Never override file system if the file really is read-only marked.
1062 (if desktop-buffer-read-only (setq buffer-read-only desktop-buffer-read-only))
1063 (while desktop-buffer-locals
1064 (let ((this (car desktop-buffer-locals)))
1065 (if (consp this)
1066 ;; an entry of this form `(symbol . value)'
1067 (progn
1068 (make-local-variable (car this))
1069 (set (car this) (cdr this)))
1070 ;; an entry of the form `symbol'
1071 (make-local-variable this)
1072 (makunbound this)))
1073 (setq desktop-buffer-locals (cdr desktop-buffer-locals)))))))
1074
1075 ;; ----------------------------------------------------------------------------
1076 ;; Backward compatibility -- update parameters to 205 standards.
1077 (defun desktop-buffer (desktop-buffer-file-name desktop-buffer-name
1078 desktop-buffer-major-mode
1079 mim pt mk ro tl fc cfs cr desktop-buffer-misc)
1080 (desktop-create-buffer 205 desktop-buffer-file-name desktop-buffer-name
1081 desktop-buffer-major-mode (cdr mim) pt mk ro
1082 desktop-buffer-misc
1083 (list (cons 'truncate-lines tl)
1084 (cons 'fill-column fc)
1085 (cons 'case-fold-search cfs)
1086 (cons 'case-replace cr)
1087 (cons 'overwrite-mode (car mim)))))
1088
1089 (defun desktop-append-buffer-args (&rest args)
1090 "Append ARGS at end of `desktop-buffer-args-list'.
1091 ARGS must be an argument list for `desktop-create-buffer'."
1092 (setq desktop-buffer-args-list (nconc desktop-buffer-args-list (list args)))
1093 (unless desktop-lazy-timer
1094 (setq desktop-lazy-timer
1095 (run-with-idle-timer desktop-lazy-idle-delay t 'desktop-idle-create-buffers))))
1096
1097 (defun desktop-lazy-create-buffer ()
1098 "Pop args from `desktop-buffer-args-list', create buffer and bury it."
1099 (when desktop-buffer-args-list
1100 (let* ((remaining (length desktop-buffer-args-list))
1101 (args (pop desktop-buffer-args-list))
1102 (buffer-name (nth 2 args))
1103 (msg (format "Desktop lazily opening %s (%s remaining)..."
1104 buffer-name remaining)))
1105 (when desktop-lazy-verbose
1106 (message "%s" msg))
1107 (let ((desktop-first-buffer nil)
1108 (desktop-buffer-ok-count 0)
1109 (desktop-buffer-fail-count 0))
1110 (apply 'desktop-create-buffer args)
1111 (run-hooks 'desktop-delay-hook)
1112 (setq desktop-delay-hook nil)
1113 (bury-buffer (get-buffer buffer-name))
1114 (when desktop-lazy-verbose
1115 (message "%s%s" msg (if (> desktop-buffer-ok-count 0) "done" "failed")))))))
1116
1117 (defun desktop-idle-create-buffers ()
1118 "Create buffers until the user does something, then stop.
1119 If there are no buffers left to create, kill the timer."
1120 (let ((repeat 1))
1121 (while (and repeat desktop-buffer-args-list)
1122 (save-window-excursion
1123 (desktop-lazy-create-buffer))
1124 (setq repeat (sit-for 0.2))
1125 (unless desktop-buffer-args-list
1126 (cancel-timer desktop-lazy-timer)
1127 (setq desktop-lazy-timer nil)
1128 (message "Lazy desktop load complete")
1129 (sit-for 3)
1130 (message "")))))
1131
1132 (defun desktop-lazy-complete ()
1133 "Run the desktop load to completion."
1134 (interactive)
1135 (let ((desktop-lazy-verbose t))
1136 (while desktop-buffer-args-list
1137 (save-window-excursion
1138 (desktop-lazy-create-buffer)))
1139 (message "Lazy desktop load complete")))
1140
1141 (defun desktop-lazy-abort ()
1142 "Abort lazy loading of the desktop."
1143 (interactive)
1144 (when desktop-lazy-timer
1145 (cancel-timer desktop-lazy-timer)
1146 (setq desktop-lazy-timer nil))
1147 (when desktop-buffer-args-list
1148 (setq desktop-buffer-args-list nil)
1149 (when (interactive-p)
1150 (message "Lazy desktop load aborted"))))
1151
1152 ;; ----------------------------------------------------------------------------
1153 ;; When `desktop-save-mode' is non-nil and "--no-desktop" is not specified on the
1154 ;; command line, we do the rest of what it takes to use desktop, but do it
1155 ;; after finishing loading the init file.
1156 ;; We cannot use `command-switch-alist' to process "--no-desktop" because these
1157 ;; functions are processed after `after-init-hook'.
1158 (add-hook
1159 'after-init-hook
1160 '(lambda ()
1161 (let ((key "--no-desktop"))
1162 (when (member key command-line-args)
1163 (setq command-line-args (delete key command-line-args))
1164 (setq desktop-save-mode nil)))
1165 (when desktop-save-mode (desktop-read))))
1166
1167 (provide 'desktop)
1168
1169 ;;; arch-tag: 221907c3-1771-4fd3-9c2e-c6f700c6ede9
1170 ;;; desktop.el ends here