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