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