XEmacs 21.2.4
[chise/xemacs-chise.git.1] / lisp / wid-edit.el
1 ;;; wid-edit.el --- Functions for creating and using widgets.
2 ;;
3 ;; Copyright (C) 1996, 1997 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Per Abrahamsen <abraham@dina.kvl.dk>
6 ;; Maintainer: Hrvoje Niksic <hniksic@srce.hr>
7 ;; Keywords: extensions
8 ;; Version: 1.9960-x
9 ;; X-URL: http://www.dina.kvl.dk/~abraham/custom/
10
11 ;; This file is part of XEmacs.
12
13 ;; XEmacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
17
18 ;; XEmacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with XEmacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
27
28 ;;; Commentary:
29 ;;
30 ;; See `widget.el'.
31
32 \f
33 ;;; Code:
34
35 (require 'widget)
36
37 (autoload 'finder-commentary "finder" nil t)
38
39 ;;; Customization.
40
41 (defgroup widgets nil
42   "Customization support for the Widget Library."
43   :link '(custom-manual "(widget)Top")
44   :link '(url-link :tag "Development Page"
45                    "http://www.dina.kvl.dk/~abraham/custom/")
46   :link '(emacs-library-link :tag "Lisp File" "widget.el")
47   :prefix "widget-"
48   :group 'extensions
49   :group 'hypermedia)
50
51 (defgroup widget-documentation nil
52   "Options controling the display of documentation strings."
53   :group 'widgets)
54
55 (defgroup widget-faces nil
56   "Faces used by the widget library."
57   :group 'widgets
58   :group 'faces)
59
60 (defvar widget-documentation-face 'widget-documentation-face
61   "Face used for documentation strings in widges.
62 This exists as a variable so it can be set locally in certain buffers.")
63
64 (defface widget-documentation-face '((((class color)
65                                        (background dark))
66                                       (:foreground "lime green"))
67                                      (((class color)
68                                        (background light))
69                                       (:foreground "dark green"))
70                                      (t nil))
71   "Face used for documentation text."
72   :group 'widget-documentation
73   :group 'widget-faces)
74
75 (defvar widget-button-face 'widget-button-face
76   "Face used for buttons in widges.
77 This exists as a variable so it can be set locally in certain buffers.")
78
79 (defface widget-button-face '((t (:bold t)))
80   "Face used for widget buttons."
81   :group 'widget-faces)
82
83 (defcustom widget-mouse-face 'highlight
84   "Face used for widget buttons when the mouse is above them."
85   :type 'face
86   :group 'widget-faces)
87
88 (defface widget-field-face '((((class grayscale color)
89                                (background light))
90                               (:background "gray85"))
91                              (((class grayscale color)
92                                (background dark))
93                               (:background "dim gray"))
94                              (t
95                               (:italic t)))
96   "Face used for editable fields."
97   :group 'widget-faces)
98
99 ;; Currently unused
100 ;(defface widget-single-line-field-face '((((class grayscale color)
101 ;                                          (background light))
102 ;                                         (:background "gray85"))
103 ;                                        (((class grayscale color)
104 ;                                          (background dark))
105 ;                                         (:background "dim gray"))
106 ;                                        (t
107 ;                                         (:italic t)))
108 ;  "Face used for editable fields spanning only a single line."
109 ;  :group 'widget-faces)
110 ;
111 ;(defvar widget-single-line-display-table
112 ;  (let ((table (make-display-table)))
113 ;    (aset table 9  "^I")
114 ;    (aset table 10 "^J")
115 ;    table)
116 ;  "Display table used for single-line editable fields.")
117 ;
118 ;(set-face-display-table 'widget-single-line-field-face
119 ;                       widget-single-line-display-table)
120
121
122 ;; Some functions from this file have been ported to C for speed.
123 ;; Setting this to t (*before* loading wid-edit.el) will make them
124 ;; shadow the subrs.  It should be used only for debugging purposes.
125 (defvar widget-shadow-subrs nil)
126
127 \f
128 ;;; Utility functions.
129 ;;
130 ;; These are not really widget specific.
131
132 (when (or (not (fboundp 'widget-plist-member))
133           widget-shadow-subrs)
134   ;; Recoded in C, for efficiency.  It used to be a defsubst, but old
135   ;; compiled code won't fail -- it will just be slower.
136   (defun widget-plist-member (plist prop)
137     ;; Return non-nil if PLIST has the property PROP.
138     ;; PLIST is a property list, which is a list of the form
139     ;; (PROP1 VALUE1 PROP2 VALUE2 ...).  PROP is a symbol.
140     ;; Unlike `plist-get', this allows you to distinguish between a missing
141     ;; property and a property with the value nil.
142     ;; The value is actually the tail of PLIST whose car is PROP.
143     (while (and plist (not (eq (car plist) prop)))
144       (setq plist (cddr plist)))
145     plist))
146
147 (defun widget-princ-to-string (object)
148   ;; Return string representation of OBJECT, any Lisp object.
149   ;; No quoting characters are used; no delimiters are printed around
150   ;; the contents of strings.
151   (with-current-buffer (get-buffer-create " *widget-tmp*")
152     (erase-buffer)
153     (princ object (current-buffer))
154     (buffer-string)))
155
156 (defun widget-prettyprint-to-string (object)
157   ;; Like pp-to-string, but uses `cl-prettyprint'
158   (with-current-buffer (get-buffer-create " *widget-tmp*")
159     (erase-buffer)
160     (cl-prettyprint object)
161     ;; `cl-prettyprint' always surrounds the text with newlines.
162     (when (eq (char-after (point-min)) ?\n)
163       (delete-region (point-min) (1+ (point-min))))
164     (when (eq (char-before (point-max)) ?\n)
165       (delete-region (1- (point-max)) (point-max)))
166     (buffer-string)))
167
168 (defun widget-clear-undo ()
169   "Clear all undo information."
170   (buffer-disable-undo)
171   (buffer-enable-undo))
172
173 (defcustom widget-menu-max-size 40
174   "Largest number of items allowed in a popup-menu.
175 Larger menus are read through the minibuffer."
176   :group 'widgets
177   :type 'integer)
178
179 (defcustom widget-menu-minibuffer-flag nil
180   "*Control how to ask for a choice from the keyboard.
181 Non-nil means use the minibuffer;
182 nil means read a single character."
183   :group 'widgets
184   :type 'boolean)
185
186 (defun widget-choose (title items &optional event)
187   "Choose an item from a list.
188
189 First argument TITLE is the name of the list.
190 Second argument ITEMS is an list whose members are either
191  (NAME . VALUE), to indicate selectable items, or just strings to
192  indicate unselectable items.
193 Optional third argument EVENT is an input event.
194
195 The user is asked to choose between each NAME from the items alist,
196 and the VALUE of the chosen element will be returned.  If EVENT is a
197 mouse event, and the number of elements in items is less than
198 `widget-menu-max-size', a popup menu will be used, otherwise the
199 minibuffer."
200   (cond ((and (< (length items) widget-menu-max-size)
201               event
202               (console-on-window-system-p))
203          ;; Pressed by the mouse.
204          (let ((val (get-popup-menu-response
205                      (cons title
206                            (mapcar (lambda (x)
207                                      (if (stringp x)
208                                          (vector x nil nil)
209                                        (vector (car x) (list (car x)) t)))
210                                    items)))))
211            (setq val (and val
212                           (listp (event-object val))
213                           (stringp (car-safe (event-object val)))
214                           (car (event-object val))))
215            (cdr (assoc val items))))
216         ((and (not widget-menu-minibuffer-flag)
217               ;; Can't handle more than 10 items (as many digits)
218               (<= (length items) 10))
219          ;; Construct a menu of the choices
220          ;; and then use it for prompting for a single character.
221          (let* ((overriding-terminal-local-map (make-sparse-keymap))
222                 (map (make-sparse-keymap title))
223                 (next-digit ?0)
224                 some-choice-enabled value)
225            ;; Define SPC as a prefix char to get to this menu.
226            (define-key overriding-terminal-local-map " " map)
227            (with-current-buffer (get-buffer-create " widget-choose")
228              (erase-buffer)
229              (insert "Available choices:\n\n")
230              (dolist (choice items)
231                (when (consp choice)
232                  (let* ((name (car choice))
233                         (function (cdr choice)))
234                    (insert (format "%c = %s\n" next-digit name))
235                    (define-key map (vector next-digit) function)
236                    (setq some-choice-enabled t)))
237                ;; Allocate digits to disabled alternatives
238                ;; so that the digit of a given alternative never varies.
239                (incf next-digit))
240              (insert "\nC-g = Quit"))
241            (or some-choice-enabled
242                (error "None of the choices is currently meaningful"))
243            (define-key map [?\C-g] 'keyboard-quit)
244            (define-key map [t] 'keyboard-quit)
245            ;(setcdr map (nreverse (cdr map)))
246            ;; Unread a SPC to lead to our new menu.
247            (push (character-to-event ?\ ) unread-command-events)
248            ;; Read a char with the menu, and return the result
249            ;; that corresponds to it.
250            (save-window-excursion
251              (display-buffer (get-buffer " widget-choose"))
252              (let ((cursor-in-echo-area t))
253                (setq value
254                      (lookup-key overriding-terminal-local-map
255                                  (read-key-sequence (concat title ": ") t)))))
256            (message "")
257            (when (or (eq value 'keyboard-quit)
258                      (null value))
259              (error "Canceled"))
260            value))
261         (t
262          ;; Read the choice of name from the minibuffer.
263          (setq items (remove-if 'stringp items))
264          (let ((val (completing-read (concat title ": ") items nil t)))
265            (if (stringp val)
266                (let ((try (try-completion val items)))
267                  (when (stringp try)
268                    (setq val try))
269                  (cdr (assoc val items)))
270              nil)))))
271
272 \f
273 ;;; Widget text specifications.
274 ;;
275 ;; These functions are for specifying text properties.
276
277 (defcustom widget-field-add-space t
278   ;; Setting this to nil might be available, once some problems are resolved.
279   "Non-nil means add extra space at the end of editable text fields.
280
281 This is needed on all versions of Emacs.  If you don't add the space,
282 it will become impossible to edit a zero size field."
283   :type 'boolean
284   :group 'widgets)
285
286 (defcustom widget-field-use-before-change
287   (and (or (> emacs-minor-version 34)
288            (> emacs-major-version 19))
289        (not (string-match "XEmacs" emacs-version)))
290   "Non-nil means use `before-change-functions' to track editable fields.
291 This enables the use of undo, but doesn't work on Emacs 19.34 and earlier.
292 Using before hooks also means that the :notify function can't know the
293 new value."
294   :type 'boolean
295   :group 'widgets)
296
297 (defun widget-echo-this-extent (extent)
298   (let* ((widget (or (extent-property extent 'button)
299                      (extent-property extent 'field)
300                      (extent-property extent 'glyph-widget)))
301          (help-echo (and widget (widget-get widget :help-echo))))
302     (and (functionp help-echo)
303          (setq help-echo (funcall help-echo widget)))
304     (when (stringp help-echo)
305       (display-message 'help-echo help-echo))))
306
307 (defsubst widget-handle-help-echo (extent help-echo)
308   (set-extent-property extent 'balloon-help help-echo)
309   (set-extent-property extent 'help-echo help-echo)
310   (when (functionp help-echo)
311     (set-extent-property extent 'balloon-help 'widget-echo-this-extent)
312     (set-extent-property extent 'help-echo 'widget-echo-this-extent)))
313
314 (defun widget-specify-field (widget from to)
315   "Specify editable button for WIDGET between FROM and TO."
316   (save-excursion
317     (goto-char to)
318     (cond ((null (widget-get widget :size))
319            (forward-char 1))
320           ;; Terminating space is not part of the field, but necessary in
321           ;; order for local-map to work.  Remove next sexp if local-map works
322           ;; at the end of the extent.
323           (widget-field-add-space
324            (insert-and-inherit " ")))
325     (setq to (point)))
326   (let ((map (widget-get widget :keymap))
327         (face (or (widget-get widget :value-face) 'widget-field-face))
328         (help-echo (widget-get widget :help-echo))
329         (extent (make-extent from to)))
330     (unless (or (stringp help-echo) (null help-echo))
331       (setq help-echo 'widget-mouse-help))
332     (widget-put widget :field-extent extent)
333     (and (or (not widget-field-add-space)
334              (widget-get widget :size))
335          (set-extent-property extent 'end-closed nil))
336     (set-extent-property extent 'detachable nil)
337     (set-extent-property extent 'field widget)
338     (set-extent-property extent 'button-or-field t)
339     (set-extent-property extent 'keymap map)
340     (set-extent-property extent 'face face)
341     (widget-handle-help-echo extent help-echo))
342   (widget-specify-secret widget))
343
344 (defun widget-specify-secret (field)
345   "Replace text in FIELD with value of `:secret', if non-nil."
346   (let ((secret (widget-get field :secret))
347         (size (widget-get field :size)))
348     (when secret
349       (let ((begin (widget-field-start field))
350             (end (widget-field-end field)))
351         (when size 
352           (while (and (> end begin)
353                       (eq (char-after (1- end)) ?\ ))
354             (setq end (1- end))))
355         (while (< begin end)
356           (let ((old (char-after begin)))
357             (unless (eq old secret)
358               (subst-char-in-region begin (1+ begin) old secret)
359               (put-text-property begin (1+ begin) 'secret old))
360             (setq begin (1+ begin))))))))
361
362 (defun widget-specify-button (widget from to)
363   "Specify button for WIDGET between FROM and TO."
364   (let ((face (widget-apply widget :button-face-get))
365         (help-echo (widget-get widget :help-echo))
366         (extent (make-extent from to))
367         (map (widget-get widget :button-keymap)))
368     (widget-put widget :button-extent extent)
369     (unless (or (null help-echo) (stringp help-echo))
370       (setq help-echo 'widget-mouse-help))
371     (set-extent-property extent 'start-open t)
372     (set-extent-property extent 'button widget)
373     (set-extent-property extent 'button-or-field t)
374     (set-extent-property extent 'mouse-face widget-mouse-face)
375     (widget-handle-help-echo extent help-echo)
376     (set-extent-property extent 'face face)
377     (set-extent-property extent 'keymap map)))
378
379 (defun widget-mouse-help (extent)
380   "Find mouse help string for button in extent."
381   (let* ((widget (widget-at (extent-start-position extent)))
382          (help-echo (and widget (widget-get widget :help-echo))))
383     (cond ((stringp help-echo)
384            help-echo)
385           ((and (functionp help-echo)
386                 (stringp (setq help-echo (funcall help-echo widget))))
387            help-echo)
388           (t
389            (format "(widget %S :help-echo %S)" widget help-echo)))))
390
391 (defun widget-specify-sample (widget from to)
392   ;; Specify sample for WIDGET between FROM and TO.
393   (let ((face (widget-apply widget :sample-face-get))
394         (extent (make-extent from to nil)))
395     (set-extent-property extent 'start-open t)
396     (set-extent-property extent 'face face)
397     (widget-put widget :sample-extent extent)))
398
399 (defun widget-specify-doc (widget from to)
400   ;; Specify documentation for WIDGET between FROM and TO.
401   (let ((extent (make-extent from to)))
402     (set-extent-property extent 'start-open t)
403     (set-extent-property extent 'widget-doc widget)
404     (set-extent-property extent 'face widget-documentation-face)
405     (widget-put widget :doc-extent extent)))
406
407 (defmacro widget-specify-insert (&rest form)
408   ;; Execute FORM without inheriting any text properties.
409   `(save-restriction
410      (let ((inhibit-read-only t)
411            before-change-functions
412            after-change-functions)
413        (insert "<>")
414        (narrow-to-region (- (point) 2) (point))
415        (goto-char (1+ (point-min)))
416        ;; We use `prog1' instead of a `result' variable, as the latter
417        ;; confuses the byte-compiler in some cases (a warning).
418        (prog1 (progn ,@form)
419          (delete-region (point-min) (1+ (point-min)))
420          (delete-region (1- (point-max)) (point-max))
421          (goto-char (point-max))))))
422
423 (put 'widget-specify-insert 'edebug-form-spec '(&rest form))
424
425 \f
426 ;;; Inactive Widgets.
427
428 (defface widget-inactive-face '((((class grayscale color)
429                                   (background dark))
430                                  (:foreground "light gray"))
431                                 (((class grayscale color)
432                                   (background light))
433                                  (:foreground "dim gray"))
434                                 (t
435                                  (:italic t)))
436   "Face used for inactive widgets."
437   :group 'widget-faces)
438
439 ;; For inactiveness to work on complex structures, it is not
440 ;; sufficient to keep track of whether a button/field/glyph is
441 ;; inactive or not -- we must know how many time it was deactivated
442 ;; (inactiveness level).  Successive deactivations of the same button
443 ;; increment its inactive-count, and activations decrement it.  When
444 ;; inactive-count reaches 0, the button/field/glyph is reactivated.
445
446 (defun widget-activation-widget-mapper (extent action)
447   "Activate or deactivate EXTENT's widget (button or field).
448 Suitable for use with `map-extents'."
449   (ecase action
450     (:activate
451      (decf (extent-property extent :inactive-count))
452      (when (zerop (extent-property extent :inactive-count))
453        (set-extent-properties
454         extent (extent-property extent :inactive-plist))
455        (set-extent-property extent :inactive-plist nil)))
456     (:deactivate
457      (incf (extent-property extent :inactive-count 0))
458      ;; Store a plist of old properties, which will be fed to
459      ;; `set-extent-properties'.
460      (unless (extent-property extent :inactive-plist)
461        (set-extent-property
462         extent :inactive-plist
463         (list 'mouse-face (extent-property extent 'mouse-face)
464               'help-echo (extent-property extent 'help-echo)
465               'keymap (extent-property extent 'keymap)))
466        (set-extent-properties
467         extent '(mouse-face nil help-echo nil keymap nil)))))
468   nil)
469
470 (defun widget-activation-glyph-mapper (extent action)
471   (let ((activate-p (if (eq action :activate) t nil)))
472     (if activate-p
473         (decf (extent-property extent :inactive-count))
474       (incf (extent-property extent :inactive-count 0)))
475     (when (or (and activate-p
476                    (zerop (extent-property extent :inactive-count)))
477               (and (not activate-p)
478                    (not (zerop (extent-property extent :inactive-count)))))
479       (let* ((glyph-widget (extent-property extent 'glyph-widget))
480              (up-glyph (widget-get glyph-widget :glyph-up))
481              (inactive-glyph (widget-get glyph-widget :glyph-inactive))
482              (new-glyph (if activate-p up-glyph inactive-glyph)))
483          ;; Check that the new glyph exists, and differs from the
484          ;; default one.
485         (and up-glyph inactive-glyph (not (eq up-glyph inactive-glyph))
486              ;; Check if the glyph is already installed.
487              (not (eq (extent-end-glyph extent) new-glyph))
488              ;; Change it.
489              (set-extent-end-glyph extent new-glyph)))))
490   nil)
491
492 (defun widget-specify-inactive (widget from to)
493   "Make WIDGET inactive for user modifications."
494   (unless (widget-get widget :inactive)
495     (let ((extent (make-extent from to)))
496       ;; It is no longer necessary for the extent to be read-only, as
497       ;; the inactive editable fields now lose their keymaps.
498       (set-extent-properties
499        extent '(start-open t face widget-inactive-face
500                 detachable t priority 2001 widget-inactive t))
501       (widget-put widget :inactive extent))
502     ;; Deactivate the buttons and fields within the range.  In some
503     ;; cases, the fields are not yet setup at the time this function
504     ;; is called.  Those fields are deactivated explicitly by
505     ;; `widget-setup'.
506     (map-extents 'widget-activation-widget-mapper
507                  nil from to :deactivate nil 'button-or-field)
508     ;; Deactivate glyphs.
509     (map-extents 'widget-activation-glyph-mapper
510                  nil from to :deactivate nil 'glyph-widget)))
511
512 (defun widget-specify-active (widget)
513   "Make WIDGET active for user modifications."
514   (let ((inactive (widget-get widget :inactive)))
515     (when (and inactive (not (extent-detached-p inactive)))
516       ;; Reactivate the buttons and fields covered by the extent.
517       (map-extents 'widget-activation-widget-mapper
518                    inactive nil nil :activate nil 'button-or-field)
519       ;; Reactivate the glyphs.
520       (map-extents 'widget-activation-glyph-mapper
521                    inactive nil nil :activate nil 'end-glyph)
522       (delete-extent inactive)
523       (widget-put widget :inactive nil))))
524
525 \f
526 ;;; Widget Properties.
527
528 (defsubst widget-type (widget)
529   "Return the type of WIDGET, a symbol."
530   (car widget))
531
532 (when (or (not (fboundp 'widget-put))
533           widget-shadow-subrs)
534   (defun widget-put (widget property value)
535     "In WIDGET set PROPERTY to VALUE.
536 The value can later be retrived with `widget-get'."
537     (setcdr widget (plist-put (cdr widget) property value))))
538
539 ;; Recoded in C, for efficiency:
540 (when (or (not (fboundp 'widget-get))
541           widget-shadow-subrs)
542   (defun widget-get (widget property)
543     "In WIDGET, get the value of PROPERTY.
544 The value could either be specified when the widget was created, or
545 later with `widget-put'."
546     (let ((missing t)
547           value tmp)
548       (while missing
549         (cond ((setq tmp (widget-plist-member (cdr widget) property))
550                (setq value (car (cdr tmp))
551                      missing nil))
552               ((setq tmp (car widget))
553                (setq widget (get tmp 'widget-type)))
554               (t
555                (setq missing nil))))
556       value)))
557
558 (defun widget-get-indirect (widget property)
559   "In WIDGET, get the value of PROPERTY.
560 If the value is a symbol, return its binding.
561 Otherwise, just return the value."
562   (let ((value (widget-get widget property)))
563     (if (symbolp value)
564         (symbol-value value)
565       value)))
566
567 (defun widget-member (widget property)
568   "Non-nil iff there is a definition in WIDGET for PROPERTY."
569   (cond ((widget-plist-member (cdr widget) property)
570          t)
571         ((car widget)
572          (widget-member (get (car widget) 'widget-type) property))
573         (t nil)))
574
575 (when (or (not (fboundp 'widget-apply))
576           widget-shadow-subrs)
577   ;;This is in C, so don't ###utoload
578   (defun widget-apply (widget property &rest args)
579     "Apply the value of WIDGET's PROPERTY to the widget itself.
580 ARGS are passed as extra arguments to the function."
581     (apply (widget-get widget property) widget args)))
582
583 (defun widget-value (widget)
584   "Extract the current value of WIDGET."
585   (widget-apply widget
586                 :value-to-external (widget-apply widget :value-get)))
587
588 (defun widget-value-set (widget value)
589   "Set the current value of WIDGET to VALUE."
590   (widget-apply widget
591                 :value-set (widget-apply widget
592                                          :value-to-internal value)))
593
594 (defun widget-default-get (widget)
595   "Extract the defaylt value of WIDGET."
596   (or (widget-get widget :value)
597       (widget-apply widget :default-get)))
598
599 (defun widget-match-inline (widget vals)
600   ;; In WIDGET, match the start of VALS.
601   (cond ((widget-get widget :inline)
602          (widget-apply widget :match-inline vals))
603         ((and vals
604               (widget-apply widget :match (car vals)))
605          (cons (list (car vals)) (cdr vals)))
606         (t nil)))
607
608 (defun widget-apply-action (widget &optional event)
609   "Apply :action in WIDGET in response to EVENT."
610   (if (widget-apply widget :active)
611       (widget-apply widget :action event)
612     (error "Attempt to perform action on inactive widget")))
613
614 \f
615 ;;; Helper functions.
616 ;;
617 ;; These are widget specific.
618
619 ;;;###autoload
620 (defun widget-prompt-value (widget prompt &optional value unbound)
621   "Prompt for a value matching WIDGET, using PROMPT.
622 The current value is assumed to be VALUE, unless UNBOUND is non-nil."
623   (unless (listp widget)
624     (setq widget (list widget)))
625   (setq prompt (format "[%s] %s" (widget-type widget) prompt))
626   (setq widget (widget-convert widget))
627   (let ((answer (widget-apply widget :prompt-value prompt value unbound)))
628     (while (not (widget-apply widget :match answer))
629       (setq answer (signal 'error (list "Answer does not match type"
630                                         answer (widget-type widget)))))
631     answer))
632
633 (defun widget-get-sibling (widget)
634   "Get the item WIDGET is assumed to toggle.
635 This is only meaningful for radio buttons or checkboxes in a list."
636   (let* ((parent (widget-get widget :parent))
637          (children (widget-get parent :children))
638          child)
639     (catch 'child
640       (while children
641         (setq child (car children)
642               children (cdr children))
643         (when (eq (widget-get child :button) widget)
644           (throw 'child child)))
645       nil)))
646
647 (defun widget-map-buttons (function &optional buffer maparg)
648   "Map FUNCTION over the buttons in BUFFER.
649 FUNCTION is called with the arguments WIDGET and MAPARG.
650
651 If FUNCTION returns non-nil, the walk is cancelled.
652
653 The arguments MAPARG, and BUFFER default to nil and (current-buffer),
654 respectively."
655   (map-extents (lambda (extent ignore)
656                  ;; If FUNCTION returns non-nil, we bail out
657                  (funcall function (extent-property extent 'button) maparg))
658                nil nil nil nil nil
659                'button))
660
661 \f
662 ;;; Glyphs.
663
664 (defcustom widget-glyph-directory (locate-data-directory "custom")
665   "Where widget glyphs are located.
666 If this variable is nil, widget will try to locate the directory
667 automatically."
668   :group 'widgets
669   :type 'directory)
670
671 (defcustom widget-glyph-enable t
672   "If non nil, use glyphs in images when available."
673   :group 'widgets
674   :type 'boolean)
675
676 (defcustom widget-image-conversion
677   '((xpm ".xpm") (gif ".gif") (png ".png") (jpeg ".jpg" ".jpeg")
678     (xbm ".xbm"))
679   "Conversion alist from image formats to file name suffixes."
680   :group 'widgets
681   :type '(repeat (cons :format "%v"
682                        (symbol :tag "Image Format" unknown)
683                        (repeat :tag "Suffixes"
684                                (string :format "%v")))))
685
686 ;; Don't use this, because we cannot yet distinguish between widget
687 ;; glyphs associated with user action, and actionless ones.
688 ;(defvar widget-glyph-pointer-glyph
689 ;  (make-pointer-glyph [cursor-font :data "hand2"])
690 ;  "Glyph to be used as the mouse pointer shape over glyphs.
691 ;Use `set-glyph-image' to change this.")
692
693 (defvar widget-glyph-cache nil
694   "Cache of glyphs associated with strings (files).")
695
696 (defun widget-glyph-find (image tag)
697   "Create a glyph corresponding to IMAGE with string TAG as fallback.
698 IMAGE can already be a glyph, or a file name sans extension (xpm,
699  xbm, gif, jpg, or png) located in `widget-glyph-directory', or
700  in one of the data directories.
701 It can also be a valid image instantiator, in which case it will be
702  used to make the glyph, with an additional TAG string fallback."
703   (cond ((not (and image widget-glyph-enable))
704          ;; We don't want to use glyphs.
705          nil)
706         ((and (not (console-on-window-system-p))
707               ;; We don't use glyphs on TTY consoles, although we
708               ;; could.  However, glyph faces aren't yet working
709               ;; properly, and movement through glyphs is unintuitive.
710               ;; As an exception, when TAG is nil, we assume that the
711               ;; caller knows what he is doing, and that the tag is
712               ;; encoded within the glyph.
713               (not (glyphp image)))
714          nil)
715         ((glyphp image)
716          ;; Already a glyph.  Use it.
717          image)
718         ((stringp image)
719          ;; A string.  Look it up in the cache first...
720          (or (lax-plist-get widget-glyph-cache image)
721              ;; ...and then in the relevant directories
722              (let* ((dirlist (cons (or widget-glyph-directory
723                                        (locate-data-directory "custom"))
724                                    data-directory-list))
725                     (formats widget-image-conversion)
726                     file)
727                (while (and formats (not file))
728                  ;; This dance is necessary, because XEmacs signals an
729                  ;; error when it encounters an unrecognized image
730                  ;; format.
731                  (when (valid-image-instantiator-format-p (caar formats))
732                    (setq file (locate-file image dirlist
733                                            (mapconcat 'identity (cdar formats)
734                                                       ":"))))
735                  (unless file
736                    (pop formats)))
737                (when file
738                  ;; We create a glyph with the file as the default image
739                  ;; instantiator, and the TAG fallback
740                  (let ((glyph (make-glyph `([,(caar formats) :file ,file]
741                                             [string :data ,tag]))))
742                    ;; Cache the glyph
743                    (laxputf widget-glyph-cache image glyph)
744                    ;; ...and return it
745                    glyph)))))
746         ((valid-instantiator-p image 'image)
747          ;; A valid image instantiator (e.g. [gif :file "somefile"] etc.)
748          (make-glyph `(,image [string :data ,tag])))
749         (t
750          ;; Oh well.
751          nil)))
752
753 (defun widget-glyph-insert (widget tag image &optional down inactive)
754   "In WIDGET, insert the text TAG or, if supported, IMAGE.
755 IMAGE should either be a glyph, an image instantiator, an image file
756 name sans extension (xpm, xbm, gif, jpg, or png) located in
757 `widget-glyph-directory', or anything else allowed by
758 `widget-glyph-find'.
759
760 If IMAGE is a list, it will be taken as a list of (UP DOWN INACTIVE)
761 glyphs.  The down and inactive glyphs are shown when glyph is pressed
762 or inactive, respectively.
763
764 The optional DOWN and INACTIVE arguments are deprecated, and exist
765 only because of compatibility."
766   ;; Convert between IMAGE being a list, etc.  Must use `psetq',
767   ;; because otherwise change to `image' screws up the rest.
768   (psetq image (or (and (consp image)
769                         (car image))
770                    image)
771          down (or (and (consp image)
772                        (nth 1 image))
773                   down)
774          inactive (or (and (consp image)
775                            (nth 2 image))
776                       inactive))
777   (let ((glyph (widget-glyph-find image tag)))
778     (if glyph
779         (widget-glyph-insert-glyph widget glyph
780                                    (widget-glyph-find down tag)
781                                    (widget-glyph-find inactive tag))
782       (insert tag))
783     glyph))
784
785 (defun widget-glyph-insert-glyph (widget glyph &optional down inactive)
786   "In WIDGET, insert GLYPH.
787 If optional arguments DOWN and INACTIVE are given, they should be
788 glyphs used when the widget is pushed and inactive, respectively."
789   (insert "*")
790   (let ((extent (make-extent (point) (1- (point))))
791         (help-echo (and widget (widget-get widget :help-echo)))
792         (map (and widget (widget-get widget :button-keymap))))
793     (set-extent-property extent 'glyph-widget widget)
794     ;; It would be fun if we could make this extent atomic, so it
795     ;; doesn't mess with cursor motion.  But atomic-extents library is
796     ;; currently a mess, so I'd rather not use it.
797     (set-extent-property extent 'invisible t)
798     (set-extent-property extent 'start-open t)
799     (set-extent-property extent 'end-open t)
800     (set-extent-property extent 'keymap map)
801     ;;(set-extent-property extent 'pointer widget-glyph-pointer-glyph)
802     (set-extent-end-glyph extent glyph)
803     (unless (or (stringp help-echo) (null help-echo))
804       (setq help-echo 'widget-mouse-help))
805     (when help-echo
806       (widget-handle-help-echo extent help-echo)))
807   (when widget
808     (widget-put widget :glyph-up glyph)
809     (when down (widget-put widget :glyph-down down))
810     (when inactive (widget-put widget :glyph-inactive inactive))))
811
812 \f
813 ;;; Buttons.
814
815 (defgroup widget-button nil
816   "The look of various kinds of buttons."
817   :group 'widgets)
818
819 (defcustom widget-button-prefix ""
820   "String used as prefix for buttons."
821   :type 'string
822   :group 'widget-button)
823
824 (defcustom widget-button-suffix ""
825   "String used as suffix for buttons."
826   :type 'string
827   :group 'widget-button)
828
829 \f
830 ;;; Creating Widgets.
831
832 ;;;###autoload
833 (defun widget-create (type &rest args)
834   "Create widget of TYPE.
835 The optional ARGS are additional keyword arguments."
836   (let ((widget (apply 'widget-convert type args)))
837     (widget-apply widget :create)
838     widget))
839
840 (defun widget-create-child-and-convert (parent type &rest args)
841   "As part of the widget PARENT, create a child widget TYPE.
842 The child is converted, using the keyword arguments ARGS."
843   (let ((widget (apply 'widget-convert type args)))
844     (widget-put widget :parent parent)
845     (unless (widget-get widget :indent)
846       (widget-put widget :indent (+ (or (widget-get parent :indent) 0)
847                                     (or (widget-get widget :extra-offset) 0)
848                                     (widget-get parent :offset))))
849     (widget-apply widget :create)
850     widget))
851
852 (defun widget-create-child (parent type)
853   "Create widget of TYPE."
854   (let ((widget (copy-sequence type)))
855     (widget-put widget :parent parent)
856     (unless (widget-get widget :indent)
857       (widget-put widget :indent (+ (or (widget-get parent :indent) 0)
858                                     (or (widget-get widget :extra-offset) 0)
859                                     (widget-get parent :offset))))
860     (widget-apply widget :create)
861     widget))
862
863 (defun widget-create-child-value (parent type value)
864   "Create widget of TYPE with value VALUE."
865   (let ((widget (copy-sequence type)))
866     (widget-put widget :value (widget-apply widget :value-to-internal value))
867     (widget-put widget :parent parent)
868     (unless (widget-get widget :indent)
869       (widget-put widget :indent (+ (or (widget-get parent :indent) 0)
870                                     (or (widget-get widget :extra-offset) 0)
871                                     (widget-get parent :offset))))
872     (widget-apply widget :create)
873     widget))
874
875 ;;;###autoload
876 (defun widget-delete (widget)
877   "Delete WIDGET."
878   (widget-apply widget :delete))
879
880 (defun widget-convert (type &rest args)
881   "Convert TYPE to a widget without inserting it in the buffer.
882 The optional ARGS are additional keyword arguments."
883   ;; Don't touch the type.
884   (let* ((widget (if (symbolp type)
885                      (list type)
886                    (copy-sequence type)))
887          (current widget)
888          (keys args))
889     ;; First set the :args keyword.
890     (while (cdr current)                ;Look in the type.
891       (let ((next (car (cdr current))))
892         (if (and (symbolp next) (eq (aref (symbol-name next) 0) ?:))
893             (setq current (cdr (cdr current)))
894           (setcdr current (list :args (cdr current)))
895           (setq current nil))))
896     (while args                         ;Look in the args.
897       (let ((next (nth 0 args)))
898         (if (and (symbolp next) (eq (aref (symbol-name next) 0) ?:))
899             (setq args (nthcdr 2 args))
900           (widget-put widget :args args)
901           (setq args nil))))
902     ;; Then Convert the widget.
903     (setq type widget)
904     (while type
905       (let ((convert-widget (plist-get (cdr type) :convert-widget)))
906         (if convert-widget
907             (setq widget (funcall convert-widget widget))))
908       (setq type (get (car type) 'widget-type)))
909     ;; Finally set the keyword args.
910     (while keys
911       (let ((next (nth 0 keys)))
912         (if (and (symbolp next) (eq (aref (symbol-name next) 0) ?:))
913             (progn
914               (widget-put widget next (nth 1 keys))
915               (setq keys (nthcdr 2 keys)))
916           (setq keys nil))))
917     ;; Convert the :value to internal format.
918     (if (widget-member widget :value)
919         (let ((value (widget-get widget :value)))
920           (widget-put widget
921                       :value (widget-apply widget :value-to-internal value))))
922     ;; Return the newly created widget.
923     widget))
924
925 (defun widget-insert (&rest args)
926   "Call `insert' with ARGS and make the text read only."
927   (let ((inhibit-read-only t)
928         before-change-functions
929         after-change-functions)
930     (apply 'insert args)))
931
932 (defun widget-convert-text (type from to
933                                  &optional button-from button-to
934                                  &rest args)
935   "Return a widget of type TYPE with endpoint FROM TO.
936 Optional ARGS are extra keyword arguments for TYPE.
937 and TO will be used as the widgets end points. If optional arguments
938 BUTTON-FROM and BUTTON-TO are given, these will be used as the widgets
939 button end points.
940 Optional ARGS are extra keyword arguments for TYPE."
941   (let ((widget (apply 'widget-convert type :delete 'widget-leave-text args))
942         (from (copy-marker from))
943         (to (copy-marker to)))
944     (set-marker-insertion-type from t)
945     (set-marker-insertion-type to nil)
946     (widget-put widget :from from)
947     (widget-put widget :to to)
948     (when button-from
949       (widget-specify-button widget button-from button-to))
950     widget))
951
952 (defun widget-convert-button (type from to &rest args)
953   "Return a widget of type TYPE with endpoint FROM TO.
954 Optional ARGS are extra keyword arguments for TYPE.
955 No text will be inserted to the buffer, instead the text between FROM
956 and TO will be used as the widgets end points, as well as the widgets
957 button end points."
958   (apply 'widget-convert-text type from to from to args))
959
960 (defun widget-leave-text (widget)
961   "Remove markers and extents from WIDGET and its children."
962   (let ((from (widget-get widget :from))
963         (to (widget-get widget :to))
964         (button (widget-get widget :button-extent))
965         (sample (widget-get widget :sample-extent))
966         (doc (widget-get widget :doc-extent))
967         (field (widget-get widget :field-extent))
968         (children (widget-get widget :children)))
969     (set-marker from nil)
970     (set-marker to nil)
971     ;; Maybe we should delete the extents here?  As this code doesn't
972     ;; remove them from widget structures, maybe it's safer to just
973     ;; detach them.  That's what `delete-overlay' did.
974     (when button
975       (detach-extent button))
976     (when sample
977       (detach-extent sample))
978     (when doc
979       (detach-extent doc))
980     (when field
981       (detach-extent field))
982     (mapc 'widget-leave-text children)))
983
984 \f
985 ;;; Keymap and Commands.
986
987 (defvar widget-keymap nil
988   "Keymap containing useful binding for buffers containing widgets.
989 Recommended as a parent keymap for modes using widgets.")
990
991 (unless widget-keymap
992   (setq widget-keymap (make-sparse-keymap))
993   (define-key widget-keymap [tab] 'widget-forward)
994   (define-key widget-keymap [(shift tab)] 'widget-backward)
995   (define-key widget-keymap [(meta tab)] 'widget-backward)
996   (define-key widget-keymap [backtab] 'widget-backward))
997
998 (defvar widget-global-map global-map
999   "Keymap used for events the widget does not handle themselves.")
1000 (make-variable-buffer-local 'widget-global-map)
1001
1002 (defvar widget-field-keymap nil
1003   "Keymap used inside an editable field.")
1004
1005 (unless widget-field-keymap
1006   (setq widget-field-keymap (make-sparse-keymap))
1007   (set-keymap-parents widget-field-keymap global-map)
1008   (define-key widget-field-keymap "\C-k" 'widget-kill-line)
1009   (define-key widget-field-keymap [(meta tab)] 'widget-complete)
1010   (define-key widget-field-keymap [tab] 'widget-forward)
1011   (define-key widget-field-keymap [(shift tab)] 'widget-backward)
1012   (define-key widget-field-keymap "\C-m" 'widget-field-activate)
1013   (define-key widget-field-keymap "\C-a" 'widget-beginning-of-line)
1014   (define-key widget-field-keymap "\C-e" 'widget-end-of-line)
1015   (define-key widget-field-keymap "\C-t" 'widget-transpose-chars))
1016
1017 (defvar widget-text-keymap nil
1018   "Keymap used inside a text field.")
1019
1020 (unless widget-text-keymap
1021   (setq widget-text-keymap (make-sparse-keymap))
1022   (set-keymap-parents widget-field-keymap global-map)
1023   (define-key widget-text-keymap "\C-a" 'widget-beginning-of-line)
1024   (define-key widget-text-keymap "\C-e" 'widget-end-of-line)
1025   (define-key widget-text-keymap "\C-t" 'widget-transpose-chars))
1026
1027 (defvar widget-button-keymap nil
1028   "Keymap used inside a button.")
1029
1030 (unless widget-button-keymap
1031   (setq widget-button-keymap (make-sparse-keymap))
1032   (set-keymap-parents widget-button-keymap widget-keymap)
1033   (define-key widget-button-keymap "\C-m" 'widget-button-press)
1034   (define-key widget-button-keymap [button2] 'widget-button-click)
1035   ;; Ideally, button3 within a button should invoke a button-specific
1036   ;; menu.
1037   (define-key widget-button-keymap [button3] 'widget-button-click)
1038   ;;Glyph support.
1039   (define-key widget-button-keymap [button1] 'widget-button1-click))
1040
1041
1042 (defun widget-field-activate (pos &optional event)
1043   "Invoke the ediable field at point."
1044   (interactive "@d")
1045   (let ((field (widget-field-find pos)))
1046     (if field
1047         (widget-apply-action field event)
1048       (call-interactively
1049        (lookup-key widget-global-map (this-command-keys))))))
1050
1051 (defface widget-button-pressed-face
1052   '((((class color))
1053      (:foreground "red"))
1054     (t
1055      (:bold t :underline t)))
1056   "Face used for pressed buttons."
1057   :group 'widget-faces)
1058
1059 (defun widget-event-point (event)
1060   "Character position of the mouse event, or nil."
1061   (and (mouse-event-p event)
1062        (event-point event)))
1063
1064 (defun widget-button-click (event)
1065   "Invoke button below mouse pointer."
1066   (interactive "e")
1067   (with-current-buffer (event-buffer event)
1068     (cond ((event-glyph event)
1069            (widget-glyph-click event))
1070           ((widget-event-point event)
1071            (let* ((pos (widget-event-point event))
1072                   (button (get-char-property pos 'button)))
1073              (if button
1074                  (let* ((extent (widget-get button :button-extent))
1075                         (face (extent-property extent 'face))
1076                         (mouse-face (extent-property extent 'mouse-face))
1077                         (help-echo (extent-property extent 'help-echo)))
1078                    (unwind-protect
1079                        (progn
1080                          ;; Merge relevant faces, and make the result mouse-face.
1081                          (let ((merge `(widget-button-pressed-face ,mouse-face)))
1082                            (nconc merge (if (listp face)
1083                                             face (list face)))
1084                            (setq merge (delete-if-not 'find-face merge))
1085                            (set-extent-property extent 'mouse-face merge))
1086                          (unless (widget-apply button :mouse-down-action event)
1087                            ;; Wait for button release.
1088                            (while (not (button-release-event-p
1089                                         (setq event (next-event))))
1090                              (dispatch-event event)))
1091                          ;; Disallow mouse-face and help-echo.
1092                          (set-extent-property extent 'mouse-face nil)
1093                          (set-extent-property extent 'help-echo nil)
1094                          (setq pos (widget-event-point event))
1095                          (unless (eq (current-buffer) (extent-object extent))
1096                            ;; Barf if dispatch-event tripped us by
1097                            ;; changing buffer.
1098                            (error "Buffer changed during mouse motion"))
1099                          ;; Do the associated action.
1100                          (when (and pos (extent-in-region-p extent pos pos))
1101                            (widget-apply-action button event)))
1102                      ;; Unwinding: fully release the button.
1103                      (set-extent-property extent 'mouse-face mouse-face)
1104                      (set-extent-property extent 'help-echo help-echo)))
1105                ;; This should not happen!
1106                (error "`widget-button-click' called outside button"))))
1107           (t
1108            (message "You clicked somewhere weird")))))
1109
1110 (defun widget-button1-click (event)
1111   "Invoke glyph below mouse pointer."
1112   (interactive "@e")
1113   (if (event-glyph event)
1114       (widget-glyph-click event)
1115     ;; Should somehow avoid this.
1116     (let ((command (lookup-key widget-global-map (this-command-keys))))
1117       (and (commandp command)
1118            (call-interactively command)))))
1119
1120 (defun widget-glyph-click (event)
1121   "Handle click on a glyph."
1122   (let* ((glyph (event-glyph event))
1123          (extent (event-glyph-extent event))
1124          (widget (extent-property extent 'glyph-widget))
1125          (down-glyph (or (and widget (widget-get widget :glyph-down)) glyph))
1126          (up-glyph (or (and widget (widget-get widget :glyph-up)) glyph))
1127          (last event))
1128     (unless (widget-apply widget :active)
1129       (error "This widget is inactive"))
1130     (let ((current-glyph 'down))
1131       ;; We always know what glyph is drawn currently, to avoid
1132       ;; unnecessary extent changes.  Is this any noticable gain?
1133       (unwind-protect
1134           (progn
1135             ;; Press the glyph.
1136             (set-extent-end-glyph extent down-glyph)
1137             ;; Redisplay (shouldn't be needed, but...)
1138             (sit-for 0)
1139             (unless (widget-apply widget :mouse-down-action event)
1140               ;; Wait for the release.
1141               (while (not (button-release-event-p last))
1142                 (unless (button-press-event-p last)
1143                   (dispatch-event last))
1144                 (when (motion-event-p last)
1145                   ;; Update glyphs on mouse motion.
1146                   (if (eq extent (event-glyph-extent last))
1147                       (unless (eq current-glyph 'down)
1148                         (set-extent-end-glyph extent down-glyph)
1149                         (setq current-glyph 'down))
1150                     (unless (eq current-glyph 'up)
1151                       (set-extent-end-glyph extent up-glyph)
1152                       (setq current-glyph 'up))))
1153                 (setq last (next-event event))))
1154             (unless (eq (current-buffer) (extent-object extent))
1155               ;; Barf if dispatch-event tripped us by changing buffer.
1156               (error "Buffer changed during mouse motion"))
1157             ;; Apply widget action.
1158             (when (eq extent (event-glyph-extent last))
1159               (let ((widget (extent-property (event-glyph-extent event)
1160                                              'glyph-widget)))
1161                 (cond ((null widget)
1162                        (message "You clicked on a glyph"))
1163                       ((not (widget-apply widget :active))
1164                        (error "This glyph is inactive"))
1165                       (t
1166                        (widget-apply-action widget event))))))
1167         ;; Release the glyph.
1168         (and (eq current-glyph 'down)
1169              ;; The extent might have been detached or deleted
1170              (extent-live-p extent)
1171              (not (extent-detached-p extent))
1172              (set-extent-end-glyph extent up-glyph))))))
1173
1174 (defun widget-button-press (pos &optional event)
1175   "Invoke button at POS."
1176   (interactive "@d")
1177   (let ((button (get-char-property pos 'button)))
1178     (if button
1179         (widget-apply-action button event)
1180       (let ((command (lookup-key widget-global-map (this-command-keys))))
1181         (when (commandp command)
1182           (call-interactively command))))))
1183
1184 (defun widget-tabable-at (&optional pos last-tab backwardp)
1185   "Return the tabable widget at POS, or nil.
1186 POS defaults to the value of (point)."
1187   (unless pos
1188     (setq pos (point)))
1189   (let ((widget (widget-at pos)))
1190     (if widget
1191         (let ((order (widget-get widget :tab-order)))
1192           (if order
1193               (if last-tab (and (= order (if backwardp
1194                                              (1- last-tab)
1195                                            (1+ last-tab)))
1196                                 widget)
1197                 (and (> order 0) widget))
1198             widget))
1199       nil)))
1200
1201 ;; Return the button or field extent at point.
1202 (defun widget-button-or-field-extent (pos)
1203   (or (and (get-char-property pos 'button)
1204            (widget-get (get-char-property pos 'button)
1205                        :button-extent))
1206       (and (get-char-property pos 'field)
1207            (widget-get (get-char-property pos 'field)
1208                        :field-extent))))
1209
1210 (defun widget-next-button-or-field (pos)
1211   "Find the next button, or field, and return its start position, or nil.
1212 Internal function, don't use it outside `wid-edit'."
1213   (let* ((at-point (widget-button-or-field-extent pos))
1214          (extent (map-extents
1215                   (lambda (ext ignore)
1216                     ext)
1217                   nil (if at-point (extent-end-position at-point) pos)
1218                   nil nil 'start-open 'button-or-field)))
1219     (and extent
1220          (extent-start-position extent))))
1221
1222 ;; This is too slow in buffers with many buttons (W3).
1223 (defun widget-previous-button-or-field (pos)
1224   "Find the previous button, or field, and return its start position, or nil.
1225 Internal function, don't use it outside `wid-edit'."
1226   (let* ((at-point (widget-button-or-field-extent pos))
1227          previous-extent)
1228     (map-extents
1229      (lambda (ext ignore)
1230        (if (eq ext at-point)
1231            ;; We reached the extent we were on originally
1232            (if (= pos (extent-start-position at-point))
1233                previous-extent
1234              (setq previous-extent at-point))
1235          (setq previous-extent ext)
1236          nil))
1237      nil nil pos nil 'start-open 'button-or-field)
1238     (and previous-extent
1239          (extent-start-position previous-extent))))
1240
1241 (defun widget-move (arg)
1242   "Move point to the ARG next field or button.
1243 ARG may be negative to move backward."
1244   (let ((opoint (point)) (wrapped 0)
1245         (last-tab (widget-get (widget-at (point)) :tab-order))
1246         nextpos found)
1247     ;; Movement backward
1248     (while (< arg 0)
1249       (setq nextpos (widget-previous-button-or-field (point)))
1250       (if nextpos
1251           (progn
1252             (goto-char nextpos)
1253             (when (and (not (get-char-property nextpos 'widget-inactive))
1254                        (widget-tabable-at nil last-tab t))
1255               (incf arg)
1256               (setq found t
1257                     last-tab (widget-get (widget-at (point))
1258                                          :tab-order))))
1259         (if (and (not found) (> wrapped 1))
1260             (setq arg 0
1261                   found nil)
1262           (goto-char (point-max))
1263           (incf wrapped))))
1264     ;; Movement forward
1265     (while (> arg 0)
1266       (setq nextpos (widget-next-button-or-field (point)))
1267       (if nextpos
1268           (progn
1269             (goto-char nextpos)
1270             (when (and (not (get-char-property nextpos 'widget-inactive))
1271                        (widget-tabable-at nil last-tab))
1272               (decf arg)
1273               (setq found t
1274                     last-tab (widget-get (widget-at (point))
1275                                          :tab-order))))
1276         (if (and (not found) (> wrapped 1))
1277             (setq arg 0
1278                   found nil)
1279           (goto-char (point-min))
1280           (incf wrapped))))
1281     (if (not found)
1282         (goto-char opoint)
1283       (widget-echo-help (point))
1284       (run-hooks 'widget-move-hook))))
1285
1286 (defun widget-forward (arg)
1287   "Move point to the next field or button.
1288 With optional ARG, move across that many fields."
1289   (interactive "p")
1290   (run-hooks 'widget-forward-hook)
1291   (widget-move arg))
1292
1293 (defun widget-backward (arg)
1294   "Move point to the previous field or button.
1295 With optional ARG, move across that many fields."
1296   (interactive "p")
1297   (run-hooks 'widget-backward-hook)
1298   (widget-move (- arg)))
1299
1300 (defun widget-beginning-of-line ()
1301   "Go to beginning of field or beginning of line, whichever is first."
1302   (interactive "_")
1303   (let* ((field (widget-field-find (point)))
1304          (start (and field (widget-field-start field))))
1305     (if (and start (not (eq start (point))))
1306         (goto-char start)
1307       (call-interactively 'beginning-of-line))))
1308
1309 (defun widget-end-of-line ()
1310   "Go to end of field or end of line, whichever is first."
1311   (interactive "_")
1312   (let* ((field (widget-field-find (point)))
1313          (end (and field (widget-field-end field))))
1314     (if (and end (not (eq end (point))))
1315         (goto-char end)
1316       (call-interactively 'end-of-line))))
1317
1318 (defun widget-kill-line ()
1319   "Kill to end of field or end of line, whichever is first."
1320   (interactive)
1321   (let* ((field (widget-field-find (point)))
1322          (newline (save-excursion (forward-line 1) (point)))
1323          (end (and field (widget-field-end field))))
1324     (if (and field (> newline end))
1325         (kill-region (point) end)
1326       (call-interactively 'kill-line))))
1327
1328 (defun widget-transpose-chars (arg)
1329   "Like `transpose-chars', but works correctly at end of widget."
1330   (interactive "*P")
1331   (let* ((field (widget-field-find (point)))
1332          (start (and field (widget-field-start field)))
1333          (end (and field (widget-field-end field)))
1334          (last-non-space (and start end
1335                               (save-excursion
1336                                 (goto-char end)
1337                                 (skip-chars-backward " \t\n" start)
1338                                 (point)))))
1339     (cond ((and last-non-space
1340                 (or (= last-non-space start)
1341                     (= last-non-space (1+ start))))
1342            ;; empty or one-character field
1343            nil)
1344           ((= (point) start)
1345            ;; at the beginning of the field -- we would get an error here.
1346            (error "Cannot transpose at beginning of field"))
1347           (t
1348            (when (and (null arg)
1349                       (= last-non-space (point)))
1350              (forward-char -1))
1351            (transpose-chars arg)))))
1352
1353 (defcustom widget-complete-field (lookup-key global-map "\M-\t")
1354   "Default function to call for completion inside fields."
1355   :options '(ispell-complete-word complete-tag lisp-complete-symbol)
1356   :type 'function
1357   :group 'widgets)
1358
1359 (defun widget-complete ()
1360   "Complete content of editable field from point.
1361 When not inside a field, move to the previous button or field."
1362   (interactive)
1363   ;; Somehow, this should make pressing M-TAB twice scroll the
1364   ;; completions window.
1365   (let ((field (widget-field-find (point))))
1366     (if field
1367         (widget-apply field :complete)
1368       (error "Not in an editable field"))))
1369
1370 \f
1371 ;;; Setting up the buffer.
1372
1373 (defvar widget-field-new nil)
1374 ;; List of all newly created editable fields in the buffer.
1375 (make-variable-buffer-local 'widget-field-new)
1376
1377 (defvar widget-field-list nil)
1378 ;; List of all editable fields in the buffer.
1379 (make-variable-buffer-local 'widget-field-list)
1380
1381 (defun widget-setup ()
1382   "Setup current buffer so editing string widgets works."
1383   (let ((inhibit-read-only t)
1384         (after-change-functions nil)
1385         before-change-functions
1386         field)
1387     (while widget-field-new
1388       (setq field (car widget-field-new)
1389             widget-field-new (cdr widget-field-new)
1390             widget-field-list (cons field widget-field-list))
1391       (let ((from (car (widget-get field :field-extent)))
1392             (to (cdr (widget-get field :field-extent))))
1393         (widget-specify-field field
1394                               (marker-position from) (marker-position to))
1395         (set-marker from nil)
1396         (set-marker to nil))
1397       ;; If the field is placed within the inactive zone, deactivate it.
1398       (let ((extent (widget-get field :field-extent)))
1399         (when (get-char-property (extent-start-position extent)
1400                                  'widget-inactive)
1401           (widget-activation-widget-mapper extent :deactivate)))))
1402   (widget-clear-undo)
1403   (widget-add-change))
1404
1405 (defvar widget-field-last nil)
1406 ;; Last field containing point.
1407 (make-variable-buffer-local 'widget-field-last)
1408
1409 (defvar widget-field-was nil)
1410 ;; The widget data before the change.
1411 (make-variable-buffer-local 'widget-field-was)
1412
1413 (defun widget-field-buffer (widget)
1414   "Return the start of WIDGET's editing field."
1415   (let ((extent (widget-get widget :field-extent)))
1416     (and extent (extent-object extent))))
1417
1418 (defun widget-field-start (widget)
1419   "Return the start of WIDGET's editing field."
1420   (let ((extent (widget-get widget :field-extent)))
1421     (and extent (extent-start-position extent))))
1422
1423 (defun widget-field-end (widget)
1424   "Return the end of WIDGET's editing field."
1425   (let ((extent (widget-get widget :field-extent)))
1426     ;; Don't subtract one if local-map works at the end of the extent.
1427     (and extent (if (or widget-field-add-space
1428                         (null (widget-get widget :size)))
1429                     (1- (extent-end-position extent))
1430                   (extent-end-position extent)))))
1431
1432 (defun widget-field-find (pos)
1433   "Return the field at POS.
1434 Unlike (get-char-property POS 'field) this, works with empty fields too."
1435   (let ((field-extent (map-extents (lambda (extent ignore)
1436                                      extent)
1437                                    nil pos pos nil nil 'field)))
1438     (and field-extent
1439          (extent-property field-extent 'field))))
1440
1441 ;; Old version, without `map-extents'.
1442 ;(defun widget-field-find (pos)
1443 ;  (let ((fields widget-field-list)
1444 ;       field found)
1445 ;    (while fields
1446 ;      (setq field (car fields)
1447 ;           fields (cdr fields))
1448 ;      (let ((start (widget-field-start field))
1449 ;           (end (widget-field-end field)))
1450 ;       (when (and (<= start pos) (<= pos end))
1451 ;         (when found
1452 ;           (debug "Overlapping fields"))
1453 ;         (setq found field))))
1454 ;    found))
1455
1456 (defun widget-before-change (from to)
1457   ;; Barf if the text changed is outside the editable fields.
1458   (unless inhibit-read-only
1459     (let ((from-field (widget-field-find from))
1460           (to-field (widget-field-find to)))
1461       (cond ((or (null from-field)
1462                  (null to-field))
1463              ;; Either end of change is not within a field.
1464              (add-hook 'post-command-hook 'widget-add-change nil t)
1465              (error "Attempt to change text outside editable field"))
1466             ((not (eq from-field to-field))
1467              ;; The change begins in one fields, and ends in another one.
1468              (add-hook 'post-command-hook 'widget-add-change nil t)
1469              (error "Change should be restricted to a single field"))
1470             ((or (and from-field
1471                       (get-char-property from 'widget-inactive))
1472                  (and to-field
1473                       (get-char-property to 'widget-inactive)))
1474              ;; Trying to change an inactive editable field.
1475              (add-hook 'post-command-hook 'widget-add-change nil t)
1476              (error "Attempt to change an inactive field"))
1477             (widget-field-use-before-change
1478              ;; #### Bletch!  This loses because XEmacs get confused
1479              ;; if before-change-functions change the contents of
1480              ;; buffer before from/to.
1481              (condition-case nil
1482                  (widget-apply from-field :notify from-field)
1483                (error (debug "Before Change"))))))))
1484
1485 (defun widget-add-change ()
1486   (make-local-hook 'post-command-hook)
1487   (remove-hook 'post-command-hook 'widget-add-change t)
1488   (make-local-hook 'before-change-functions)
1489   (add-hook 'before-change-functions 'widget-before-change nil t)
1490   (make-local-hook 'after-change-functions)
1491   (add-hook 'after-change-functions 'widget-after-change nil t))
1492
1493 (defun widget-after-change (from to old)
1494   ;; Adjust field size and text properties.
1495
1496   ;; Also, notify the widgets (so, for example, a variable changes its
1497   ;; state to `modified'.  when it is being edited.)
1498   (condition-case nil
1499       (let ((field (widget-field-find from))
1500             (other (widget-field-find to)))
1501         (when field
1502           (unless (eq field other)
1503             (debug "Change in different fields"))
1504           (let ((size (widget-get field :size)))
1505             (when size
1506               (let ((begin (widget-field-start field))
1507                     (end (widget-field-end field)))
1508                 (cond ((< (- end begin) size)
1509                        ;; Field too small.
1510                        (save-excursion
1511                          (goto-char end)
1512                          (insert-char ?\  (- (+ begin size) end))))
1513                       ((> (- end begin) size)
1514                        ;; Field too large and
1515                        (if (or (< (point) (+ begin size))
1516                                (> (point) end))
1517                            ;; Point is outside extra space.
1518                            (setq begin (+ begin size))
1519                          ;; Point is within the extra space.
1520                          (setq begin (point)))
1521                        (save-excursion
1522                          (goto-char end)
1523                          (while (and (eq (preceding-char) ?\ )
1524                                      (> (point) begin))
1525                            (delete-backward-char 1)))))))
1526             (widget-specify-secret field))
1527           (widget-apply field :notify field)))
1528     (error (debug "After Change"))))
1529
1530 \f
1531 ;;; Widget Functions
1532 ;;
1533 ;; These functions are used in the definition of multiple widgets.
1534
1535 (defun widget-parent-action (widget &optional event)
1536   "Tell :parent of WIDGET to handle the :action.
1537 Optional EVENT is the event that triggered the action."
1538   (widget-apply (widget-get widget :parent) :action event))
1539
1540 (defun widget-children-value-delete (widget)
1541   "Delete all :children and :buttons in WIDGET."
1542   (mapc 'widget-delete (widget-get widget :children))
1543   (widget-put widget :children nil)
1544   (mapc 'widget-delete (widget-get widget :buttons))
1545   (widget-put widget :buttons nil))
1546
1547 (defun widget-children-validate (widget)
1548   "All the :children must be valid."
1549   (let ((children (widget-get widget :children))
1550         child found)
1551     (while (and children (not found))
1552       (setq child (car children)
1553             children (cdr children)
1554             found (widget-apply child :validate)))
1555     found))
1556
1557 (defun widget-types-convert-widget (widget)
1558   "Convert :args as widget types in WIDGET."
1559   (widget-put widget :args (mapcar 'widget-convert (widget-get widget :args)))
1560   widget)
1561
1562 (defun widget-value-convert-widget (widget)
1563   "Initialize :value from :args in WIDGET."
1564   (let ((args (widget-get widget :args)))
1565     (when args
1566       (widget-put widget :value (car args))
1567       ;; Don't convert :value here, as this is done in `widget-convert'.
1568       ;; (widget-put widget :value (widget-apply widget
1569       ;; :value-to-internal (car args)))
1570       (widget-put widget :args nil)))
1571   widget)
1572
1573 (defun widget-value-value-get (widget)
1574   "Return the :value property of WIDGET."
1575   (widget-get widget :value))
1576
1577 ;;; The `default' Widget.
1578
1579 (define-widget 'default nil
1580   "Basic widget other widgets are derived from."
1581   :value-to-internal (lambda (widget value) value)
1582   :value-to-external (lambda (widget value) value)
1583   :button-prefix 'widget-button-prefix
1584   :button-suffix 'widget-button-suffix
1585   :complete 'widget-default-complete
1586   :create 'widget-default-create
1587   :indent nil
1588   :offset 0
1589   :format-handler 'widget-default-format-handler
1590   :button-face-get 'widget-default-button-face-get
1591   :sample-face-get 'widget-default-sample-face-get
1592   :button-keymap widget-button-keymap
1593   :delete 'widget-default-delete
1594   :value-set 'widget-default-value-set
1595   :value-inline 'widget-default-value-inline
1596   :default-get 'widget-default-default-get
1597   :menu-tag-get 'widget-default-menu-tag-get
1598   :validate (lambda (widget) nil)
1599   :active 'widget-default-active
1600   :activate 'widget-specify-active
1601   :deactivate 'widget-default-deactivate
1602   :mouse-down-action (lambda (widget event) nil)
1603   :action 'widget-default-action
1604   :notify 'widget-default-notify
1605   :prompt-value 'widget-default-prompt-value)
1606
1607 (defun widget-default-complete (widget)
1608   "Call the value of the :complete-function property of WIDGET.
1609 If that does not exists, call the value of `widget-complete-field'."
1610   (let ((fun (widget-get widget :complete-function)))
1611     (call-interactively (or fun widget-complete-field))))
1612
1613 (defun widget-default-create (widget)
1614   "Create WIDGET at point in the current buffer."
1615   (widget-specify-insert
1616    (let ((from (point))
1617          button-begin button-end button-glyph
1618          sample-begin sample-end
1619          doc-begin doc-end
1620          value-pos)
1621      (insert (widget-get widget :format))
1622      (goto-char from)
1623      ;; Parse escapes in format.  Coding this in C would speed up
1624      ;; things *a lot*.
1625      (while (re-search-forward "%\\(.\\)" nil t)
1626        (let ((escape (aref (match-string 1) 0)))
1627          (replace-match "" t t)
1628          (cond ((eq escape ?%)
1629                 (insert "%"))
1630                ((eq escape ?\[)
1631                 (setq button-begin (point-marker))
1632                 (set-marker-insertion-type button-begin nil))
1633                ((eq escape ?\])
1634                 (setq button-end (point-marker))
1635                 (set-marker-insertion-type button-end nil))
1636                ((eq escape ?\{)
1637                 (setq sample-begin (point)))
1638                ((eq escape ?\})
1639                 (setq sample-end (point)))
1640                ((eq escape ?n)
1641                 (when (widget-get widget :indent)
1642                   (insert "\n")
1643                   (insert-char ?\  (widget-get widget :indent))))
1644                ((eq escape ?t)
1645                 (let* ((tag (widget-get widget :tag))
1646                        (glyph (widget-get widget :tag-glyph)))
1647                   (cond (glyph
1648                          (setq button-glyph
1649                                (widget-glyph-insert
1650                                 widget (or tag "Image") glyph)))
1651                         (tag
1652                          (insert tag))
1653                         (t
1654                          (let ((standard-output (current-buffer)))
1655                            (princ (widget-get widget :value)))))))
1656                ((eq escape ?d)
1657                 (let ((doc (widget-get widget :doc)))
1658                   (when doc
1659                     (setq doc-begin (point))
1660                     (insert doc)
1661                     (while (eq (preceding-char) ?\n)
1662                       (delete-backward-char 1))
1663                     (insert "\n")
1664                     (setq doc-end (point)))))
1665                ((eq escape ?v)
1666                 (if (and button-begin (not button-end))
1667                     (widget-apply widget :value-create)
1668                   (setq value-pos (point-marker))))
1669                (t
1670                 (widget-apply widget :format-handler escape)))))
1671      ;; Specify button, sample, and doc, and insert value.
1672      (when (and button-begin button-end)
1673        (unless button-glyph
1674          (goto-char button-begin)
1675          (insert (widget-get-indirect widget :button-prefix))
1676          (goto-char button-end)
1677          (set-marker-insertion-type button-end t)
1678          (insert (widget-get-indirect widget :button-suffix)))
1679        (widget-specify-button widget button-begin button-end)
1680        ;; Is this necessary?
1681        (set-marker button-begin nil)
1682        (set-marker button-end nil))
1683      (and sample-begin sample-end
1684           (widget-specify-sample widget sample-begin sample-end))
1685      (and doc-begin doc-end
1686           (widget-specify-doc widget doc-begin doc-end))
1687      (when value-pos
1688        (goto-char value-pos)
1689        (widget-apply widget :value-create)))
1690    (let ((from (point-min-marker))
1691          (to (point-max-marker)))
1692      (set-marker-insertion-type from t)
1693      (set-marker-insertion-type to nil)
1694      (widget-put widget :from from)
1695      (widget-put widget :to to)))
1696   (widget-clear-undo))
1697
1698 (defun widget-default-format-handler (widget escape)
1699   ;; We recognize the %h escape by default.
1700   (let* ((buttons (widget-get widget :buttons)))
1701     (cond ((eq escape ?h)
1702            (let* ((doc-property (widget-get widget :documentation-property))
1703                   (doc-try (cond ((widget-get widget :doc))
1704                                  ((symbolp doc-property)
1705                                   (documentation-property
1706                                    (widget-get widget :value)
1707                                    doc-property))
1708                                  (t
1709                                   (funcall doc-property
1710                                            (widget-get widget :value)))))
1711                   (doc-text (and (stringp doc-try)
1712                                  (> (length doc-try) 1)
1713                                  doc-try))
1714                   (doc-indent (widget-get widget :documentation-indent)))
1715              (when doc-text
1716                (and (eq (preceding-char) ?\n)
1717                     (widget-get widget :indent)
1718                     (insert-char ?\  (widget-get widget :indent)))
1719                ;; The `*' in the beginning is redundant.
1720                (when (eq (aref doc-text  0) ?*)
1721                  (setq doc-text (substring doc-text 1)))
1722                ;; Get rid of trailing newlines.
1723                (when (string-match "\n+\\'" doc-text)
1724                  (setq doc-text (substring doc-text 0 (match-beginning 0))))
1725                (push (widget-create-child-and-convert
1726                       widget 'documentation-string
1727                       :indent (cond ((numberp doc-indent)
1728                                      doc-indent)
1729                                     ((null doc-indent)
1730                                      nil)
1731                                     (t 0))
1732                       doc-text)
1733                      buttons))))
1734           (t
1735            (signal 'error (list "Unknown escape" escape))))
1736     (widget-put widget :buttons buttons)))
1737
1738 (defun widget-default-button-face-get (widget)
1739   ;; Use :button-face or widget-button-face
1740   (or (widget-get widget :button-face)
1741       (let ((parent (widget-get widget :parent)))
1742         (if parent
1743             (widget-apply parent :button-face-get)
1744           widget-button-face))))
1745
1746 (defun widget-default-sample-face-get (widget)
1747   ;; Use :sample-face.
1748   (widget-get widget :sample-face))
1749
1750 (defun widget-default-delete (widget)
1751   ;; Remove widget from the buffer.
1752   (let ((from (widget-get widget :from))
1753         (to (widget-get widget :to))
1754         (inactive-extent (widget-get widget :inactive))
1755         (button-extent (widget-get widget :button-extent))
1756         (sample-extent (widget-get widget :sample-extent))
1757         (doc-extent (widget-get widget :doc-extent))
1758         before-change-functions
1759         after-change-functions
1760         (inhibit-read-only t))
1761     (widget-apply widget :value-delete)
1762     (when inactive-extent
1763       (detach-extent inactive-extent))
1764     (when button-extent
1765       (detach-extent button-extent))
1766     (when sample-extent
1767       (detach-extent sample-extent))
1768     (when doc-extent
1769       (detach-extent doc-extent))
1770     (when (< from to)
1771       ;; Kludge: this doesn't need to be true for empty formats.
1772       (delete-region from to))
1773     (set-marker from nil)
1774     (set-marker to nil))
1775   (widget-clear-undo))
1776
1777 (defun widget-default-value-set (widget value)
1778   ;; Recreate widget with new value.
1779   (let* ((old-pos (point))
1780          (from (copy-marker (widget-get widget :from)))
1781          (to (copy-marker (widget-get widget :to)))
1782          (offset (if (and (<= from old-pos) (<= old-pos to))
1783                      (if (>= old-pos (1- to))
1784                          (- old-pos to 1)
1785                        (- old-pos from)))))
1786     ;;??? Bug: this ought to insert the new value before deleting the old one,
1787     ;; so that markers on either side of the value automatically
1788     ;; stay on the same side.  -- rms.
1789     (save-excursion
1790       (goto-char (widget-get widget :from))
1791       (widget-apply widget :delete)
1792       (widget-put widget :value value)
1793       (widget-apply widget :create))
1794     (when offset
1795       (if (< offset 0)
1796           (goto-char (+ (widget-get widget :to) offset 1))
1797         (goto-char (min (+ from offset) (1- (widget-get widget :to))))))))
1798
1799 (defun widget-default-value-inline (widget)
1800   ;; Wrap value in a list unless it is inline.
1801   (if (widget-get widget :inline)
1802       (widget-value widget)
1803     (list (widget-value widget))))
1804
1805 (defun widget-default-default-get (widget)
1806   ;; Get `:value'.
1807   (widget-get widget :value))
1808
1809 (defun widget-default-menu-tag-get (widget)
1810   ;; Use tag or value for menus.
1811   (or (widget-get widget :menu-tag)
1812       (widget-get widget :tag)
1813       (widget-princ-to-string (widget-get widget :value))))
1814
1815 (defun widget-default-active (widget)
1816   "Return t iff this widget active (user modifiable)."
1817   (and (not (widget-get widget :inactive))
1818        (let ((parent (widget-get widget :parent)))
1819          (or (null parent)
1820              (widget-apply parent :active)))))
1821
1822 (defun widget-default-deactivate (widget)
1823   "Make WIDGET inactive for user modifications."
1824   (widget-specify-inactive widget
1825                            (widget-get widget :from)
1826                            (widget-get widget :to)))
1827
1828 (defun widget-default-action (widget &optional event)
1829   ;; Notify the parent when a widget change
1830   (let ((parent (widget-get widget :parent)))
1831     (when parent
1832       (widget-apply parent :notify widget event))))
1833
1834 (defun widget-default-notify (widget child &optional event)
1835   ;; Pass notification to parent.
1836   (widget-default-action widget event))
1837
1838 (defun widget-default-prompt-value (widget prompt value unbound)
1839   ;; Read an arbitrary value.  Stolen from `set-variable'.
1840 ;;  (let ((initial (if unbound
1841 ;;                   nil
1842 ;;                 ;; It would be nice if we could do a `(cons val 1)' here.
1843 ;;                 (prin1-to-string (custom-quote value))))))
1844   (eval-minibuffer prompt ))
1845
1846 ;;; The `item' Widget.
1847
1848 (define-widget 'item 'default
1849   "Constant items for inclusion in other widgets."
1850   :convert-widget 'widget-value-convert-widget
1851   :value-create 'widget-item-value-create
1852   :value-delete 'ignore
1853   :value-get 'widget-value-value-get
1854   :match 'widget-item-match
1855   :match-inline 'widget-item-match-inline
1856   :action 'widget-item-action
1857   :format "%t\n")
1858
1859 (defun widget-item-value-create (widget)
1860   ;; Insert the printed representation of the value.
1861   (let ((standard-output (current-buffer)))
1862     (princ (widget-get widget :value))))
1863
1864 (defun widget-item-match (widget value)
1865   ;; Match if the value is the same.
1866   (equal (widget-get widget :value) value))
1867
1868 (defun widget-item-match-inline (widget values)
1869   ;; Match if the value is the same.
1870   (let ((value (widget-get widget :value)))
1871     (and (listp value)
1872          (<= (length value) (length values))
1873          (let ((head (widget-sublist values 0 (length value))))
1874            (and (equal head value)
1875                 (cons head (widget-sublist values (length value))))))))
1876
1877 (defun widget-sublist (list start &optional end)
1878   "Return the sublist of LIST from START to END.
1879 If END is omitted, it defaults to the length of LIST."
1880   (if (> start 0) (setq list (nthcdr start list)))
1881   (if end
1882       (if (<= end start)
1883           nil
1884         (setq list (copy-sequence list))
1885         (setcdr (nthcdr (- end start 1) list) nil)
1886         list)
1887     (copy-sequence list)))
1888
1889 (defun widget-item-action (widget &optional event)
1890   ;; Just notify itself.
1891   (widget-apply widget :notify widget event))
1892
1893 ;;; The `push-button' Widget.
1894
1895 (defcustom widget-push-button-gui widget-glyph-enable
1896   "If non nil, use GUI push buttons when available."
1897   :group 'widgets
1898   :type 'boolean)
1899
1900 ;; Cache already created GUI objects.
1901 (defvar widget-push-button-cache nil)
1902
1903 (defcustom widget-push-button-prefix "["
1904   "String used as prefix for buttons."
1905   :type 'string
1906   :group 'widget-button)
1907
1908 (defcustom widget-push-button-suffix "]"
1909   "String used as suffix for buttons."
1910   :type 'string
1911   :group 'widget-button)
1912
1913 (define-widget 'push-button 'item
1914   "A pushable button."
1915   :button-prefix ""
1916   :button-suffix ""
1917   :value-create 'widget-push-button-value-create
1918   :format "%[%v%]")
1919
1920 (defun widget-push-button-value-create (widget)
1921   ;; Insert text representing the `on' and `off' states.
1922   (let* ((tag (or (widget-get widget :tag)
1923                   (widget-get widget :value)))
1924          (tag-glyph (widget-get widget :tag-glyph))
1925          (text (concat widget-push-button-prefix
1926                        tag widget-push-button-suffix))
1927          (gui-glyphs (lax-plist-get widget-push-button-cache tag)))
1928     (cond (tag-glyph
1929            (widget-glyph-insert widget text tag-glyph))
1930           ;; We must check for console-on-window-system-p here,
1931           ;; because GUI will not work otherwise (it needs RGB
1932           ;; components for colors, and they are not known on TTYs).
1933           ((and widget-push-button-gui
1934                 (console-on-window-system-p))
1935            (unless gui-glyphs
1936              (let* ((gui-button-shadow-thickness 1)
1937                     (gui (make-gui-button tag 'widget-gui-action widget)))
1938                (setq
1939                 gui-glyphs
1940                 (list
1941                  (make-glyph `(,(nth 0 (aref gui 1)) [string :data ,text]))
1942                  (make-glyph `(,(nth 1 (aref gui 1)) [string :data ,text]))
1943                  (make-glyph `(,(nth 2 (aref gui 1)) [string :data ,text]))))
1944                (laxputf widget-push-button-cache tag gui-glyphs)))
1945            (widget-glyph-insert-glyph
1946             widget (nth 0 gui-glyphs) (nth 1 gui-glyphs) (nth 2 gui-glyphs)))
1947           (t
1948            (insert text)))))
1949
1950 (defun widget-gui-action (widget)
1951   "Apply :action for WIDGET."
1952   (widget-apply-action widget (this-command-keys)))
1953
1954 ;;; The `link' Widget.
1955
1956 (defcustom widget-link-prefix "["
1957   "String used as prefix for links."
1958   :type 'string
1959   :group 'widget-button)
1960
1961 (defcustom widget-link-suffix "]"
1962   "String used as suffix for links."
1963   :type 'string
1964   :group 'widget-button)
1965
1966 (define-widget 'link 'item
1967   "An embedded link."
1968   :button-prefix 'widget-link-prefix
1969   :button-suffix 'widget-link-suffix
1970   :help-echo "Follow the link"
1971   :format "%[%t%]")
1972
1973 ;;; The `info-link' Widget.
1974
1975 (define-widget 'info-link 'link
1976   "A link to an info file."
1977   :help-echo 'widget-info-link-help-echo
1978   :action 'widget-info-link-action)
1979
1980 (defun widget-info-link-help-echo (widget)
1981   (concat "Read the manual entry `" (widget-value widget) "'"))
1982
1983 (defun widget-info-link-action (widget &optional event)
1984   "Open the info node specified by WIDGET."
1985   (Info-goto-node (widget-value widget)))
1986
1987 ;;; The `url-link' Widget.
1988
1989 (define-widget 'url-link 'link
1990   "A link to an www page."
1991   :help-echo 'widget-url-link-help-echo
1992   :action 'widget-url-link-action)
1993
1994 (defun widget-url-link-help-echo (widget)
1995   (concat "Visit <URL:" (widget-value widget) ">"))
1996
1997 (defun widget-url-link-action (widget &optional event)
1998   "Open the url specified by WIDGET."
1999   (if (boundp 'browse-url-browser-function)
2000       (funcall browse-url-browser-function (widget-value widget))
2001     (error "Cannot follow URLs in this XEmacs")))
2002
2003 ;;; The `function-link' Widget.
2004
2005 (define-widget 'function-link 'link
2006   "A link to an Emacs function."
2007   :action 'widget-function-link-action)
2008
2009 (defun widget-function-link-action (widget &optional event)
2010   "Show the function specified by WIDGET."
2011   (describe-function (widget-value widget)))
2012
2013 ;;; The `variable-link' Widget.
2014
2015 (define-widget 'variable-link 'link
2016   "A link to an Emacs variable."
2017   :action 'widget-variable-link-action)
2018
2019 (defun widget-variable-link-action (widget &optional event)
2020   "Show the variable specified by WIDGET."
2021   (describe-variable (widget-value widget)))
2022
2023 ;;; The `file-link' Widget.
2024
2025 (define-widget 'file-link 'link
2026   "A link to a file."
2027   :action 'widget-file-link-action)
2028
2029 (defun widget-file-link-action (widget &optional event)
2030   "Find the file specified by WIDGET."
2031   (find-file (widget-value widget)))
2032
2033 ;;; The `emacs-library-link' Widget.
2034
2035 (define-widget 'emacs-library-link 'link
2036   "A link to an Emacs Lisp library file."
2037   :help-echo 'widget-emacs-library-link-help-echo
2038   :action 'widget-emacs-library-link-action)
2039
2040 (defun widget-emacs-library-link-help-echo (widget)
2041   (concat "Visit " (widget-value widget)))
2042
2043 (defun widget-emacs-library-link-action (widget &optional event)
2044   "Find the Emacs Library file specified by WIDGET."
2045   (find-file (locate-library (widget-value widget))))
2046
2047 ;;; The `emacs-commentary-link' Widget.
2048
2049 (define-widget 'emacs-commentary-link 'link
2050   "A link to Commentary in an Emacs Lisp library file."
2051   :action 'widget-emacs-commentary-link-action)
2052
2053 (defun widget-emacs-commentary-link-action (widget &optional event)
2054   "Find the Commentary section of the Emacs file specified by WIDGET."
2055   (finder-commentary (widget-value widget)))
2056
2057 ;;; The `editable-field' Widget.
2058
2059 (define-widget 'editable-field 'default
2060   "An editable text field."
2061   :convert-widget 'widget-value-convert-widget
2062   :keymap widget-field-keymap
2063   :format "%v"
2064   :value ""
2065   :prompt-internal 'widget-field-prompt-internal
2066   :prompt-history 'widget-field-history
2067   :prompt-value 'widget-field-prompt-value
2068   :action 'widget-field-action
2069   :validate 'widget-field-validate
2070   :valid-regexp ""
2071   :error "No match"
2072   :value-create 'widget-field-value-create
2073   :value-delete 'widget-field-value-delete
2074   :value-get 'widget-field-value-get
2075   :match 'widget-field-match)
2076
2077 (defvar widget-field-history nil
2078   "History of field minibuffer edits.")
2079
2080 (defun widget-field-prompt-internal (widget prompt initial history)
2081   ;; Read string for WIDGET prompting with PROMPT.
2082   ;; INITIAL is the initial input and HISTORY is a symbol containing
2083   ;; the earlier input.
2084   (read-string prompt initial history))
2085
2086 (defun widget-field-prompt-value (widget prompt value unbound)
2087   ;; Prompt for a string.
2088   (let ((initial (if unbound
2089                      nil
2090                    (cons (widget-apply widget :value-to-internal
2091                                        value) 0)))
2092         (history (widget-get widget :prompt-history)))
2093     (let ((answer (widget-apply widget
2094                                 :prompt-internal prompt initial history)))
2095       (widget-apply widget :value-to-external answer))))
2096
2097 (defvar widget-edit-functions nil)
2098
2099 (defun widget-field-action (widget &optional event)
2100   ;; Edit the value in the minibuffer.
2101   (let* ((invalid (widget-apply widget :validate))
2102          (prompt (concat (widget-apply widget :menu-tag-get) ": "))
2103          (value (unless invalid
2104                   (widget-value widget)))
2105          (answer (widget-apply widget :prompt-value prompt value invalid)))
2106     (unless (equal value answer)
2107       ;; This is a hack.  We can't properly validate the widget
2108       ;; because validation requires the new value to be in the field.
2109       ;; However, widget-field-value-create will not function unless
2110       ;; the new value matches.  So, we check whether the thing
2111       ;; matches, and if it does, use either the real or a dummy error
2112       ;; message.
2113       (unless (widget-apply widget :match answer)
2114         (let ((error-message (or (widget-get widget :type-error)
2115                                  "Invalid field contents")))
2116           (widget-put widget :error error-message)
2117           (error error-message)))
2118       (widget-value-set widget answer)
2119       (widget-apply widget :notify widget event)
2120       (widget-setup))
2121     (run-hook-with-args 'widget-edit-functions widget)))
2122
2123 ;(defun widget-field-action (widget &optional event)
2124 ;  ;; Move to next field.
2125 ;  (widget-forward 1)
2126 ;  (run-hook-with-args 'widget-edit-functions widget))
2127
2128 (defun widget-field-validate (widget)
2129   ;; Valid if the content matches `:valid-regexp'.
2130   (save-excursion
2131     (let ((value (widget-apply widget :value-get))
2132           (regexp (widget-get widget :valid-regexp)))
2133       (if (string-match regexp value)
2134           nil
2135         widget))))
2136
2137 (defun widget-field-value-create (widget)
2138   ;; Create an editable text field.
2139   (let ((size (widget-get widget :size))
2140         (value (widget-get widget :value))
2141         (from (point))
2142         ;; This is changed to a real extent in `widget-setup'.  We
2143         ;; need the end points to behave differently until
2144         ;; `widget-setup' is called.  Should probably be replaced with
2145         ;; a genuine extent, but some things break, then.
2146         (extent (cons (make-marker) (make-marker))))
2147     (widget-put widget :field-extent extent)
2148     (insert value)
2149     (and size
2150          (< (length value) size)
2151          (insert-char ?\  (- size (length value))))
2152     (unless (memq widget widget-field-list)
2153       (push widget widget-field-new))
2154     (move-marker (cdr extent) (point))
2155     (set-marker-insertion-type (cdr extent) nil)
2156     (when (null size)
2157       (insert ?\n))
2158     (move-marker (car extent) from)
2159     (set-marker-insertion-type (car extent) t)))
2160
2161 (defun widget-field-value-delete (widget)
2162   ;; Remove the widget from the list of active editing fields.
2163   (setq widget-field-list (delq widget widget-field-list))
2164   ;; These are nil if the :format string doesn't contain `%v'.
2165   (let ((extent (widget-get widget :field-extent)))
2166     (when extent
2167       (detach-extent extent))))
2168
2169 (defun widget-field-value-get (widget)
2170   ;; Return current text in editing field.
2171   (let ((from (widget-field-start widget))
2172         (to (widget-field-end widget))
2173         (buffer (widget-field-buffer widget))
2174         (size (widget-get widget :size))
2175         (secret (widget-get widget :secret))
2176         (old (current-buffer)))
2177     (cond
2178      ((and from to)
2179       (set-buffer buffer)
2180       (while (and size
2181                   (not (zerop size))
2182                   (> to from)
2183                   (eq (char-after (1- to)) ?\ ))
2184         (setq to (1- to)))
2185       (let ((result (buffer-substring-no-properties from to)))
2186         (when secret
2187           (let ((index 0))
2188             (while (< (+ from index) to)
2189               (aset result index
2190                     (get-char-property (+ from index) 'secret))
2191               (incf index))))
2192         (set-buffer old)
2193         result))
2194      (t
2195       (widget-get widget :value)))))
2196
2197 (defun widget-field-match (widget value)
2198   ;; Match any string.
2199   (stringp value))
2200
2201 ;;; The `text' Widget.
2202
2203 (define-widget 'text 'editable-field
2204   :keymap widget-text-keymap
2205   "A multiline text area.")
2206
2207 ;;; The `menu-choice' Widget.
2208
2209 (define-widget 'menu-choice 'default
2210   "A menu of options."
2211   :convert-widget  'widget-types-convert-widget
2212   :format "%[%t%]: %v"
2213   :case-fold t
2214   :tag "choice"
2215   :void '(item :format "invalid (%t)\n")
2216   :value-create 'widget-choice-value-create
2217   :value-delete 'widget-children-value-delete
2218   :value-get 'widget-choice-value-get
2219   :value-inline 'widget-choice-value-inline
2220   :default-get 'widget-choice-default-get
2221   :mouse-down-action 'widget-choice-mouse-down-action
2222   :action 'widget-choice-action
2223   :error "Make a choice"
2224   :validate 'widget-choice-validate
2225   :match 'widget-choice-match
2226   :match-inline 'widget-choice-match-inline)
2227
2228 (defun widget-choice-value-create (widget)
2229   ;; Insert the first choice that matches the value.
2230   (let ((value (widget-get widget :value))
2231         (args (widget-get widget :args))
2232         (explicit (widget-get widget :explicit-choice))
2233         current)
2234     (if explicit
2235         (progn
2236           (widget-put widget :children (list (widget-create-child-value
2237                                               widget explicit value)))
2238           (widget-put widget :choice explicit))
2239       (while args
2240         (setq current (car args)
2241               args (cdr args))
2242         (when (widget-apply current :match value)
2243           (widget-put widget :children (list (widget-create-child-value
2244                                               widget current value)))
2245           (widget-put widget :choice current)
2246           (setq args nil
2247                 current nil)))
2248       (when current
2249         (let ((void (widget-get widget :void)))
2250           (widget-put widget :children (list (widget-create-child-and-convert
2251                                               widget void :value value)))
2252           (widget-put widget :choice void))))))
2253
2254 (defun widget-choice-value-get (widget)
2255   ;; Get value of the child widget.
2256   (widget-value (car (widget-get widget :children))))
2257
2258 (defun widget-choice-value-inline (widget)
2259   ;; Get value of the child widget.
2260   (widget-apply (car (widget-get widget :children)) :value-inline))
2261
2262 (defun widget-choice-default-get (widget)
2263   ;; Get default for the first choice.
2264   (widget-default-get (car (widget-get widget :args))))
2265
2266 (defcustom widget-choice-toggle nil
2267   "If non-nil, a binary choice will just toggle between the values.
2268 Otherwise, the user will explicitly have to choose between the values
2269 when he invoked the menu."
2270   :type 'boolean
2271   :group 'widgets)
2272
2273 (defun widget-choice-mouse-down-action (widget &optional event)
2274   ;; Return non-nil if we need a menu.
2275   (let ((args (widget-get widget :args))
2276         (old (widget-get widget :choice)))
2277     (cond ((not (console-on-window-system-p))
2278            ;; No place to pop up a menu.
2279            nil)
2280           ((< (length args) 2)
2281            ;; Empty or singleton list, just return the value.
2282            nil)
2283           ((> (length args) widget-menu-max-size)
2284            ;; Too long, prompt.
2285            nil)
2286           ((> (length args) 2)
2287            ;; Reasonable sized list, use menu.
2288            t)
2289           ((and widget-choice-toggle (memq old args))
2290            ;; We toggle.
2291            nil)
2292           (t
2293            ;; Ask which of the two.
2294            t))))
2295
2296 (defun widget-choice-action (widget &optional event)
2297   ;; Make a choice.
2298   (let ((args (widget-get widget :args))
2299         (old (widget-get widget :choice))
2300         (tag (widget-apply widget :menu-tag-get))
2301         (completion-ignore-case (widget-get widget :case-fold))
2302         current choices)
2303     ;; Remember old value.
2304     (if (and old (not (widget-apply widget :validate)))
2305         (let* ((external (widget-value widget))
2306                (internal (widget-apply old :value-to-internal external)))
2307           (widget-put old :value internal)))
2308     ;; Find new choice.
2309     (setq current
2310           (cond ((= (length args) 0)
2311                  nil)
2312                 ((= (length args) 1)
2313                  (nth 0 args))
2314                 ((and widget-choice-toggle
2315                       (= (length args) 2)
2316                       (memq old args))
2317                  (if (eq old (nth 0 args))
2318                      (nth 1 args)
2319                    (nth 0 args)))
2320                 (t
2321                  (while args
2322                    (setq current (car args)
2323                          args (cdr args))
2324                    (setq choices
2325                          (cons (cons (widget-apply current :menu-tag-get)
2326                                      current)
2327                                choices)))
2328                  (let ((choice
2329                         (widget-choose tag (reverse choices) event)))
2330                    (widget-put widget :explicit-choice choice)
2331                    choice))))
2332     (when current
2333       (let ((value (widget-default-get current)))
2334         (widget-value-set widget
2335                           (widget-apply current :value-to-external value)))
2336       (widget-setup)
2337       (widget-apply widget :notify widget event)))
2338   (run-hook-with-args 'widget-edit-functions widget))
2339
2340 (defun widget-choice-validate (widget)
2341   ;; Valid if we have made a valid choice.
2342   (let ((void (widget-get widget :void))
2343         (choice (widget-get widget :choice))
2344         (child (car (widget-get widget :children))))
2345     (if (eq void choice)
2346         widget
2347       (widget-apply child :validate))))
2348
2349 (defun widget-choice-match (widget value)
2350   ;; Matches if one of the choices matches.
2351   (let ((args (widget-get widget :args))
2352         current found)
2353     (while (and args (not found))
2354       (setq current (car args)
2355             args (cdr args)
2356             found (widget-apply current :match value)))
2357     found))
2358
2359 (defun widget-choice-match-inline (widget values)
2360   ;; Matches if one of the choices matches.
2361   (let ((args (widget-get widget :args))
2362         current found)
2363     (while (and args (null found))
2364       (setq current (car args)
2365             args (cdr args)
2366             found (widget-match-inline current values)))
2367     found))
2368
2369 ;;; The `toggle' Widget.
2370
2371 (define-widget 'toggle 'item
2372   "Toggle between two states."
2373   :format "%[%v%]\n"
2374   :value-create 'widget-toggle-value-create
2375   :action 'widget-toggle-action
2376   :match (lambda (widget value) t)
2377   :on "on"
2378   :off "off")
2379
2380 (defun widget-toggle-value-create (widget)
2381   ;; Insert text representing the `on' and `off' states.
2382   (if (widget-value widget)
2383       (widget-glyph-insert widget
2384                            (widget-get widget :on)
2385                            (widget-get widget :on-glyph))
2386       (widget-glyph-insert widget
2387                            (widget-get widget :off)
2388                            (widget-get widget :off-glyph))))
2389
2390 (defun widget-toggle-action (widget &optional event)
2391   ;; Toggle value.
2392   (widget-value-set widget (not (widget-value widget)))
2393   (widget-apply widget :notify widget event)
2394   (run-hook-with-args 'widget-edit-functions widget))
2395
2396 ;;; The `checkbox' Widget.
2397
2398 (define-widget 'checkbox 'toggle
2399   "A checkbox toggle."
2400   :button-suffix ""
2401   :button-prefix ""
2402   :format "%[%v%]"
2403   :on "[X]"
2404   :on-glyph "check1"
2405   :off "[ ]"
2406   :off-glyph "check0"
2407   :action 'widget-checkbox-action)
2408
2409 (defun widget-checkbox-action (widget &optional event)
2410   "Toggle checkbox, notify parent, and set active state of sibling."
2411   (widget-toggle-action widget event)
2412   (let ((sibling (widget-get-sibling widget)))
2413     (when sibling
2414       (if (widget-value widget)
2415           (widget-apply sibling :activate)
2416         (widget-apply sibling :deactivate)))))
2417
2418 ;;; The `checklist' Widget.
2419
2420 (define-widget 'checklist 'default
2421   "A multiple choice widget."
2422   :convert-widget 'widget-types-convert-widget
2423   :format "%v"
2424   :offset 4
2425   :entry-format "%b %v"
2426   :menu-tag "checklist"
2427   :greedy nil
2428   :value-create 'widget-checklist-value-create
2429   :value-delete 'widget-children-value-delete
2430   :value-get 'widget-checklist-value-get
2431   :validate 'widget-checklist-validate
2432   :match 'widget-checklist-match
2433   :match-inline 'widget-checklist-match-inline)
2434
2435 (defun widget-checklist-value-create (widget)
2436   ;; Insert all values
2437   (let ((alist (widget-checklist-match-find widget (widget-get widget :value)))
2438         (args (widget-get widget :args)))
2439     (while args
2440       (widget-checklist-add-item widget (car args) (assq (car args) alist))
2441       (setq args (cdr args)))
2442     (widget-put widget :children (nreverse (widget-get widget :children)))))
2443
2444 (defun widget-checklist-add-item (widget type chosen)
2445   ;; Create checklist item in WIDGET of type TYPE.
2446   ;; If the item is checked, CHOSEN is a cons whose cdr is the value.
2447   (and (eq (preceding-char) ?\n)
2448        (widget-get widget :indent)
2449        (insert-char ?\  (widget-get widget :indent)))
2450   (widget-specify-insert
2451    (let* ((children (widget-get widget :children))
2452           (buttons (widget-get widget :buttons))
2453           (button-args (or (widget-get type :sibling-args)
2454                            (widget-get widget :button-args)))
2455           (from (point))
2456           child button)
2457      (insert (widget-get widget :entry-format))
2458      (goto-char from)
2459      ;; Parse % escapes in format.
2460      (while (re-search-forward "%\\([bv%]\\)" nil t)
2461        (let ((escape (aref (match-string 1) 0)))
2462          (replace-match "" t t)
2463          (cond ((eq escape ?%)
2464                 (insert "%"))
2465                ((eq escape ?b)
2466                 (setq button (apply 'widget-create-child-and-convert
2467                                     widget 'checkbox
2468                                     :value (not (null chosen))
2469                                     button-args)))
2470                ((eq escape ?v)
2471                 (setq child
2472                       (cond ((not chosen)
2473                              (let ((child (widget-create-child widget type)))
2474                                (widget-apply child :deactivate)
2475                                child))
2476                             ((widget-get type :inline)
2477                              (widget-create-child-value
2478                               widget type (cdr chosen)))
2479                             (t
2480                              (widget-create-child-value
2481                               widget type (car (cdr chosen)))))))
2482                (t
2483                 (signal 'error (list "Unknown escape" escape))))))
2484      ;; Update properties.
2485      (and button child (widget-put child :button button))
2486      (and button (widget-put widget :buttons (cons button buttons)))
2487      (and child (widget-put widget :children (cons child children))))))
2488
2489 (defun widget-checklist-match (widget values)
2490   ;; All values must match a type in the checklist.
2491   (and (listp values)
2492        (null (cdr (widget-checklist-match-inline widget values)))))
2493
2494 (defun widget-checklist-match-inline (widget values)
2495   ;; Find the values which match a type in the checklist.
2496   (let ((greedy (widget-get widget :greedy))
2497         (args (copy-sequence (widget-get widget :args)))
2498         found rest)
2499     (while values
2500       (let ((answer (widget-checklist-match-up args values)))
2501         (cond (answer
2502                (let ((vals (widget-match-inline answer values)))
2503                  (setq found (append found (car vals))
2504                        values (cdr vals)
2505                        args (delq answer args))))
2506               (greedy
2507                (setq rest (append rest (list (car values)))
2508                      values (cdr values)))
2509               (t
2510                (setq rest (append rest values)
2511                      values nil)))))
2512     (cons found rest)))
2513
2514 (defun widget-checklist-match-find (widget vals)
2515   ;; Find the vals which match a type in the checklist.
2516   ;; Return an alist of (TYPE MATCH).
2517   (let ((greedy (widget-get widget :greedy))
2518         (args (copy-sequence (widget-get widget :args)))
2519         found)
2520     (while vals
2521       (let ((answer (widget-checklist-match-up args vals)))
2522         (cond (answer
2523                (let ((match (widget-match-inline answer vals)))
2524                  (setq found (cons (cons answer (car match)) found)
2525                        vals (cdr match)
2526                        args (delq answer args))))
2527               (greedy
2528                (setq vals (cdr vals)))
2529               (t
2530                (setq vals nil)))))
2531     found))
2532
2533 (defun widget-checklist-match-up (args vals)
2534   ;; Rerturn the first type from ARGS that matches VALS.
2535   (let (current found)
2536     (while (and args (null found))
2537       (setq current (car args)
2538             args (cdr args)
2539             found (widget-match-inline current vals)))
2540     (if found
2541         current
2542       nil)))
2543
2544 (defun widget-checklist-value-get (widget)
2545   ;; The values of all selected items.
2546   (let ((children (widget-get widget :children))
2547         child result)
2548     (while children
2549       (setq child (car children)
2550             children (cdr children))
2551       (if (widget-value (widget-get child :button))
2552           (setq result (append result (widget-apply child :value-inline)))))
2553     result))
2554
2555 (defun widget-checklist-validate (widget)
2556   ;; Ticked chilren must be valid.
2557   (let ((children (widget-get widget :children))
2558         child button found)
2559     (while (and children (not found))
2560       (setq child (car children)
2561             children (cdr children)
2562             button (widget-get child :button)
2563             found (and (widget-value button)
2564                        (widget-apply child :validate))))
2565     found))
2566
2567 ;;; The `option' Widget
2568
2569 (define-widget 'option 'checklist
2570   "An widget with an optional item."
2571   :inline t)
2572
2573 ;;; The `choice-item' Widget.
2574
2575 (define-widget 'choice-item 'item
2576   "Button items that delegate action events to their parents."
2577   :action 'widget-parent-action
2578   :format "%[%t%] \n")
2579
2580 ;;; The `radio-button' Widget.
2581
2582 (define-widget 'radio-button 'toggle
2583   "A radio button for use in the `radio' widget."
2584   :notify 'widget-radio-button-notify
2585   :format "%[%v%]"
2586   :button-suffix ""
2587   :button-prefix ""
2588   :on "(*)"
2589   :on-glyph '("radio1" nil "radio0")
2590   :off "( )"
2591   :off-glyph "radio0")
2592
2593 (defun widget-radio-button-notify (widget child &optional event)
2594   ;; Tell daddy.
2595   (widget-apply (widget-get widget :parent) :action widget event))
2596
2597 ;;; The `radio-button-choice' Widget.
2598
2599 (define-widget 'radio-button-choice 'default
2600   "Select one of multiple options."
2601   :convert-widget 'widget-types-convert-widget
2602   :offset 4
2603   :format "%v"
2604   :entry-format "%b %v"
2605   :menu-tag "radio"
2606   :value-create 'widget-radio-value-create
2607   :value-delete 'widget-children-value-delete
2608   :value-get 'widget-radio-value-get
2609   :value-inline 'widget-radio-value-inline
2610   :value-set 'widget-radio-value-set
2611   :error "You must push one of the buttons"
2612   :validate 'widget-radio-validate
2613   :match 'widget-choice-match
2614   :match-inline 'widget-choice-match-inline
2615   :action 'widget-radio-action)
2616
2617 (defun widget-radio-value-create (widget)
2618   ;; Insert all values
2619   (let ((args (widget-get widget :args))
2620         arg)
2621     (while args
2622       (setq arg (car args)
2623             args (cdr args))
2624       (widget-radio-add-item widget arg))))
2625
2626 (defun widget-radio-add-item (widget type)
2627   "Add to radio widget WIDGET a new radio button item of type TYPE."
2628   ;; (setq type (widget-convert type))
2629   (and (eq (preceding-char) ?\n)
2630        (widget-get widget :indent)
2631        (insert-char ?\  (widget-get widget :indent)))
2632   (widget-specify-insert
2633    (let* ((value (widget-get widget :value))
2634           (children (widget-get widget :children))
2635           (buttons (widget-get widget :buttons))
2636           (button-args (or (widget-get type :sibling-args)
2637                            (widget-get widget :button-args)))
2638           (from (point))
2639           (chosen (and (null (widget-get widget :choice))
2640                        (widget-apply type :match value)))
2641           child button)
2642      (insert (widget-get widget :entry-format))
2643      (goto-char from)
2644      ;; Parse % escapes in format.
2645      (while (re-search-forward "%\\([bv%]\\)" nil t)
2646        (let ((escape (aref (match-string 1) 0)))
2647          (replace-match "" t t)
2648          (cond ((eq escape ?%)
2649                 (insert "%"))
2650                ((eq escape ?b)
2651                 (setq button (apply 'widget-create-child-and-convert
2652                                     widget 'radio-button
2653                                     :value (not (null chosen))
2654                                     button-args)))
2655                ((eq escape ?v)
2656                 (setq child (if chosen
2657                                 (widget-create-child-value
2658                                  widget type value)
2659                               (widget-create-child widget type)))
2660                 (unless chosen
2661                   (widget-apply child :deactivate)))
2662                (t
2663                 (signal 'error (list "Unknown escape" escape))))))
2664      ;; Update properties.
2665      (when chosen
2666        (widget-put widget :choice type))
2667      (when button
2668        (widget-put child :button button)
2669        (widget-put widget :buttons (nconc buttons (list button))))
2670      (when child
2671        (widget-put widget :children (nconc children (list child))))
2672      child)))
2673
2674 (defun widget-radio-value-get (widget)
2675   ;; Get value of the child widget.
2676   (let ((chosen (widget-radio-chosen widget)))
2677     (and chosen (widget-value chosen))))
2678
2679 (defun widget-radio-chosen (widget)
2680   "Return the widget representing the chosen radio button."
2681   (let ((children (widget-get widget :children))
2682         current found)
2683     (while children
2684       (setq current (car children)
2685             children (cdr children))
2686       (let* ((button (widget-get current :button))
2687              (value (widget-apply button :value-get)))
2688         (when value
2689           (setq found current
2690                 children nil))))
2691     found))
2692
2693 (defun widget-radio-value-inline (widget)
2694   ;; Get value of the child widget.
2695   (let ((children (widget-get widget :children))
2696         current found)
2697     (while children
2698       (setq current (car children)
2699             children (cdr children))
2700       (let* ((button (widget-get current :button))
2701              (value (widget-apply button :value-get)))
2702         (when value
2703           (setq found (widget-apply current :value-inline)
2704                 children nil))))
2705     found))
2706
2707 (defun widget-radio-value-set (widget value)
2708   ;; We can't just delete and recreate a radio widget, since children
2709   ;; can be added after the original creation and won't be recreated
2710   ;; by `:create'.
2711   (let ((children (widget-get widget :children))
2712         current found)
2713     (while children
2714       (setq current (car children)
2715             children (cdr children))
2716       (let* ((button (widget-get current :button))
2717              (match (and (not found)
2718                          (widget-apply current :match value))))
2719         (widget-value-set button match)
2720         (if match
2721             (progn
2722               (widget-value-set current value)
2723               (widget-apply current :activate))
2724           (widget-apply current :deactivate))
2725         (setq found (or found match))))))
2726
2727 (defun widget-radio-validate (widget)
2728   ;; Valid if we have made a valid choice.
2729   (let ((children (widget-get widget :children))
2730         current found button)
2731     (while (and children (not found))
2732       (setq current (car children)
2733             children (cdr children)
2734             button (widget-get current :button)
2735             found (widget-apply button :value-get)))
2736     (if found
2737         (widget-apply current :validate)
2738       widget)))
2739
2740 (defun widget-radio-action (widget child event)
2741   ;; Check if a radio button was pressed.
2742   (let ((children (widget-get widget :children))
2743         (buttons (widget-get widget :buttons))
2744         current)
2745     (when (memq child buttons)
2746       (while children
2747         (setq current (car children)
2748               children (cdr children))
2749         (let* ((button (widget-get current :button)))
2750           (cond ((eq child button)
2751                  (widget-value-set button t)
2752                  (widget-apply current :activate))
2753                 ((widget-value button)
2754                  (widget-value-set button nil)
2755                  (widget-apply current :deactivate)))))))
2756   ;; Pass notification to parent.
2757   (widget-apply widget :notify child event))
2758
2759 ;;; The `insert-button' Widget.
2760
2761 (define-widget 'insert-button 'push-button
2762   "An insert button for the `editable-list' widget."
2763   :tag "INS"
2764   :help-echo "Insert a new item into the list at this position"
2765   :action 'widget-insert-button-action)
2766
2767 (defun widget-insert-button-action (widget &optional event)
2768   ;; Ask the parent to insert a new item.
2769   (widget-apply (widget-get widget :parent)
2770                 :insert-before (widget-get widget :widget)))
2771
2772 ;;; The `delete-button' Widget.
2773
2774 (define-widget 'delete-button 'push-button
2775   "A delete button for the `editable-list' widget."
2776   :tag "DEL"
2777   :help-echo "Delete this item from the list"
2778   :action 'widget-delete-button-action)
2779
2780 (defun widget-delete-button-action (widget &optional event)
2781   ;; Ask the parent to insert a new item.
2782   (widget-apply (widget-get widget :parent)
2783                 :delete-at (widget-get widget :widget)))
2784
2785 ;;; The `editable-list' Widget.
2786
2787 (defcustom widget-editable-list-gui nil
2788   "If non nil, use GUI push-buttons in editable list when available."
2789   :type 'boolean
2790   :group 'widgets)
2791
2792 (define-widget 'editable-list 'default
2793   "A variable list of widgets of the same type."
2794   :convert-widget 'widget-types-convert-widget
2795   :offset 12
2796   :format "%v%i\n"
2797   :format-handler 'widget-editable-list-format-handler
2798   :entry-format "%i %d %v"
2799   :menu-tag "editable-list"
2800   :value-create 'widget-editable-list-value-create
2801   :value-delete 'widget-children-value-delete
2802   :value-get 'widget-editable-list-value-get
2803   :validate 'widget-children-validate
2804   :match 'widget-editable-list-match
2805   :match-inline 'widget-editable-list-match-inline
2806   :insert-before 'widget-editable-list-insert-before
2807   :delete-at 'widget-editable-list-delete-at)
2808
2809 (defun widget-editable-list-format-handler (widget escape)
2810   ;; We recognize the insert button.
2811   (let ((widget-push-button-gui widget-editable-list-gui))
2812     (cond ((eq escape ?i)
2813            (and (widget-get widget :indent)
2814                 (insert-char ?\  (widget-get widget :indent)))
2815            (apply 'widget-create-child-and-convert
2816                   widget 'insert-button
2817                   (widget-get widget :append-button-args)))
2818           (t
2819            (widget-default-format-handler widget escape)))))
2820
2821 (defun widget-editable-list-value-create (widget)
2822   ;; Insert all values
2823   (let* ((value (widget-get widget :value))
2824          (type (nth 0 (widget-get widget :args)))
2825          (inlinep (widget-get type :inline))
2826          children)
2827     (widget-put widget :value-pos (copy-marker (point)))
2828     (set-marker-insertion-type (widget-get widget :value-pos) t)
2829     (while value
2830       (let ((answer (widget-match-inline type value)))
2831         (if answer
2832             (setq children (cons (widget-editable-list-entry-create
2833                                   widget
2834                                   (if inlinep
2835                                       (car answer)
2836                                     (car (car answer)))
2837                                   t)
2838                                  children)
2839                   value (cdr answer))
2840           (setq value nil))))
2841     (widget-put widget :children (nreverse children))))
2842
2843 (defun widget-editable-list-value-get (widget)
2844   ;; Get value of the child widget.
2845   (apply 'append (mapcar (lambda (child) (widget-apply child :value-inline))
2846                          (widget-get widget :children))))
2847
2848 (defun widget-editable-list-match (widget value)
2849   ;; Value must be a list and all the members must match the type.
2850   (and (listp value)
2851        (null (cdr (widget-editable-list-match-inline widget value)))))
2852
2853 (defun widget-editable-list-match-inline (widget value)
2854   (let ((type (nth 0 (widget-get widget :args)))
2855         (ok t)
2856         found)
2857     (while (and value ok)
2858       (let ((answer (widget-match-inline type value)))
2859         (if answer
2860             (setq found (append found (car answer))
2861                   value (cdr answer))
2862           (setq ok nil))))
2863     (cons found value)))
2864
2865 (defun widget-editable-list-insert-before (widget before)
2866   ;; Insert a new child in the list of children.
2867   (save-excursion
2868     (let ((children (widget-get widget :children))
2869           (inhibit-read-only t)
2870           before-change-functions
2871           after-change-functions)
2872       (cond (before
2873              (goto-char (widget-get before :entry-from)))
2874             (t
2875              (goto-char (widget-get widget :value-pos))))
2876       (let ((child (widget-editable-list-entry-create
2877                     widget nil nil)))
2878         (when (< (widget-get child :entry-from) (widget-get widget :from))
2879           (set-marker (widget-get widget :from)
2880                       (widget-get child :entry-from)))
2881         (if (eq (car children) before)
2882             (widget-put widget :children (cons child children))
2883           (while (not (eq (car (cdr children)) before))
2884             (setq children (cdr children)))
2885           (setcdr children (cons child (cdr children)))))))
2886   (widget-setup)
2887   (widget-apply widget :notify widget))
2888
2889 (defun widget-editable-list-delete-at (widget child)
2890   ;; Delete child from list of children.
2891   (save-excursion
2892     (let ((buttons (copy-sequence (widget-get widget :buttons)))
2893           button
2894           (inhibit-read-only t)
2895           before-change-functions
2896           after-change-functions)
2897       (while buttons
2898         (setq button (car buttons)
2899               buttons (cdr buttons))
2900         (when (eq (widget-get button :widget) child)
2901           (widget-put widget
2902                       :buttons (delq button (widget-get widget :buttons)))
2903           (widget-delete button))))
2904     (let ((entry-from (widget-get child :entry-from))
2905           (entry-to (widget-get child :entry-to))
2906           (inhibit-read-only t)
2907           before-change-functions
2908           after-change-functions)
2909       (widget-delete child)
2910       (delete-region entry-from entry-to)
2911       (set-marker entry-from nil)
2912       (set-marker entry-to nil))
2913     (widget-put widget :children (delq child (widget-get widget :children))))
2914   (widget-setup)
2915   (widget-apply widget :notify widget))
2916
2917 (defun widget-editable-list-entry-create (widget value conv)
2918   ;; Create a new entry to the list.
2919   (let ((type (nth 0 (widget-get widget :args)))
2920         (widget-push-button-gui widget-editable-list-gui)
2921         child delete insert)
2922     (widget-specify-insert
2923      (save-excursion
2924        (and (widget-get widget :indent)
2925             (insert-char ?\  (widget-get widget :indent)))
2926        (insert (widget-get widget :entry-format)))
2927      ;; Parse % escapes in format.
2928      (while (re-search-forward "%\\(.\\)" nil t)
2929        (let ((escape (aref (match-string 1) 0)))
2930          (replace-match "" t t)
2931          (cond ((eq escape ?%)
2932                 (insert "%"))
2933                ((eq escape ?i)
2934                 (setq insert (apply 'widget-create-child-and-convert
2935                                     widget 'insert-button
2936                                     (widget-get widget :insert-button-args))))
2937                ((eq escape ?d)
2938                 (setq delete (apply 'widget-create-child-and-convert
2939                                     widget 'delete-button
2940                                     (widget-get widget :delete-button-args))))
2941                ((eq escape ?v)
2942                 (if conv
2943                     (setq child (widget-create-child-value
2944                                  widget type value))
2945                   (setq child (widget-create-child-value
2946                                widget type (widget-default-get type)))))
2947                (t
2948                 (signal 'error (list "Unknown escape" escape))))))
2949      (widget-put widget
2950                  :buttons (cons delete
2951                                 (cons insert
2952                                       (widget-get widget :buttons))))
2953      (let ((entry-from (copy-marker (point-min)))
2954            (entry-to (copy-marker (point-max))))
2955        (set-marker-insertion-type entry-from t)
2956        (set-marker-insertion-type entry-to nil)
2957        (widget-put child :entry-from entry-from)
2958        (widget-put child :entry-to entry-to)))
2959     (widget-put insert :widget child)
2960     (widget-put delete :widget child)
2961     child))
2962
2963 ;;; The `group' Widget.
2964
2965 (define-widget 'group 'default
2966   "A widget which group other widgets inside."
2967   :convert-widget 'widget-types-convert-widget
2968   :format "%v"
2969   :value-create 'widget-group-value-create
2970   :value-delete 'widget-children-value-delete
2971   :value-get 'widget-editable-list-value-get
2972   :default-get 'widget-group-default-get
2973   :validate 'widget-children-validate
2974   :match 'widget-group-match
2975   :match-inline 'widget-group-match-inline)
2976
2977 (defun widget-group-value-create (widget)
2978   ;; Create each component.
2979   (let ((args (widget-get widget :args))
2980         (value (widget-get widget :value))
2981         arg answer children)
2982     (while args
2983       (setq arg (car args)
2984             args (cdr args)
2985             answer (widget-match-inline arg value)
2986             value (cdr answer))
2987       (and (eq (preceding-char) ?\n)
2988            (widget-get widget :indent)
2989            (insert-char ?\  (widget-get widget :indent)))
2990       (push (cond ((null answer)
2991                    (widget-create-child widget arg))
2992                   ((widget-get arg :inline)
2993                    (widget-create-child-value widget arg  (car answer)))
2994                   (t
2995                    (widget-create-child-value widget arg  (car (car answer)))))
2996             children))
2997     (widget-put widget :children (nreverse children))))
2998
2999 (defun widget-group-default-get (widget)
3000   ;; Get the default of the components.
3001   (mapcar 'widget-default-get (widget-get widget :args)))
3002
3003 (defun widget-group-match (widget values)
3004   ;; Match if the components match.
3005   (and (listp values)
3006        (let ((match (widget-group-match-inline widget values)))
3007          (and match (null (cdr match))))))
3008
3009 (defun widget-group-match-inline (widget vals)
3010   ;; Match if the components match.
3011   (let ((args (widget-get widget :args))
3012         argument answer found)
3013     (while args
3014       (setq argument (car args)
3015             args (cdr args)
3016             answer (widget-match-inline argument vals))
3017       (if answer
3018           (setq vals (cdr answer)
3019                 found (append found (car answer)))
3020         (setq vals nil
3021               args nil)))
3022     (if answer
3023         (cons found vals)
3024       nil)))
3025
3026 ;;; The `visibility' Widget.
3027
3028 (define-widget 'visibility 'item
3029   "An indicator and manipulator for hidden items."
3030   :format "%[%v%]"
3031   :button-prefix ""
3032   :button-suffix ""
3033   :on "Hide"
3034   :off "Show"
3035   :value-create 'widget-visibility-value-create
3036   :action 'widget-toggle-action
3037   :match (lambda (widget value) t))
3038
3039 (defun widget-visibility-value-create (widget)
3040   ;; Insert text representing the `on' and `off' states.
3041   (let ((on (widget-get widget :on))
3042         (off (widget-get widget :off)))
3043     (if on
3044         (setq on (concat widget-push-button-prefix
3045                          on
3046                          widget-push-button-suffix))
3047       (setq on ""))
3048     (if off
3049         (setq off (concat widget-push-button-prefix
3050                           off
3051                           widget-push-button-suffix))
3052       (setq off ""))
3053     (if (widget-value widget)
3054         (widget-glyph-insert widget on '("down" "down-pushed"))
3055       (widget-glyph-insert widget off '("right" "right-pushed")))))
3056
3057 ;;; The `documentation-link' Widget.
3058 ;;
3059 ;; This is a helper widget for `documentation-string'.
3060
3061 (define-widget 'documentation-link 'link
3062   "Link type used in documentation strings."
3063   :tab-order -1
3064   :help-echo 'widget-documentation-link-echo-help
3065   :action 'widget-documentation-link-action)
3066
3067 (defun widget-documentation-link-echo-help (widget)
3068   "Tell what this link will describe."
3069   (concat "Describe the `" (widget-get widget :value) "' symbol."))
3070
3071 (defun widget-documentation-link-action (widget &optional event)
3072   "Display documentation for WIDGET's value.  Ignore optional argument EVENT."
3073   (let* ((string (widget-get widget :value))
3074          (symbol (intern string)))
3075     (if (and (fboundp symbol) (boundp symbol))
3076         ;; If there are two doc strings, give the user a way to pick one.
3077         (apropos (concat "\\`" (regexp-quote string) "\\'"))
3078       (if (fboundp symbol)
3079           (describe-function symbol)
3080         (describe-variable symbol)))))
3081
3082 (defcustom widget-documentation-links t
3083   "Add hyperlinks to documentation strings when non-nil."
3084   :type 'boolean
3085   :group 'widget-documentation)
3086
3087 (defcustom widget-documentation-link-regexp "`\\([^\n`' ]+\\)'"
3088   "Regexp for matching potential links in documentation strings.
3089 The first group should be the link itself."
3090   :type 'regexp
3091   :group 'widget-documentation)
3092
3093 (defcustom widget-documentation-link-p 'intern-soft
3094   "Predicate used to test if a string is useful as a link.
3095 The value should be a function.  The function will be called one
3096 argument, a string, and should return non-nil if there should be a
3097 link for that string."
3098   :type 'function
3099   :options '(widget-documentation-link-p)
3100   :group 'widget-documentation)
3101
3102 (defcustom widget-documentation-link-type 'documentation-link
3103   "Widget type used for links in documentation strings."
3104   :type 'symbol
3105   :group 'widget-documentation)
3106
3107 (defun widget-documentation-link-add (widget from to)
3108   (widget-specify-doc widget from to)
3109   (when widget-documentation-links
3110     (let ((regexp widget-documentation-link-regexp)
3111           (predicate widget-documentation-link-p)
3112           (type widget-documentation-link-type)
3113           (buttons (widget-get widget :buttons)))
3114       (save-excursion
3115         (goto-char from)
3116         (while (re-search-forward regexp to t)
3117           (let ((name (match-string 1))
3118                 (begin (match-beginning 1))
3119                 (end (match-end 1)))
3120             (when (funcall predicate name)
3121               (push (widget-convert-button type begin end :value name)
3122                     buttons)))))
3123       (widget-put widget :buttons buttons)))
3124   (let ((indent (widget-get widget :indent)))
3125     (when (and indent (not (zerop indent)))
3126       (save-excursion
3127         (save-restriction
3128           (narrow-to-region from to)
3129           (goto-char (point-min))
3130           (while (search-forward "\n" nil t)
3131             (insert-char ?\  indent)))))))
3132
3133 ;;; The `documentation-string' Widget.
3134
3135 (define-widget 'documentation-string 'item
3136   "A documentation string."
3137   :format "%v"
3138   :action 'widget-documentation-string-action
3139   :value-delete 'widget-children-value-delete
3140   :value-create 'widget-documentation-string-value-create)
3141
3142 (defun widget-documentation-string-value-create (widget)
3143   ;; Insert documentation string.
3144   (let ((doc (widget-value widget))
3145         (indent (widget-get widget :indent))
3146         (shown (widget-get (widget-get widget :parent) :documentation-shown))
3147         (start (point)))
3148     (if (string-match "\n" doc)
3149         (let ((before (substring doc 0 (match-beginning 0)))
3150               (after (substring doc (match-beginning 0)))
3151               buttons)
3152           (insert before " ")
3153           (widget-documentation-link-add widget start (point))
3154           (push (widget-create-child-and-convert
3155                  widget 'visibility
3156                  :help-echo (lambda (widget)
3157                               (concat
3158                                (if (widget-value widget)
3159                                    "Hide" "Show")
3160                                " the rest of the documentation"))
3161                  :off "More"
3162                  :action 'widget-parent-action
3163                  shown)
3164                 buttons)
3165           (when shown
3166             (setq start (point))
3167             (when indent
3168               (insert-char ?\  indent))
3169             (insert after)
3170             (widget-documentation-link-add widget start (point)))
3171           (widget-put widget :buttons buttons))
3172       (insert doc)
3173       (widget-documentation-link-add widget start (point))))
3174   (insert "\n"))
3175
3176 (defun widget-documentation-string-action (widget &rest ignore)
3177   ;; Toggle documentation.
3178   (let ((parent (widget-get widget :parent)))
3179     (widget-put parent :documentation-shown
3180                 (not (widget-get parent :documentation-shown))))
3181   ;; Redraw.
3182   (widget-value-set widget (widget-value widget)))
3183
3184 ;;; The Sexp Widgets.
3185
3186 (define-widget 'const 'item
3187   "An immutable sexp."
3188   :prompt-value 'widget-const-prompt-value
3189   :format "%t\n%d")
3190
3191 (defun widget-const-prompt-value (widget prompt value unbound)
3192   ;; Return the value of the const.
3193   (widget-value widget))
3194
3195 (define-widget 'function-item 'const
3196   "An immutable function name."
3197   :format "%v\n%h"
3198   :documentation-property (lambda (symbol)
3199                             (condition-case nil
3200                                 (documentation symbol t)
3201                               (error nil))))
3202
3203 (define-widget 'variable-item 'const
3204   "An immutable variable name."
3205   :format "%v\n%h"
3206   :documentation-property 'variable-documentation)
3207
3208 (defvar widget-string-prompt-value-history nil
3209   "History of input to `widget-string-prompt-value'.")
3210
3211 (define-widget 'string 'editable-field
3212   "A string"
3213   :tag "String"
3214   :format "%{%t%}: %v"
3215   :complete-function 'ispell-complete-word
3216   :prompt-history 'widget-string-prompt-value-history)
3217
3218 (define-widget 'regexp 'string
3219   "A regular expression."
3220   :match 'widget-regexp-match
3221   :validate 'widget-regexp-validate
3222   ;; Doesn't work well with terminating newline.
3223   ;; :value-face 'widget-single-line-field-face
3224   :tag "Regexp")
3225
3226 (defun widget-regexp-match (widget value)
3227   ;; Match valid regexps.
3228   (and (stringp value)
3229        (condition-case nil
3230            (prog1 t
3231              (string-match value ""))
3232          (error nil))))
3233
3234 (defun widget-regexp-validate (widget)
3235   "Check that the value of WIDGET is a valid regexp."
3236   (let ((value (widget-value widget)))
3237     (condition-case data
3238         (prog1 nil
3239           (string-match value ""))
3240       (error (widget-put widget :error (error-message-string data))
3241              widget))))
3242
3243 (define-widget 'file 'string
3244   "A file widget.
3245 It will read a file name from the minibuffer when invoked."
3246   :complete-function 'widget-file-complete
3247   :prompt-value 'widget-file-prompt-value
3248   :format "%{%t%}: %v"
3249   ;; Doesn't work well with terminating newline.
3250   ;; :value-face 'widget-single-line-field-face
3251   :tag "File")
3252
3253 (defun widget-file-complete ()
3254   "Perform completion on file name preceding point."
3255   (interactive)
3256   (let* ((end (point))
3257          (beg (save-excursion
3258                 (skip-chars-backward "^ ")
3259                 (point)))
3260          (pattern (buffer-substring beg end))
3261          (name-part (file-name-nondirectory pattern))
3262          (directory (file-name-directory pattern))
3263          (completion (file-name-completion name-part directory)))
3264     (cond ((eq completion t))
3265           ((null completion)
3266            (message "Can't find completion for \"%s\"" pattern)
3267            (ding))
3268           ((not (string= name-part completion))
3269            (delete-region beg end)
3270            (insert (expand-file-name completion directory)))
3271           (t
3272            (message "Making completion list...")
3273            (let ((list (file-name-all-completions name-part directory)))
3274              (setq list (sort list 'string<))
3275              (with-output-to-temp-buffer "*Completions*"
3276                (display-completion-list list)))
3277            (message "Making completion list...%s" "done")))))
3278
3279 (defun widget-file-prompt-value (widget prompt value unbound)
3280   ;; Read file from minibuffer.
3281   (abbreviate-file-name
3282    (if unbound
3283        (read-file-name prompt)
3284      (let ((prompt2 (format "%s (default %s) " prompt value))
3285            (dir (file-name-directory value))
3286            (file (file-name-nondirectory value))
3287            (must-match (widget-get widget :must-match)))
3288        (read-file-name prompt2 dir nil must-match file)))))
3289
3290 ;;;(defun widget-file-action (widget &optional event)
3291 ;;;  ;; Read a file name from the minibuffer.
3292 ;;;  (let* ((value (widget-value widget))
3293 ;;;      (dir (file-name-directory value))
3294 ;;;      (file (file-name-nondirectory value))
3295 ;;;      (menu-tag (widget-apply widget :menu-tag-get))
3296 ;;;      (must-match (widget-get widget :must-match))
3297 ;;;      (answer (read-file-name (concat menu-tag ": (default `" value "') ")
3298 ;;;                              dir nil must-match file)))
3299 ;;;    (widget-value-set widget (abbreviate-file-name answer))
3300 ;;;    (widget-setup)
3301 ;;;    (widget-apply widget :notify widget event)))
3302
3303 (define-widget 'directory 'file
3304   "A directory widget.
3305 It will read a directory name from the minibuffer when invoked."
3306   :tag "Directory")
3307
3308 (defvar widget-symbol-prompt-value-history nil
3309   "History of input to `widget-symbol-prompt-value'.")
3310
3311 (define-widget 'symbol 'editable-field
3312   "A lisp symbol."
3313   :value nil
3314   :tag "Symbol"
3315   :format "%{%t%}: %v"
3316   :match (lambda (widget value) (symbolp value))
3317   :complete-function 'lisp-complete-symbol
3318   :prompt-internal 'widget-symbol-prompt-internal
3319   :prompt-match 'symbolp
3320   :prompt-history 'widget-symbol-prompt-value-history
3321   :value-to-internal (lambda (widget value)
3322                        (if (symbolp value)
3323                            (symbol-name value)
3324                          value))
3325   :value-to-external (lambda (widget value)
3326                        (if (stringp value)
3327                            (intern value)
3328                          value)))
3329
3330 (defun widget-symbol-prompt-internal (widget prompt initial history)
3331   ;; Read file from minibuffer.
3332   (let ((answer (completing-read prompt obarray
3333                                  (widget-get widget :prompt-match)
3334                                  nil initial history)))
3335     (if (and (stringp answer)
3336              (not (zerop (length answer))))
3337         answer
3338       (error "No value"))))
3339
3340 (defvar widget-function-prompt-value-history nil
3341   "History of input to `widget-function-prompt-value'.")
3342
3343 (define-widget 'function 'sexp
3344   "A lisp function."
3345   :complete-function 'lisp-complete-symbol
3346   :prompt-value 'widget-field-prompt-value
3347   :prompt-internal 'widget-symbol-prompt-internal
3348   :prompt-match 'fboundp
3349   :prompt-history 'widget-function-prompt-value-history
3350   :action 'widget-field-action
3351   :tag "Function")
3352
3353 (defvar widget-variable-prompt-value-history nil
3354   "History of input to `widget-variable-prompt-value'.")
3355
3356 (define-widget 'variable 'symbol
3357   ;; Should complete on variables.
3358   "A lisp variable."
3359   :prompt-match 'boundp
3360   :prompt-history 'widget-variable-prompt-value-history
3361   :tag "Variable")
3362
3363 ;; This part issues a warning when compiling without Mule.  Is there a
3364 ;; way of shutting it up?
3365 ;;
3366 ;; OK, I'll simply comment the whole thing out, until someone decides
3367 ;; to do something with it.
3368 ;(defvar widget-coding-system-prompt-value-history nil
3369 ;  "History of input to `widget-coding-system-prompt-value'.")
3370
3371 ;(define-widget 'coding-system 'symbol
3372 ;  "A MULE coding-system."
3373 ;  :format "%{%t%}: %v"
3374 ;  :tag "Coding system"
3375 ;  :prompt-history 'widget-coding-system-prompt-value-history
3376 ;  :prompt-value 'widget-coding-system-prompt-value
3377 ;  :action 'widget-coding-system-action)
3378
3379 ;(defun widget-coding-system-prompt-value (widget prompt value unbound)
3380 ;  ;; Read coding-system from minibuffer.
3381 ;  (intern
3382 ;   (completing-read (format "%s (default %s) " prompt value)
3383 ;                   (mapcar (lambda (sym)
3384 ;                             (list (symbol-name sym)))
3385 ;                           (coding-system-list)))))
3386
3387 ;(defun widget-coding-system-action (widget &optional event)
3388 ;  ;; Read a file name from the minibuffer.
3389 ;  (let ((answer
3390 ;        (widget-coding-system-prompt-value
3391 ;         widget
3392 ;         (widget-apply widget :menu-tag-get)
3393 ;         (widget-value widget)
3394 ;         t)))
3395 ;    (widget-value-set widget answer)
3396 ;    (widget-apply widget :notify widget event)
3397 ;    (widget-setup)))
3398
3399 (define-widget 'sexp 'editable-field
3400   "An arbitrary lisp expression."
3401   :tag "Lisp expression"
3402   :format "%{%t%}: %v"
3403   :value nil
3404   :validate 'widget-sexp-validate
3405   :match (lambda (widget value) t)
3406   :value-to-internal 'widget-sexp-value-to-internal
3407   :value-to-external (lambda (widget value) (read value))
3408   :prompt-history 'widget-sexp-prompt-value-history
3409   :prompt-value 'widget-sexp-prompt-value)
3410
3411 (defun widget-sexp-value-to-internal (widget value)
3412   ;; Use cl-prettyprint for printer representation.
3413   (let ((pp (if (symbolp value)
3414                 (prin1-to-string value)
3415               (widget-prettyprint-to-string value))))
3416     (if (> (length pp) 40)
3417         (concat "\n" pp)
3418       pp)))
3419
3420 (defun widget-sexp-validate (widget)
3421   ;; Valid if we can read the string and there is no junk left after it.
3422   (save-excursion
3423     (let ((buffer (set-buffer (get-buffer-create " *Widget Scratch*"))))
3424       (erase-buffer)
3425       (insert (widget-apply widget :value-get))
3426       (goto-char (point-min))
3427       (condition-case data
3428           (let ((value (read buffer)))
3429             (if (eobp)
3430                 (if (widget-apply widget :match value)
3431                     nil
3432                   (widget-put widget :error (widget-get widget :type-error))
3433                   widget)
3434               (widget-put widget
3435                           :error (format "Junk at end of expression: %s"
3436                                          (buffer-substring (point)
3437                                                            (point-max))))
3438               widget))
3439         (error (widget-put widget :error (error-message-string data))
3440                widget)))))
3441
3442 (defvar widget-sexp-prompt-value-history nil
3443   "History of input to `widget-sexp-prompt-value'.")
3444
3445 (defun widget-sexp-prompt-value (widget prompt value unbound)
3446   ;; Read an arbitrary sexp.
3447   (let ((found (read-string prompt
3448                             (if unbound nil (cons (prin1-to-string value) 0))
3449                             (widget-get widget :prompt-history))))
3450     (save-excursion
3451       (let ((buffer (set-buffer (get-buffer-create " *Widget Scratch*"))))
3452         (erase-buffer)
3453         (insert found)
3454         (goto-char (point-min))
3455         (let ((answer (read buffer)))
3456           (unless (eobp)
3457             (signal 'error
3458                     (list "Junk at end of expression"
3459                           (buffer-substring (point) (point-max)))))
3460           answer)))))
3461
3462 (define-widget 'restricted-sexp 'sexp
3463   "A Lisp expression restricted to values that match.
3464 To use this type, you must define :match or :match-alternatives."
3465   :type-error "The specified value is not valid"
3466   :match 'widget-restricted-sexp-match
3467   :value-to-internal (lambda (widget value)
3468                        (if (widget-apply widget :match value)
3469                            (prin1-to-string value)
3470                          value)))
3471
3472 (defun widget-restricted-sexp-match (widget value)
3473   (let ((alternatives (widget-get widget :match-alternatives))
3474         matched)
3475     (while (and alternatives (not matched))
3476       (if (cond ((functionp (car alternatives))
3477                  (funcall (car alternatives) value))
3478                 ((and (consp (car alternatives))
3479                       (eq (car (car alternatives)) 'quote))
3480                  (eq value (nth 1 (car alternatives)))))
3481           (setq matched t))
3482       (setq alternatives (cdr alternatives)))
3483     matched))
3484
3485 (define-widget 'integer 'restricted-sexp
3486   "An integer."
3487   :tag "Integer"
3488   :value 0
3489   :type-error "This field should contain an integer"
3490   :match-alternatives '(integerp))
3491
3492 (define-widget 'number 'restricted-sexp
3493   "A floating point number."
3494   :tag "Number"
3495   :value 0.0
3496   :type-error "This field should contain a number"
3497   :match-alternatives '(numberp))
3498
3499 (define-widget 'character 'editable-field
3500   "A character."
3501   :tag "Character"
3502   :value ?\0
3503   :format "%{%t%}: %v"
3504   :valid-regexp "\\`[\0-\377]\\'"
3505   :error "This field should contain a single character"
3506   :value-to-internal (lambda (widget value)
3507                        (if (stringp value)
3508                            value
3509                          (char-to-string value)))
3510   :value-to-external (lambda (widget value)
3511                        (if (stringp value)
3512                            (aref value 0)
3513                          value))
3514   :match (lambda (widget value)
3515            (characterp value)))
3516
3517 (define-widget 'list 'group
3518   "A lisp list."
3519   :tag "List"
3520   :format "%{%t%}:\n%v")
3521
3522 (define-widget 'vector 'group
3523   "A lisp vector."
3524   :tag "Vector"
3525   :format "%{%t%}:\n%v"
3526   :match 'widget-vector-match
3527   :value-to-internal (lambda (widget value) (append value nil))
3528   :value-to-external (lambda (widget value) (vconcat value)))
3529
3530 (defun widget-vector-match (widget value)
3531   (and (vectorp value)
3532        (widget-group-match widget
3533                            (widget-apply widget :value-to-internal value))))
3534
3535 (define-widget 'cons 'group
3536   "A cons-cell."
3537   :tag "Cons-cell"
3538   :format "%{%t%}:\n%v"
3539   :match 'widget-cons-match
3540   :value-to-internal (lambda (widget value)
3541                        (list (car value) (cdr value)))
3542   :value-to-external (lambda (widget value)
3543                        (cons (car value) (cadr value))))
3544
3545 (defun widget-cons-match (widget value)
3546   (and (consp value)
3547        (widget-group-match widget
3548                            (widget-apply widget :value-to-internal value))))
3549
3550 (define-widget 'choice 'menu-choice
3551   "A union of several sexp types."
3552   :tag "Choice"
3553   :format "%{%t%}: %[Value Menu%] %v"
3554   :button-prefix 'widget-push-button-prefix
3555   :button-suffix 'widget-push-button-suffix
3556   :prompt-value 'widget-choice-prompt-value)
3557
3558 (defun widget-choice-prompt-value (widget prompt value unbound)
3559   "Make a choice."
3560   (let ((args (widget-get widget :args))
3561         (completion-ignore-case (widget-get widget :case-fold))
3562         current choices old)
3563     ;; Find the first arg that match VALUE.
3564     (let ((look args))
3565       (while look
3566         (if (widget-apply (car look) :match value)
3567             (setq old (car look)
3568                   look nil)
3569           (setq look (cdr look)))))
3570     ;; Find new choice.
3571     (setq current
3572           (cond ((= (length args) 0)
3573                  nil)
3574                 ((= (length args) 1)
3575                  (nth 0 args))
3576                 ((and (= (length args) 2)
3577                       (memq old args))
3578                  (if (eq old (nth 0 args))
3579                      (nth 1 args)
3580                    (nth 0 args)))
3581                 (t
3582                  (while args
3583                    (setq current (car args)
3584                          args (cdr args))
3585                    (setq choices
3586                          (cons (cons (widget-apply current :menu-tag-get)
3587                                      current)
3588                                choices)))
3589                  (let ((val (completing-read prompt choices nil t)))
3590                    (if (stringp val)
3591                        (let ((try (try-completion val choices)))
3592                          (when (stringp try)
3593                            (setq val try))
3594                          (cdr (assoc val choices)))
3595                      nil)))))
3596     (if current
3597         (widget-prompt-value current prompt nil t)
3598       value)))
3599
3600 (define-widget 'radio 'radio-button-choice
3601   "A union of several sexp types."
3602   :tag "Choice"
3603   :format "%{%t%}:\n%v"
3604   :prompt-value 'widget-choice-prompt-value)
3605
3606 (define-widget 'repeat 'editable-list
3607   "A variable length homogeneous list."
3608   :tag "Repeat"
3609   :format "%{%t%}:\n%v%i\n")
3610
3611 (define-widget 'set 'checklist
3612   "A list of members from a fixed set."
3613   :tag "Set"
3614   :format "%{%t%}:\n%v")
3615
3616 (define-widget 'boolean 'toggle
3617   "To be nil or non-nil, that is the question."
3618   :tag "Boolean"
3619   :prompt-value 'widget-boolean-prompt-value
3620   :button-prefix 'widget-push-button-prefix
3621   :button-suffix 'widget-push-button-suffix
3622   :format "%{%t%}: %[Toggle%]  %v\n"
3623   :on "on (non-nil)"
3624   :off "off (nil)")
3625
3626 (defun widget-boolean-prompt-value (widget prompt value unbound)
3627   ;; Toggle a boolean.
3628   (y-or-n-p prompt))
3629
3630 ;;; The `color' Widget.
3631
3632 (define-widget 'color 'editable-field
3633   "Choose a color name (with sample)."
3634   :format "%[%t%]: %v (%{sample%})\n"
3635   :size 10
3636   :tag "Color"
3637   :value "black"
3638   :complete 'widget-color-complete
3639   :sample-face-get 'widget-color-sample-face-get
3640   :notify 'widget-color-notify
3641   :action 'widget-color-action)
3642
3643 (defun widget-color-complete (widget)
3644   "Complete the color in WIDGET."
3645   (let* ((prefix (buffer-substring-no-properties (widget-field-start widget)
3646                                                  (point)))
3647          (list (read-color-completion-table))
3648          (completion (try-completion prefix list)))
3649     (cond ((eq completion t)
3650            (message "Exact match"))
3651           ((null completion)
3652            (error "Can't find completion for \"%s\"" prefix))
3653           ((not (string-equal prefix completion))
3654            (insert (substring completion (length prefix))))
3655           (t
3656            (message "Making completion list...")
3657            (let ((list (all-completions prefix list nil)))
3658              (with-output-to-temp-buffer "*Completions*"
3659                (display-completion-list list)))
3660            (message "Making completion list...done")))))
3661
3662 (defun widget-color-sample-face-get (widget)
3663   (or (widget-get widget :sample-face)
3664       (let ((color (widget-value widget))
3665             (face (make-face (gensym "sample-face-") nil t)))
3666         ;; Use the face object, not its name, to prevent lossage if gc
3667         ;; happens before applying the face.
3668         (widget-put widget :sample-face face)
3669         (and color
3670              (not (equal color ""))
3671              (valid-color-name-p color)
3672              (set-face-foreground face color))
3673         face)))
3674
3675 (defvar widget-color-history nil
3676   "History of entered colors.")
3677
3678 (defun widget-color-action (widget &optional event)
3679   ;; Prompt for a color.
3680   (let* ((tag (widget-apply widget :menu-tag-get))
3681          (answer (read-color (concat tag ": "))))
3682     (unless (zerop (length answer))
3683       (widget-value-set widget answer)
3684       (widget-setup)
3685       (widget-apply widget :notify widget event))))
3686
3687 (defun widget-color-notify (widget child &optional event)
3688   "Update the sample, and notify the parent."
3689   (let* ((face (widget-apply widget :sample-face-get))
3690          (color (widget-value widget)))
3691     (if (valid-color-name-p color)
3692         (set-face-foreground face color)
3693       (remove-face-property face 'foreground)))
3694   (widget-default-notify widget child event))
3695
3696 ;; Is this a misnomer?
3697 (defun widget-at (pos)
3698   "The button or field at POS."
3699   (or (get-char-property pos 'button)
3700       (get-char-property pos 'field)))
3701
3702 (defun widget-echo-help (pos)
3703   "Display the help echo for widget at POS."
3704   (let* ((widget (widget-at pos))
3705          (help-echo (and widget (widget-get widget :help-echo))))
3706     (and (functionp help-echo)
3707          (setq help-echo (funcall help-echo widget)))
3708     (when (stringp help-echo)
3709       (display-message 'help-echo help-echo))))
3710
3711 ;;; The End:
3712
3713 (provide 'wid-edit)
3714
3715 ;; wid-edit.el ends here