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