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