*** empty log message ***
[gnus] / lisp / custom.el
1 ;;; custom.el --- User friendly customization support.
2 ;; Copyright (C) 1995 Free Software Foundation, Inc.
3 ;;
4 ;; Author: Per Abrahamsen <abraham@iesd.auc.dk>
5 ;; Keywords: help
6 ;; Version: 0.5
7
8 ;;; Commentary:
9 ;;
10 ;; WARNING: This package is still under construction and not all of
11 ;; the features below are implemented.
12 ;;
13 ;; This package provides a framework for adding user friendly
14 ;; customization support to Emacs.  Having to do customization by
15 ;; editing a text file in some arcane syntax is user hostile in the
16 ;; extreme, and to most users emacs lisp definitely count as arcane.
17 ;;
18 ;; The intension is that authors of emacs lisp packages declare the
19 ;; variables intended for user customization with `custom-declare'.
20 ;; Custom can then automatically generate a customization buffer with
21 ;; `custom-buffer-create' where the user can edit the package
22 ;; variables in a simple and intuitive way, as well as a menu with
23 ;; `custom-menu-create' where he can set the more commonly used
24 ;; variables interactively.
25 ;;
26 ;; It is also possible to use custom for modifying the properties of
27 ;; other objects than the package itself, by specifying extra optional
28 ;; arguments to `custom-buffer-create'.
29 ;;
30 ;; Custom is inspired by OPEN LOOK property windows.
31
32 ;;; Todo:  
33 ;;
34 ;; - Toggle documentation in three states `none', `one-line', `full'.
35 ;; - Function to generate an XEmacs menu from a CUSTOM.
36 ;; - Write TeXinfo documentation.
37 ;; - Make it possible to hide sections by clicking at the level.
38 ;; - Declare AUC TeX variables.
39 ;; - Declare (ding) Gnus variables.
40 ;; - Declare Emacs variables.
41 ;; - Implement remaining types.
42 ;; - XEmacs port.
43 ;; - Allow `URL', `info', and internal hypertext buttons.
44 ;; - Support meta-variables and goal directed customization.
45 ;; - Make it easy to declare custom types independently.
46 ;; - Make it possible to declare default value and type for a single
47 ;;   variable, storing the data in a symbol property.
48 ;; - Syntactic sugar for CUSTOM declarations.
49 ;; - Use W3 for variable documenation.
50
51 ;;; Code:
52
53 ;;; Compatibility:
54
55 (or (fboundp 'buffer-substring-no-properties)
56     ;; Introduced in Emacs 19.29.
57     (defun buffer-substring-no-properties (beg end)
58       "Return the text from BEG to END, without text properties, as a string."
59       (let ((string (buffer-substring beg end)))
60         (custom-set-text-properties 0 (length string) nil string)
61         string)))
62
63 (or (fboundp 'add-to-list)
64     ;; Introduced in Emacs 19.29.
65     (defun add-to-list (list-var element)
66       "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
67 If you want to use `add-to-list' on a variable that is not defined
68 until a certain package is loaded, you should put the call to `add-to-list'
69 into a hook function that will be run only after loading the package.
70 `eval-after-load' provides one way to do this.  In some cases
71 other hooks, such as major mode hooks, can do the job."
72       (or (member element (symbol-value list-var))
73           (set list-var (cons element (symbol-value list-var))))))
74
75 (or (fboundp 'plist-get)
76     ;; Introduced in Emacs 19.29.
77     (defun plist-get (plist prop)
78       "Extract a value from a property list.
79 PLIST is a property list, which is a list of the form
80 \(PROP1 VALUE1 PROP2 VALUE2...).  This function returns the value
81 corresponding to the given PROP, or nil if PROP is not
82 one of the properties on the list."
83       (let (result)
84         (while plist
85           (if (eq (car plist) prop)
86               (setq result (car (cdr plist))
87                     plist nil)
88             (set plist (cdr (cdr plist)))))
89         result)))
90
91 (or (fboundp 'plist-put)
92     ;; Introduced in Emacs 19.29.
93     (defun plist-put (plist prop val)    
94       "Change value in PLIST of PROP to VAL.
95 PLIST is a property list, which is a list of the form
96 \(PROP1 VALUE1 PROP2 VALUE2 ...).  PROP is a symbol and VAL is any object.
97 If PROP is already a property on the list, its value is set to VAL,
98 otherwise the new PROP VAL pair is added.  The new plist is returned;
99 use `(setq x (plist-put x prop val))' to be sure to use the new value.
100 The PLIST is modified by side effects."
101       (if (null plist)
102           (list prop val)
103         (let ((current plist))
104           (while current
105             (cond ((eq (car current) prop)
106                    (setcar (cdr current) val)
107                    (setq current nil))
108                   ((null (cdr (cdr current)))
109                    (setcdr (cdr current) (list prop val))
110                    (setq current nil))
111                   (t
112                    (setq current (cdr (cdr current)))))))
113         plist)))
114
115 (or (fboundp 'match-string)
116     ;; Introduced in Emacs 19.29.
117     (defun match-string (num &optional string)
118   "Return string of text matched by last search.
119 NUM specifies which parenthesized expression in the last regexp.
120  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
121 Zero means the entire text matched by the whole regexp or whole string.
122 STRING should be given if the last search was by `string-match' on STRING."
123   (if (match-beginning num)
124       (if string
125           (substring string (match-beginning num) (match-end num))
126         (buffer-substring (match-beginning num) (match-end num))))))
127
128 (or (fboundp 'facep)
129     ;; Introduced in Emacs 19.29.
130     (defun facep (x)
131       "Return t if X is a face name or an internal face vector."
132       (and (or (and (fboundp 'internal-facep) (internal-facep x))
133                (and 
134                 (symbolp x) 
135                 (assq x (and (boundp 'global-face-data) global-face-data))))
136            t)))
137
138 ;; XEmacs and Emacs 19.29 facep does different things.
139 (if (fboundp 'find-face)
140     (fset 'custom-facep 'find-face)
141   (fset 'custom-facep 'facep))
142
143 (if (custom-facep 'underline)
144     ()
145   ;; No underline face in XEmacs 19.12.
146   (and (fboundp 'make-face)
147        (funcall (intern "make-face") 'underline))
148   ;; Must avoid calling set-face-underline-p directly, because it
149   ;; is a defsubst in emacs19, and will make the .elc files non
150   ;; portable!
151   (or (and (fboundp 'face-differs-from-default-p)
152            (face-differs-from-default-p 'underline))
153       (and (fboundp 'set-face-underline-p)
154            (funcall 'set-face-underline-p 'underline t))))
155
156 (defun custom-xmas-set-text-properties (start end props &optional buffer)
157   "You should NEVER use this function.  It is ideologically blasphemous.
158 It is provided only to ease porting of broken FSF Emacs programs."
159   (if (stringp buffer) 
160       nil
161     (map-extents (lambda (extent ignored)
162                    (remove-text-properties 
163                     start end
164                     (list (extent-property extent 'text-prop) nil)
165                     buffer))
166                  buffer start end nil nil 'text-prop)
167     (add-text-properties start end props buffer)))
168
169 (if (string-match "XEmacs" emacs-version)
170     (fset 'custom-set-text-properties 'gnus-xmas-set-text-properties)
171   (fset 'custom-set-text-properties 'set-text-properties))
172
173 (or (fboundp 'event-point)
174     ;; Missing in Emacs 19.29.
175     (defun event-point (event)
176       "Return the character position of the given mouse-motion, button-press,
177 or button-release event.  If the event did not occur over a window, or did
178 not occur over text, then this returns nil.  Otherwise, it returns an index
179 into the buffer visible in the event's window."
180       (posn-point (event-start event))))
181
182 (eval-when-compile
183   (defvar x-colors nil)
184   (defvar custom-button-face nil)
185   (defvar custom-field-uninitialized-face nil)
186   (defvar custom-field-invalid-face nil)
187   (defvar custom-field-modified-face nil)
188   (defvar custom-field-face nil)
189   (defvar custom-mouse-face nil)
190   (defvar custom-field-active-face nil))
191
192 (or (and (fboundp 'modify-face) (not (featurep 'face-lock)))
193     ;; Introduced in Emacs 19.29.  Incompatible definition also introduced
194     ;; by face-lock.el version 3.00 and above for Emacs 19.28 and below.
195     ;; face-lock does not call modify-face, so we can safely redefine it.
196     (defun modify-face (face foreground background stipple
197                              bold-p italic-p underline-p)
198   "Change the display attributes for face FACE.
199 FOREGROUND and BACKGROUND should be color strings or nil.
200 STIPPLE should be a stipple pattern name or nil.
201 BOLD-P, ITALIC-P, and UNDERLINE-P specify whether the face should be set bold,
202 in italic, and underlined, respectively.  (Yes if non-nil.)
203 If called interactively, prompts for a face and face attributes."
204   (interactive
205    (let* ((completion-ignore-case t)
206           (face        (symbol-name (read-face-name "Modify face: ")))
207           (colors      (mapcar 'list x-colors))
208           (stipples    (mapcar 'list
209                                (apply 'nconc
210                                       (mapcar 'directory-files
211                                               x-bitmap-file-path))))
212           (foreground  (modify-face-read-string
213                         face (face-foreground (intern face))
214                         "foreground" colors))
215           (background  (modify-face-read-string
216                         face (face-background (intern face))
217                         "background" colors))
218           (stipple     (modify-face-read-string
219                         face (face-stipple (intern face))
220                         "stipple" stipples))
221           (bold-p      (y-or-n-p (concat "Set face " face " bold ")))
222           (italic-p    (y-or-n-p (concat "Set face " face " italic ")))
223           (underline-p (y-or-n-p (concat "Set face " face " underline "))))
224      (message "Face %s: %s" face
225       (mapconcat 'identity
226        (delq nil
227         (list (and foreground (concat (downcase foreground) " foreground"))
228               (and background (concat (downcase background) " background"))
229               (and stipple (concat (downcase stipple) " stipple"))
230               (and bold-p "bold") (and italic-p "italic")
231               (and underline-p "underline"))) ", "))
232      (list (intern face) foreground background stipple
233            bold-p italic-p underline-p)))
234   (condition-case nil (set-face-foreground face foreground) (error nil))
235   (condition-case nil (set-face-background face background) (error nil))
236   (condition-case nil (set-face-stipple face stipple) (error nil))
237   (if (string-match "XEmacs" emacs-version)
238       (progn
239         (funcall (if bold-p 'make-face-bold 'make-face-unbold) face)
240         (funcall (if italic-p 'make-face-italic 'make-face-unitalic) face))
241     (funcall (if bold-p 'make-face-bold 'make-face-unbold) face nil t)
242     (funcall (if italic-p 'make-face-italic 'make-face-unitalic) face nil t))
243   (set-face-underline-p face underline-p)
244   (and (interactive-p) (redraw-display))))
245
246 ;; We can't easily check for a working intangible.
247 (defconst intangible (if (and (boundp 'emacs-minor-version)
248                               (or (> emacs-major-version 19)
249                                   (and (> emacs-major-version 18)
250                                        (> emacs-minor-version 28))))
251                          (setq intangible 'intangible)
252                        (setq intangible 'intangible-if-it-had-been-working))
253   "The symbol making text intangible")
254
255 (defconst rear-nonsticky (if (string-match "XEmacs" emacs-version)
256                              'end-open
257                            'rear-nonsticky)
258   "The symbol making text proeprties non-sticky in the rear end.")
259
260 (defconst front-sticky (if (string-match "XEmacs" emacs-version)
261                            'front-closed
262                          'front-sticky)
263   "The symbol making text properties sticky in the front.")
264
265 (defconst mouse-face (if (string-match "XEmacs" emacs-version)
266                          'highlight
267                        'mouse-face)
268   "Symbol used for highlighting text under mouse.")
269
270 ;; Put it in the Help menu, if possible.
271 (if (string-match "XEmacs" emacs-version)
272     ;; XEmacs (disabled because it doesn't work)
273     (and current-menubar
274          (add-menu-item '("Help") "Customize..." 'customize nil))
275   ;; Emacs 19.28 and earlier
276   (global-set-key [ menu-bar help customize ]
277                   '("Customize..." . customize))
278   ;; Emacs 19.29 and later
279   (global-set-key [ menu-bar help-menu customize ] 
280                   '("Customize..." . customize)))
281
282 ;; XEmacs popup-menu stolen from w3.el.
283 (defun custom-x-really-popup-menu (pos title menudesc)
284   "My hacked up function to do a blocking popup menu..."
285   (let ((echo-keystrokes 0)
286         event menu)
287     (while menudesc
288       (setq menu (cons (vector (car (car menudesc))
289                                (list (car (car menudesc))) t) menu)
290             menudesc (cdr menudesc)))
291     (setq menu (cons title menu))
292     (popup-menu menu)
293     (catch 'popup-done
294       (while t
295         (setq event (next-command-event event))
296         (cond ((and (misc-user-event-p event) (stringp (car-safe                                                   (event-object event))))
297                (throw 'popup-done (event-object event)))
298               ((and (misc-user-event-p event)
299                     (or (eq (event-object event) 'abort)
300                         (eq (event-object event) 'menu-no-selection-hook)))
301                nil)
302               ((not (popup-menu-up-p))
303                (throw 'popup-done nil))
304               ((button-release-event-p event);; don't beep twice
305                nil)
306               (t
307                (beep)
308                (message "please make a choice from the menu.")))))))
309
310 ;;; Categories:
311 ;;
312 ;; XEmacs use inheritable extents for the same purpose as Emacs uses
313 ;; the category text property.
314
315 (if (string-match "XEmacs" emacs-version)
316     (progn 
317       ;; XEmacs categories.
318       (defun custom-category-create (name)
319         (set name (make-extent nil nil))
320         "Create a text property category named NAME.")
321
322       (defun custom-category-put (name property value)
323         "In CATEGORY set PROPERTY to VALUE."
324         (set-extent-property (symbol-value name) property value))
325       
326       (defun custom-category-get (name property)
327         "In CATEGORY get PROPERTY."
328         (extent-property (symbol-value name) property))
329       
330       (defun custom-category-set (from to category)
331         "Make text between FROM and TWO have category CATEGORY."
332         (let ((extent (make-extent from to)))
333           (set-extent-parent extent (symbol-value category)))))
334       
335   ;; Emacs categories.
336   (defun custom-category-create (name)
337     "Create a text property category named NAME."
338     (set name name))
339
340   (defun custom-category-put (name property value)
341     "In CATEGORY set PROPERTY to VALUE."
342     (put name property value))
343
344   (defun custom-category-get (name property)
345     "In CATEGORY get PROPERTY."
346     (get name property))
347
348   (defun custom-category-set (from to category)
349     "Make text between FROM and TWO have category CATEGORY."
350     (put-text-property from to 'category category)))
351
352 ;;; External Data:
353 ;; 
354 ;; The following functions and variables defines the interface for
355 ;; connecting a CUSTOM with an external entity, by default an emacs
356 ;; lisp variable.
357
358 (defvar custom-external 'default-value
359   "Function returning the external value of NAME.")
360
361 (defvar custom-external-set 'set-default
362   "Function setting the external value of NAME to VALUE.")
363
364 (defun custom-external (name)
365   "Get the external value associated with NAME."
366   (funcall custom-external name))
367
368 (defun custom-external-set (name value)
369   "Set the external value associated with NAME to VALUE."
370   (funcall custom-external-set name value))
371
372 (defvar custom-name-fields nil
373   "Alist of custom names and their associated editing field.")
374 (make-variable-buffer-local 'custom-name-fields)
375
376 (defun custom-name-enter (name field)
377   "Associate NAME with FIELD."
378   (if (null name)
379       ()
380     (custom-assert 'field)
381     (setq custom-name-fields (cons (cons name field) custom-name-fields))))
382
383 (defun custom-name-field (name)
384   "The editing field associated with NAME."
385   (cdr (assq name custom-name-fields)))
386
387 (defun custom-name-value (name)
388   "The value currently displayed for NAME in the customization buffer."
389   (let* ((field (custom-name-field name))
390          (custom (custom-field-custom field)))
391     (custom-field-parse field)
392     (funcall (custom-property custom 'export) custom
393              (car (custom-field-extract custom field)))))
394
395 (defvar custom-save 'custom-save
396   "Function that will save current customization buffer.")
397
398 ;;; Custom Functions:
399 ;;
400 ;; The following functions are part of the public interface to the
401 ;; CUSTOM datastructure.  Each CUSTOM describes a group of variables,
402 ;; a single variable, or a component of a structured variable.  The
403 ;; CUSTOM instances are part of two hiearachies, the first is the
404 ;; `part-of' hierarchy in which each CUSTOM is a component of another
405 ;; CUSTOM, except for the top level CUSTOM which is contained in
406 ;; `custom-data'.  The second hiearachy is a `is-a' type hierarchy
407 ;; where each CUSTOM is a leaf in the hierarchy defined by the `type'
408 ;; property and `custom-type-properties'.
409
410 (defvar custom-file "~/.custom.el"
411   "Name of file with customization information.")
412
413 (defconst custom-data
414   '((tag . "Emacs")
415     (doc . "The extensible self-documenting text editor.")
416     (type . group)
417     (data "\n"
418           ((header . nil)
419            (compact . t)
420            (type . group)
421            (doc . "\
422 Press [Save] to save any changes permanently after you are done editing.  
423 You can load customization information from other files by editing the
424 `File' field and pressing the [Load] button.  When you press [Save] the
425 customization information of all files you have loaded, plus any
426 changes you might have made manually, will be stored in the file 
427 specified by the `File' field.")
428            (data ((tag . "Load")
429                   (type . button)
430                   (query . custom-load))
431                  ((tag . "Save")
432                   (type . button)
433                   (query . custom-save))
434                  ((name . custom-file)
435                   (default . "~/.custom.el")
436                   (doc . "Name of file with customization information.\n")
437                   (tag . "File")
438                   (type . file))))))
439   "The global customization information.  
440 A custom association list.")
441
442 (defun custom-declare (path custom)
443   "Declare variables for customization.  
444 PATH is a list of tags leading to the place in the customization
445 hierarchy the new entry should be added.  CUSTOM is the entry to add."
446   (custom-initialize custom)
447   (let ((current (custom-travel-path custom-data path)))
448     (or (member custom (custom-data current))
449         (nconc (custom-data current) (list custom)))))
450
451 (put 'custom-declare 'lisp-indent-hook 1)
452
453 (defconst custom-type-properties
454   '((repeat (type . default)
455             ;; See `custom-match'.
456             (import . custom-repeat-import)
457             (eval . custom-repeat-eval)
458             (quote . custom-repeat-quote)
459             (accept . custom-repeat-accept)
460             (extract . custom-repeat-extract)
461             (validate . custom-repeat-validate)
462             (insert . custom-repeat-insert)
463             (match . custom-repeat-match)
464             (query . custom-repeat-query)
465             (prefix . "")
466             (del-tag . "[DEL]")
467             (add-tag . "[INS]"))
468     (pair (type . group)
469           ;; A cons-cell.
470           (accept . custom-pair-accept)
471           (eval . custom-pair-eval)
472           (import . custom-pair-import)
473           (quote . custom-pair-quote)
474           (valid . (lambda (c d) (consp d)))
475           (extract . custom-pair-extract))
476     (list (type . group)
477           ;; A lisp list.
478           (quote . custom-list-quote)
479           (valid . (lambda (c d)
480                      (listp d)))
481           (extract . custom-list-extract))
482     (group (type . default)
483            ;; See `custom-match'.
484            (face-tag . nil)
485            (eval . custom-group-eval)
486            (import . custom-group-import)
487            (initialize . custom-group-initialize)
488            (apply . custom-group-apply)
489            (reset . custom-group-reset)
490            (factory-reset . custom-group-factory-reset)
491            (extract . nil)
492            (validate . custom-group-validate)
493            (query . custom-toggle-hide)
494            (accept . custom-group-accept)
495            (insert . custom-group-insert)
496            (find . custom-group-find))
497     (toggle (type . choice)
498             ;; Booleans.
499             (data ((type . const)
500                    (tag . "On ")
501                    (default . t))
502                   ((type . const)
503                    (tag . "Off")
504                    (default . nil))))
505     (choice (type . default)
506             ;; See `custom-match'.
507             (query . custom-choice-query)
508             (accept . custom-choice-accept)
509             (extract . custom-choice-extract)
510             (validate . custom-choice-validate)
511             (insert . custom-choice-insert)
512             (none (tag . "Unknown")
513                   (default . __uninitialized__)
514                   (type . const)))
515     (const (type . default)
516            ;; A `const' only matches a single lisp value.
517            (extract . (lambda (c f) (list (custom-default c))))
518            (validate . (lambda (c f) nil))
519            (valid . custom-const-valid)
520            (update . custom-const-update)
521            (insert . custom-const-insert))
522     (face-doc (type . doc)
523               ;; A variable containing a face.
524               (doc . "\
525 You can customize the look of Emacs by deciding which faces should be
526 used when.  If you push one of the face buttons below, you will be
527 given a choice between a number of standard faces.  The name of the
528 selected face is shown right after the face button, and it is
529 displayed its own face so you can see how it looks.  If you know of
530 another standard face not listed and want to use it, you can select
531 `Other' and write the name in the editing field.
532
533 If none of the standard faces suits you, you can select `Customize' to
534 create your own face.  This will make six fields appear under the face
535 button.  The `Fg' and `Bg' fields are the foreground and background
536 colors for the face, respectively.  You should type the name of the
537 color in the field.  You can use any X11 color name.  A list of X11
538 color names may be available in the file `/usr/lib/X11/rgb.txt' on
539 your system.  The special color name `default' means that the face
540 will not change the color of the text.  The `Stipple' field is weird,
541 so just ignore it.  The three remaining fields are toggles, which will
542 make the text `bold', `italic', or `underline' respectively.  For some
543 fonts `bold' or `italic' will not make any visible change."))
544     (face (type . choice)
545           (eval . custom-face-eval)
546           (import . custom-face-import)
547           (data ((tag . "None")
548                  (default . nil)
549                  (type . const))
550                 ((tag . "Default")
551                  (default . default)
552                  (face . custom-const-face)
553                  (type . const))
554                 ((tag . "Bold")
555                  (default . bold)
556                  (face . custom-const-face)
557                  (type . const))
558                 ((tag . "Bold-italic")
559                  (default . bold-italic)
560                  (face . custom-const-face)
561                  (type . const))
562                 ((tag . "Italic")
563                  (default . italic)
564                  (face . custom-const-face)
565                  (type . const))
566                 ((tag . "Underline")
567                  (default . underline)
568                  (face . custom-const-face)
569                  (type . const))
570                 ((tag . "Highlight")
571                  (default . highlight)
572                  (face . custom-const-face)
573                  (type . const))
574                 ((tag . "Modeline")
575                  (default . modeline)
576                  (face . custom-const-face)
577                  (type . const))
578                 ((tag . "Region")
579                  (default . region)
580                  (face . custom-const-face)
581                  (type . const))
582                 ((tag . "Secondary Selection")
583                  (default . secondary-selection)
584                  (face . custom-const-face)
585                  (type . const))
586                 ((tag . "Customized")
587                  (compact . t)
588                  (face-tag . custom-face-hack)
589                  (eval . custom-face-eval)
590                  (data ((hidden . t)
591                         (tag . "")
592                         (doc . "\
593 Select the properties you want this face to have.")
594                         (default . custom-face-lookup)
595                         (type . const))
596                        "\n"
597                        ((tag . "Fg")
598                         (hidden . t)
599                         (default . "default")
600                         (width . 20)
601                         (type . string))
602                        ((tag . "Bg")
603                         (default . "default")
604                         (width . 20)
605                         (type . string))
606                        ((tag . "Stipple")
607                         (default . "default")
608                         (width . 20)
609                         (type . string))
610                        "\n"
611                        ((tag . "Bold")
612                         (default . nil)
613                         (type . toggle))
614                        "              "
615                        ((tag . "Italic")
616                         (default . nil)
617                         (type . toggle))
618                        "             "
619                        ((tag . "Underline")
620                         (hidden . t)
621                         (default . nil)
622                         (type . toggle)))
623                  (default . (custom-face-lookup "default" "default" "default"
624                                                 nil nil nil))
625                  (type . list))
626                 ((prompt . "Other")
627                  (face . custom-field-value)
628                  (default . __uninitialized__)
629                  (type . symbol))))
630     (file (type . string)
631           ;; A string containing a file or directory name.
632           (directory . nil)
633           (default-file . nil)
634           (query . custom-file-query))
635     (sexp (type . default)
636           ;; Any lisp expression.
637           (width . 40)
638           (default . (__uninitialized__ . "Uninitialized"))
639           (read . custom-sexp-read)
640           (write . custom-sexp-write))
641     (symbol (type . sexp)
642             ;; A lisp symbol.
643             (width . 40)
644             (valid . (lambda (c d) (symbolp d))))
645     (integer (type . sexp)
646              ;; A lisp integer.
647              (width . 10)
648              (valid . (lambda (c d) (integerp d))))
649     (string (type . default)
650             ;; A lisp string.
651             (width . 40) 
652             (valid . (lambda (c d) (stringp d)))
653             (read . custom-string-read)
654             (write . custom-string-write))
655     (button (type . default)
656             ;; Push me.
657             (accept . ignore)
658             (extract . nil)
659             (validate . ignore)
660             (insert . custom-button-insert))
661     (doc (type . default)
662          ;; A documentation only entry with no value.
663          (header . nil)
664          (reset . ignore)
665          (extract . nil)
666          (validate . ignore)
667          (insert . custom-documentation-insert))
668     (default (width . 20)
669              (valid . (lambda (c v) t))
670              (insert . custom-default-insert)
671              (update . custom-default-update)
672              (query . custom-default-query)
673              (tag . nil)
674              (prompt . nil)
675              (doc . nil)
676              (header . t)
677              (padding . ? )
678              (quote . custom-default-quote)
679              (eval . (lambda (c v) nil))
680              (export . custom-default-export)
681              (import . (lambda (c v) (list v)))
682              (synchronize . ignore)
683              (initialize . custom-default-initialize)
684              (extract . custom-default-extract)
685              (validate . custom-default-validate)
686              (apply . custom-default-apply)
687              (reset . custom-default-reset)
688              (factory-reset . custom-default-factory-reset)
689              (accept . custom-default-accept)
690              (match . custom-default-match)
691              (name . nil)
692              (compact . nil)
693              (hidden . nil)
694              (face . custom-default-face)
695              (data . nil)
696              (calculate . nil)
697              (default . __uninitialized__)))
698   "Alist of default properties for type symbols.
699 The format is `((SYMBOL (PROPERTY . VALUE)... )... )'.")
700
701 (defconst custom-local-type-properties nil
702   "Local type properties.
703 Entries in this list take precedence over `custom-type-properties'.")
704
705 (make-variable-buffer-local 'custom-local-type-properties)
706
707 (defconst custom-nil '__uninitialized__
708   "Special value representing an uninitialized field.")
709
710 (defconst custom-invalid '__invalid__
711   "Special value representing an invalid field.")
712
713 (defun custom-property (custom property)
714   "Extract from CUSTOM property PROPERTY."
715   (let ((entry (assq property custom)))
716     (while (null entry)
717       ;; Look in superclass.
718       (let ((type (custom-type custom)))
719         (setq custom (cdr (or (assq type custom-local-type-properties)
720                               (assq type custom-type-properties)))
721               entry (assq property custom))
722         (custom-assert 'custom)))
723     (cdr entry)))
724
725 (defun custom-super (custom property)
726   "Extract from CUSTOM property PROPERTY.  Start with CUSTOM's superclass."
727   (let ((entry nil))
728     (while (null entry)
729       ;; Look in superclass.
730       (let ((type (custom-type custom)))
731         (setq custom (cdr (or (assq type custom-local-type-properties)
732                               (assq type custom-type-properties)))
733               entry (assq property custom))
734         (custom-assert 'custom)))
735     (cdr entry)))
736
737 (defun custom-property-set (custom property value)
738   "Set CUSTOM PROPERY to VALUE by side effect.
739 CUSTOM must have at least one property already."
740   (let ((entry (assq property custom)))
741     (if entry
742         (setcdr entry value)
743       (setcdr custom (cons (cons property value) (cdr custom))))))
744
745 (defun custom-type (custom)
746   "Extract `type' from CUSTOM."
747   (cdr (assq 'type custom)))
748
749 (defun custom-name (custom)
750   "Extract `name' from CUSTOM."
751   (custom-property custom 'name))
752
753 (defun custom-tag (custom)
754   "Extract `tag' from CUSTOM."
755   (custom-property custom 'tag))
756
757 (defun custom-face-tag (custom)
758   "Extract `face-tag' from CUSTOM."
759   (custom-property custom 'face-tag))
760
761 (defun custom-prompt (custom)
762   "Extract `prompt' from CUSTOM.  
763 If none exist, default to `tag' or, failing that, `type'."
764   (or (custom-property custom 'prompt)
765       (custom-property custom 'tag)
766       (capitalize (symbol-name (custom-type custom)))))
767
768 (defun custom-default (custom)
769   "Extract `default' from CUSTOM."
770   (let ((value (custom-property custom 'calculate)))
771     (if value
772         (eval value)
773       (custom-property custom 'default))))
774                
775 (defun custom-data (custom)
776   "Extract the `data' from CUSTOM."
777   (custom-property custom 'data))
778
779 (defun custom-documentation (custom)
780   "Extract `doc' from CUSTOM."
781   (custom-property custom 'doc))
782
783 (defun custom-width (custom)
784   "Extract `width' from CUSTOM."
785   (custom-property custom 'width))
786
787 (defun custom-compact (custom)
788   "Extract `compact' from CUSTOM."
789   (custom-property custom 'compact))
790
791 (defun custom-padding (custom)
792   "Extract `padding' from CUSTOM."
793   (custom-property custom 'padding))
794
795 (defun custom-valid (custom value)
796   "Non-nil if CUSTOM may validly be set to VALUE."
797   (and (not (and (listp value) (eq custom-invalid (car value))))
798        (funcall (custom-property custom 'valid) custom value)))
799
800 (defun custom-import (custom value)
801   "Import CUSTOM VALUE from external variable.
802
803 This function change VALUE into a form that makes it easier to edit 
804 internally.  What the internal form is exactly depends on CUSTOM.  
805 The internal form is returned."
806   (if (eq custom-nil value)
807       (list custom-nil)
808     (funcall (custom-property custom 'import) custom value)))
809
810 (defun custom-eval (custom value)
811   "Return non-nil if CUSTOM's VALUE needs to be evaluated."
812   (funcall (custom-property custom 'eval) custom value))
813
814 (defun custom-quote (custom value)
815   "Quote CUSTOM's VALUE if necessary."
816   (funcall (custom-property custom 'quote) custom value))
817
818 (defun custom-write (custom value)
819   "Convert CUSTOM VALUE to a string."
820   (cond ((eq value custom-nil) 
821          "")
822         ((and (listp value) (eq (car value) custom-invalid))
823          (cdr value))
824         (t
825          (funcall (custom-property custom 'write) custom value))))
826
827 (defun custom-read (custom string)
828   "Convert CUSTOM field content STRING into lisp."
829   (condition-case nil
830       (funcall (custom-property custom 'read) custom string)
831     (error (cons custom-invalid string))))
832
833 (defun custom-match (custom values)
834   "Match CUSTOM with a list of VALUES.
835
836 Return a cons-cell where the car is the sublist of VALUES matching CUSTOM,
837 and the cdr is the remaining VALUES.
838
839 A CUSTOM is actually a regular expression over the alphabet of lisp
840 types.  Most CUSTOM types are just doing a literal match, e.g. the
841 `symbol' type matches any lisp symbol.  The exceptions are:
842
843 group:    which corresponds to a `(' and `)' group in a regular expression.
844 choice:   which corresponds to a group of `|' in a regular expression.
845 repeat:   which corresponds to a `*' in a regular expression.
846 optional: which corresponds to a `?', and isn't implemented yet."
847   (if (memq values (list custom-nil nil))
848       ;; Nothing matches the uninitialized or empty list.
849       (cons custom-nil nil)
850     (funcall (custom-property custom 'match) custom values)))
851
852 (defun custom-initialize (custom)
853   "Initialize `doc' and `default' attributes of CUSTOM."
854   (funcall (custom-property custom 'initialize) custom))
855
856 (defun custom-find (custom tag)
857   "Find child in CUSTOM with `tag' TAG."
858   (funcall (custom-property custom 'find) custom tag))
859
860 (defun custom-travel-path (custom path)
861   "Find decedent of CUSTOM by looking through PATH."
862   (if (null path)
863       custom
864     (custom-travel-path (custom-find custom (car path)) (cdr path))))
865
866 (defun custom-field-extract (custom field)
867   "Extract CUSTOM's value in FIELD."
868   (if (stringp custom)
869       nil
870     (funcall (custom-property (custom-field-custom field) 'extract)
871              custom field)))
872
873 (defun custom-field-validate (custom field)
874   "Validate CUSTOM's value in FIELD.
875 Return nil if valid, otherwise return a cons-cell where the car is the
876 position of the error, and the cdr is a text describing the error."
877   (if (stringp custom)
878       nil
879     (funcall (custom-property custom 'validate) custom field)))
880
881 ;;; Field Functions:
882 ;;
883 ;; This section defines the public functions for manipulating the
884 ;; FIELD datatype.  The FIELD instance hold information about a
885 ;; specific editing field in the customization buffer.
886 ;;
887 ;; Each FIELD can be seen as an instanciation of a CUSTOM.
888
889 (defvar custom-field-last nil)
890 ;; Last field containing point.
891 (make-variable-buffer-local 'custom-field-last)
892
893 (defvar custom-modified-list nil)
894 ;; List of modified fields.
895 (make-variable-buffer-local 'custom-modified-list)
896
897 (defun custom-field-create (custom value)
898   "Create a field structure of type CUSTOM containing VALUE.
899
900 A field structure is an array [ CUSTOM VALUE ORIGINAL START END ], where
901 CUSTOM defines the type of the field, 
902 VALUE is the current value of the field,
903 ORIGINAL is the original value when created, and
904 START and END are markers to the start and end of the field."
905   (vector custom value custom-nil nil nil))
906
907 (defun custom-field-custom (field)
908   "Return the `custom' attribute of FIELD."
909   (aref field 0))
910   
911 (defun custom-field-value (field)
912   "Return the `value' attribute of FIELD."
913   (aref field 1))
914
915 (defun custom-field-original (field)
916   "Return the `original' attribute of FIELD."
917   (aref field 2))
918
919 (defun custom-field-start (field)
920   "Return the `start' attribute of FIELD."
921   (aref field 3))
922
923 (defun custom-field-end (field)
924   "Return the `end' attribute of FIELD."
925   (aref field 4))
926   
927 (defun custom-field-value-set (field value)
928   "Set the `value' attribute of FIELD to VALUE."
929   (aset field 1 value))
930
931 (defun custom-field-original-set (field original)
932   "Set the `original' attribute of FIELD to ORIGINAL."
933   (aset field 2 original))
934
935 (defun custom-field-move (field start end)
936   "Set the `start'and `end' attributes of FIELD to START and END."
937   (set-marker (or (aref field 3) (aset field 3 (make-marker))) start)
938   (set-marker (or (aref field 4) (aset field 4 (make-marker))) end))
939
940 (defun custom-field-query (field)
941   "Query user for content of current field."
942   (funcall (custom-property (custom-field-custom field) 'query) field))
943
944 (defun custom-field-accept (field value &optional original)
945   "Store a new value into field FIELD, taking it from VALUE.
946 If optional ORIGINAL is non-nil, concider VALUE for the original value."
947   (let ((inhibit-point-motion-hooks t))
948     (funcall (custom-property (custom-field-custom field) 'accept) 
949              field value original)))
950
951 (defun custom-field-face (field)
952   "The face used for highlighting FIELD."
953   (let ((custom (custom-field-custom field)))
954     (if (stringp custom)
955         nil
956       (let ((face (funcall (custom-property custom 'face) field)))
957         (if (custom-facep face) face nil)))))
958
959 (defun custom-field-update (field)
960   "Update the screen appearance of FIELD to correspond with the field's value."
961   (let ((custom (custom-field-custom field)))
962     (if (stringp custom)
963         nil
964       (funcall (custom-property custom 'update) field))))
965
966 ;;; Types:
967 ;;
968 ;; The following functions defines type specific actions.
969
970 (defun custom-repeat-eval (custom value)
971   "Non-nil if CUSTOM's VALUE needs to be evaluated."
972   (if (eq value custom-nil)
973       nil
974     (let ((child (custom-data custom))
975           (found nil))
976       (mapcar (lambda (v) (if (custom-eval child v) (setq found t)))
977               value))))
978
979 (defun custom-repeat-quote (custom value)
980   "A list of CUSTOM's VALUEs quoted."
981   (let ((child (custom-data custom)))
982     (apply 'append (mapcar (lambda (v) (custom-quote child v))
983                            value))))
984
985   
986 (defun custom-repeat-import (custom value)
987   "Modify CUSTOM's VALUE to match internal expectations."
988   (let ((child (custom-data custom)))
989     (apply 'append (mapcar (lambda (v) (custom-import child v))
990                            value))))
991
992 (defun custom-repeat-accept (field value &optional original)
993   "Store a new value into field FIELD, taking it from VALUE."
994   (let ((values (copy-sequence (custom-field-value field)))
995         (all (custom-field-value field))
996         (start (custom-field-start field))
997         current new)
998     (if original 
999         (custom-field-original-set field value))
1000     (while (consp value)
1001       (setq new (car value)
1002             value (cdr value))
1003       (if values
1004           ;; Change existing field.
1005           (setq current (car values)
1006                 values (cdr values))
1007         ;; Insert new field if series has grown.
1008         (goto-char start)
1009         (setq current (custom-repeat-insert-entry field))
1010         (setq all (custom-insert-before all nil current))
1011         (custom-field-value-set field all))
1012       (custom-field-accept current new original))
1013     (while (consp values)
1014       ;; Delete old field if series has scrunk.
1015       (setq current (car values)
1016             values (cdr values))
1017       (let ((pos (custom-field-start current))
1018             data)
1019         (while (not data)
1020           (setq pos (previous-single-property-change pos 'custom-data))
1021           (custom-assert 'pos)
1022           (setq data (get-text-property pos 'custom-data))
1023           (or (and (arrayp data)
1024                    (> (length data) 1)
1025                    (eq current (aref data 1)))
1026               (setq data nil)))
1027         (custom-repeat-delete data)))))
1028
1029 (defun custom-repeat-insert (custom level)
1030   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
1031   (let* ((field (custom-field-create custom nil))
1032          (add-tag (custom-property custom 'add-tag))
1033          (start (make-marker))
1034          (data (vector field nil start nil)))
1035     (custom-text-insert "\n")
1036     (let ((pos (point)))
1037       (custom-text-insert (custom-property custom 'prefix))
1038       (custom-tag-insert add-tag 'custom-repeat-add data)
1039       (set-marker start pos))
1040     (custom-field-move field start (point))
1041     (custom-documentation-insert custom)
1042     field))
1043
1044 (defun custom-repeat-insert-entry (repeat)
1045   "Insert entry at point in the REPEAT field."
1046   (let* ((inhibit-point-motion-hooks t)
1047          (inhibit-read-only t)
1048          (before-change-functions nil)
1049          (after-change-functions nil)
1050          (custom (custom-field-custom repeat))
1051          (add-tag (custom-property custom 'add-tag))
1052          (del-tag (custom-property custom 'del-tag))
1053          (start (make-marker))
1054          (end (make-marker))
1055          (data (vector repeat nil start end))
1056          field)
1057     (insert-before-markers "\n")
1058     (backward-char 1)
1059     (set-marker start (point))
1060     (custom-text-insert " ")
1061     (aset data 1 (setq field (custom-insert (custom-data custom) nil)))
1062     (custom-text-insert " ")
1063     (set-marker end (point))
1064     (goto-char start)
1065     (custom-text-insert (custom-property custom 'prefix))
1066     (custom-tag-insert add-tag 'custom-repeat-add data)
1067     (custom-text-insert " ")
1068     (custom-tag-insert del-tag 'custom-repeat-delete data)
1069     (forward-char 1)
1070     field))
1071
1072 (defun custom-repeat-add (data)
1073   "Add list entry."
1074   (let ((parent (aref data 0))
1075         (field (aref data 1))
1076         (at (aref data 2))
1077         new)
1078     (goto-char at)
1079     (setq new (custom-repeat-insert-entry parent))
1080     (custom-field-value-set parent
1081                             (custom-insert-before (custom-field-value parent)
1082                                                   field new))))
1083
1084 (defun custom-repeat-delete (data)
1085   "Delete list entry."
1086   (let ((inhibit-point-motion-hooks t)
1087         (inhibit-read-only t)
1088         (before-change-functions nil)
1089         (after-change-functions nil)
1090         (parent (aref data 0))
1091         (field (aref data 1)))
1092     (delete-region (aref data 2) (1+ (aref data 3)))
1093     (custom-field-untouch (aref data 1))
1094     (custom-field-value-set parent 
1095                             (delq field (custom-field-value parent)))))
1096
1097 (defun custom-repeat-match (custom values)
1098   "Match CUSTOM with VALUES."
1099   (let* ((child (custom-data custom))
1100          (match (custom-match child values))
1101          matches)
1102     (while (not (eq (car match) custom-nil))
1103       (setq matches (cons (car match) matches)
1104             values (cdr match)
1105             match (custom-match child values)))
1106     (cons (nreverse matches) values)))
1107
1108 (defun custom-repeat-extract (custom field)
1109   "Extract list of childrens values."
1110   (let ((values (custom-field-value field))
1111         (data (custom-data custom))
1112         result)
1113     (if (eq values custom-nil)
1114         ()
1115       (while values
1116         (setq result (append result (custom-field-extract data (car values)))
1117               values (cdr values))))
1118     result))
1119
1120 (defun custom-repeat-validate (custom field)
1121   "Validate children."
1122   (let ((values (custom-field-value field))
1123         (data (custom-data custom))
1124         result)
1125     (if (eq values custom-nil)
1126         (setq result (cons (custom-field-start field) "Uninitialized list")))
1127     (while (and values (not result))
1128       (setq result (custom-field-validate data (car values))
1129             values (cdr values)))
1130     result))
1131
1132 (defun custom-pair-accept (field value &optional original)
1133   "Store a new value into field FIELD, taking it from VALUE."
1134   (custom-group-accept field (list (car value) (cdr value)) original))
1135
1136 (defun custom-pair-eval (custom value)
1137   "Non-nil if CUSTOM's VALUE needs to be evaluated."
1138   (custom-group-eval custom (list (car value) (cdr value))))
1139
1140 (defun custom-pair-import (custom value)
1141   "Modify CUSTOM's VALUE to match internal expectations."
1142   (let ((result (car (custom-group-import custom 
1143                                           (list (car value) (cdr value))))))
1144     (custom-assert '(eq (length result) 2))
1145     (list (cons (nth 0 result) (nth 1 result)))))
1146
1147 (defun custom-pair-quote (custom value)
1148   "Quote CUSTOM's VALUE if necessary."
1149   (if (custom-eval custom value)
1150       (let ((v (car (custom-group-quote custom 
1151                                         (list (car value) (cdr value))))))
1152         (list (list 'cons (nth 0 v) (nth 1 v))))
1153     (custom-default-quote custom value)))
1154
1155 (defun custom-pair-extract (custom field)
1156   "Extract cons of childrens values."
1157   (let ((values (custom-field-value field))
1158         (data (custom-data custom))
1159         result)
1160     (custom-assert '(eq (length values) (length data)))
1161     (while values
1162       (setq result (append result
1163                            (custom-field-extract (car data) (car values)))
1164             data (cdr data)
1165             values (cdr values)))
1166     (custom-assert '(null data))
1167     (list (cons (nth 0 result) (nth 1 result)))))
1168
1169 (defun custom-list-quote (custom value)
1170   "Quote CUSTOM's VALUE if necessary."
1171   (if (custom-eval custom value)
1172       (let ((v (car (custom-group-quote custom value))))
1173         (list (cons 'list v)))
1174     (custom-default-quote custom value)))
1175
1176 (defun custom-list-extract (custom field)
1177   "Extract list of childrens values."
1178   (let ((values (custom-field-value field))
1179         (data (custom-data custom))
1180         result)
1181     (custom-assert '(eq (length values) (length data)))
1182     (while values
1183       (setq result (append result
1184                            (custom-field-extract (car data) (car values)))
1185             data (cdr data)
1186             values (cdr values)))
1187     (custom-assert '(null data))
1188     (list result)))
1189
1190 (defun custom-group-validate (custom field)
1191   "Validate children."
1192   (let ((values (custom-field-value field))
1193         (data (custom-data custom))
1194         result)
1195     (if (eq values custom-nil)
1196         (setq result (cons (custom-field-start field) "Uninitialized list"))
1197       (custom-assert '(eq (length values) (length data))))
1198     (while (and values (not result))
1199       (setq result (custom-field-validate (car data) (car values))
1200             data (cdr data)
1201             values (cdr values)))
1202     result))
1203
1204 (defun custom-group-eval (custom value)
1205   "Non-nil if CUSTOM's VALUE needs to be evaluated."
1206   (let ((found nil))
1207     (mapcar (lambda (c)
1208               (or (stringp c)
1209                   (let ((match (custom-match c value)))
1210                     (if (custom-eval c (car match))
1211                         (setq found t))
1212                     (setq value (cdr match)))))
1213             (custom-data custom))
1214     found))
1215
1216 (defun custom-group-quote (custom value)
1217   "A list of CUSTOM's VALUE members, quoted."
1218   (list (apply 'append 
1219                (mapcar (lambda (c)
1220                          (if (stringp c)
1221                              ()
1222                            (let ((match (custom-match c value)))
1223                              (prog1 (custom-quote c (car match))
1224                                (setq value (cdr match))))))
1225                        (custom-data custom)))))
1226
1227 (defun custom-group-import (custom value)
1228   "Modify CUSTOM's VALUE to match internal expectations."
1229   (list (apply 'append 
1230                (mapcar (lambda (c)
1231                          (if (stringp c)
1232                              ()
1233                            (let ((match (custom-match c value)))
1234                              (prog1 (custom-import c (car match))
1235                                (setq value (cdr match))))))
1236                        (custom-data custom)))))
1237
1238 (defun custom-group-initialize (custom)
1239   "Initialize `doc' and `default' entries in CUSTOM."
1240   (if (custom-name custom)
1241       (custom-default-initialize custom)
1242     (mapcar 'custom-initialize (custom-data custom))))
1243
1244 (defun custom-group-apply (field)
1245   "Reset `value' in FIELD to `original'."
1246   (let ((custom (custom-field-custom field))
1247         (values (custom-field-value field)))
1248     (if (custom-name custom)
1249         (custom-default-apply field)
1250       (mapcar 'custom-field-apply values))))
1251
1252 (defun custom-group-reset (field)
1253   "Reset `value' in FIELD to `original'."
1254   (let ((custom (custom-field-custom field))
1255         (values (custom-field-value field)))
1256     (if (custom-name custom)
1257         (custom-default-reset field)
1258       (mapcar 'custom-field-reset values))))
1259
1260 (defun custom-group-factory-reset (field)
1261   "Reset `value' in FIELD to `default'."
1262   (let ((custom (custom-field-custom field))
1263         (values (custom-field-value field)))
1264     (if (custom-name custom)
1265         (custom-default-factory-reset field)
1266       (mapcar 'custom-field-factory-reset values))))
1267
1268 (defun custom-group-find (custom tag)
1269   "Find child in CUSTOM with `tag' TAG."
1270   (let ((data (custom-data custom))
1271         (result nil))
1272     (while (not result)
1273       (custom-assert 'data)
1274       (if (equal (custom-tag (car data)) tag)
1275           (setq result (car data))
1276         (setq data (cdr data))))))
1277
1278 (defun custom-group-accept (field value &optional original)
1279   "Store a new value into field FIELD, taking it from VALUE."
1280   (let* ((values (custom-field-value field))
1281          (custom (custom-field-custom field))
1282          (from (custom-field-start field))
1283          (face-tag (custom-face-tag custom))
1284          current)
1285     (if face-tag 
1286         (put-text-property from (+ from (length (custom-tag custom)))
1287                            'face (funcall face-tag field value)))
1288     (if original 
1289         (custom-field-original-set field value))
1290     (while values
1291       (setq current (car values)
1292             values (cdr values))
1293       (if current
1294           (let* ((custom (custom-field-custom current))
1295                  (match (custom-match custom value)))
1296             (setq value (cdr match))
1297             (custom-field-accept current (car match) original))))))
1298
1299 (defun custom-group-insert (custom level)
1300   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
1301   (let* ((field (custom-field-create custom nil))
1302          fields hidden
1303          (from (point))
1304          (compact (custom-compact custom))
1305          (tag (custom-tag custom))
1306          (face-tag (custom-face-tag custom)))
1307     (cond (face-tag (custom-text-insert tag))
1308           (tag (custom-tag-insert tag field)))
1309     (or compact (custom-documentation-insert custom))
1310     (or compact (custom-text-insert "\n"))
1311     (let ((data (custom-data custom)))
1312       (while data
1313         (setq fields (cons (custom-insert (car data) (if level (1+ level)))
1314                            fields))
1315         (setq hidden (or (stringp (car data))
1316                          (custom-property (car data) 'hidden)))
1317         (setq data (cdr data))
1318         (if data (custom-text-insert (cond (hidden "")
1319                                            (compact " ")
1320                                            (t "\n"))))))
1321     (if compact (custom-documentation-insert custom))
1322     (custom-field-value-set field (nreverse fields))
1323     (custom-field-move field from (point))
1324     field))
1325
1326 (defun custom-choice-insert (custom level)
1327   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
1328   (let* ((field (custom-field-create custom nil))
1329          (from (point)))
1330     (custom-text-insert "lars er en nisse")
1331     (custom-field-move field from (point))
1332     (custom-documentation-insert custom)
1333     (custom-field-reset field)
1334     field))
1335
1336 (defun custom-choice-accept (field value &optional original)
1337   "Store a new value into field FIELD, taking it from VALUE."
1338   (let ((custom (custom-field-custom field))
1339         (start (custom-field-start field))
1340         (end (custom-field-end field))
1341         (inhibit-read-only t)
1342         (before-change-functions nil)
1343         (after-change-functions nil)
1344         from)
1345     (cond (original 
1346            (setq custom-modified-list (delq field custom-modified-list))
1347            (custom-field-original-set field value))
1348           ((equal value (custom-field-original field))
1349            (setq custom-modified-list (delq field custom-modified-list)))
1350           (t
1351            (add-to-list 'custom-modified-list field)))
1352     (custom-field-untouch (custom-field-value field))
1353     (delete-region start end)
1354     (goto-char start)
1355     (setq from (point))
1356     (insert-before-markers " ")
1357     (backward-char 1)
1358     (custom-category-set (point) (1+ (point)) 'custom-hidden-properties)
1359     (custom-tag-insert (custom-tag custom) field)
1360     (custom-text-insert ": ")
1361     (let ((data (custom-data custom))
1362           found begin)
1363       (while (and data (not found))
1364         (if (not (custom-valid (car data) value))
1365             (setq data (cdr data))
1366           (setq found (custom-insert (car data) nil))
1367           (setq data nil)))
1368       (if found 
1369           ()
1370         (setq begin (point)
1371               found (custom-insert (custom-property custom 'none) nil))
1372         (add-text-properties begin (point)
1373                              (list rear-nonsticky t
1374                                    'face custom-field-uninitialized-face)))
1375       (or original
1376           (custom-field-original-set found (custom-field-original field)))
1377       (custom-field-accept found value original)
1378       (custom-field-value-set field found)
1379       (custom-field-move field from end))))
1380
1381 (defun custom-choice-extract (custom field)
1382   "Extract childs value."
1383   (let ((value (custom-field-value field)))
1384     (custom-field-extract (custom-field-custom value) value)))
1385
1386 (defun custom-choice-validate (custom field)
1387   "Validate childs value."
1388   (let ((value (custom-field-value field))
1389         (custom (custom-field-custom field)))
1390     (if (or (eq value custom-nil)
1391             (eq (custom-field-custom value) (custom-property custom 'none)))
1392         (cons (custom-field-start field) "Make a choice")
1393       (custom-field-validate (custom-field-custom value) value))))
1394
1395 (defun custom-choice-query (field)
1396   "Choose a child."
1397   (let* ((custom (custom-field-custom field))
1398          (old (custom-field-custom (custom-field-value field)))
1399          (default (custom-prompt old))
1400          (tag (custom-prompt custom))
1401          (data (custom-data custom))
1402          current alist)
1403     (if (eq (length data) 2)
1404         (custom-field-accept field (custom-default (if (eq (nth 0 data) old)
1405                                                        (nth 1 data)
1406                                                      (nth 0 data))))
1407       (while data
1408         (setq current (car data)
1409               data (cdr data))
1410         (setq alist (cons (cons (custom-prompt current) current) alist)))
1411       (let ((answer (cond ((and (fboundp 'button-press-event-p)
1412                                 (fboundp 'popup-menu)
1413                                 (button-press-event-p last-input-event))
1414                            (cdr (assoc (car (custom-x-really-popup-menu 
1415                                              last-input-event tag 
1416                                              (reverse alist)))
1417                                        alist)))
1418                           ((listp last-input-event)
1419                            (x-popup-menu last-input-event
1420                                          (list tag (cons "" (reverse alist)))))
1421                           (t 
1422                            (let ((choice (completing-read (concat tag
1423                                                                   " (default "
1424                                                                   default 
1425                                                                   "): ") 
1426                                                           alist nil t)))
1427                              (if (or (null choice) (string-equal choice ""))
1428                                  (setq choice default))
1429                              (cdr (assoc choice alist)))))))
1430         (if answer
1431             (custom-field-accept field (custom-default answer)))))))
1432
1433 (defun custom-file-query (field)
1434   "Prompt for a file name"
1435   (let* ((value (custom-field-value field))
1436          (custom (custom-field-custom field))
1437          (valid (custom-valid custom value))
1438          (directory (custom-property custom 'directory))
1439          (default (and (not valid)
1440                        (custom-property custom 'default-file)))
1441          (tag (custom-tag custom))
1442          (prompt (if default
1443                      (concat tag " (" default "): ")
1444                    (concat tag ": "))))
1445     (custom-field-accept field 
1446                          (if (custom-valid custom value)
1447                              (read-file-name prompt 
1448                                              (if (file-name-absolute-p value)
1449                                                  ""
1450                                                directory)
1451                                              default nil value)
1452                            (read-file-name prompt directory default)))))
1453
1454 (defun custom-face-eval (custom value)
1455   "Return non-nil if CUSTOM's VALUE needs to be evaluated."
1456   (not (symbolp value)))
1457
1458 (defun custom-face-import (custom value)
1459   "Modify CUSTOM's VALUE to match internal expectations."
1460   (let ((name (symbol-name value)))
1461     (list (if (string-match "\
1462 custom-face-\\(.*\\)-\\(.*\\)-\\(.*\\)-\\(.*\\)-\\(.*\\)-\\(.*\\)"
1463                             name)
1464               (list 'custom-face-lookup 
1465                     (match-string 1 name)
1466                     (match-string 2 name)
1467                     (match-string 3 name)
1468                     (intern (match-string 4 name))
1469                     (intern (match-string 5 name))
1470                     (intern (match-string 6 name)))
1471             value))))
1472
1473 (defun custom-face-lookup (fg bg stipple bold italic underline)
1474   "Lookup or create a face with specified attributes.
1475 FG BG STIPPLE BOLD ITALIC UNDERLINE"
1476   (let ((name (intern (format "custom-face-%s-%s-%s-%S-%S-%S"
1477                               (or fg "default")
1478                               (or bg "default")
1479                               (or stipple "default")
1480                               bold italic underline))))
1481     (if (and (custom-facep name)
1482              (fboundp 'make-face))
1483         ()
1484       (make-face name)
1485       (modify-face name
1486                    (if (string-equal fg "default") nil fg)
1487                    (if (string-equal bg "default") nil bg)
1488                    (if (string-equal stipple "default") nil stipple)
1489                    bold italic underline))
1490     name))
1491
1492 (defun custom-face-hack (field value)
1493   "Face that should be used for highlighting FIELD containing VALUE."
1494   (let* ((custom (custom-field-custom field))
1495          (face (eval (funcall (custom-property custom 'export) 
1496                               custom value))))
1497     (if (custom-facep face) face nil)))
1498
1499 (defun custom-const-insert (custom level)
1500   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
1501   (let* ((field (custom-field-create custom custom-nil))
1502          (face (custom-field-face field))
1503          (from (point)))
1504     (custom-text-insert (custom-tag custom))
1505     (add-text-properties from (point) 
1506                          (list 'face face
1507                                rear-nonsticky t))
1508     (custom-documentation-insert custom)
1509     (custom-field-move field from (point))
1510     field))
1511
1512 (defun custom-const-update (field)
1513   "Update face of FIELD."
1514   (let ((from (custom-field-start field))
1515         (custom (custom-field-custom field)))
1516     (put-text-property from (+ from (length (custom-tag custom)))
1517                        'face (custom-field-face field))))
1518
1519 (defun custom-const-valid (custom value)
1520   "Non-nil if CUSTOM can validly have the value VALUE."
1521   (equal (custom-default custom) value))
1522
1523 (defun custom-const-face (field)
1524   "Face used for a FIELD."
1525   (custom-default (custom-field-custom field)))
1526
1527 (defun custom-sexp-read (custom string)
1528   "Read from CUSTOM an STRING."
1529   (save-match-data
1530     (save-excursion
1531       (set-buffer (get-buffer-create " *Custom Scratch*"))
1532       (erase-buffer)
1533       (insert string)
1534       (goto-char (point-min))
1535       (prog1 (read (current-buffer))
1536         (or (looking-at
1537              (concat (regexp-quote (char-to-string
1538                                     (custom-padding custom)))
1539                      "*\\'"))
1540             (error "Junk at end of expression"))))))
1541
1542 (autoload 'pp-to-string "pp")
1543
1544 (defun custom-sexp-write (custom sexp)
1545   "Write CUSTOM SEXP as string."
1546   (let ((string (prin1-to-string sexp)))
1547     (if (<= (length string) (custom-width custom))
1548         string
1549       (setq string (pp-to-string sexp))
1550       (string-match "[ \t\n]*\\'" string)
1551       (concat "\n" (substring string 0 (match-beginning 0))))))
1552
1553 (defun custom-string-read (custom string)
1554   "Read string by ignoring trailing padding characters."
1555   (let ((last (length string))
1556         (padding (custom-padding custom)))
1557     (while (and (> last 0)
1558                 (eq (aref string (1- last)) padding))
1559       (setq last (1- last)))
1560     (substring string 0 last)))
1561
1562 (defun custom-string-write (custom string)
1563   "Write raw string."
1564   string)
1565
1566 (defun custom-button-insert (custom level)
1567   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
1568   (custom-tag-insert (concat "[" (custom-tag custom) "]") 
1569                      (custom-property custom 'query))
1570   (custom-documentation-insert custom)
1571   nil)
1572
1573 (defun custom-default-export (custom value)
1574   ;; Convert CUSTOM's VALUE to external representation.
1575   ;; See `custom-import'.
1576   (if (custom-eval custom value)
1577       (eval (car (custom-quote custom value)))
1578     value))
1579
1580 (defun custom-default-quote (custom value)
1581   "Quote CUSTOM's VALUE if necessary."
1582   (list (if (and (not (custom-eval custom value))
1583                  (or (and (symbolp value)
1584                           value 
1585                           (not (eq t value)))
1586                      (and (listp value)
1587                           value
1588                           (not (memq (car value) '(quote function lambda))))))
1589             (list 'quote value)
1590           value)))
1591
1592 (defun custom-default-initialize (custom)
1593   "Initialize `doc' and `default' entries in CUSTOM."
1594   (let ((name (custom-name custom)))
1595     (if (null name)
1596         ()
1597       (let ((default (custom-default custom))
1598             (doc (custom-documentation custom))
1599             (vdoc (documentation-property name 'variable-documentation t)))
1600         (if doc
1601             (or vdoc (put name 'variable-documentation doc))
1602           (if vdoc (custom-property-set custom 'doc vdoc)))
1603         (if (eq default custom-nil)
1604             (if (boundp name)
1605                 (custom-property-set custom 'default (symbol-value name)))
1606           (or (boundp name)
1607               (set name default)))))))
1608
1609 (defun custom-default-insert (custom level)
1610   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
1611   (let ((field (custom-field-create custom custom-nil))
1612         (tag (custom-tag custom)))
1613     (if (null tag)
1614         ()
1615       (custom-tag-insert tag field)
1616       (custom-text-insert ": "))
1617     (custom-field-insert field)
1618     (custom-documentation-insert custom)
1619     field))
1620
1621 (defun custom-default-accept (field value &optional original)
1622   "Store a new value into field FIELD, taking it from VALUE."
1623   (if original 
1624       (custom-field-original-set field value))
1625   (custom-field-value-set field value)
1626   (custom-field-update field))
1627   
1628 (defun custom-default-apply (field)
1629   "Apply any changes in FIELD since the last apply."
1630   (let* ((custom (custom-field-custom field))
1631          (name (custom-name custom)))
1632     (if (null name)
1633         (error "This field cannot be applied alone"))
1634     (custom-external-set name (custom-name-value name))
1635     (custom-field-reset field)))
1636
1637 (defun custom-default-reset (field)
1638   "Reset content of editing FIELD to `original'."
1639   (custom-field-accept field (custom-field-original field) t))
1640
1641 (defun custom-default-factory-reset (field)
1642   "Reset content of editing FIELD to `default'."
1643   (let* ((custom (custom-field-custom field))
1644          (default (car (custom-import custom (custom-default custom)))))
1645     (or (eq default custom-nil)
1646         (custom-field-accept field default nil))))
1647
1648 (defun custom-default-query (field)
1649   "Prompt for a FIELD"
1650   (let* ((custom (custom-field-custom field))
1651          (value (custom-field-value field))
1652          (initial (custom-write custom value))
1653          (prompt (concat (custom-prompt custom) ": ")))
1654     (custom-field-accept field 
1655                          (custom-read custom 
1656                                       (if (custom-valid custom value)
1657                                           (read-string prompt (cons initial 1))
1658                                         (read-string prompt))))))
1659
1660 (defun custom-default-match (custom values)
1661   "Match CUSTOM with VALUES."
1662   values)
1663
1664 (defun custom-default-extract (custom field)
1665   "Extract CUSTOM's content in FIELD."
1666   (list (custom-field-value field)))
1667
1668 (defun custom-default-validate (custom field)
1669   "Validate FIELD."
1670   (let ((value (custom-field-value field))
1671         (start (custom-field-start field)))
1672     (cond ((eq value custom-nil)
1673            (cons start "Uninitialized field"))
1674           ((and (consp value) (eq (car value) custom-invalid))
1675            (cons start "Unparseable field content"))
1676           ((custom-valid custom value)
1677            nil)
1678           (t
1679            (cons start "Wrong type of field content")))))
1680
1681 (defun custom-default-face (field)
1682   "Face used for a FIELD."
1683   (let ((value (custom-field-value field)))
1684     (cond ((eq value custom-nil)
1685            custom-field-uninitialized-face)
1686           ((not (custom-valid (custom-field-custom field) value))
1687            custom-field-invalid-face)
1688           ((not (equal (custom-field-original field) value))
1689            custom-field-modified-face)
1690           (t
1691            custom-field-face))))
1692
1693 (defun custom-default-update (field)
1694   "Update the content of FIELD."
1695   (let ((inhibit-point-motion-hooks t)
1696         (before-change-functions nil)
1697         (after-change-functions nil)
1698         (start (custom-field-start field))
1699         (end (custom-field-end field)) 
1700         (pos (point)))
1701     ;; Keep track of how many modified fields we have.
1702     (cond ((equal (custom-field-value field) (custom-field-original field))
1703            (setq custom-modified-list (delq field custom-modified-list)))
1704           ((memq field custom-modified-list))
1705           (t
1706            (setq custom-modified-list (cons field custom-modified-list))))
1707     ;; Update the field.
1708     (goto-char end)
1709     (insert-before-markers " ")
1710     (delete-region start (1- end))
1711     (goto-char start)
1712     (custom-field-insert field)
1713     (goto-char end)
1714     (delete-char 1)
1715     (goto-char pos)
1716     (and (<= start pos) 
1717          (<= pos end)
1718          (custom-field-enter field))))
1719
1720 ;;; Create Buffer:
1721 ;;
1722 ;; Public functions to create a customization buffer and to insert
1723 ;; various forms of text, fields, and buttons in it.
1724
1725 (defun customize ()
1726   "Customize GNU Emacs.
1727 Create a *Customize* buffer with editable customization information
1728 about GNU Emacs." 
1729   (interactive)
1730   (custom-buffer-create "*Customize*")
1731   (custom-reset-all))
1732
1733 (defun custom-buffer-create (name &optional custom types set get save)
1734   "Create a customization buffer named NAME.
1735 If the optional argument CUSTOM is non-nil, use that as the custom declaration.
1736 If the optional argument TYPES is non-nil, use that as the local types.
1737 If the optional argument SET is non-nil, use that to set external data.
1738 If the optional argument GET is non-nil, use that to get external data.
1739 If the optional argument SAVE is non-nil, use that for saving changes."
1740   (switch-to-buffer name)
1741   (buffer-disable-undo (current-buffer))
1742   (custom-mode)
1743   (setq custom-local-type-properties types)
1744   (if (null custom)
1745       ()
1746     (make-local-variable 'custom-data)
1747     (setq custom-data custom))
1748   (if (null set)
1749       ()
1750     (make-local-variable 'custom-external-set)
1751     (setq custom-external-set set))
1752   (if (null get)
1753       ()
1754     (make-local-variable 'custom-external)
1755     (setq custom-external get))
1756   (if (null save)
1757       ()
1758     (make-local-variable 'custom-save)
1759     (setq custom-save save))
1760   (let ((inhibit-point-motion-hooks t)
1761         (before-change-functions nil)
1762         (after-change-functions nil))
1763     (erase-buffer)
1764     (insert "\n")
1765     (goto-char (point-min))
1766     (custom-text-insert "This is a customization buffer.\n")
1767     (custom-help-insert "\n")
1768     (custom-help-button 'custom-forward-field)
1769     (custom-help-button 'custom-backward-field)
1770     (custom-help-button 'custom-enter-value)
1771     (custom-help-button 'custom-field-factory-reset)
1772     (custom-help-button 'custom-field-reset)
1773     (custom-help-button 'custom-field-apply)
1774     (custom-help-button 'custom-save-and-exit)
1775     (custom-help-button 'custom-toggle-documentation)
1776     (custom-help-insert "\nClick mouse-2 on any button to activate it.\n")
1777     (custom-text-insert "\n")
1778     (custom-insert custom-data 0)
1779     (goto-char (point-min))))
1780
1781 (defun custom-insert (custom level)
1782   "Insert custom declaration CUSTOM in current buffer at level LEVEL."
1783   (if (stringp custom)
1784       (progn 
1785         (custom-text-insert custom)
1786         nil)
1787     (and level (null (custom-property custom 'header))
1788          (setq level nil))
1789     (and level 
1790          (> level 0)
1791          (custom-text-insert (concat "\n" (make-string level ?*) " ")))
1792     (let ((field (funcall (custom-property custom 'insert) custom level)))
1793       (custom-name-enter (custom-name custom) field)
1794       field)))
1795
1796 (defun custom-text-insert (text)
1797   "Insert TEXT in current buffer." 
1798   (insert text))
1799
1800 (defun custom-tag-insert (tag field &optional data)
1801   "Insert TAG for FIELD in current buffer."
1802   (let ((from (point)))
1803     (insert tag)
1804     (custom-category-set from (point) 'custom-button-properties)
1805     (put-text-property from (point) 'custom-tag field)
1806     (if data
1807         (add-text-properties from (point) (list 'custom-data data)))))
1808
1809 (defun custom-documentation-insert (custom &rest ignore)
1810   "Insert documentation from CUSTOM in current buffer."
1811   (let ((doc (custom-documentation custom)))
1812     (if (null doc)
1813         ()
1814       (custom-help-insert "\n" doc))))
1815
1816 (defun custom-help-insert (&rest args)
1817   "Insert ARGS as documentation text."
1818   (let ((from (point)))
1819     (apply 'insert args)
1820     (custom-category-set from (point) 'custom-documentation-properties)))
1821
1822 (defun custom-help-button (command)
1823   "Describe how to execute COMMAND."
1824   (let ((from (point)))
1825     (insert "`" (key-description (where-is-internal command nil t)) "'")
1826     (custom-set-text-properties from (point)
1827                          (list 'face custom-button-face
1828                                mouse-face custom-mouse-face
1829                                'custom-jump t ;Make TAB jump over it.
1830                                'custom-tag command))
1831     (custom-category-set from (point) 'custom-documentation-properties))
1832   (custom-help-insert ": " (custom-first-line (documentation command)) "\n"))
1833
1834 ;;; Mode:
1835 ;;
1836 ;; The Customization major mode and interactive commands. 
1837
1838 (defvar custom-mode-map nil
1839   "Keymap for Custum Mode.")
1840 (if custom-mode-map
1841     nil
1842   (setq custom-mode-map (make-sparse-keymap))
1843   (define-key custom-mode-map (if (string-match "XEmacs" emacs-version) [button2] [mouse-2]) 'custom-push-button)
1844   (define-key custom-mode-map "\t" 'custom-forward-field)
1845   (define-key custom-mode-map "\M-\t" 'custom-backward-field)
1846   (define-key custom-mode-map "\r" 'custom-enter-value)
1847   (define-key custom-mode-map "\C-k" 'custom-kill-line)
1848   (define-key custom-mode-map "\C-c\C-r" 'custom-field-reset)
1849   (define-key custom-mode-map "\C-c\M-\C-r" 'custom-reset-all)
1850   (define-key custom-mode-map "\C-c\C-z" 'custom-field-factory-reset)
1851   (define-key custom-mode-map "\C-c\M-\C-z" 'custom-factory-reset-all)
1852   (define-key custom-mode-map "\C-c\C-a" 'custom-field-apply)
1853   (define-key custom-mode-map "\C-c\M-\C-a" 'custom-apply-all)
1854   (define-key custom-mode-map "\C-c\C-c" 'custom-save-and-exit)
1855   (define-key custom-mode-map "\C-c\C-d" 'custom-toggle-documentation))
1856
1857 ;; C-c keymap ideas: C-a field-beginning, C-e field-end, C-f
1858 ;; forward-field, C-b backward-field, C-n next-field, C-p
1859 ;; previous-field, ? describe-field.
1860
1861 (defun custom-mode ()
1862   "Major mode for doing customizations.
1863
1864 \\{custom-mode-map}"
1865   (kill-all-local-variables)
1866   (setq major-mode 'custom-mode
1867         mode-name "Custom")
1868   (use-local-map custom-mode-map)
1869   (make-local-variable 'before-change-functions)
1870   (setq before-change-functions '(custom-before-change))
1871   (make-local-variable 'after-change-functions)
1872   (setq after-change-functions '(custom-after-change))
1873   (if (not (fboundp 'make-local-hook))
1874       ;; Emacs 19.28 and earlier.
1875       (add-hook 'post-command-hook 
1876                 (lambda ()
1877                   (if (eq major-mode 'custom-mode)
1878                       (custom-post-command))))
1879     ;; Emacs 19.29.
1880     (make-local-hook 'post-command-hook)
1881     (add-hook 'post-command-hook 'custom-post-command nil t)))
1882
1883 (defun custom-forward-field (arg)
1884   "Move point to the next field or button.
1885 With optional ARG, move across that many fields."
1886   (interactive "p")
1887   (while (> arg 0)
1888     (let ((next (if (get-text-property (point) 'custom-tag)
1889                     (next-single-property-change (point) 'custom-tag)
1890                   (point))))
1891       (setq next (or (next-single-property-change next 'custom-tag)
1892                      (next-single-property-change (point-min) 'custom-tag)))
1893       (if next
1894           (goto-char next)
1895         (error "No customization fields in this buffer.")))
1896     (or (get-text-property (point) 'custom-jump)
1897         (setq arg (1- arg))))
1898   (while (< arg 0)
1899     (let ((previous (if (get-text-property (1- (point)) 'custom-tag)
1900                         (previous-single-property-change (point) 'custom-tag)
1901                       (point))))
1902       (setq previous
1903             (or (previous-single-property-change previous 'custom-tag)
1904                 (previous-single-property-change (point-max) 'custom-tag)))
1905       (if previous
1906           (goto-char previous)
1907         (error "No customization fields in this buffer.")))
1908     (or (get-text-property (1- (point)) 'custom-jump)
1909         (setq arg (1+ arg)))))
1910
1911 (defun custom-backward-field (arg)
1912   "Move point to the previous field or button.
1913 With optional ARG, move across that many fields."
1914   (interactive "p")
1915   (custom-forward-field (- arg)))
1916
1917 (defun custom-toggle-documentation (&optional arg)
1918   "Toggle display of documentation text.
1919 If the optional argument is non-nil, show text iff the argument is positive."
1920   (interactive "P")
1921   (let ((hide (or (and (null arg) 
1922                        (null (custom-category-get 
1923                               'custom-documentation-properties 'invisible)))
1924                   (<= (prefix-numeric-value arg) 0))))
1925     (custom-category-put 'custom-documentation-properties 'invisible hide)
1926     (custom-category-put 'custom-documentation-properties intangible hide))
1927   (redraw-display))
1928
1929 (defun custom-enter-value (field data)
1930   "Enter value for current customization field or push button."
1931   (interactive (list (get-text-property (point) 'custom-tag)
1932                      (get-text-property (point) 'custom-data)))
1933   (cond (data
1934          (funcall field data))
1935         ((eq field 'custom-enter-value)
1936          (error "Don't be silly"))
1937         ((and (symbolp field) (fboundp field))
1938          (call-interactively field))
1939         (field
1940          (custom-field-query field))
1941         (t
1942          (message "Nothing to enter here"))))
1943
1944 (defun custom-kill-line ()
1945   "Kill to end of field or end of line, whichever is first."
1946   (interactive)
1947   (let ((field (get-text-property (point) 'custom-field))
1948         (newline (save-excursion (search-forward "\n")))
1949         (next (next-single-property-change (point) 'custom-field)))
1950     (if (and field (> newline next))
1951         (kill-region (point) next)
1952       (call-interactively 'kill-line))))
1953
1954 (defun custom-push-button (event)
1955   "Activate button below mouse pointer."
1956   (interactive "@e")
1957   (let* ((pos (event-point event))
1958          (field (get-text-property pos 'custom-field))
1959          (tag (get-text-property pos 'custom-tag))
1960          (data (get-text-property pos 'custom-data)))
1961     (cond (data
1962             (funcall tag data))
1963           ((and (symbolp tag) (fboundp tag))
1964            (call-interactively tag))
1965           (field
1966            (call-interactively (lookup-key global-map (this-command-keys))))
1967           (tag
1968            (custom-enter-value tag data))
1969           (t 
1970            (error "Nothing to click on here.")))))
1971
1972 (defun custom-reset-all ()
1973   "Undo any changes since the last apply in all fields."
1974   (interactive (and custom-modified-list
1975                     (not (y-or-n-p "Discard all changes? "))
1976                     (error "Reset aborted")))
1977   (let ((all custom-name-fields)
1978         current field)
1979     (while all
1980       (setq current (car all)
1981             field (cdr current)
1982             all (cdr all))
1983       (custom-field-reset field))))
1984
1985 (defun custom-field-reset (field)
1986   "Undo any changes in FIELD since the last apply."
1987   (interactive (list (or (get-text-property (point) 'custom-field)
1988                          (get-text-property (point) 'custom-tag))))
1989   (if (arrayp field)
1990       (let* ((custom (custom-field-custom field))
1991              (name (custom-name custom)))
1992         (save-excursion
1993           (if name
1994               (custom-field-original-set 
1995                field (car (custom-import custom (custom-external name)))))
1996           (if (not (custom-valid custom (custom-field-original field)))
1997               (error "This field cannot be reset alone")
1998             (funcall (custom-property custom 'reset) field)
1999             (funcall (custom-property custom 'synchronize) field))))))
2000
2001 (defun custom-factory-reset-all ()
2002   "Reset all field to their default values."
2003   (interactive (and custom-modified-list
2004                     (not (y-or-n-p "Discard all changes? "))
2005                     (error "Reset aborted")))
2006   (let ((all custom-name-fields)
2007         field)
2008     (while all
2009       (setq field (cdr (car all))
2010             all (cdr all))
2011       (custom-field-factory-reset field))))
2012
2013 (defun custom-field-factory-reset (field)
2014   "Reset FIELD to its default value."
2015   (interactive (list (or (get-text-property (point) 'custom-field)
2016                          (get-text-property (point) 'custom-tag))))
2017   (if (arrayp field)
2018       (save-excursion
2019         (funcall (custom-property (custom-field-custom field) 'factory-reset)
2020                  field))))
2021
2022 (defun custom-apply-all ()
2023   "Apply any changes since the last reset in all fields."
2024   (interactive (if custom-modified-list
2025                    nil
2026                  (error "No changes to apply.")))
2027   (custom-field-parse custom-field-last)
2028   (let ((all custom-name-fields)
2029         field)
2030     (while all
2031       (setq field (cdr (car all))
2032             all (cdr all))
2033       (let ((error (custom-field-validate (custom-field-custom field) field)))
2034         (if (null error)
2035             ()
2036           (goto-char (car error))
2037           (error (cdr error))))))
2038   (let ((all custom-name-fields)
2039         field)
2040     (while all
2041       (setq field (cdr (car all))
2042             all (cdr all))
2043       (custom-field-apply field))))
2044
2045 (defun custom-field-apply (field)
2046   "Apply any changes in FIELD since the last apply."
2047   (interactive (list (or (get-text-property (point) 'custom-field)
2048                          (get-text-property (point) 'custom-tag))))
2049   (custom-field-parse custom-field-last)
2050   (if (arrayp field)
2051       (let* ((custom (custom-field-custom field))
2052              (error (custom-field-validate custom field)))
2053         (if error
2054             (error (cdr error)))
2055         (funcall (custom-property custom 'apply) field))))
2056
2057 (defun custom-toggle-hide (&rest ignore)
2058   "Hide or show entry."
2059   (interactive)
2060   (error "This button is not yet implemented"))
2061
2062 (defun custom-save-and-exit ()
2063   "Save and exit customization buffer."
2064   (interactive "@")
2065   (save-excursion
2066    (funcall custom-save))
2067   (kill-buffer (current-buffer)))
2068
2069 (defun custom-save ()
2070   "Save customization information."
2071   (interactive)
2072   (custom-apply-all)
2073   (let ((new custom-name-fields))
2074     (set-buffer (find-file-noselect custom-file))
2075     (goto-char (point-min))
2076     (save-excursion
2077       (let ((old (condition-case nil
2078                      (read (current-buffer))
2079                    (end-of-file (append '(setq custom-dummy
2080                                                'custom-dummy) ())))))
2081         (or (eq (car old) 'setq)
2082             (error "Invalid customization file: %s" custom-file))
2083         (while new
2084           (let* ((field (cdr (car new)))
2085                  (custom (custom-field-custom field))
2086                  (value (custom-field-original field))
2087                  (default (car (custom-import custom (custom-default custom))))
2088                  (name (car (car new))))
2089             (setq new (cdr new))
2090             (custom-assert '(eq name (custom-name custom)))
2091             (if (equal default value)
2092                 (setcdr old (custom-plist-delq name (cdr old)))
2093               (setcdr old (plist-put (cdr old) name 
2094                                      (car (custom-quote custom value)))))))
2095         (erase-buffer)
2096         (insert ";; " custom-file "\
2097  --- Automatically generated customization information.
2098 ;; 
2099 ;; Feel free to edit by hand, but the entire content should consist of
2100 ;; a single setq.  Any other lisp expressions will confuse the
2101 ;; automatic configuration engine.
2102
2103 \(setq ")
2104         (setq old (cdr old))
2105         (while old
2106           (prin1 (car old) (current-buffer))
2107           (setq old (cdr old))
2108           (insert " ")
2109           (pp (car old) (current-buffer))
2110           (setq old (cdr old))
2111           (if old (insert "\n      ")))
2112         (insert ")\n")
2113         (save-buffer)
2114         (kill-buffer (current-buffer))))))
2115
2116 (defun custom-load ()
2117   "Save customization information."
2118   (interactive (and custom-modified-list
2119                     (not (equal (list (custom-name-field 'custom-file))
2120                                 custom-modified-list))
2121                     (not (y-or-n-p "Discard all changes? "))
2122                     (error "Load aborted")))
2123   (load-file (custom-name-value 'custom-file))
2124   (custom-reset-all))
2125
2126 ;;; Field Editing:
2127 ;;
2128 ;; Various internal functions for implementing the direct editing of
2129 ;; fields in the customization buffer.
2130
2131 (defun custom-field-untouch (field)
2132   ;; Remove FIELD and its children from `custom-modified-list'.
2133   (setq custom-modified-list (delq field custom-modified-list))
2134   (if (arrayp field)
2135       (let ((value (custom-field-value field)))
2136         (cond ((null (custom-data (custom-field-custom field))))
2137               ((arrayp value)
2138                (custom-field-untouch value))
2139               ((listp value)
2140                (mapcar 'custom-field-untouch value))))))
2141
2142
2143 (defun custom-field-insert (field)
2144   ;; Insert editing FIELD in current buffer.
2145   (let ((from (point))
2146         (custom (custom-field-custom field))
2147         (value (custom-field-value field)))
2148     (insert (custom-write custom value))
2149     (insert-char (custom-padding custom)
2150                  (- (custom-width custom) (- (point) from)))
2151     (custom-field-move field from (point))
2152     (custom-set-text-properties 
2153      from (point)
2154      (list 'custom-field field
2155            'custom-tag field
2156            'face (custom-field-face field)
2157            front-sticky t))))
2158
2159 (defun custom-field-read (field)
2160   ;; Read the screen content of FIELD.
2161   (custom-read (custom-field-custom field)
2162                (buffer-substring-no-properties (custom-field-start field)
2163                                                (custom-field-end field))))
2164
2165 ;; Fields are shown in a special `active' face when point is inside
2166 ;; it.  You activate the field by moving point inside (entering) it
2167 ;; and deactivate the field by moving point outside (leaving) it.
2168
2169 (defun custom-field-leave (field)
2170   ;; Deactivate FIELD.
2171   (let ((before-change-functions nil)
2172         (after-change-functions nil))
2173     (put-text-property (custom-field-start field) (custom-field-end field)
2174                        'face (custom-field-face field))))
2175
2176 (defun custom-field-enter (field)
2177   ;; Activate FIELD.
2178   (let* ((start (custom-field-start field)) 
2179          (end (custom-field-end field))
2180          (custom (custom-field-custom field))
2181          (padding (custom-padding custom))
2182          (before-change-functions nil)
2183          (after-change-functions nil))
2184     (or (eq this-command 'self-insert-command)
2185         (let ((pos end))
2186           (while (and (< start pos)
2187                       (eq (char-after (1- pos)) padding))
2188             (setq pos (1- pos)))
2189           (if (< pos (point))
2190               (goto-char pos))))
2191     (put-text-property start end 'face custom-field-active-face)))
2192
2193 (defun custom-field-resize (field)
2194   ;; Resize FIELD after change.
2195   (let* ((custom (custom-field-custom field))
2196          (begin (custom-field-start field))
2197          (end (custom-field-end field))
2198          (pos (point))
2199          (padding (custom-padding custom))
2200          (width (custom-width custom))
2201          (size (- end begin)))
2202     (cond ((< size width)
2203            (goto-char end)
2204            (if (fboundp 'insert-before-markers-and-inherit)
2205                ;; Emacs 19.
2206                (insert-before-markers-and-inherit
2207                 (make-string (- width size) padding))
2208              ;; XEmacs:  BUG:  Doesn't work!
2209              (insert-before-markers (make-string (- width size) padding)))
2210            (goto-char pos))
2211           ((> size width)
2212            (let ((start (if (and (< (+ begin width) pos) (<= pos end))
2213                             pos
2214                           (+ begin width))))
2215              (goto-char end)
2216              (while (and (< start (point)) (= (preceding-char) padding))
2217                (backward-delete-char 1))
2218              (goto-char pos))))))
2219
2220 (defvar custom-field-changed nil)
2221 ;; List of fields changed on the screen but whose VALUE attribute has
2222 ;; not yet been updated to reflect the new screen content.
2223 (make-variable-buffer-local 'custom-field-changed)
2224
2225 (defun custom-field-parse (field)
2226   ;; Parse FIELD content iff changed.
2227   (if (memq field custom-field-changed)
2228       (progn 
2229         (setq custom-field-changed (delq field custom-field-changed))
2230         (custom-field-value-set field (custom-field-read field))
2231         (custom-field-update field))))
2232
2233 (defun custom-post-command ()
2234   ;; Keep track of their active field.
2235   (custom-assert '(eq major-mode 'custom-mode))
2236   (let ((field (custom-field-property (point))))
2237     (if (eq field custom-field-last)
2238         (if (memq field custom-field-changed)
2239             (custom-field-resize field))
2240       (custom-field-parse custom-field-last)
2241       (if custom-field-last
2242           (custom-field-leave custom-field-last))
2243       (if field
2244           (custom-field-enter field))
2245       (setq custom-field-last field))
2246     (set-buffer-modified-p (or custom-modified-list
2247                                custom-field-changed))))
2248
2249 (defvar custom-field-was nil)
2250 ;; The custom data before the change.
2251 (make-variable-buffer-local 'custom-field-was)
2252
2253 (defun custom-before-change (begin end)
2254   ;; Check that we the modification is allowed.
2255   (if (not (eq major-mode 'custom-mode))
2256       (message "Aargh! Why is custom-before-change called here?")
2257     (let ((from (custom-field-property begin))
2258           (to (custom-field-property end)))
2259       (cond ((or (null from) (null to))
2260              (error "You can only modify the fields"))
2261             ((not (eq from to))
2262              (error "Changes must be limited to a single field."))
2263             (t
2264              (setq custom-field-was from))))))
2265
2266 (defun custom-after-change (begin end length)
2267   ;; Keep track of field content.
2268   (if (not (eq major-mode 'custom-mode))
2269       (message "Aargh! Why is custom-after-change called here?")
2270     (let ((field custom-field-was))
2271       (custom-assert '(prog1 field (setq custom-field-was nil)))
2272       ;; Prevent mixing fields properties.
2273       (put-text-property begin end 'custom-field field)
2274       ;; Update the field after modification.
2275       (if (eq (custom-field-property begin) field)
2276           (let ((field-end (custom-field-end field)))
2277             (if (> end field-end)
2278                 (set-marker field-end end))
2279             (add-to-list 'custom-field-changed field))
2280         ;; We deleted the entire field, reinsert it.
2281         (custom-assert '(eq begin end))
2282         (save-excursion
2283           (goto-char begin)
2284           (custom-field-value-set field
2285                                   (custom-read (custom-field-custom field) ""))
2286           (custom-field-insert field))))))
2287
2288 (defun custom-field-property (pos)
2289   ;; The `custom-field' text property valid for POS.
2290   (or (get-text-property pos 'custom-field)
2291       (and (not (eq pos (point-min)))
2292            (get-text-property (1- pos) 'custom-field))))
2293
2294 ;;; Generic Utilities:
2295 ;;
2296 ;; Some utility functions that are not really specific to custom.
2297
2298 (defun custom-assert (expr)
2299   "Assert that EXPR evaluates to non-nil at this point"
2300   (or (eval expr)
2301       (error "Assertion failed: %S" expr)))
2302
2303 (defun custom-first-line (string)
2304   "Return the part of STRING before the first newline."
2305   (let ((pos 0)
2306         (len (length string)))
2307     (while (and (< pos len) (not (eq (aref string pos) ?\n)))
2308       (setq pos (1+ pos)))
2309     (if (eq pos len)
2310         string
2311     (substring string 0 pos))))
2312
2313 (defun custom-insert-before (list old new)
2314   "In LIST insert before OLD a NEW element."
2315   (cond ((null list)
2316          (list new))
2317         ((null old)
2318          (nconc list (list new)))
2319         ((eq old (car list))
2320          (cons new list))
2321         (t
2322          (let ((list list))
2323            (while (not (eq old (car (cdr list))))
2324              (setq list (cdr list))
2325              (custom-assert '(cdr list)))
2326            (setcdr list (cons new (cdr list))))
2327          list)))
2328
2329 (defun custom-strip-padding (string padding)
2330   "Remove padding from STRING."
2331   (let ((regexp (concat (regexp-quote (char-to-string padding)) "+")))
2332     (while (string-match regexp string)
2333       (setq string (concat (substring string 0 (match-beginning 0))
2334                            (substring string (match-end 0))))))
2335   string)
2336
2337 (defun custom-plist-memq (prop plist)
2338   "Return non-nil if PROP is a property of PLIST.  Comparison done with EQ."
2339   (let (result)
2340     (while plist
2341       (if (eq (car plist) prop)
2342           (setq result plist
2343                 plist nil)
2344         (setq plist (cdr (cdr plist)))))
2345     result))
2346
2347 (defun custom-plist-delq (prop plist)
2348   "Delete property PROP from property list PLIST."
2349   (while (eq (car plist) prop)
2350     (setq plist (cdr (cdr plist))))
2351   (let ((list plist)
2352         (next (cdr (cdr plist))))
2353     (while next
2354       (if (eq (car next) prop)
2355           (progn 
2356             (setq next (cdr (cdr next)))
2357             (setcdr (cdr list) next))
2358         (setq list next
2359               next (cdr (cdr next))))))
2360   plist)
2361
2362 ;;; Meta Customization:
2363
2364 (custom-declare '()
2365   '((tag . "Meta Customization")
2366     (doc . "Customization of the customization support.")
2367     (type . group)
2368     (data ((type . face-doc))
2369           ((tag . "Button Face")
2370            (default . bold)
2371            (doc . "Face used for tags in customization buffers.")
2372            (name . custom-button-face)
2373            (synchronize . (lambda (f)
2374                             (custom-category-put 'custom-button-properties 
2375                                                  'face custom-button-face)))
2376            (type . face))
2377           ((tag . "Mouse Face")
2378            (default . highlight)
2379            (doc . "\
2380 Face used when mouse is above a button in customization buffers.")
2381            (name . custom-mouse-face)
2382            (synchronize . (lambda (f)
2383                             (custom-category-put 'custom-button-properties 
2384                                                  mouse-face 
2385                                                  custom-mouse-face)))
2386            (type . face))
2387           ((tag . "Field Face")
2388            (default . italic)
2389            (doc . "Face used for customization fields.")
2390            (name . custom-field-face)
2391            (type . face))
2392           ((tag . "Uninitialized Face")
2393            (default . modeline)
2394            (doc . "Face used for uninitialized customization fields.")
2395            (name . custom-field-uninitialized-face)
2396            (type . face))
2397           ((tag . "Invalid Face")
2398            (default . highlight)
2399            (doc . "\
2400 Face used for customization fields containing invalid data.")
2401            (name . custom-field-invalid-face)
2402            (type . face))
2403           ((tag . "Modified Face")
2404            (default . bold-italic)
2405            (doc . "Face used for modified customization fields.")
2406            (name . custom-field-modified-face)
2407            (type . face))
2408           ((tag . "Active Face")
2409            (default . underline)
2410            (doc . "\
2411 Face used for customization fields while they are being edited.")
2412            (name . custom-field-active-face)
2413            (type . face)))))
2414
2415 ;; custom.el uses two categories.
2416
2417 (custom-category-create 'custom-documentation-properties)
2418 (custom-category-put 'custom-documentation-properties rear-nonsticky t)
2419
2420 (custom-category-create 'custom-button-properties)
2421 (custom-category-put 'custom-button-properties 'face custom-button-face)
2422 (custom-category-put 'custom-button-properties mouse-face custom-mouse-face)
2423 (custom-category-put 'custom-button-properties rear-nonsticky t)
2424
2425 (custom-category-create 'custom-hidden-properties)
2426 (custom-category-put 'custom-hidden-properties 'invisible
2427                      (not (string-match "XEmacs" emacs-version)))
2428 (custom-category-put 'custom-hidden-properties intangible t)
2429
2430 (if (file-readable-p custom-file)
2431     (load-file custom-file))
2432
2433 (provide 'custom)
2434
2435 ;;; custom.el ends here