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