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