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