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