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