*** 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.2
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 ;; - Add description of faces to buffer and mode.
36 ;; - Function to generate a XEmacs menu from a CUSTOM.
37 ;; - Add support for customizing packages.
38 ;; - Make it possible to hide sections by clicling at the level stars.
39 ;; - Declare AUC TeX variables.
40 ;; - Declare (ding) Gnus variables.
41 ;; - Declare Emacs variables.
42 ;; - Implement remaining types.
43 ;; - XEmacs port.
44
45 ;;; Code:
46
47 ;;; Compatibility:
48
49 (or (fboundp 'buffer-substring-no-properties)
50     ;; Introduced in Emacs 19.29.
51     (defun buffer-substring-no-properties (beg end)
52       "Return the text from BEG to END, without text properties, as a string."
53       (let ((string (buffer-substring beg end)))
54         (set-text-properties 0 (length string) nil string)
55         string)))
56
57 (or (fboundp 'add-to-list)
58     ;; Introduced in Emacs 19.29.
59     (defun add-to-list (list-var element)
60       "Add to the value of LIST-VAR the element ELEMENT if it isn't there yet.
61 If you want to use `add-to-list' on a variable that is not defined
62 until a certain package is loaded, you should put the call to `add-to-list'
63 into a hook function that will be run only after loading the package.
64 `eval-after-load' provides one way to do this.  In some cases
65 other hooks, such as major mode hooks, can do the job."
66       (or (member element (symbol-value list-var))
67           (set list-var (cons element (symbol-value list-var))))))
68
69 (defvar intangible nil
70   "The symbol making text intangible")
71
72 ;; We can't easily check for a working intangible.
73 (if (and (boundp 'emacs-minor-version)
74          (or (> emacs-major-version 19)
75              (and (> emacs-major-version 18)
76                   (> emacs-minor-version 28))))
77     (setq intangible 'intangible)
78   (setq intangible 'intangible-if-it-had-been-working))
79
80 (defvar custom-modified-list nil)
81
82 ;;; Faces:
83 ;;
84 ;; The following variables define the faces used in the customization
85 ;; buffer. 
86
87 (defvar custom-button-face 'bold
88   "Face used for tags in customization buffers.")
89
90 (defvar custom-field-uninitialized-face 'modeline
91   "Face used for uninitialized customization fields.")
92
93 (defvar custom-field-invalid-face 'highlight
94   "Face used for customization fields containing invalid data.")
95
96 (defvar custom-field-modified-face 'bold-italic
97   "Face used for modified customization fields.")
98
99 (defvar custom-field-active-face 'underline
100   "Face used for customization fields while they are being edited.")
101
102 (defvar custom-field-face 'italic
103   "Face used for customization fields.")
104
105 (defvar custom-mouse-face 'highlight
106   "Face used for tags in customization buffers.")
107
108 (defvar custom-documentation-properties 'custom-documentation-properties
109   "The properties of this symbol will be in effect for all documentation.")
110 (put custom-documentation-properties 'rear-nonsticky t)
111
112 (defvar custom-button-properties 'custom-button-properties 
113   "The properties of this symbol will be in effect for all buttons.")
114 (put custom-button-properties 'face custom-button-face)
115 (put custom-button-properties 'mouse-face custom-mouse-face)
116 (put custom-button-properties 'rear-nonsticky t)
117
118 ;;; External Data:
119 ;; 
120 ;; The following functions and variables defines the interface for
121 ;; connecting a CUSTOM with an external entity, by default an emacs
122 ;; lisp variable.
123
124 (defvar custom-external 'default-value
125   "Function returning the external value of NAME.")
126
127 (defvar custom-external-set 'set-default
128   "Function setting the external value of NAME to VALUE.")
129
130 (defun custom-external (name)
131   "Get the external value associated with NAME."
132   (funcall custom-external name))
133
134 (defun custom-external-set (name value)
135   "Set the external value associated with NAME to VALUE."
136   (funcall custom-external-set name value))
137
138 (defvar custom-name-fields nil
139   "Alist of custom names and their associated editing field.")
140 (make-variable-buffer-local 'custom-name-fields)
141
142 (defun custom-name-enter (name field)
143   "Associate NAME with FIELD."
144   (if (null name)
145       ()
146     (custom-assert 'field)
147     (setq custom-name-fields (cons (cons name field) custom-name-fields))))
148
149 (defun custom-name-value (name)
150   "The value currently displayed for NAME in the customization buffer."
151   (let ((field (cdr (assq name custom-name-fields))))
152     (car (custom-field-extract (custom-field-custom field) field))))
153
154 ;;; Custom Functions:
155 ;;
156 ;; The following functions are part of the public interface to the
157 ;; CUSTOM datastructure.  Each CUSTOM describes a group of variables,
158 ;; a single variable, or a component of a structured variable.  The
159 ;; CUSTOM instances are part of two hiearachies, the first is the
160 ;; `part-of' hierarchy in which each CUSTOM is a component of another
161 ;; CUSTOM, except for the top level CUSTOM which is contained in
162 ;; `custom-data'.  The second hiearachy is a `is-a' type hierarchy
163 ;; where each CUSTOM is a leaf in the hierarchy defined by the `type'
164 ;; property and `custom-type-properties'.
165
166 (defconst custom-data
167   '((tag . "Emacs")
168     (doc . "The extensible self-documenting text editor.")
169     (type . group)
170     (data . nil))
171   "The global customization information.  
172 A custom association list.")
173
174 (defconst custom-type-properties
175   '((repeat (type . default)
176             (accept . custom-repeat-accept)
177             (extract . custom-repeat-extract)
178             (validate . custom-repeat-validate)
179             (insert . custom-repeat-insert)
180             (match . custom-repeat-match)
181             (query . custom-repeat-query)
182             (del-tag . "[DEL]")
183             (add-tag . "[INS]"))
184     (list (type . group)
185           (extract . custom-list-extract)
186           (validate . custom-list-validate)
187           (check . custom-list-check))
188     (group (type . default)
189            (extract . nil)
190            (validate . nil)
191            (query . custom-toggle-hide)
192            (accept . custom-group-accept)
193            (insert . custom-group-insert))
194     (toggle (type . choice)
195             (data ((type . const)
196                    (tag . "On")
197                    (default . t))
198                   ((type . const)
199                    (tag . "Off")
200                    (default . nil))))
201     (choice (type . default)
202             (query . custom-choice-query)
203             (accept . custom-choice-accept)
204             (extract . custom-choice-extract)
205             (validate . custom-choice-validate)
206             (check . custom-choice-check)
207             (insert . custom-choice-insert)
208             (none (tag . "Unknown")
209                   (default . __uninitialized__)
210                   (type . const)))
211     (const (type . default)
212            (accept . ignore)
213            (extract . (lambda (c f) (list (custom-default c))))
214            (validate . (lambda (c f) nil))
215            (valid . custom-const-valid)
216            (insert . custom-const-insert))
217     (file (type . string)
218           (directory . nil)
219           (default-file . nil)
220           (query . custom-file-query))
221     (integer (type . default)
222              (width . 10)
223              (valid . (lambda (c d) (integerp d)))
224              (allow-padding . nil)
225              (read . custom-integer-read)
226              (write . custom-integer-write))
227     (string (type . default)
228             (width . 40) 
229             (valid . (lambda (c d) (stringp d)))
230             (read . custom-string-read)
231             (write . custom-string-write))
232     (button (type . default)
233             (accept . ignore)
234             (extract . nil)
235             (validate . nil)
236             (insert . custom-button-insert))
237     (doc (type . default)
238          (rest . nil)
239          (extract . nil)
240          (validate . nil)
241          (insert . custom-documentation-insert))
242     (default (width . 20)
243              (valid . (lambda (c v) t))
244              (insert . custom-default-insert)
245              (query . custom-default-query)
246              (tag . nil)
247              (doc . nil)
248              (header . t)
249              (padding . ? )
250              (allow-padding . t)
251              (extract . custom-default-extract)
252              (validate . custom-default-validate)
253              (reset . custom-default-reset)
254              (accept . custom-default-accept)
255              (match . custom-default-match)
256              (name . nil)
257              (compact . nil)
258              (default . __uninitialized__)))
259   "Alist of default properties for type symbols.
260 The format is `((SYMBOL (PROPERTY . VALUE)... )... )'.")
261
262 (defconst custom-local-type-properties nil
263   "Local type properties.")
264 (make-variable-buffer-local 'custom-local-type-properties)
265
266 (defconst custom-nil '__uninitialized__
267   "Special value representing an uninitialized field.")
268
269 (defun custom-property (custom property)
270   "Extract from CUSTOM property PROPERTY."
271   (let ((entry (assq property custom)))
272     (while (null entry)
273       ;; Look in superclass.
274       (let ((type (custom-type custom)))
275         (setq custom (cdr (or (assq type custom-local-type-properties)
276                               (assq type custom-type-properties)))
277               entry (assq property custom))
278         (custom-assert 'custom)))
279     (cdr entry)))
280
281 (defun custom-type (custom)
282   "Extract `type' from CUSTOM."
283   (cdr (assq 'type custom)))
284
285 (defun custom-name (custom)
286   "Extract `name' from CUSTOM."
287   (custom-property custom 'name))
288
289 (defun custom-tag (custom)
290   "Extract `tag' from CUSTOM."
291   (custom-property custom 'tag))
292
293 (defun custom-tag-or-type (custom)
294   "Extract `tag' from CUSTOM.  If none exist, create one from `type'"
295   (or (custom-property custom 'tag)
296       (capitalize (symbol-name (custom-type custom)))))
297
298 (defun custom-default (custom)
299   "Extract `default' from CUSTOM."
300   (custom-property custom 'default))
301
302 (defun custom-data (custom)
303   "Extract the `data' from CUSTOM."
304   (custom-property custom 'data))
305
306 (defun custom-documentation (custom)
307   "Extract `doc' from CUSTOM."
308   (custom-property custom 'doc))
309
310 (defun custom-width (custom)
311   "Extract `width' from CUSTOM."
312   (custom-property custom 'width))
313
314 (defun custom-compact (custom)
315   "Extract `compact' from CUSTOM."
316   (custom-property custom 'compact))
317
318 (defun custom-padding (custom)
319   "Extract `padding' from CUSTOM."
320   (custom-property custom 'padding))
321
322 (defun custom-allow-padding (custom)
323   "Extract `allow-padding' from CUSTOM."
324   (custom-property custom 'allow-padding))
325
326 (defun custom-valid (custom value)
327   "Non-nil if CUSTOM may legally be set to VALUE."
328   (funcall (custom-property custom 'valid) custom value))
329
330 (defun custom-write (custom value)
331   "Convert CUSTOM VALUE to a string."
332   (if (eq value custom-nil) 
333       ""
334     (funcall (custom-property custom 'write) custom value)))
335
336 (defun custom-read (custom string)
337   "Convert CUSTOM field content STRING into external form."
338   (funcall (custom-property custom 'read) custom string))
339
340 (defun custom-match (custom values)
341   "Match CUSTOM with a list of VALUES.
342 Return a cons-cell where the car is the sublist of VALUES matching CUSTOM,
343 and the cdr is the remaining VALUES."
344   (if (memq values (list custom-nil nil))
345       (cons custom-nil nil)
346     (funcall (custom-property custom 'match) custom values)))
347
348 (defun custom-field-extract (custom field)
349   "Extract CUSTOM's value in FIELD."
350   (if (stringp custom)
351       nil
352     (funcall (custom-property (custom-field-custom field) 'extract)
353              custom field)))
354
355 (defun custom-field-validate (custom field)
356   "Validate CUSTOM's value in FIELD.
357 Return nil if valid, otherwise return a cons-cell where the car is the
358 position of the error, and the cdr is a text describing the error."
359   (if (stringp custom)
360       nil
361     (funcall (custom-property custom 'validate) custom field)))
362
363 ;;; Field Functions:
364 ;;
365 ;; This section defines the public functions for manipulating the
366 ;; FIELD datatype.  The FIELD instance hold information about a
367 ;; specific editing field in the customization buffer.
368 ;;
369 ;; Each FIELD can be seen as an instanciation of a CUSTOM.
370
371 (defun custom-field-create (custom value)
372   "Create a field structure of type CUSTOM containing VALUE.
373
374 A field structure is an array [ CUSTOM VALUE ORIGINAL START END ], where
375 CUSTOM defines the type of the field, 
376 VALUE is the current value of the field,
377 ORIGINAL is the original value when created, and
378 START and END are markers to the start and end of the field."
379   (vector custom value custom-nil nil nil))
380
381 (defun custom-field-custom (field)
382   "Return the `custom' attribute of FIELD."
383   (aref field 0))
384   
385 (defun custom-field-value (field)
386   "Return the `value' attribute of FIELD."
387   (aref field 1))
388
389 (defun custom-field-original (field)
390   "Return the `original' attribute of FIELD."
391   (aref field 2))
392
393 (defun custom-field-start (field)
394   "Return the `start' attribute of FIELD."
395   (aref field 3))
396
397 (defun custom-field-end (field)
398   "Return the `end' attribute of FIELD."
399   (aref field 4))
400   
401 (defun custom-field-value-set (field value)
402   "Set the `value' attribute of FIELD to VALUE."
403   (aset field 1 value))
404
405 (defun custom-field-original-set (field original)
406   "Set the `original' attribute of FIELD to ORIGINAL."
407   (aset field 2 original))
408
409 (defun custom-field-move (field start end)
410   "Set the `start'and `end' attributes of FIELD to START and END."
411   (set-marker (or (aref field 3) (aset field 3 (make-marker))) start)
412   (set-marker (or (aref field 4) (aset field 4 (make-marker))) end))
413
414 (defun custom-field-query (field)
415   "Query user for content of current field."
416   (funcall (custom-property (custom-field-custom field) 'query) field))
417
418 (defun custom-field-accept (field value &optional original)
419   "Accept FIELD VALUE.  
420 If optional ORIGINAL is non-nil, consider VALUE for the original value."
421   (funcall (custom-property (custom-field-custom field) 'accept) 
422            field value original))
423
424 ;;; Types:
425 ;;
426 ;; The following functions defines type specific actions.
427
428 (defun custom-repeat-accept (field value &optional original)
429   "Enter content of editing FIELD."
430   (let ((values (copy-sequence (custom-field-value field)))
431         (all (custom-field-value field))
432         (start (custom-field-start field))
433         current new)
434     (if original 
435         (custom-field-original-set field value))
436     (while (consp value)
437       (setq new (car value)
438             value (cdr value))
439       (if values
440           ;; Change existing field.
441           (setq current (car values)
442                 values (cdr values))
443         ;; Insert new field if series has grown.
444         (goto-char start)
445         (setq current (custom-repeat-insert-entry field))
446         (setq all (custom-insert-before all nil current))
447         (custom-field-value-set field all))
448       (custom-field-accept current new original))
449     (while (consp values)
450       ;; Delete old field if series has scrunk.
451       (setq current (car values)
452             values (cdr values))
453       (let ((pos (custom-field-start current))
454             data)
455         (while (not data)
456           (setq pos (previous-single-property-change pos 'custom-data))
457           (custom-assert 'pos)
458           (setq data (get-text-property pos 'custom-data))
459           (or (and (arrayp data)
460                    (> (length data) 1)
461                    (eq current (aref data 1)))
462               (setq data nil)))
463         (custom-repeat-delete data)))))
464
465 (defun custom-repeat-insert (custom level)
466   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
467   (let* ((field (custom-field-create custom nil))
468          (add-tag (custom-property custom 'add-tag))
469          (del-tag (custom-property custom 'del-tag))
470          (start (make-marker))
471          (data (vector field nil start nil)))
472     (custom-text-insert "\n")
473     (let ((pos (point)))
474       (custom-tag-insert add-tag 'custom-repeat-add data)
475       (set-marker start pos))
476     (custom-field-move field start (point))
477     (custom-documentation-insert custom)
478     field))
479
480 (defun custom-repeat-insert-entry (repeat)
481   "Insert entry at point in the REPEAT field."
482   (let* ((inhibit-point-motion-hooks t)
483          (inhibit-read-only t)
484          (before-change-function nil)
485          (after-change-function nil)
486          (custom (custom-field-custom repeat))
487          (add-tag (custom-property custom 'add-tag))
488          (del-tag (custom-property custom 'del-tag))
489          (start (make-marker))
490          (end (make-marker))
491          (data (vector repeat nil start end))
492          field)
493     (insert-before-markers "\n")
494     (backward-char 1)
495     (set-marker start (point))
496     (custom-text-insert " ")
497     (aset data 1 (setq field (custom-insert (custom-data custom) nil)))
498     (custom-text-insert " ")
499     (set-marker end (point))
500     (goto-char start)
501     (custom-tag-insert add-tag 'custom-repeat-add data)
502     (custom-text-insert " ")
503     (custom-tag-insert del-tag 'custom-repeat-delete data)
504     (forward-char 1)
505     field))
506
507 (defun custom-repeat-add (data)
508   "Add list entry."
509   (let ((parent (aref data 0))
510         (field (aref data 1))
511         (at (aref data 2))
512         new)
513     (goto-char at)
514     (setq new (custom-repeat-insert-entry parent))
515     (custom-field-value-set parent
516                             (custom-insert-before (custom-field-value parent)
517                                                   field new))))
518
519 (defun custom-repeat-delete (data)
520   "Delete list entry."
521   (let ((inhibit-point-motion-hooks t)
522         (inhibit-read-only t)
523         (before-change-function nil)
524         (after-change-function nil)
525         (parent (aref data 0))
526         (field (aref data 1)))
527     (delete-region (aref data 2) (1+ (aref data 3)))
528     (custom-field-untouch (aref data 1))
529     (custom-field-value-set parent 
530                             (delq field (custom-field-value parent)))))
531
532 (defun custom-repeat-match (custom values)
533   "Match CUSTOM with VALUES."
534   (let* ((child (custom-data custom))
535          (match (custom-match child values))
536          matches)
537     (while (not (eq (car match) custom-nil))
538       (setq matches (cons (car match) matches)
539             values (cdr match)
540             match (custom-match child values)))
541     (cons (nreverse matches) values)))
542
543 (defun custom-repeat-extract (custom field)
544   "Extract list of childrens values."
545   (let ((values (custom-field-value field))
546         (data (custom-data custom))
547         result)
548     (if (eq values custom-nil)
549         ()
550       (while values
551 ;;      (message "Before values = %S result = %S" values result)
552         (setq result (append result (custom-field-extract data (car values)))
553               values (cdr values))
554 ;;      (message "After values = %S result = %S" values result)
555         ))
556     result))
557
558 (defun custom-repeat-validate (custom field)
559   "Validate children."
560   (let ((values (custom-field-value field))
561         (data (custom-data custom))
562         result)
563     (if (eq values custom-nil)
564         (setq result (cons (custom-field-start field) "Uninitialized list")))
565     (while (and values (not result))
566       (setq result (custom-field-validate data (car values))
567             values (cdr values)))
568     result))
569
570 (defun custom-list-extract (custom field)
571   "Extract list of childrens values."
572   (let ((values (custom-field-value field))
573         (data (custom-data custom))
574         result)
575     (custom-assert '(eq (length values) (length data)))
576     (while values
577       (setq result (append result
578                            (custom-field-extract (car data) (car values)))
579             data (cdr data)
580             values (cdr values)))
581     (custom-assert '(null data))
582     (list result)))
583
584 (defun custom-list-validate (custom field)
585   "Validate children."
586   (let ((values (custom-field-value field))
587         (data (custom-data custom))
588         result)
589     (if (eq values custom-nil)
590         (setq result (cons (custom-field-start field) "Uninitialized list"))
591       (custom-assert '(eq (length values) (length data))))
592     (while (and values (not result))
593       (setq result (custom-field-validate (car data) (car values))
594             data (cdr data)
595             values (cdr values)))
596     result))
597
598 (defun custom-group-accept (field value &optional original)
599   "Enter content of editing FIELD with VALUE."
600   (let ((values (custom-field-value field))
601         current)
602     (if original 
603         (custom-field-original-set field value))
604     (while values
605       (setq current (car values)
606             values (cdr values))
607       (if current
608           (let* ((custom (custom-field-custom current))
609                  (match (custom-match custom value)))
610             (setq value (cdr match))
611             (custom-field-accept current (car match) original))))))
612
613 (defun custom-group-insert (custom level)
614   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
615   (let* ((field (custom-field-create custom nil))
616          fields
617          (from (point))
618          (compact (custom-compact custom))
619          (tag (custom-tag custom)))
620     (if tag (custom-tag-insert tag field))
621     (or compact (custom-documentation-insert custom))
622     (or compact (custom-text-insert "\n"))
623     (let ((data (custom-data custom)))
624       (while data
625         (setq fields (cons (custom-insert (car data) (if level (1+ level)))
626                            fields))
627         (setq data (cdr data))
628         (if data (custom-text-insert (if compact " " "\n")))))
629     (if compact (custom-documentation-insert custom))
630     (custom-field-value-set field (nreverse fields))
631     (custom-field-move field from (point))
632     field))
633
634 (defun custom-choice-insert (custom level)
635   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
636   (let* ((field (custom-field-create custom nil))
637          (from (point))
638          (tag (custom-tag custom)))
639     (custom-text-insert "lars er en nisse")
640     (custom-field-move field from (point))
641     (custom-documentation-insert custom)
642     (custom-field-reset field)
643     field))
644
645 (defun custom-choice-accept (field value &optional original)
646   "Reset content of editing FIELD."
647   (let ((custom (custom-field-custom field))
648         (start (custom-field-start field))
649         (end (custom-field-end field))
650         (inhibit-read-only t)
651         (before-change-function nil)
652         (after-change-function nil)
653         from)
654     (cond (original 
655            (setq custom-modified-list (delq field custom-modified-list))
656            (custom-field-original-set field value))
657           ((equal value (custom-field-original field))
658            (setq custom-modified-list (delq field custom-modified-list)))
659           (t
660            (add-to-list 'custom-modified-list field)))
661     (custom-field-untouch (custom-field-value field))
662     (delete-region start end)
663     (goto-char start)
664     (setq from (point))
665     (insert-before-markers " ")
666     (backward-char 1)
667     (set-text-properties (point) (1+ (point)) 
668                          (list 'invisible t 
669                                intangible t))
670     (custom-tag-insert (custom-tag custom) field)
671     (custom-text-insert ": ")
672     (let ((data (custom-data custom))
673           found begin)
674       (while (and data (not found))
675         (if (not (custom-valid (car data) value))
676             (setq data (cdr data))
677           (setq found (custom-insert (car data) nil))
678           (setq data nil)))
679       (if found 
680           ()
681         (setq begin (point)
682               found (custom-insert (custom-property custom 'none) nil))
683         (add-text-properties begin (point)
684                              (list 'rear-nonsticky t
685                                    'face custom-field-uninitialized-face)))
686       (custom-field-accept found value original)
687       (custom-field-value-set field found)
688       (custom-field-move field from end))))
689
690 (defun custom-choice-extract (custom field)
691   "Extract childs value."
692   (let ((value (custom-field-value field)))
693     (custom-field-extract (custom-field-custom value) value)))
694
695 (defun custom-choice-validate (custom field)
696   "Validate childs value."
697   (let ((value (custom-field-value field))
698         (custom (custom-field-custom field)))
699     (if (or (eq value custom-nil)
700             (eq (custom-field-custom value) (custom-property custom 'none)))
701         (cons (custom-field-start field) "Make a choice")
702       (custom-field-validate (custom-field-custom value) value))))
703
704 (defun custom-choice-query (field)
705   "Choose a child."
706   (let* ((custom (custom-field-custom field))
707          (default (custom-tag-or-type 
708                    (custom-field-custom (custom-field-value field))))
709          (tag (custom-tag-or-type custom))
710          (data (custom-data custom))
711          current alist)
712     (while data
713       (setq current (car data)
714             data (cdr data))
715       (setq alist (cons (cons (custom-tag-or-type current) current) alist)))
716     (let ((answer (if (listp last-input-event)
717                       (x-popup-menu last-input-event
718                                (list tag (cons "" (reverse alist))))
719                     (let ((choice (completing-read (concat tag " (default "
720                                                            default "): ") 
721                                                    alist nil t)))
722                       (if (or (null choice) (string-equal choice ""))
723                           (setq choice default))
724                       (cdr (assoc choice alist))))))
725       (if answer
726           (custom-field-accept field (custom-default answer))))))
727
728 (defun custom-file-query (field)
729   "Prompt for a file name"
730   (let* ((value (custom-field-value field))
731          (custom (custom-field-custom field))
732          (valid (custom-valid custom value))
733          (directory (custom-property custom 'directory))
734          (default (and (not valid)
735                        (custom-property custom 'default-file)))
736          (tag (custom-tag custom))
737          (prompt (if default
738                      (concat tag " (" default "): ")
739                    (concat tag ": "))))
740     (custom-field-accept field 
741                          (if (custom-valid custom value)
742                              (read-file-name prompt 
743                                              (if (file-name-absolute-p value)
744                                                  ""
745                                                directory)
746                                              default nil value)
747                            (read-file-name prompt directory default)))))
748
749 (defun custom-const-insert (custom level)
750   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
751   (let ((field (custom-field-create custom custom-nil))
752         (from (point)))
753     (custom-text-insert (custom-tag custom))
754     (custom-documentation-insert custom)
755     (custom-field-move field from (point))
756     field))
757
758 (defun custom-const-valid (custom value)
759   "Non-nil if CUSTOM can legally have the value VALUE."
760   (equal (custom-default custom) value))
761
762 (defun custom-integer-read (custom integer)
763   "Read from CUSTOM an INTEGER."
764   (string-to-int (save-match-data
765                    (custom-strip-padding integer (custom-padding custom)))))
766
767 (defun custom-integer-write (custom integer)
768   "Write CUSTOM INTEGER as string."
769   (int-to-string integer))
770
771 (defun custom-string-read (custom string)
772   "Read string by ignoring trailing padding characters."
773   (let ((last (length string))
774         (padding (custom-padding custom)))
775     (while (and (> last 0)
776                 (eq (aref string (1- last)) padding))
777       (setq last (1- last)))
778     (substring string 0 last)))
779
780 (defun custom-string-write (custom string)
781   "Write raw string."
782   string)
783
784 (defun custom-button-insert (custom level)
785   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
786   (custom-tag-insert (concat "[" (custom-tag custom) "]") 
787                      (custom-property custom 'query))
788   (custom-documentation-insert custom)
789   nil)
790
791 (defun custom-default-insert (custom level)
792   "Insert field for CUSTOM at nesting LEVEL in customization buffer."
793   (let ((field (custom-field-create custom custom-nil))
794         (tag (custom-tag custom)))
795     (if (null tag)
796         ()
797       (custom-tag-insert tag field)
798       (custom-text-insert ": "))
799     (custom-field-insert field)
800     (custom-documentation-insert custom)
801     field))
802
803 (defun custom-default-accept (field value &optional original)
804   "Enter into FIELD the value VALUE."
805   (if original 
806       (custom-field-original-set field value))
807   (custom-field-value-set field value)
808   (custom-field-update field))
809   
810 (defun custom-default-reset (field)
811   "Reset content of editing FIELD."
812   (custom-field-accept field (custom-field-original field) t))
813
814 (defun custom-default-query (field)
815   "Prompt for a FIELD"
816   (let* ((custom (custom-field-custom field))
817          (value (custom-field-value field))
818          (initial (custom-write custom value))
819          (prompt (concat (custom-tag-or-type custom) ": ")))
820     (custom-field-accept field 
821                          (custom-read custom 
822                                       (if (custom-valid custom value)
823                                           (read-string prompt (cons initial 1))
824                                         (read-string prompt))))))
825
826 (defun custom-default-match (custom values)
827   "Match CUSTOM with VALUES."
828   values)
829
830 (defun custom-default-extract (custom field)
831   "Extract CUSTOM's content in FIELD."
832   (list (custom-field-value field)))
833
834 (defun custom-default-validate (custom field)
835   "Validate FIELD."
836   (let ((value (custom-field-value field))
837         (start (custom-field-start field)))
838     (cond ((eq value custom-nil)
839            (cons (custom-field-start field) "Uninitialized field"))
840           ((custom-valid custom value)
841            nil)
842           (t
843            (cons start "Wrong type")))))
844
845 ;;; Create Buffer:
846 ;;
847 ;; Public functions to create a customization buffer and to insert
848 ;; various forms of text, fields, and buttons in it.
849
850 (defun custom-buffer-create (name &optional custom types set get)
851   "Create a customization buffer named NAME.
852 If the optional argument CUSTOM is non-nil, use that as the custom declaration.
853 If the optional argument TYPES is non-nil, use that as the local types.
854 If the optional argument SET is non-nil, use that to set external data.
855 If the optional argument GET is non-nil, use that to get external data."
856   (switch-to-buffer name)
857   (buffer-disable-undo (current-buffer))
858   (custom-mode)
859   (setq custom-local-type-properties types)
860   (if (null custom)
861       ()
862     (make-local-variable 'custom-data)
863     (setq custom-data custom))
864   (if (null set)
865       ()
866     (make-local-variable 'custom-external-set)
867     (setq custom-external-set set))
868   (if (null get)
869       ()
870     (make-local-variable 'custom-external)
871     (setq custom-external get))
872   (let ((inhibit-point-motion-hooks t)
873         (before-change-function nil)
874         (after-change-function nil))
875     (erase-buffer)
876     (insert "\n")
877     (goto-char (point-min))
878     (custom-text-insert "This is a customization buffer.\n")
879     (custom-help-insert "\n")
880     (custom-help-button 'custom-forward-field)
881     (custom-help-button 'custom-enter-value)
882     (custom-help-button 'custom-field-reset)
883     (custom-help-button 'custom-field-apply)
884     (custom-help-button 'custom-toggle-documentation)
885     (custom-help-insert "\nClick mouse-2 on any button to activate it.\n")
886     (custom-insert custom 1)
887     (goto-char (point-min))))
888
889 (defun custom-insert (custom level)
890   "Insert custom declaration CUSTOM in current buffer at level LEVEL."
891   (if (stringp custom)
892       (progn 
893         (custom-text-insert custom)
894         nil)
895     (and level (null (custom-property custom 'header))
896          (setq level nil))
897     (if level 
898         (custom-text-insert (concat "\n" (make-string level ?*) " ")))
899     (let ((field (funcall (custom-property custom 'insert) custom level)))
900       (custom-name-enter (custom-name custom) field)
901       field)))
902
903 (defun custom-text-insert (text)
904   "Insert TEXT in current buffer." 
905   (insert text))
906
907 (defun custom-tag-insert (tag field &optional data)
908   "Insert TAG for FIELD in current buffer."
909   (let ((from (point)))
910     (insert tag)
911     (set-text-properties from (point) 
912                          (list 'category custom-button-properties
913                                'custom-tag field))
914     (if data
915         (add-text-properties from (point) (list 'custom-data data)))))
916
917 (defun custom-documentation-insert (custom &rest ignore)
918   "Insert documentation from CUSTOM in current buffer."
919   (let ((doc (custom-documentation custom)))
920     (if (null doc)
921         ()
922       (custom-help-insert "\n" doc))))
923
924 (defun custom-help-insert (&rest args)
925   "Insert ARGS as documentation text."
926   (let ((from (point)))
927     (apply 'insert args)
928     (set-text-properties from (point) 
929                          (list 'category custom-documentation-properties))))
930
931 (defun custom-help-button (command)
932   "Describe how to execute COMMAND."
933   (let ((from (point)))
934     (insert "`" (key-description (where-is-internal command nil t)) "'")
935     (set-text-properties from (point)
936                          (list 'category custom-documentation-properties
937                                'face custom-button-face
938                                'mouse-face custom-mouse-face
939                                'custom-tag command)))
940   (custom-help-insert ": " (custom-first-line (documentation command)) "\n"))
941
942 ;;; Mode:
943 ;;
944 ;; The Customization major mode and interactive commands. 
945
946 (defvar custom-mode-map nil
947   "Keymap for Custom Mode.")
948 (if custom-mode-map
949     nil
950   (setq custom-mode-map (make-sparse-keymap))
951   (define-key custom-mode-map [ mouse-2 ] 'custom-push-button)
952   (define-key custom-mode-map "\t" 'custom-forward-field)
953   (define-key custom-mode-map "\r" 'custom-enter-value)
954   (define-key custom-mode-map "\C-k" 'custom-kill-line)
955   (define-key custom-mode-map "\C-c\C-r" 'custom-field-reset)
956   (define-key custom-mode-map "\C-c\M-\C-r" 'custom-reset-all)
957   (define-key custom-mode-map "\C-c\C-a" 'custom-field-apply)
958   (define-key custom-mode-map "\C-c\M-\C-a" 'custom-apply-all)
959   (define-key custom-mode-map "\C-c\C-d" 'custom-toggle-documentation))
960
961 ;; C-c keymap ideas: C-a field-beginning, C-e field-end, C-f
962 ;; forward-field, C-b backward-field, C-n next-field, C-p
963 ;; previous-field, ? describe-field.
964
965 (defun custom-mode ()
966   "Major mode for doing customizations.
967
968 \\{custom-mode-map}"
969   (kill-all-local-variables)
970   (setq major-mode 'custom-mode
971         mode-name "Custom")
972   (use-local-map custom-mode-map)
973   (make-local-variable 'before-change-function)
974   (setq before-change-function 'custom-before-change)
975   (make-local-variable 'after-change-function)
976   (setq after-change-function 'custom-after-change)
977   (if (not (fboundp 'make-local-hook))
978       ;; Emacs 19.28 and earlier.
979       (add-hook 'post-command-hook 'custom-post-command nil)      
980     ;; Emacs 19.29.
981     (make-local-hook 'post-command-hook)
982     (add-hook 'post-command-hook 'custom-post-command nil t)))
983
984 (defun custom-forward-field (arg)
985   "Move point to the next field or button.
986 With optional ARG, move across that many fields."
987   (interactive "p")
988   (while (> arg 0)
989     (setq arg (1- arg))
990     (let ((next (if (get-text-property (point) 'custom-tag)
991                     (next-single-property-change (point) 'custom-tag)
992                   (point))))
993       (setq next (or (next-single-property-change next 'custom-tag)
994                      (next-single-property-change (point-min) 'custom-tag)))
995       (if next
996           (goto-char next)
997         (error "No customization fields in this buffer.")))))
998
999 (defun custom-toggle-documentation (&optional arg)
1000   "Toggle display of documentation text.
1001 If the optional argument is non-nil, show text iff the argument is positive."
1002   (interactive "P")
1003   (let ((hide (or (and (null arg) 
1004                        (null (get custom-documentation-properties 'invisible)))
1005                   (<= (prefix-numeric-value arg) 0))))
1006     (put custom-documentation-properties 'invisible hide)
1007     (put custom-documentation-properties intangible hide))
1008   (redraw-display))
1009
1010 (defun custom-enter-value (field data)
1011   "Enter value for current customization field or push button."
1012   (interactive (list (get-text-property (point) 'custom-tag)
1013                      (get-text-property (point) 'custom-data)))
1014   (cond (data
1015          (funcall field data))
1016         ((eq field 'custom-enter-value)
1017          (error "Don't be silly"))
1018         ((and (symbolp field) (fboundp field))
1019          (call-interactively field))
1020         (field
1021          (custom-field-query field))
1022         (t
1023          (message "Nothing to enter here"))))
1024
1025 (defun custom-kill-line ()
1026   "Kill to end of field or end of line, whichever is first."
1027   (interactive)
1028   (let ((field (get-text-property (point) 'custom-field))
1029         (newline (save-excursion (search-forward "\n")))
1030         (next (next-single-property-change (point) 'custom-field)))
1031     (if (and field (> newline next))
1032         (kill-region (point) next)
1033       (call-interactively 'kill-line))))
1034
1035 (defun custom-push-button (event)
1036   "Activate button below mouse pointer."
1037   (interactive "e")
1038   (set-buffer (window-buffer (posn-window (event-start event))))
1039   (let* ((pos (posn-point (event-start event)))
1040          (field (get-text-property pos 'custom-field))
1041          (tag (get-text-property pos 'custom-tag))
1042          (data (get-text-property pos 'custom-data)))
1043     (cond (data
1044             (funcall tag data))
1045           ((and (symbolp tag) (fboundp tag))
1046            (call-interactively tag))
1047           (field
1048            (call-interactively (lookup-key global-map (this-command-keys))))
1049           (tag
1050            (custom-enter-value tag data))
1051           (t 
1052            (error "Nothing to click on here.")))))
1053
1054 (defun custom-reset-all ()
1055   "Undo any changes since the last apply in all fields."
1056   (interactive (and custom-modified-list
1057                     (not (y-or-n-p "Discard all changes? "))
1058                     (error "Reset aborted")))
1059   (let ((all custom-name-fields)
1060         current name field)
1061     (while all
1062       (setq current (car all)
1063             name (car current)
1064             field (cdr current)
1065             all (cdr all))
1066       (custom-field-reset field))))
1067
1068 (defun custom-field-reset (field)
1069   "Undo any changes in FIELD since the last apply."
1070   (interactive (list (or (get-text-property (point) 'custom-field)
1071                          (get-text-property (point) 'custom-tag))))
1072   (if (not (arrayp field))
1073       (error "No field to reset here"))
1074   (let* ((custom (custom-field-custom field))
1075          (name (custom-name custom)))
1076     (save-excursion
1077       (if name
1078           (custom-field-original-set field (custom-external name)))
1079       (funcall (custom-property custom 'reset) field))))
1080
1081 (defun custom-apply-all ()
1082   "Apply any changes since the last reset in all fields."
1083   (interactive (or custom-modified-list
1084                    (error "No changes to apply.")))
1085   (let ((all custom-name-fields)
1086         name field)
1087     (while all
1088       (setq field (cdr (car all))
1089             all (cdr all))
1090       (let ((error (custom-field-validate (custom-field-custom field) field)))
1091         (if (null error)
1092             ()
1093           (goto-char (car error))
1094           (error (cdr error))))))
1095   (let ((all custom-name-fields)
1096         current name field)
1097     (while all
1098       (setq field (cdr (car all))
1099             all (cdr all))
1100       (custom-field-apply field))))
1101
1102 (defun custom-field-apply (field)
1103   "Apply any changes in FIELD since the last apply."
1104   (interactive (list (or (get-text-property (point) 'custom-field)
1105                          (get-text-property (point) 'custom-tag))))
1106   (if (not (arrayp field))
1107       (error "No field to reset here"))
1108   (let* ((custom (custom-field-custom field))
1109          (name (custom-name custom))
1110          (error (custom-field-validate custom field)))
1111     (cond ((null name)
1112            (error "This field cannot be applied alone"))
1113           (error
1114            (error (cdr error)))
1115           (t
1116            (custom-external-set name (car (custom-field-extract custom field)))
1117            (custom-field-reset field)))))
1118
1119 (defun custom-toggle-hide (&rest ignore)
1120   "Hide or show entry."
1121   (interactive)
1122   (error "This button is not yet implemented"))
1123
1124 ;;; Field Editing:
1125 ;;
1126 ;; Various internal functions for implementing the direct editing of
1127 ;; fields in the customization buffer.
1128
1129 (defvar custom-modified-list nil)
1130 ;; List of modified fields.
1131 (make-variable-buffer-local 'custom-modified-list)
1132
1133 (defun custom-field-untouch (field)
1134   ;; Remove FIELD and its children from `custom-modified-list'.
1135   (setq custom-modified-list (delq field custom-modified-list))
1136   (if (arrayp field)
1137       (let ((value (custom-field-value field)))
1138         (cond ((arrayp value)
1139                (custom-field-untouch value))
1140               ((listp value)
1141                (mapcar 'custom-field-untouch value))))))
1142
1143
1144 (defun custom-field-insert (field)
1145   ;; Insert editing FIELD in current buffer.
1146   (let ((from (point))
1147         (custom (custom-field-custom field))
1148         (value (custom-field-value field)))
1149     (insert (custom-write custom value))
1150     (insert-char (custom-padding custom)
1151                  (- (custom-width custom) (- (point) from)))
1152     (custom-field-move field from (point))
1153     (set-text-properties 
1154      from (point)
1155      (list 'custom-field field
1156            'custom-tag field
1157            'face (custom-field-face field)
1158            'front-sticky t))))
1159
1160 (defun custom-field-update (field)
1161   ;; Update the content of FIELD.
1162   (let ((inhibit-point-motion-hooks t)
1163         (before-change-function nil)
1164         (after-change-function nil)
1165         (start (custom-field-start field))
1166         (end (custom-field-end field)) 
1167         (pos (point)))
1168     ;; Keep track of how many modified fields we have.
1169     (cond ((equal (custom-field-value field) (custom-field-original field))
1170            (setq custom-modified-list (delq field custom-modified-list)))
1171           ((memq field custom-modified-list))
1172           (t
1173            (setq custom-modified-list (cons field custom-modified-list))))
1174     ;; Update the field.
1175     (goto-char end)
1176     (insert-before-markers " ")
1177     (delete-region start (1- end))
1178     (goto-char start)
1179     (custom-field-insert field)
1180     (goto-char end)
1181     (delete-char 1)
1182     (goto-char pos)
1183     (and (<= start pos) 
1184          (<= pos end)
1185          (custom-field-enter field))))
1186
1187 (defun custom-field-read (field)
1188   ;; Read the screen content of FIELD.
1189   (custom-read (custom-field-custom field)
1190                (buffer-substring-no-properties (custom-field-start field)
1191                                                (custom-field-end field))))
1192
1193 (defun custom-field-face (field)
1194   ;; Face used for an inactive field FIELD.
1195   (let ((value (custom-field-value field)))
1196     (cond ((eq value custom-nil)
1197            custom-field-uninitialized-face)
1198           ((not (custom-valid (custom-field-custom field) value))
1199            custom-field-invalid-face)
1200           ((not (equal (custom-field-original field) value))
1201            custom-field-modified-face)
1202           (t
1203            custom-field-face))))
1204
1205 (defun custom-field-leave (field)
1206   ;; Deactivate FIELD.
1207   (let ((before-change-function nil)
1208         (after-change-function nil))
1209     (put-text-property (custom-field-start field) (custom-field-end field)
1210                        'face (custom-field-face field))))
1211
1212 (defun custom-field-enter (field)
1213   ;; Activate FIELD.
1214   (let* ((start (custom-field-start field)) 
1215          (end (custom-field-end field))
1216          (custom (custom-field-custom field))
1217          (padding (custom-padding custom))
1218          (allow (custom-allow-padding custom))
1219          (before-change-function nil)
1220          (after-change-function nil))
1221     (or (and (eq this-command 'self-insert-command)
1222              allow)
1223         (let ((pos end))
1224           (while (and (< start pos)
1225                       (eq (char-after (1- pos)) padding))
1226             (setq pos (1- pos)))
1227           (if (< pos (point))
1228               (goto-char pos))))
1229     (put-text-property start end 'face custom-field-active-face)))
1230
1231 (defvar custom-field-last nil)
1232 ;; Last field containing point.
1233 (make-variable-buffer-local 'custom-field-last)
1234
1235 (defun custom-post-command ()
1236   ;; Keep track of their active field.
1237   (if (not (eq major-mode 'custom-mode))
1238       ;; BUG: Should have been local!
1239       ()
1240     (let ((field (custom-field-property (point))))
1241       (if (eq field custom-field-last)
1242           ()
1243         (if custom-field-last
1244             (custom-field-leave custom-field-last))
1245         (if field
1246             (custom-field-enter field))
1247         (setq custom-field-last field)))
1248     (set-buffer-modified-p custom-modified-list)))
1249
1250 (defvar custom-field-was nil)
1251 ;; The custom data before the change.
1252 (make-variable-buffer-local 'custom-field-was)
1253
1254 (defun custom-before-change (begin end)
1255   ;; Check that we the modification is allowed.
1256   (if (not (eq major-mode 'custom-mode))
1257       (message "Aargh! Why is custom-before-change called here?")
1258     (let ((from (custom-field-property begin))
1259           (to (custom-field-property end)))
1260       (cond ((or (null from) (null to))
1261              (error "You can only modify the fields"))
1262             ((not (eq from to))
1263              (error "Changes must be limited to a single field."))
1264             (t
1265              (setq custom-field-was from))))))
1266
1267 (defun custom-after-change (begin end length)
1268   ;; Keep track of field content.
1269   (if (not (eq major-mode 'custom-mode))
1270       (message "Aargh! Why is custom-after-change called here?")
1271     (let ((field custom-field-was))
1272       (custom-assert '(prog1 field (setq custom-field-was nil)))
1273       ;; Prevent mixing fields properties.
1274       (put-text-property begin end 'custom-field field)
1275       ;; Update the field after modification.
1276       (if (eq (custom-field-property begin) field)
1277           (let ((field-end (custom-field-end field)))
1278             (if (> end field-end)
1279                 (set-marker field-end end))
1280             (custom-field-value-set field (custom-field-read field))
1281             (custom-field-update field))
1282         ;; We deleted the entire field, reinsert it.
1283         (custom-assert '(eq begin end))
1284         (save-excursion
1285           (goto-char begin)
1286           (custom-field-value-set field
1287                                   (custom-read (custom-field-custom field) ""))
1288           (custom-field-insert field))))))
1289
1290 (defun custom-field-property (pos)
1291   ;; The `custom-field' text property valid for POS.
1292   (or (get-text-property pos 'custom-field)
1293       (and (not (eq pos (point-min)))
1294            (get-text-property (1- pos) 'custom-field))))
1295
1296 ;;; Generic Utilities:
1297 ;;
1298 ;; Some utility functions that are not really specific to custom.
1299
1300 (defun custom-assert (expr)
1301   "Assert that EXPR evaluates to non-nil at this point"
1302   (or (eval expr)
1303       (error "Assertion failed: %S" expr)))
1304
1305 (defun custom-first-line (string)
1306   "Return the part of STRING before the first newline."
1307   (let ((pos 0)
1308         (len (length string)))
1309     (while (and (< pos len) (not (eq (aref string pos) ?\n)))
1310       (setq pos (1+ pos)))
1311     (if (eq pos len)
1312         string
1313     (substring string 0 pos))))
1314
1315 (defun custom-insert-before (list old new)
1316   "In LIST insert before OLD a NEW element."
1317   (cond ((null list)
1318          (list new))
1319         ((null old)
1320          (nconc list (list new)))
1321         ((eq old (car list))
1322          (cons new list))
1323         (t
1324          (let ((list list))
1325            (while (not (eq old (car (cdr list))))
1326              (setq list (cdr list))
1327              (custom-assert '(cdr list)))
1328            (setcdr list (cons new (cdr list))))
1329          list)))
1330
1331 (defun custom-strip-padding (string padding)
1332   "Remove padding from STRING."
1333   (let ((regexp (concat (regexp-quote (char-to-string padding)) "+")))
1334     (while (string-match regexp string)
1335       (setq string (concat (substring string 0 (match-beginning 0))
1336                            (substring string (match-end 0))))))
1337   string)
1338
1339 (provide 'custom)
1340
1341 ;;; custom.el ends here