69074020ee3eb40518171a41710565d5d3c78da5
[gnus] / lisp / widget-edit.el
1 ;;; widget-edit.el --- Functions for creating and using widgets.
2 ;;
3 ;; Copyright (C) 1996 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Per Abrahamsen <abraham@dina.kvl.dk>
6 ;; Keywords: extensions
7 ;; Version: 1.02
8 ;; X-URL: http://www.dina.kvl.dk/~abraham/custom/
9
10 ;;; Commentary:
11 ;;
12 ;; See `widget.el'.
13
14 ;;; Code:
15
16 (require 'widget)
17 (require 'cl)
18 (autoload 'pp-to-string "pp")
19 (autoload 'Info-goto-node "info")
20
21 ;; The following should go away when bundled with Emacs.
22 (eval-and-compile
23   (condition-case ()
24       (require 'custom)
25     (error nil)))
26
27 (unless (and (featurep 'custom) (fboundp 'custom-declare-variable))
28   ;; We have the old custom-library, hack around it!
29   (defmacro defgroup (&rest args) nil)
30   (defmacro defcustom (&rest args) nil)
31   (defmacro defface (&rest args) nil)
32   (when (fboundp 'copy-face)
33     (copy-face 'default 'widget-documentation-face)
34     (copy-face 'bold 'widget-button-face)
35     (copy-face 'italic 'widget-field-face))
36   (defvar widget-mouse-face 'highlight)
37   (defvar widget-menu-max-size 40))
38
39 ;;; Compatibility.
40
41 (or (fboundp 'event-point)
42     ;; XEmacs function missing in Emacs.
43     (defun event-point (event)
44       "Return the character position of the given mouse-motion, button-press,
45 or button-release event.  If the event did not occur over a window, or did
46 not occur over text, then this returns nil.  Otherwise, it returns an index
47 into the buffer visible in the event's window."
48       (posn-point (event-start event))))
49
50 ;;; Customization.
51
52 (defgroup widgets nil
53   "Customization support for the Widget Library."
54   :group 'emacs)
55
56 (defface widget-documentation-face '((t ()))
57   "Face used for documentation text."
58   :group 'widgets)
59
60 (defface widget-button-face '((t (:bold t)))
61   "Face used for widget buttons."
62   :group 'widgets)
63
64 (defcustom widget-mouse-face 'highlight
65   "Face used for widget buttons when the mouse is above them."
66   :type 'face
67   :group 'widgets)
68
69 (defface widget-field-face '((((type x)
70                                (class grayscale color)
71                                (background light))
72                               (:background "light gray"))
73                              (((type x)
74                                (class grayscale color)
75                                (background dark))
76                               (:background "dark gray"))
77                              (t 
78                               (:italic t)))
79   "Face used for editable fields."
80   :group 'widgets)
81
82 (defcustom widget-menu-max-size 40
83   "Largest number of items allowed in a popup-menu.
84 Larger menus are read through the minibuffer."
85   :type 'integer)
86
87 ;;; Utility functions.
88 ;;
89 ;; These are not really widget specific.
90
91 (defun widget-plist-member (plist prop)
92   ;; Return non-nil if PLIST has the property PROP.
93   ;; PLIST is a property list, which is a list of the form
94   ;; (PROP1 VALUE1 PROP2 VALUE2 ...).  PROP is a symbol.
95   ;; Unlike `plist-get', this allows you to distinguish between a missing
96   ;; property and a property with the value nil.
97   ;; The value is actually the tail of PLIST whose car is PROP.
98   (while (and plist (not (eq (car plist) prop)))
99     (setq plist (cdr (cdr plist))))
100   plist)
101
102 (defun widget-princ-to-string (object)
103   ;; Return string representation of OBJECT, any Lisp object.
104   ;; No quoting characters are used; no delimiters are printed around
105   ;; the contents of strings.
106   (save-excursion
107     (set-buffer (get-buffer-create " *widget-tmp*"))
108     (erase-buffer)
109     (let ((standard-output (current-buffer)))
110       (princ object))
111     (buffer-string)))
112
113 (defun widget-clear-undo ()
114   "Clear all undo information."
115   (buffer-disable-undo (current-buffer))
116   (buffer-enable-undo))
117
118 (defun widget-choose (title items &optional event)
119   "Choose an item from a list.
120
121 First argument TITLE is the name of the list.
122 Second argument ITEMS is an alist (NAME . VALUE).
123 Optional third argument EVENT is an input event.
124
125 The user is asked to choose between each NAME from the items alist,
126 and the VALUE of the chosen element will be returned.  If EVENT is a
127 mouse event, and the number of elements in items is less than
128 `widget-menu-max-size', a popup menu will be used, otherwise the
129 minibuffer."
130   (cond ((and (< (length items) widget-menu-max-size)
131               event (fboundp 'x-popup-menu) window-system)
132          ;; We are in Emacs-19, pressed by the mouse
133          (x-popup-menu event
134                        (list title (cons "" items))))
135         ((and (< (length items) widget-menu-max-size)
136               event (fboundp 'popup-menu) window-system)
137          ;; We are in XEmacs, pressed by the mouse
138          (let ((val (get-popup-menu-response
139                      (cons ""
140                            (mapcar
141                             (function
142                              (lambda (x)
143                                (vector (car x) (list (car x)) t)))
144                             items)))))
145            (setq val (and val
146                           (listp (event-object val))
147                           (stringp (car-safe (event-object val)))
148                           (car (event-object val))))
149            (cdr (assoc val items))))
150         (t
151          (cdr (assoc (completing-read (concat title ": ")
152                                       items nil t)
153                      items)))))
154
155 ;;; Widget text specifications.
156 ;; 
157 ;; These functions are for specifying text properties. 
158
159 (defun widget-specify-none (from to)
160   ;; Clear all text properties between FROM and TO.
161   (set-text-properties from to nil))
162
163 (defun widget-specify-text (from to)
164   ;; Default properties.
165   (add-text-properties from to (list 'read-only t
166                                      'front-sticky t
167                                      'rear-nonsticky nil)))
168
169 (defun widget-specify-field (widget from to)
170   ;; Specify editable button for WIDGET between FROM and TO.
171   (widget-specify-field-update widget from to)
172
173   ;; Make it possible to edit the front end of the field.
174   (add-text-properties (1- from) from (list 'rear-nonsticky t
175                                             'end-open t
176                                             'invisible t))
177   (when (or (string-match "\\(.\\|\n\\)%v" (widget-get widget :format))
178             (widget-get widget :hide-front-space))
179     ;; WARNING: This is going to lose horrible if the character just
180     ;; before the field can be modified (e.g. if it belongs to a
181     ;; choice widget).  We try to compensate by checking the format
182     ;; string, and hope the user hasn't changed the :create method.
183     (put-text-property (- from 2) from 'intangible 'front))
184   
185   ;; Make it possible to edit back end of the field.
186   (add-text-properties to (1+ to) (list 'front-sticky nil
187                                         'start-open t))
188
189   (when (widget-get widget :size)
190     (put-text-property to (1+ to) 'invisible t)
191     (when (or (string-match "%v\\(.\\|\n\\)" (widget-get widget :format))
192               (widget-get widget :hide-rear-space))
193       ;; WARNING: This is going to lose horrible if the character just
194       ;; after the field can be modified (e.g. if it belongs to a
195       ;; choice widget).  We try to compensate by checking the format
196       ;; string, and hope the user hasn't changed the :create method.
197       (put-text-property to (+ to 2) 'intangible 'rear))))
198
199 (defun widget-specify-field-update (widget from to)
200   ;; Specify editable button for WIDGET between FROM and TO.
201   (let ((map (widget-get widget :keymap))
202         (face (or (widget-get widget :value-face)
203                   'widget-field-face)))
204     (set-text-properties from to (list 'field widget
205                                        'read-only nil
206                                        'keymap map
207                                        'local-map map
208                                        'face face))
209     (unless (widget-get widget :size)
210       (put-text-property to (1+ to) 'face face))))
211
212 (defun widget-specify-button (widget from to)
213   ;; Specify button for WIDGET between FROM and TO.
214   (let ((face (widget-apply widget :button-face-get)))
215     (add-text-properties from to (list 'button widget
216                                        'mouse-face widget-mouse-face
217                                        'start-open t
218                                        'end-open t
219                                        'face face))))
220
221 (defun widget-specify-doc (widget from to)
222   ;; Specify documentation for WIDGET between FROM and TO.
223   (add-text-properties from to (list 'widget-doc widget
224                                      'face 'widget-documentation-face)))
225
226 (defmacro widget-specify-insert (&rest form)
227   ;; Execute FORM without inheriting any text properties.
228   `(save-restriction
229      (let ((inhibit-read-only t)
230            result
231            after-change-functions)
232        (insert "<>")
233        (narrow-to-region (- (point) 2) (point))
234        (widget-specify-none (point-min) (point-max))
235        (goto-char (1+ (point-min)))
236        (setq result (progn ,@form))
237        (delete-region (point-min) (1+ (point-min)))
238        (delete-region (1- (point-max)) (point-max))
239        (goto-char (point-max))
240        result)))
241
242 ;;; Widget Properties.
243
244 (defun widget-put (widget property value)
245   "In WIDGET set PROPERTY to VALUE.
246 The value can later be retrived with `widget-get'."
247   (setcdr widget (plist-put (cdr widget) property value)))
248
249 (defun widget-get (widget property)
250   "In WIDGET, get the value of PROPERTY.
251 The value could either be specified when the widget was created, or
252 later with `widget-put'."
253   (cond ((widget-plist-member (cdr widget) property)
254          (plist-get (cdr widget) property))
255         ((car widget)
256          (widget-get (get (car widget) 'widget-type) property))
257         (t nil)))
258
259 (defun widget-member (widget property)
260   "Non-nil iff there is a definition in WIDGET for PROPERTY."
261   (cond ((widget-plist-member (cdr widget) property)
262          t)
263         ((car widget)
264          (widget-member (get (car widget) 'widget-type) property))
265         (t nil)))
266
267 (defun widget-apply (widget property &rest args)
268   "Apply the value of WIDGET's PROPERTY to the widget itself.
269 ARGS are passed as extra argments to the function."
270   (apply (widget-get widget property) widget args))
271
272 (defun widget-value (widget)
273   "Extract the current value of WIDGET."
274   (widget-apply widget
275                 :value-to-external (widget-apply widget :value-get)))
276
277 (defun widget-value-set (widget value)
278   "Set the current value of WIDGET to VALUE."
279   (widget-apply widget
280                 :value-set (widget-apply widget
281                                          :value-to-internal value)))
282
283 (defun widget-match-inline (widget vals)
284   ;; In WIDGET, match the start of VALS.
285   (cond ((widget-get widget :inline)
286          (widget-apply widget :match-inline vals))
287         ((and vals
288               (widget-apply widget :match (car vals)))
289          (cons (list (car vals)) (cdr vals)))
290         (t nil)))
291
292 ;;; Creating Widgets.
293
294 ;;;###autoload
295 (defun widget-create (type &rest args)
296   "Create widget of TYPE.  
297 The optional ARGS are additional keyword arguments."
298   (let ((widget (apply 'widget-convert type args)))
299     (widget-apply widget :create)
300     widget))
301
302 (defun widget-create-child-and-convert (parent type &rest args)
303   "As part of the widget PARENT, create a child widget TYPE.
304 The child is converted, using the keyword arguments ARGS."
305   (let ((widget (apply 'widget-convert type args)))
306     (widget-put widget :parent parent)
307     (unless (widget-get widget :indent)
308       (widget-put widget :indent (+ (or (widget-get parent :indent) 0)
309                                     (or (widget-get widget :extra-offset) 0)
310                                     (widget-get parent :offset))))
311     (widget-apply widget :create)
312     widget))
313
314 (defun widget-create-child (parent type)
315   "Create widget of TYPE.  "
316   (let ((widget (copy-list type)))
317     (widget-put widget :parent parent)
318     (unless (widget-get widget :indent)
319       (widget-put widget :indent (+ (or (widget-get parent :indent) 0)
320                                     (widget-get parent :offset))))
321     (widget-apply widget :create)
322     widget))
323
324 ;;;###autoload
325 (defun widget-delete (widget)
326   "Delete WIDGET."
327   (widget-apply widget :delete))
328
329 (defun widget-convert (type &rest args)
330   "Convert TYPE to a widget without inserting it in the buffer. 
331 The optional ARGS are additional keyword arguments."
332   ;; Don't touch the type.
333   (let* ((widget (if (symbolp type) 
334                      (list type)
335                    (copy-list type)))
336          (current widget)
337          (keys args))
338     ;; First set the :args keyword.
339     (while (cdr current)                ;Look in the type.
340       (let ((next (car (cdr current))))
341         (if (and (symbolp next) (eq (aref (symbol-name next) 0) ?:))
342             (setq current (cdr (cdr current)))
343           (setcdr current (list :args (cdr current)))
344           (setq current nil))))
345     (while args                         ;Look in the args.
346       (let ((next (nth 0 args)))
347         (if (and (symbolp next) (eq (aref (symbol-name next) 0) ?:))
348             (setq args (nthcdr 2 args))
349           (widget-put widget :args args)
350           (setq args nil))))
351     ;; Then Convert the widget.
352     (setq type widget)
353     (while type
354       (let ((convert-widget (plist-get (cdr type) :convert-widget)))
355         (if convert-widget
356             (setq widget (funcall convert-widget widget))))
357       (setq type (get (car type) 'widget-type)))
358     ;; Finally set the keyword args.
359     (while keys 
360       (let ((next (nth 0 keys)))
361         (if (and (symbolp next) (eq (aref (symbol-name next) 0) ?:))
362             (progn 
363               (widget-put widget next (nth 1 keys))
364               (setq keys (nthcdr 2 keys)))
365           (setq keys nil))))
366     ;; Convert the :value to internal format.
367     (if (widget-member widget :value)
368         (let ((value (widget-get widget :value)))
369           (widget-put widget
370                       :value (widget-apply widget :value-to-internal value))))
371     ;; Return the newly create widget.
372     widget))
373
374 (defun widget-insert (&rest args)
375   "Call `insert' with ARGS and make the text read only."
376   (let ((inhibit-read-only t)
377         after-change-functions
378         (from (point)))
379     (apply 'insert args)
380     (widget-specify-text from (point))))
381
382 ;;; Keymap and Comands.
383
384 (defvar widget-keymap nil
385   "Keymap containing useful binding for buffers containing widgets.
386 Recommended as a parent keymap for modes using widgets.")
387
388 (if widget-keymap 
389     ()
390   (setq widget-keymap (make-sparse-keymap))
391   (set-keymap-parent widget-keymap global-map)
392   (define-key widget-keymap "\t" 'widget-forward)
393   (define-key widget-keymap "\M-\t" 'widget-backward)
394   (define-key widget-keymap [(shift tab)] 'widget-backward)
395   (define-key widget-keymap [(shift tab)] 'widget-backward)
396   (define-key widget-keymap [backtab] 'widget-backward)
397   (if (string-match "XEmacs" (emacs-version))
398       (define-key widget-keymap [button2] 'widget-button-click)
399     (define-key widget-keymap [menu-bar] 'nil)
400     (define-key widget-keymap [mouse-2] 'widget-button-click))
401   (define-key widget-keymap "\C-m" 'widget-button-press))
402
403 (defvar widget-global-map global-map
404   "Keymap used for events the widget does not handle themselves.")
405 (make-variable-buffer-local 'widget-global-map)
406
407 (defun widget-button-click (event)
408   "Activate button below mouse pointer."
409   (interactive "@e")
410   (widget-button-press (event-point event) event))
411
412 (defun widget-button-press (pos &optional event)
413   "Activate button at POS."
414   (interactive "@d")
415   (let* ((button (get-text-property pos 'button)))
416     (if button
417         (widget-apply button :action event)
418       (call-interactively
419        (lookup-key widget-global-map (this-command-keys))))))
420
421 (defun widget-forward (arg)
422   "Move point to the next field or button.
423 With optional ARG, move across that many fields."
424   (interactive "p")
425   (while (> arg 0)
426     (setq arg (1- arg))
427     (let ((next (cond ((get-text-property (point) 'button)
428                        (next-single-property-change (point) 'button))
429                       ((get-text-property (point) 'field)
430                        (next-single-property-change (point) 'field))
431                       (t
432                        (point)))))
433       (if (null next)                   ; Widget extends to end. of buffer
434           (setq next (point-min)))
435       (let ((button (next-single-property-change next 'button))
436             (field (next-single-property-change next 'field)))
437         (cond ((or (get-text-property next 'button)
438                    (get-text-property next 'field))
439                (goto-char next))
440               ((and button field)
441                (goto-char (min button field)))
442               (button (goto-char button))
443               (field (goto-char field))
444               (t
445                (let ((button (next-single-property-change (point-min) 'button))
446                      (field (next-single-property-change (point-min) 'field)))
447                  (cond ((and button field) (goto-char (min button field)))
448                        (button (goto-char button))
449                        (field (goto-char field))
450                        (t
451                         (error "No buttons or fields found")))))))))
452   (while (< arg 0)
453     (if (= (point-min) (point))
454         (forward-char 1))
455     (setq arg (1+ arg))
456     (let ((previous (cond ((get-text-property (1- (point)) 'button)
457                            (previous-single-property-change (point) 'button))
458                           ((get-text-property (1- (point)) 'field)
459                            (previous-single-property-change (point) 'field))
460                           (t
461                            (point)))))
462       (if (null previous)               ; Widget extends to beg. of buffer
463           (setq previous (point-max)))
464       (let ((button (previous-single-property-change previous 'button))
465             (field (previous-single-property-change previous 'field)))
466         (cond ((and button field)
467                (goto-char (max button field)))
468               (button (goto-char button))
469               (field (goto-char field))
470               (t
471                (let ((button (previous-single-property-change
472                               (point-max) 'button))
473                      (field (previous-single-property-change
474                              (point-max) 'field)))
475                  (cond ((and button field) (goto-char (max button field)))
476                        (button (goto-char button))
477                        (field (goto-char field))
478                        (t
479                         (error "No buttons or fields found"))))))))
480     (let ((button (previous-single-property-change (point) 'button))
481           (field (previous-single-property-change (point) 'field)))
482       (cond ((and button field)
483              (goto-char (max button field)))
484             (button (goto-char button))
485             (field (goto-char field)))))
486   (widget-echo-help (point)))
487
488 (defun widget-backward (arg)
489   "Move point to the previous field or button.
490 With optional ARG, move across that many fields."
491   (interactive "p")
492   (widget-forward (- arg)))
493
494 ;;; Setting up the buffer.
495
496 (defvar widget-field-new nil)
497 ;; List of all newly created editable fields in the buffer.
498 (make-variable-buffer-local 'widget-field-new)
499
500 (defvar widget-field-list nil)
501 ;; List of all editable fields in the buffer.
502 (make-variable-buffer-local 'widget-field-list)
503
504 (defun widget-setup ()
505   "Setup current buffer so editing string widgets works."
506   (let ((inhibit-read-only t)
507         (after-change-functions nil)
508         field)
509     (while widget-field-new
510       (setq field (car widget-field-new)
511             widget-field-new (cdr widget-field-new)
512             widget-field-list (cons field widget-field-list))
513       (let ((from (widget-get field :value-from))
514             (to (widget-get field :value-to)))
515         (widget-specify-field field from to)
516         (move-marker from (1- from))
517         (move-marker to (1+ to)))))
518   (widget-clear-undo)
519   ;; We need to maintain text properties and size of the editing fields.
520   (make-local-variable 'after-change-functions)
521   (if widget-field-list
522       (setq after-change-functions '(widget-after-change))
523     (setq after-change-functions nil)))
524
525 (defvar widget-field-last nil)
526 ;; Last field containing point.
527 (make-variable-buffer-local 'widget-field-last)
528
529 (defvar widget-field-was nil)
530 ;; The widget data before the change.
531 (make-variable-buffer-local 'widget-field-was)
532
533 (defun widget-field-find (pos)
534   ;; Find widget whose editing field is located at POS.
535   ;; Return nil if POS is not inside and editing field.
536   ;; 
537   ;; This is only used in `widget-field-modified', since ordinarily
538   ;; you would just test the field property.
539   (let ((fields widget-field-list)
540         field found)
541     (while fields
542       (setq field (car fields)
543             fields (cdr fields))
544       (let ((from (widget-get field :value-from))
545             (to (widget-get field :value-to)))
546         (if (and from to (< from pos) (> to  pos))
547             (setq fields nil
548                   found field))))
549     found))
550
551 (defun widget-after-change (from to old)
552   ;; Adjust field size and text properties.
553   (condition-case nil
554       (let ((field (widget-field-find from))
555             (inhibit-read-only t))
556         (cond ((null field))
557               ((not (eq field (widget-field-find to)))
558                (debug)
559                (message "Error: `widget-after-change' called on two fields"))
560               (t
561                (let ((size (widget-get field :size)))
562                  (and (string-match "XEmacs" emacs-version)
563                       ;; XEmacs cannot handle zero-sized fields.
564                       (or (null size)
565                           (zerop size))
566                       (setq size 1))
567                  (if size 
568                      (let ((begin (1+ (widget-get field :value-from)))
569                            (end (1- (widget-get field :value-to))))
570                        (widget-specify-field-update field begin end)
571                        (cond ((< (- end begin) size)
572                               ;; Field too small.
573                               (save-excursion
574                                 (goto-char end)
575                                 (insert-char ?\  (- (+ begin size) end))
576                                 (widget-specify-field-update field 
577                                                              begin
578                                                              (+ begin size))))
579                              ((> (- end begin) size)
580                               ;; Field too large and
581                               (if (or (< (point) (+ begin size))
582                                       (> (point) end))
583                                   ;; Point is outside extra space.
584                                   (setq begin (+ begin size))
585                                 ;; Point is within the extra space.
586                                 (setq begin (point)))
587                               (save-excursion
588                                 (goto-char end)
589                                 (while (and (eq (preceding-char) ?\ )
590                                             (> (point) begin))
591                                   (delete-backward-char 1))))))
592                    (widget-specify-field-update field from to)))
593                (widget-apply field :notify field))))
594     (error (debug))))
595
596 ;;; Widget Functions
597 ;;
598 ;; These functions are used in the definition of multiple widgets. 
599
600 (defun widget-children-value-delete (widget)
601   "Delete all :children and :buttons in WIDGET."
602   (mapcar 'widget-delete (widget-get widget :children))
603   (widget-put widget :children nil)
604   (mapcar 'widget-delete (widget-get widget :buttons))
605   (widget-put widget :buttons nil))
606
607 (defun widget-types-convert-widget (widget)
608   "Convert :args as widget types in WIDGET."
609   (widget-put widget :args (mapcar 'widget-convert (widget-get widget :args)))
610   widget)
611
612 ;;; The `default' Widget.
613
614 (define-widget 'default nil
615   "Basic widget other widgets are derived from."
616   :value-to-internal (lambda (widget value) value)
617   :value-to-external (lambda (widget value) value)
618   :create 'widget-default-create
619   :indent nil
620   :offset 0
621   :format-handler 'widget-default-format-handler
622   :button-face-get 'widget-default-button-face-get 
623   :delete 'widget-default-delete
624   :value-set 'widget-default-value-set
625   :value-inline 'widget-default-value-inline
626   :menu-tag-get 'widget-default-menu-tag-get
627   :validate (lambda (widget) nil)
628   :action 'widget-default-action
629   :notify 'widget-default-notify)
630
631 (defun widget-default-create (widget)
632   "Create WIDGET at point in the current buffer."
633   (widget-specify-insert
634    (let ((from (point))
635          (tag (widget-get widget :tag))
636          (doc (widget-get widget :doc))
637          button-begin button-end
638          doc-begin doc-end
639          value-pos)
640      (insert (widget-get widget :format))
641      (goto-char from)
642      ;; Parse % escapes in format.
643      (while (re-search-forward "%\\(.\\)" nil t)
644        (let ((escape (aref (match-string 1) 0)))
645          (replace-match "" t t)
646          (cond ((eq escape ?%)
647                 (insert "%"))
648                ((eq escape ?\[)
649                 (setq button-begin (point)))
650                ((eq escape ?\])
651                 (setq button-end (point)))
652                ((eq escape ?n)
653                 (when (widget-get widget :indent)
654                   (insert "\n")
655                   (insert-char ?  (widget-get widget :indent))))
656                ((eq escape ?t)
657                 (if tag
658                     (insert tag)
659                   (let ((standard-output (current-buffer)))
660                     (princ (widget-get widget :value)))))
661                ((eq escape ?d)
662                 (when doc
663                   (setq doc-begin (point))
664                   (insert doc)
665                   (while (eq (preceding-char) ?\n)
666                     (delete-backward-char 1))
667                   (insert "\n")
668                   (setq doc-end (point))))
669                ((eq escape ?v)
670                 (if (and button-begin (not button-end))
671                     (widget-apply widget :value-create)
672                   (setq value-pos (point))))
673                (t 
674                 (widget-apply widget :format-handler escape)))))
675      ;; Specify button and doc, and insert value.
676      (and button-begin button-end
677           (widget-specify-button widget button-begin button-end))
678      (and doc-begin doc-end
679           (widget-specify-doc widget doc-begin doc-end))
680      (when value-pos
681        (goto-char value-pos)
682        (widget-apply widget :value-create)))
683    (let ((from (copy-marker (point-min)))
684          (to (copy-marker (point-max))))
685      (widget-specify-text from to)
686      (set-marker-insertion-type from t)
687      (set-marker-insertion-type to nil)
688      (widget-put widget :from from)
689      (widget-put widget :to to))))
690
691 (defun widget-default-format-handler (widget escape)
692   ;; We recognize the %h escape by default.
693   (let* ((buttons (widget-get widget :buttons))
694          (doc-property (widget-get widget :documentation-property))
695          (doc-try (cond ((widget-get widget :doc))
696                         ((symbolp doc-property)
697                          (documentation-property (widget-get widget :value)
698                                                  doc-property))
699                         (t
700                          (funcall doc-property (widget-get widget :value)))))
701          (doc-text (and (stringp doc-try)
702                         (> (length doc-try) 1)
703                         doc-try)))
704     (cond ((eq escape ?h)
705            (when doc-text
706              (and (eq (preceding-char) ?\n)
707                   (widget-get widget :indent)
708                   (insert-char ?  (widget-get widget :indent)))
709              ;; The `*' in the beginning is redundant.
710              (when (eq (aref doc-text  0) ?*)
711                (setq doc-text (substring doc-text 1)))
712              ;; Get rid of trailing newlines.
713              (when (string-match "\n+\\'" doc-text)
714                (setq doc-text (substring doc-text 0 (match-beginning 0))))
715              (push (if (string-match "\n." doc-text)
716                        ;; Allow multiline doc to be hiden.
717                        (widget-create-child-and-convert
718                         widget 'widget-help 
719                         :doc (progn
720                                (string-match "\\`.*" doc-text)
721                                (match-string 0 doc-text))
722                         :widget-doc doc-text
723                         "?")
724                      ;; A single line is just inserted.
725                      (widget-create-child-and-convert
726                       widget 'item :format "%d" :doc doc-text nil))
727                    buttons)))
728           (t 
729            (error "Unknown escape `%c'" escape)))
730     (widget-put widget :buttons buttons)))
731
732 (defun widget-default-button-face-get (widget)
733   ;; Use :button-face or widget-button-face
734   (or (widget-get widget :button-face) 'widget-button-face))
735
736 (defun widget-default-delete (widget)
737   ;; Remove widget from the buffer.
738   (let ((from (widget-get widget :from))
739         (to (widget-get widget :to))
740         (inhibit-read-only t)
741         after-change-functions)
742     (widget-apply widget :value-delete)
743     (delete-region from to)
744     (set-marker from nil)
745     (set-marker to nil)))
746
747 (defun widget-default-value-set (widget value)
748   ;; Recreate widget with new value.
749   (save-excursion
750     (goto-char (widget-get widget :from))
751     (widget-apply widget :delete)
752     (widget-put widget :value value)
753     (widget-apply widget :create)))
754
755 (defun widget-default-value-inline (widget)
756   ;; Wrap value in a list unless it is inline.
757   (if (widget-get widget :inline)
758       (widget-value widget)
759     (list (widget-value widget))))
760
761 (defun widget-default-menu-tag-get (widget)
762   ;; Use tag or value for menus.
763   (or (widget-get widget :menu-tag)
764       (widget-get widget :tag)
765       (widget-princ-to-string (widget-get widget :value))))
766
767 (defun widget-default-action (widget &optional event)
768   ;; Notify the parent when a widget change
769   (let ((parent (widget-get widget :parent)))
770     (when parent
771       (widget-apply parent :notify widget event))))
772
773 (defun widget-default-notify (widget child &optional event)
774   ;; Pass notification to parent.
775   (widget-default-action widget event))
776
777 ;;; The `item' Widget.
778
779 (define-widget 'item 'default
780   "Constant items for inclusion in other widgets."
781   :convert-widget 'widget-item-convert-widget
782   :value-create 'widget-item-value-create
783   :value-delete 'ignore
784   :value-get 'widget-item-value-get
785   :match 'widget-item-match
786   :match-inline 'widget-item-match-inline
787   :action 'widget-item-action
788   :format "%t\n")
789
790 (defun widget-item-convert-widget (widget)
791   ;; Initialize :value and :tag from :args in WIDGET.
792   (let ((args (widget-get widget :args)))
793     (when args 
794       (widget-put widget :value (widget-apply widget
795                                               :value-to-internal (car args)))
796       (widget-put widget :args nil)))
797   widget)
798
799 (defun widget-item-value-create (widget)
800   ;; Insert the printed representation of the value.
801   (let ((standard-output (current-buffer)))
802     (princ (widget-get widget :value))))
803
804 (defun widget-item-match (widget value)
805   ;; Match if the value is the same.
806   (equal (widget-get widget :value) value))
807
808 (defun widget-item-match-inline (widget values)
809   ;; Match if the value is the same.
810   (let ((value (widget-get widget :value)))
811     (and (listp value)
812          (<= (length value) (length values))
813          (let ((head (subseq values 0 (length value))))
814            (and (equal head value)
815                 (cons head (subseq values (length value))))))))
816
817 (defun widget-item-action (widget &optional event)
818   ;; Just notify itself.
819   (widget-apply widget :notify widget event))
820
821 (defun widget-item-value-get (widget)
822   ;; Items are simple.
823   (widget-get widget :value))
824
825 ;;; The `push-button' Widget.
826
827 (define-widget 'push-button 'item
828   "A pushable button."
829   :format "%[[%t]%]")
830
831 ;;; The `link' Widget.
832
833 (define-widget 'link 'item
834   "An embedded link."
835   :format "%[_%t_%]")
836
837 ;;; The `info-link' Widget.
838
839 (define-widget 'info-link 'link
840   "A link to an info file."
841   :action 'widget-info-link-action)
842
843 (defun widget-info-link-action (widget &optional event)
844   "Open the info node specified by WIDGET."
845   (Info-goto-node (widget-value widget)))
846
847 ;;; The `url-link' Widget.
848
849 (define-widget 'url-link 'link
850   "A link to an www page."
851   :action 'widget-url-link-action)
852
853 (defun widget-url-link-action (widget &optional event)
854   "Open the url specified by WIDGET."
855   (require 'browse-url)
856   (funcall browse-url-browser-function (widget-value widget)))
857
858 ;;; The `editable-field' Widget.
859
860 (define-widget 'editable-field 'default
861   "An editable text field."
862   :convert-widget 'widget-item-convert-widget
863   :format "%v"
864   :value ""
865   :action 'widget-field-action
866   :value-create 'widget-field-value-create
867   :value-delete 'widget-field-value-delete
868   :value-get 'widget-field-value-get
869   :match 'widget-field-match)
870
871 ;; History of field minibuffer edits.
872 (defvar widget-field-history nil)
873
874 (defun widget-field-action (widget &optional event)
875   ;; Edit the value in the minibuffer.
876   (let ((tag (widget-apply widget :menu-tag-get))
877         (invalid (widget-apply widget :validate)))
878     (when invalid
879       (error (widget-get invalid :error)))
880     (widget-value-set widget 
881                       (widget-apply widget 
882                                     :value-to-external
883                                     (read-string (concat tag ": ") 
884                                                  (widget-apply 
885                                                   widget
886                                                   :value-to-internal
887                                                   (widget-value widget))
888                                                  'widget-field-history)))
889     (widget-apply widget :notify widget event)
890     (widget-setup)))
891
892 (defun widget-field-value-create (widget)
893   ;; Create an editable text field.
894   (insert " ")
895   (let ((size (widget-get widget :size))
896         (value (widget-get widget :value))
897         (from (point)))
898     (if (null size)
899         (if (zerop (length value))
900             (insert "")
901           (insert value))
902       (insert value)
903       (if (< (length value) size)
904           (insert-char ?\  (- size (length value)))))
905     (and (string-match "XEmacs" emacs-version)
906          ;; XEmacs cannot handle zero-sized fields.
907          (or (null size)
908              (zerop size))
909          (insert " "))
910     (unless (memq widget widget-field-list)
911       (setq widget-field-new (cons widget widget-field-new)))
912     (widget-put widget :value-to (copy-marker (point)))
913     (set-marker-insertion-type (widget-get widget :value-to) nil)
914     (if (null size)
915         (insert ?\n)
916       (insert ?\ ))
917     (widget-put widget :value-from (copy-marker from))
918     (set-marker-insertion-type (widget-get widget :value-from) t)))
919
920 (defun widget-field-value-delete (widget)
921   ;; Remove the widget from the list of active editing fields.
922   (setq widget-field-list (delq widget widget-field-list))
923   (set-marker (widget-get widget :value-from) nil)
924   (set-marker (widget-get widget :value-to) nil))
925
926 (defun widget-field-value-get (widget)
927   ;; Return current text in editing field.
928   (let ((from (widget-get widget :value-from))
929         (to (widget-get widget :value-to))
930         (size (widget-get widget :size))
931         (old (current-buffer)))
932     (if (and from to)
933         (progn 
934           (set-buffer (marker-buffer from))
935           (setq from (1+ from)
936                 to (1- to))
937           (while (and size
938                       (not (zerop size))
939                       (> to from)
940                       (eq (char-after (1- to)) ?\ ))
941             (setq to (1- to)))
942           (prog1 (buffer-substring-no-properties from to)
943             (set-buffer old)))
944       (widget-get widget :value))))
945
946 (defun widget-field-match (widget value)
947   ;; Match any string.
948   (stringp value))
949
950 ;;; The `text' Widget.
951
952 (define-widget 'text 'editable-field
953   "A multiline text area.")
954
955 ;;; The `menu-choice' Widget.
956
957 (define-widget 'menu-choice 'default
958   "A menu of options."
959   :convert-widget  'widget-types-convert-widget
960   :format "%[%t%]: %v"
961   :case-fold t
962   :tag "choice"
963   :void '(item :format "invalid (%t)\n")
964   :value-create 'widget-choice-value-create
965   :value-delete 'widget-children-value-delete
966   :value-get 'widget-choice-value-get
967   :value-inline 'widget-choice-value-inline
968   :action 'widget-choice-action
969   :error "Make a choice"
970   :validate 'widget-choice-validate
971   :match 'widget-choice-match
972   :match-inline 'widget-choice-match-inline)
973
974 (defun widget-choice-value-create (widget)
975   ;; Insert the first choice that matches the value.
976   (let ((value (widget-get widget :value))
977         (args (widget-get widget :args))
978         current)
979     (while args
980       (setq current (car args)
981             args (cdr args))
982       (when (widget-apply current :match value)
983         (widget-put widget :children (list (widget-create-child-and-convert
984                                             widget current :value value)))
985         (widget-put widget :choice current)
986         (setq args nil
987               current nil)))
988     (when current
989       (let ((void (widget-get widget :void)))
990         (widget-put widget :children (list (widget-create-child-and-convert
991                                             widget void :value value)))
992         (widget-put widget :choice void)))))
993
994 (defun widget-choice-value-get (widget)
995   ;; Get value of the child widget.
996   (widget-value (car (widget-get widget :children))))
997
998 (defun widget-choice-value-inline (widget)
999   ;; Get value of the child widget.
1000   (widget-apply (car (widget-get widget :children)) :value-inline))
1001
1002 (defun widget-choice-action (widget &optional event)
1003   ;; Make a choice.
1004   (let ((args (widget-get widget :args))
1005         (old (widget-get widget :choice))
1006         (tag (widget-apply widget :menu-tag-get))
1007         (completion-ignore-case (widget-get widget :case-fold))
1008         current choices)
1009     ;; Remember old value.
1010     (if (and old (not (widget-apply widget :validate)))
1011         (let* ((external (widget-value widget))
1012                (internal (widget-apply old :value-to-internal external)))
1013           (widget-put old :value internal)))
1014     ;; Find new choice.
1015     (setq current
1016           (cond ((= (length args) 0)
1017                  nil)
1018                 ((= (length args) 1)
1019                  (nth 0 args))
1020                 ((and (= (length args) 2)
1021                       (memq old args))
1022                  (if (eq old (nth 0 args))
1023                      (nth 1 args)
1024                    (nth 0 args)))
1025                 (t
1026                  (while args
1027                    (setq current (car args)
1028                          args (cdr args))
1029                    (setq choices
1030                          (cons (cons (widget-apply current :menu-tag-get)
1031                                      current)
1032                                choices)))
1033                  (widget-choose tag (reverse choices) event))))
1034     (when current
1035       (widget-value-set widget 
1036                         (widget-apply current :value-to-external
1037                                       (widget-get current :value)))
1038     (widget-apply widget :notify widget event)
1039     (widget-setup)))
1040   ;; Notify parent.
1041   (widget-apply widget :notify widget event)
1042   (widget-clear-undo))
1043
1044 (defun widget-choice-validate (widget)
1045   ;; Valid if we have made a valid choice.
1046   (let ((void (widget-get widget :void))
1047         (choice (widget-get widget :choice))
1048         (child (car (widget-get widget :children))))
1049     (if (eq void choice)
1050         widget
1051       (widget-apply child :validate))))
1052
1053 (defun widget-choice-match (widget value)
1054   ;; Matches if one of the choices matches.
1055   (let ((args (widget-get widget :args))
1056         current found)
1057     (while (and args (not found))
1058       (setq current (car args)
1059             args (cdr args)
1060             found (widget-apply current :match value)))
1061     found))
1062
1063 (defun widget-choice-match-inline (widget values)
1064   ;; Matches if one of the choices matches.
1065   (let ((args (widget-get widget :args))
1066         current found)
1067     (while (and args (null found))
1068       (setq current (car args)
1069             args (cdr args)
1070             found (widget-match-inline current values)))
1071     found))
1072
1073 ;;; The `toggle' Widget.
1074
1075 (define-widget 'toggle 'menu-choice
1076   "Toggle between two states."
1077   :convert-widget 'widget-toggle-convert-widget
1078   :format "%v"
1079   :on "on"
1080   :off "off")
1081
1082 (defun widget-toggle-convert-widget (widget)
1083   ;; Create the types representing the `on' and `off' states.
1084   (let ((on-type (widget-get widget :on-type))
1085         (off-type (widget-get widget :off-type)))
1086     (unless on-type
1087       (setq on-type
1088             (list 'choice-item 
1089                   :value t
1090                   :match (lambda (widget value) value)
1091                   :tag (widget-get widget :on))))
1092     (unless off-type
1093       (setq off-type
1094             (list 'choice-item :value nil :tag (widget-get widget :off))))
1095     (widget-put widget :args (list on-type off-type)))
1096   widget)
1097
1098 ;;; The `checkbox' Widget.
1099
1100 (define-widget 'checkbox 'toggle
1101   "A checkbox toggle."
1102   :convert-widget 'widget-item-convert-widget
1103   :on-type '(choice-item :format "%[[X]%]" t)
1104   :off-type  '(choice-item :format "%[[ ]%]" nil))
1105
1106 ;;; The `checklist' Widget.
1107
1108 (define-widget 'checklist 'default
1109   "A multiple choice widget."
1110   :convert-widget 'widget-types-convert-widget
1111   :format "%v"
1112   :offset 4
1113   :entry-format "%b %v"
1114   :menu-tag "checklist"
1115   :greedy nil
1116   :value-create 'widget-checklist-value-create
1117   :value-delete 'widget-children-value-delete
1118   :value-get 'widget-checklist-value-get
1119   :validate 'widget-checklist-validate
1120   :match 'widget-checklist-match
1121   :match-inline 'widget-checklist-match-inline)
1122
1123 (defun widget-checklist-value-create (widget)
1124   ;; Insert all values
1125   (let ((alist (widget-checklist-match-find widget (widget-get widget :value)))
1126         (args (widget-get widget :args)))
1127     (while args 
1128       (widget-checklist-add-item widget (car args) (assq (car args) alist))
1129       (setq args (cdr args)))
1130     (widget-put widget :children (nreverse (widget-get widget :children)))))
1131
1132 (defun widget-checklist-add-item (widget type chosen)
1133   ;; Create checklist item in WIDGET of type TYPE.
1134   ;; If the item is checked, CHOSEN is a cons whose cdr is the value.
1135   (and (eq (preceding-char) ?\n)
1136        (widget-get widget :indent)
1137        (insert-char ?  (widget-get widget :indent)))
1138   (widget-specify-insert 
1139    (let* ((children (widget-get widget :children))
1140           (buttons (widget-get widget :buttons))
1141           (from (point))
1142           child button)
1143      (insert (widget-get widget :entry-format))
1144      (goto-char from)
1145      ;; Parse % escapes in format.
1146      (while (re-search-forward "%\\([bv%]\\)" nil t)
1147        (let ((escape (aref (match-string 1) 0)))
1148          (replace-match "" t t)
1149          (cond ((eq escape ?%)
1150                 (insert "%"))
1151                ((eq escape ?b)
1152                 (setq button (widget-create-child-and-convert
1153                               widget 'checkbox :value (not (null chosen)))))
1154                ((eq escape ?v)
1155                 (setq child
1156                       (cond ((not chosen)
1157                              (widget-create-child widget type))
1158                             ((widget-get type :inline)
1159                              (widget-create-child-and-convert
1160                               widget type :value (cdr chosen)))
1161                             (t
1162                              (widget-create-child-and-convert
1163                               widget type :value (car (cdr chosen)))))))
1164                (t 
1165                 (error "Unknown escape `%c'" escape)))))
1166      ;; Update properties.
1167      (and button child (widget-put child :button button))
1168      (and button (widget-put widget :buttons (cons button buttons)))
1169      (and child (widget-put widget :children (cons child children))))))
1170
1171 (defun widget-checklist-match (widget values)
1172   ;; All values must match a type in the checklist.
1173   (and (listp values)
1174        (null (cdr (widget-checklist-match-inline widget values)))))
1175
1176 (defun widget-checklist-match-inline (widget values)
1177   ;; Find the values which match a type in the checklist.
1178   (let ((greedy (widget-get widget :greedy))
1179         (args (copy-list (widget-get widget :args)))
1180         found rest)
1181     (while values
1182       (let ((answer (widget-checklist-match-up args values)))
1183         (cond (answer 
1184                (let ((vals (widget-match-inline answer values)))
1185                  (setq found (append found (car vals))
1186                        values (cdr vals)
1187                        args (delq answer args))))
1188               (greedy
1189                (setq rest (append rest (list (car values)))
1190                      values (cdr values)))
1191               (t 
1192                (setq rest (append rest values)
1193                      values nil)))))
1194     (cons found rest)))
1195
1196 (defun widget-checklist-match-find (widget vals)
1197   ;; Find the vals which match a type in the checklist.
1198   ;; Return an alist of (TYPE MATCH).
1199   (let ((greedy (widget-get widget :greedy))
1200         (args (copy-list (widget-get widget :args)))
1201         found)
1202     (while vals
1203       (let ((answer (widget-checklist-match-up args vals)))
1204         (cond (answer 
1205                (let ((match (widget-match-inline answer vals)))
1206                  (setq found (cons (cons answer (car match)) found)
1207                        vals (cdr match)
1208                        args (delq answer args))))
1209               (greedy
1210                (setq vals (cdr vals)))
1211               (t 
1212                (setq vals nil)))))
1213     found))
1214
1215 (defun widget-checklist-match-up (args vals)
1216   ;; Rerturn the first type from ARGS that matches VALS.
1217   (let (current found)
1218     (while (and args (null found))
1219       (setq current (car args)
1220             args (cdr args)
1221             found (widget-match-inline current vals)))
1222     (if found
1223         current
1224       nil)))
1225
1226 (defun widget-checklist-value-get (widget)
1227   ;; The values of all selected items.
1228   (let ((children (widget-get widget :children))
1229         child result)
1230     (while children 
1231       (setq child (car children)
1232             children (cdr children))
1233       (if (widget-value (widget-get child :button))
1234           (setq result (append result (widget-apply child :value-inline)))))
1235     result))
1236
1237 (defun widget-checklist-validate (widget)
1238   ;; Ticked chilren must be valid.
1239   (let ((children (widget-get widget :children))
1240         child button found)
1241     (while (and children (not found))
1242       (setq child (car children)
1243             children (cdr children)
1244             button (widget-get child :button)
1245             found (and (widget-value button)
1246                        (widget-apply child :validate))))
1247     found))
1248
1249 ;;; The `option' Widget
1250
1251 (define-widget 'option 'checklist
1252   "An widget with an optional item."
1253   :inline t)
1254
1255 ;;; The `choice-item' Widget.
1256
1257 (define-widget 'choice-item 'item
1258   "Button items that delegate action events to their parents."
1259   :action 'widget-choice-item-action
1260   :format "%[%t%] \n")
1261
1262 (defun widget-choice-item-action (widget &optional event)
1263   ;; Tell parent what happened.
1264   (widget-apply (widget-get widget :parent) :action event))
1265
1266 ;;; The `radio-button' Widget.
1267
1268 (define-widget 'radio-button 'toggle
1269   "A radio button for use in the `radio' widget."
1270   :notify 'widget-radio-button-notify
1271   :on-type '(choice-item :format "%[(*)%]" t)
1272   :off-type '(choice-item :format "%[( )%]" nil))
1273
1274 (defun widget-radio-button-notify (widget child &optional event)
1275   ;; Notify the parent.
1276   (widget-apply (widget-get widget :parent) :action widget event))
1277
1278 ;;; The `radio-button-choice' Widget.
1279
1280 (define-widget 'radio-button-choice 'default
1281   "Select one of multiple options."
1282   :convert-widget 'widget-types-convert-widget
1283   :offset 4
1284   :format "%v"
1285   :entry-format "%b %v"
1286   :menu-tag "radio"
1287   :value-create 'widget-radio-value-create
1288   :value-delete 'widget-children-value-delete
1289   :value-get 'widget-radio-value-get
1290   :value-inline 'widget-radio-value-inline
1291   :value-set 'widget-radio-value-set
1292   :error "You must push one of the buttons"
1293   :validate 'widget-radio-validate
1294   :match 'widget-choice-match
1295   :match-inline 'widget-choice-match-inline
1296   :action 'widget-radio-action)
1297
1298 (defun widget-radio-value-create (widget)
1299   ;; Insert all values
1300   (let ((args (widget-get widget :args))
1301         arg)
1302     (while args 
1303       (setq arg (car args)
1304             args (cdr args))
1305       (widget-radio-add-item widget arg))))
1306
1307 (defun widget-radio-add-item (widget type)
1308   "Add to radio widget WIDGET a new radio button item of type TYPE."
1309   ;; (setq type (widget-convert type))
1310   (and (eq (preceding-char) ?\n)
1311        (widget-get widget :indent)
1312        (insert-char ?  (widget-get widget :indent)))
1313   (widget-specify-insert 
1314    (let* ((value (widget-get widget :value))
1315           (children (widget-get widget :children))
1316           (buttons (widget-get widget :buttons))
1317           (from (point))
1318           (chosen (and (null (widget-get widget :choice))
1319                        (widget-apply type :match value)))
1320           child button)
1321      (insert (widget-get widget :entry-format))
1322      (goto-char from)
1323      ;; Parse % escapes in format.
1324      (while (re-search-forward "%\\([bv%]\\)" nil t)
1325        (let ((escape (aref (match-string 1) 0)))
1326          (replace-match "" t t)
1327          (cond ((eq escape ?%)
1328                 (insert "%"))
1329                ((eq escape ?b)
1330                 (setq button (widget-create-child-and-convert
1331                               widget 'radio-button 
1332                               :value (not (null chosen)))))
1333                ((eq escape ?v)
1334                 (setq child (if chosen
1335                                 (widget-create-child-and-convert
1336                                  widget type :value value)
1337                               (widget-create-child widget type))))
1338                (t 
1339                 (error "Unknown escape `%c'" escape)))))
1340      ;; Update properties.
1341      (when chosen
1342        (widget-put widget :choice type))
1343      (when button 
1344        (widget-put child :button button)
1345        (widget-put widget :buttons (nconc buttons (list button))))
1346      (when child
1347        (widget-put widget :children (nconc children (list child))))
1348      child)))
1349
1350 (defun widget-radio-value-get (widget)
1351   ;; Get value of the child widget.
1352   (let ((chosen (widget-radio-chosen widget)))
1353     (and chosen (widget-value chosen))))
1354
1355 (defun widget-radio-chosen (widget)
1356   "Return the widget representing the chosen radio button."
1357   (let ((children (widget-get widget :children))
1358         current found)
1359     (while children
1360       (setq current (car children)
1361             children (cdr children))
1362       (let* ((button (widget-get current :button))
1363              (value (widget-apply button :value-get)))
1364         (when value
1365           (setq found current
1366                 children nil))))
1367     found))
1368
1369 (defun widget-radio-value-inline (widget)
1370   ;; Get value of the child widget.
1371   (let ((children (widget-get widget :children))
1372         current found)
1373     (while children
1374       (setq current (car children)
1375             children (cdr children))
1376       (let* ((button (widget-get current :button))
1377              (value (widget-apply button :value-get)))
1378         (when value
1379           (setq found (widget-apply current :value-inline)
1380                 children nil))))
1381     found))
1382
1383 (defun widget-radio-value-set (widget value)
1384   ;; We can't just delete and recreate a radio widget, since children
1385   ;; can be added after the original creation and won't be recreated
1386   ;; by `:create'.
1387   (let ((children (widget-get widget :children))
1388         current found)
1389     (while children
1390       (setq current (car children)
1391             children (cdr children))
1392       (let* ((button (widget-get current :button))
1393              (match (and (not found)
1394                          (widget-apply current :match value))))
1395         (widget-value-set button match)
1396         (if match 
1397             (widget-value-set current value))
1398         (setq found (or found match))))))
1399
1400 (defun widget-radio-validate (widget)
1401   ;; Valid if we have made a valid choice.
1402   (let ((children (widget-get widget :children))
1403         current found button)
1404     (while (and children (not found))
1405       (setq current (car children)
1406             children (cdr children)
1407             button (widget-get current :button)
1408             found (widget-apply button :value-get)))
1409     (if found
1410         (widget-apply current :validate)
1411       widget)))
1412
1413 (defun widget-radio-action (widget child event)
1414   ;; Check if a radio button was pressed.
1415   (let ((children (widget-get widget :children))
1416         (buttons (widget-get widget :buttons))
1417         current)
1418     (when (memq child buttons)
1419       (while children
1420         (setq current (car children)
1421               children (cdr children))
1422         (let* ((button (widget-get current :button)))
1423           (cond ((eq child button)
1424                  (widget-value-set button t))
1425                 ((widget-value button)
1426                  (widget-value-set button nil)))))))
1427   ;; Pass notification to parent.
1428   (widget-apply widget :notify child event))
1429
1430 ;;; The `insert-button' Widget.
1431
1432 (define-widget 'insert-button 'push-button
1433   "An insert button for the `editable-list' widget."
1434   :tag "INS"
1435   :action 'widget-insert-button-action)
1436
1437 (defun widget-insert-button-action (widget &optional event)
1438   ;; Ask the parent to insert a new item.
1439   (widget-apply (widget-get widget :parent) 
1440                 :insert-before (widget-get widget :widget)))
1441
1442 ;;; The `delete-button' Widget.
1443
1444 (define-widget 'delete-button 'push-button
1445   "A delete button for the `editable-list' widget."
1446   :tag "DEL"
1447   :action 'widget-delete-button-action)
1448
1449 (defun widget-delete-button-action (widget &optional event)
1450   ;; Ask the parent to insert a new item.
1451   (widget-apply (widget-get widget :parent) 
1452                 :delete-at (widget-get widget :widget)))
1453
1454 ;;; The `editable-list' Widget.
1455
1456 (define-widget 'editable-list 'default
1457   "A variable list of widgets of the same type."
1458   :convert-widget 'widget-types-convert-widget
1459   :offset 12
1460   :format "%v%i\n"
1461   :format-handler 'widget-editable-list-format-handler
1462   :entry-format "%i %d %v"
1463   :menu-tag "editable-list"
1464   :value-create 'widget-editable-list-value-create
1465   :value-delete 'widget-children-value-delete
1466   :value-get 'widget-editable-list-value-get
1467   :validate 'widget-editable-list-validate
1468   :match 'widget-editable-list-match
1469   :match-inline 'widget-editable-list-match-inline
1470   :insert-before 'widget-editable-list-insert-before
1471   :delete-at 'widget-editable-list-delete-at)
1472
1473 (defun widget-editable-list-format-handler (widget escape)
1474   ;; We recognize the insert button.
1475   (cond ((eq escape ?i)
1476          (and (widget-get widget :indent)
1477               (insert-char ?  (widget-get widget :indent)))
1478          (widget-create-child-and-convert widget 'insert-button))
1479         (t 
1480          (widget-default-format-handler widget escape))))
1481
1482 (defun widget-editable-list-value-create (widget)
1483   ;; Insert all values
1484   (let* ((value (widget-get widget :value))
1485          (type (nth 0 (widget-get widget :args)))
1486          (inlinep (widget-get type :inline))
1487          children)
1488     (widget-put widget :value-pos (copy-marker (point)))
1489     (set-marker-insertion-type (widget-get widget :value-pos) t)
1490     (while value
1491       (let ((answer (widget-match-inline type value)))
1492         (if answer
1493             (setq children (cons (widget-editable-list-entry-create
1494                                   widget
1495                                   (if inlinep
1496                                       (car answer)
1497                                     (car (car answer)))
1498                                   t)
1499                                  children)
1500                   value (cdr answer))
1501           (setq value nil))))
1502     (widget-put widget :children (nreverse children))))
1503
1504 (defun widget-editable-list-value-get (widget)
1505   ;; Get value of the child widget.
1506   (apply 'append (mapcar (lambda (child) (widget-apply child :value-inline))
1507                          (widget-get widget :children))))
1508
1509 (defun widget-editable-list-validate (widget)
1510   ;; All the chilren must be valid.
1511   (let ((children (widget-get widget :children))
1512         child found)
1513     (while (and children (not found))
1514       (setq child (car children)
1515             children (cdr children)
1516             found (widget-apply child :validate)))
1517     found))
1518
1519 (defun widget-editable-list-match (widget value)
1520   ;; Value must be a list and all the members must match the type.
1521   (and (listp value)
1522        (null (cdr (widget-editable-list-match-inline widget value)))))
1523
1524 (defun widget-editable-list-match-inline (widget value)
1525   (let ((type (nth 0 (widget-get widget :args)))
1526         (ok t)
1527         found)
1528     (while (and value ok)
1529       (let ((answer (widget-match-inline type value)))
1530         (if answer 
1531             (setq found (append found (car answer))
1532                   value (cdr answer))
1533           (setq ok nil))))
1534     (cons found value)))
1535
1536 (defun widget-editable-list-insert-before (widget before)
1537   ;; Insert a new child in the list of children.
1538   (save-excursion
1539     (let ((children (widget-get widget :children))
1540           (inhibit-read-only t)
1541           after-change-functions)
1542       (cond (before 
1543              (goto-char (widget-get before :entry-from)))
1544             (t
1545              (goto-char (widget-get widget :value-pos))))
1546       (let ((child (widget-editable-list-entry-create 
1547                     widget nil nil)))
1548         (when (< (widget-get child :entry-from) (widget-get widget :from))
1549           (set-marker (widget-get widget :from)
1550                       (widget-get child :entry-from)))
1551         (widget-specify-text (widget-get child :entry-from)
1552                              (widget-get child :entry-to))
1553         (if (eq (car children) before)
1554             (widget-put widget :children (cons child children))
1555           (while (not (eq (car (cdr children)) before))
1556             (setq children (cdr children)))
1557           (setcdr children (cons child (cdr children)))))))
1558   (widget-setup)
1559   (widget-apply widget :notify widget))
1560
1561 (defun widget-editable-list-delete-at (widget child)
1562   ;; Delete child from list of children.
1563   (save-excursion
1564     (let ((buttons (copy-list (widget-get widget :buttons)))
1565           button
1566           (inhibit-read-only t)
1567           after-change-functions)
1568       (while buttons
1569         (setq button (car buttons)
1570               buttons (cdr buttons))
1571         (when (eq (widget-get button :widget) child)
1572           (widget-put widget
1573                       :buttons (delq button (widget-get widget :buttons)))
1574           (widget-delete button))))
1575     (let ((entry-from (widget-get child :entry-from))
1576           (entry-to (widget-get child :entry-to))
1577           (inhibit-read-only t)
1578           after-change-functions)
1579       (widget-delete child)
1580       (delete-region entry-from entry-to)
1581       (set-marker entry-from nil)
1582       (set-marker entry-to nil))
1583     (widget-put widget :children (delq child (widget-get widget :children))))
1584   (widget-setup)
1585   (widget-apply widget :notify widget))
1586
1587 (defun widget-editable-list-entry-create (widget value conv)
1588   ;; Create a new entry to the list.
1589   (let ((type (nth 0 (widget-get widget :args)))
1590         child delete insert)
1591     (widget-specify-insert 
1592      (save-excursion
1593        (and (widget-get widget :indent)
1594             (insert-char ?  (widget-get widget :indent)))
1595        (insert (widget-get widget :entry-format)))
1596      ;; Parse % escapes in format.
1597      (while (re-search-forward "%\\(.\\)" nil t)
1598        (let ((escape (aref (match-string 1) 0)))
1599          (replace-match "" t t)
1600          (cond ((eq escape ?%)
1601                 (insert "%"))
1602                ((eq escape ?i)
1603                 (setq insert (widget-create-child-and-convert
1604                               widget 'insert-button)))
1605                ((eq escape ?d)
1606                 (setq delete (widget-create-child-and-convert
1607                               widget 'delete-button)))
1608                ((eq escape ?v)
1609                 (if conv
1610                     (setq child (widget-create-child-and-convert 
1611                                  widget type :value value))
1612                   (setq child (widget-create-child widget type))))
1613                (t 
1614                 (error "Unknown escape `%c'" escape)))))
1615      (widget-put widget 
1616                  :buttons (cons delete 
1617                                 (cons insert
1618                                       (widget-get widget :buttons))))
1619      (let ((entry-from (copy-marker (point-min)))
1620            (entry-to (copy-marker (point-max))))
1621        (widget-specify-text entry-from entry-to)
1622        (set-marker-insertion-type entry-from t)
1623        (set-marker-insertion-type entry-to nil)
1624        (widget-put child :entry-from entry-from)
1625        (widget-put child :entry-to entry-to)))
1626     (widget-put insert :widget child)
1627     (widget-put delete :widget child)
1628     child))
1629
1630 ;;; The `group' Widget.
1631
1632 (define-widget 'group 'default
1633   "A widget which group other widgets inside."
1634   :convert-widget 'widget-types-convert-widget
1635   :format "%v"
1636   :value-create 'widget-group-value-create
1637   :value-delete 'widget-children-value-delete
1638   :value-get 'widget-editable-list-value-get
1639   :validate 'widget-editable-list-validate
1640   :match 'widget-group-match
1641   :match-inline 'widget-group-match-inline)
1642
1643 (defun widget-group-value-create (widget)
1644   ;; Create each component.
1645   (let ((args (widget-get widget :args))
1646         (value (widget-get widget :value))
1647         arg answer children)
1648     (while args
1649       (setq arg (car args)
1650             args (cdr args)
1651             answer (widget-match-inline arg value)
1652             value (cdr answer))
1653       (and (eq (preceding-char) ?\n)
1654            (widget-get widget :indent)
1655            (insert-char ?  (widget-get widget :indent)))
1656       (push (cond ((null answer)
1657                    (widget-create-child widget arg))
1658                   ((widget-get arg :inline)
1659                    (widget-create-child-and-convert
1660                     widget arg :value (car answer)))
1661                   (t
1662                    (widget-create-child-and-convert
1663                     widget arg :value (car (car answer)))))
1664             children))
1665     (widget-put widget :children (nreverse children))))
1666
1667 (defun widget-group-match (widget values)
1668   ;; Match if the components match.
1669   (and (listp values)
1670        (let ((match (widget-group-match-inline widget values)))
1671          (and match (null (cdr match))))))
1672
1673 (defun widget-group-match-inline (widget vals)
1674   ;; Match if the components match.
1675   (let ((args (widget-get widget :args))
1676         argument answer found)
1677     (while args
1678       (setq argument (car args)
1679             args (cdr args)
1680             answer (widget-match-inline argument vals))
1681       (if answer 
1682           (setq vals (cdr answer)
1683                 found (append found (car answer)))
1684         (setq vals nil
1685               args nil)))
1686     (if answer
1687         (cons found vals)
1688       nil)))
1689
1690 ;;; The `widget-help' Widget.
1691
1692 (define-widget 'widget-help 'push-button
1693   "The widget documentation button."
1694   :format "%[[%t]%] %d"
1695   :help-echo "Push me to toggle the documentation."
1696   :action 'widget-help-action)
1697
1698 (defun widget-help-action (widget &optional event)
1699   "Toggle documentation for WIDGET."
1700   (let ((old (widget-get widget :doc))
1701         (new (widget-get widget :widget-doc)))
1702     (widget-put widget :doc new)
1703     (widget-put widget :widget-doc old))
1704   (widget-value-set widget (widget-value widget)))
1705
1706 ;;; The Sexp Widgets.
1707
1708 (define-widget 'const 'item
1709   "An immutable sexp."
1710   :format "%t\n%d")
1711
1712 (define-widget 'function-item 'item
1713   "An immutable function name."
1714   :format "%v\n%h"
1715   :documentation-property (lambda (symbol)
1716                             (condition-case nil
1717                                 (documentation symbol t)
1718                               (error nil))))
1719
1720 (define-widget 'variable-item 'item
1721   "An immutable variable name."
1722   :format "%v\n%h"
1723   :documentation-property 'variable-documentation)
1724
1725 (define-widget 'string 'editable-field
1726   "A string"
1727   :tag "String"
1728   :format "%[%t%]: %v")
1729
1730 (define-widget 'regexp 'string
1731   "A regular expression."
1732   ;; Should do validation.
1733   :tag "Regexp")
1734
1735 (define-widget 'file 'string
1736   "A file widget.  
1737 It will read a file name from the minibuffer when activated."
1738   :format "%[%t%]: %v"
1739   :tag "File"
1740   :action 'widget-file-action)
1741
1742 (defun widget-file-action (widget &optional event)
1743   ;; Read a file name from the minibuffer.
1744   (let* ((value (widget-value widget))
1745          (dir (file-name-directory value))
1746          (file (file-name-nondirectory value))
1747          (menu-tag (widget-apply widget :menu-tag-get))
1748          (must-match (widget-get widget :must-match))
1749          (answer (read-file-name (concat menu-tag ": (defalt `" value "') ")
1750                                  dir nil must-match file)))
1751     (widget-value-set widget (abbreviate-file-name answer))
1752     (widget-apply widget :notify widget event)
1753     (widget-setup)))
1754
1755 (define-widget 'directory 'file
1756   "A directory widget.  
1757 It will read a directory name from the minibuffer when activated."
1758   :tag "Directory")
1759
1760 (define-widget 'symbol 'string
1761   "A lisp symbol."
1762   :value nil
1763   :tag "Symbol"
1764   :match (lambda (widget value) (symbolp value))
1765   :value-to-internal (lambda (widget value)
1766                        (if (symbolp value)
1767                            (symbol-name value)
1768                          value))
1769   :value-to-external (lambda (widget value)
1770                        (if (stringp value)
1771                            (intern value)
1772                          value)))
1773
1774 (define-widget 'function 'sexp
1775   ;; Should complete on functions.
1776   "A lisp function."
1777   :tag "Function")
1778
1779 (define-widget 'variable 'symbol
1780   ;; Should complete on variables.
1781   "A lisp variable."
1782   :tag "Variable")
1783
1784 (define-widget 'sexp 'string
1785   "An arbitrary lisp expression."
1786   :tag "Lisp expression"
1787   :value nil
1788   :validate 'widget-sexp-validate
1789   :match (lambda (widget value) t)
1790   :value-to-internal 'widget-sexp-value-to-internal
1791   :value-to-external (lambda (widget value) (read value)))
1792
1793 (defun widget-sexp-value-to-internal (widget value)
1794   ;; Use pp for printer representation.
1795   (let ((pp (pp-to-string value)))
1796     (while (string-match "\n\\'" pp)
1797       (setq pp (substring pp 0 -1)))
1798     (if (or (string-match "\n\\'" pp)
1799             (> (length pp) 40))
1800         (concat "\n" pp)
1801       pp)))
1802
1803 (defun widget-sexp-validate (widget)
1804   ;; Valid if we can read the string and there is no junk left after it.
1805   (save-excursion
1806     (let ((buffer (set-buffer (get-buffer-create " *Widget Scratch*"))))
1807       (erase-buffer)
1808       (insert (widget-apply widget :value-get))
1809       (goto-char (point-min))
1810       (condition-case data
1811           (let ((value (read buffer)))
1812             (if (eobp)
1813                 (if (widget-apply widget :match value)
1814                     nil
1815                   (widget-put widget :error (widget-get widget :type-error))
1816                   widget)
1817               (widget-put widget
1818                           :error (format "Junk at end of expression: %s"
1819                                          (buffer-substring (point)
1820                                                            (point-max))))
1821               widget))
1822         (error (widget-put widget :error (error-message-string data))
1823                widget)))))
1824
1825 (define-widget 'integer 'sexp
1826   "An integer."
1827   :tag "Integer"
1828   :value 0
1829   :type-error "This field should contain an integer"
1830   :value-to-internal (lambda (widget value)
1831                        (if (integerp value) 
1832                            (prin1-to-string value)
1833                          value))
1834   :match (lambda (widget value) (integerp value)))
1835
1836 (define-widget 'character 'string
1837   "An character."
1838   :tag "Character"
1839   :value 0
1840   :size 1 
1841   :format "%t: %v\n"
1842   :type-error "This field should contain a character"
1843   :value-to-internal (lambda (widget value)
1844                        (if (integerp value) 
1845                            (char-to-string value)
1846                          value))
1847   :value-to-external (lambda (widget value)
1848                        (if (stringp value)
1849                            (aref value 0)
1850                          value))
1851   :match (lambda (widget value) (integerp value)))
1852
1853 (define-widget 'number 'sexp
1854   "A floating point number."
1855   :tag "Number"
1856   :value 0.0
1857   :type-error "This field should contain a number"
1858   :value-to-internal (lambda (widget value)
1859                        (if (numberp value)
1860                            (prin1-to-string value)
1861                          value))
1862   :match (lambda (widget value) (numberp value)))
1863
1864 (define-widget 'list 'group
1865   "A lisp list."
1866   :tag "List"
1867   :format "%t:\n%v")
1868
1869 (define-widget 'vector 'group
1870   "A lisp vector."
1871   :tag "Vector"
1872   :format "%t:\n%v"
1873   :match 'widget-vector-match
1874   :value-to-internal (lambda (widget value) (append value nil))
1875   :value-to-external (lambda (widget value) (apply 'vector value)))
1876
1877 (defun widget-vector-match (widget value) 
1878   (and (vectorp value)
1879        (widget-group-match widget
1880                            (widget-apply :value-to-internal widget value))))
1881
1882 (define-widget 'cons 'group
1883   "A cons-cell."
1884   :tag "Cons-cell"
1885   :format "%t:\n%v"
1886   :match 'widget-cons-match
1887   :value-to-internal (lambda (widget value)
1888                        (list (car value) (cdr value)))
1889   :value-to-external (lambda (widget value)
1890                        (cons (nth 0 value) (nth 1 value))))
1891
1892 (defun widget-cons-match (widget value) 
1893   (and (consp value)
1894        (widget-group-match widget
1895                            (widget-apply widget :value-to-internal value))))
1896
1897 (define-widget 'choice 'menu-choice
1898   "A union of several sexp types."
1899   :tag "Choice"
1900   :format "%[%t%]: %v")
1901
1902 (define-widget 'radio 'radio-button-choice
1903   "A union of several sexp types."
1904   :tag "Choice"
1905   :format "%t:\n%v")
1906
1907 (define-widget 'repeat 'editable-list
1908   "A variable length homogeneous list."
1909   :tag "Repeat"
1910   :format "%t:\n%v%i\n")
1911
1912 (define-widget 'set 'checklist
1913   "A list of members from a fixed set."
1914   :tag "Set"
1915   :format "%t:\n%v")
1916
1917 (define-widget 'boolean 'toggle
1918   "To be nil or non-nil, that is the question."
1919   :tag "Boolean"
1920   :format "%t: %v")
1921
1922 ;;; The `color' Widget.
1923
1924 (define-widget 'color-item 'choice-item
1925   "A color name (with sample)."
1926   :format "%v (%[sample%])\n"
1927   :button-face-get 'widget-color-item-button-face-get)
1928
1929 (defun widget-color-item-button-face-get (widget)
1930   ;; We create a face from the value.
1931   (require 'facemenu)
1932   (condition-case nil
1933       (facemenu-get-face (intern (concat "fg:" (widget-value widget))))
1934     (error 'default)))
1935
1936 (define-widget 'color 'push-button
1937   "Choose a color name (with sample)."
1938   :format "%[%t%]: %v"
1939   :tag "Color"
1940   :value "default"
1941   :value-create 'widget-color-value-create
1942   :value-delete 'widget-children-value-delete
1943   :value-get 'widget-color-value-get
1944   :value-set 'widget-color-value-set
1945   :action 'widget-color-action
1946   :match 'widget-field-match
1947   :tag "Color")
1948
1949 (defvar widget-color-choice-list nil)
1950 ;; Variable holding the possible colors.
1951
1952 (defun widget-color-choice-list ()
1953   (unless widget-color-choice-list
1954     (setq widget-color-choice-list 
1955           (mapcar '(lambda (color) (list color))
1956                   (x-defined-colors))))
1957   widget-color-choice-list)
1958
1959 (defun widget-color-value-create (widget)
1960   (let ((child (widget-create-child-and-convert
1961                 widget 'color-item (widget-get widget :value))))
1962     (widget-put widget :children (list child))))
1963
1964 (defun widget-color-value-get (widget)
1965   ;; Pass command to first child.
1966   (widget-apply (car (widget-get widget :children)) :value-get))
1967
1968 (defun widget-color-value-set (widget value)
1969   ;; Pass command to first child.
1970   (widget-apply (car (widget-get widget :children)) :value-set value))
1971
1972 (defvar widget-color-history nil
1973   "History of entered colors")
1974
1975 (defun widget-color-action (widget &optional event)
1976   ;; Prompt for a color.
1977   (let* ((tag (widget-apply widget :menu-tag-get))
1978          (prompt (concat tag ": "))
1979          (answer (cond ((string-match "XEmacs" emacs-version)
1980                         (read-color prompt))
1981                        ((fboundp 'x-defined-colors)
1982                         (completing-read (concat tag ": ")
1983                                          (widget-color-choice-list) 
1984                                          nil nil nil 'widget-color-history))
1985                        (t
1986                         (read-string prompt (widget-value widget))))))
1987     (unless (zerop (length answer))
1988       (widget-value-set widget answer)
1989       (widget-apply widget :notify widget event)
1990       (widget-setup))))
1991
1992 ;;; The Help Echo
1993
1994 (defun widget-echo-help-mouse ()
1995   "Display the help message for the widget under the mouse.
1996 Enable with (run-with-idle-timer 1 t 'widget-echo-help-mouse)"
1997   (let* ((pos (mouse-position))
1998          (frame (car pos))
1999          (x (car (cdr pos)))
2000          (y (cdr (cdr pos)))
2001          (win (window-at x y frame))
2002          (where (coordinates-in-window-p (cons x y) win)))
2003     (when (consp where)
2004       (save-window-excursion
2005         (progn ; save-excursion
2006           (select-window win)
2007           (let* ((result (compute-motion (window-start win)
2008                                          '(0 . 0)
2009                                          (window-end win)
2010                                          where
2011                                          (window-width win)
2012                                          (cons (window-hscroll) 0)
2013                                          win)))
2014             (when (and (eq (nth 1 result) x)
2015                        (eq (nth 2 result) y))
2016               (widget-echo-help (nth 0 result))))))))
2017   (unless track-mouse
2018     (setq track-mouse t)
2019     (add-hook 'post-command-hook 'widget-stop-mouse-tracking)))
2020
2021 (defun widget-stop-mouse-tracking (&rest args)
2022   "Stop the mouse tracking done while idle."
2023   (remove-hook 'post-command-hook 'widget-stop-mouse-tracking)
2024   (setq track-mouse nil))
2025
2026 (defun widget-at (pos)
2027   "The button or field at POS."
2028   (or (get-text-property pos 'button)
2029       (get-text-property pos 'field)))
2030
2031 (defun widget-echo-help (pos)
2032   "Display the help echo for widget at POS."
2033   (let* ((widget (widget-at pos))
2034          (help-echo (and widget (widget-get widget :help-echo))))
2035     (cond ((stringp help-echo)
2036            (message "%s" help-echo))
2037           ((and (symbolp help-echo) (fboundp help-echo)
2038                 (stringp (setq help-echo (funcall help-echo widget))))
2039            (message "%s" help-echo)))))
2040
2041 ;;; The End:
2042
2043 (provide 'widget-edit)
2044
2045 ;; widget-edit.el ends here