Make FD_TO_USID available to non-unixoid event loops
[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)