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