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