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