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