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