wid-edit.el 124 KB
Newer Older
1
;;; wid-edit.el --- Functions for creating and using widgets -*-byte-compile-dynamic: t; lexical-binding:t -*-
Per Abrahamsen's avatar
Per Abrahamsen committed
2
;;
3
;; Copyright (C) 1996-1997, 1999-2013 Free Software Foundation, Inc.
Per Abrahamsen's avatar
Per Abrahamsen committed
4 5
;;
;; Author: Per Abrahamsen <abraham@dina.kvl.dk>
6
;; Maintainer: FSF
Per Abrahamsen's avatar
Per Abrahamsen committed
7
;; Keywords: extensions
8
;; Package: emacs
Per Abrahamsen's avatar
Per Abrahamsen committed
9

10 11
;; This file is part of GNU Emacs.

12
;; GNU Emacs is free software: you can redistribute it and/or modify
13
;; it under the terms of the GNU General Public License as published by
14 15
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
16 17 18 19 20 21 22

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
23
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
24

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
;;; Wishlist items (from widget.texi):

;; * The `menu-choice' tag should be prettier, something like the
;;   abbreviated menus in Open Look.

;; * Finish `:tab-order'.

;; * Make indentation work with glyphs and proportional fonts.

;; * Add commands to show overview of object and class hierarchies to
;;   the browser.

;; * Find a way to disable mouse highlight for inactive widgets.

;; * Find a way to make glyphs look inactive.

;; * Add `key-binding' widget.

;; * Add `widget' widget for editing widget specifications.

;; * Find clean way to implement variable length list.  See
;;   `TeX-printer-list' for an explanation.

;; * `C-h' in `widget-prompt-value' should give type specific help.

;; * A mailto widget. [This should work OK as a url-link if with
;;   browse-url-browser-function' set up appropriately.]

Per Abrahamsen's avatar
Per Abrahamsen committed
53 54 55 56 57 58 59
;;; Commentary:
;;
;; See `widget.el'.

;;; Code:

;;; Compatibility.
60

61 62
(defun widget-event-point (event)
  "Character position of the end of event if that exists, or nil."
63
  (posn-point (event-end event)))
64

65 66 67 68 69 70
(defun widget-button-release-event-p (event)
  "Non-nil if EVENT is a mouse-button-release event object."
  (and (eventp event)
       (memq (event-basic-type event) '(mouse-1 mouse-2 mouse-3))
       (or (memq 'click (event-modifiers event))
	   (memq  'drag (event-modifiers event)))))
Per Abrahamsen's avatar
Per Abrahamsen committed
71 72 73 74 75 76

;;; Customization.

(defgroup widgets nil
  "Customization support for the Widget Library."
  :link '(custom-manual "(widget)Top")
Per Abrahamsen's avatar
Per Abrahamsen committed
77
  :link '(emacs-library-link :tag "Lisp File" "widget.el")
Per Abrahamsen's avatar
Per Abrahamsen committed
78
  :prefix "widget-"
79
  :group 'extensions)
Per Abrahamsen's avatar
Per Abrahamsen committed
80

Per Abrahamsen's avatar
Per Abrahamsen committed
81
(defgroup widget-documentation nil
82
  "Options controlling the display of documentation strings."
Per Abrahamsen's avatar
Per Abrahamsen committed
83 84
  :group 'widgets)

Per Abrahamsen's avatar
Per Abrahamsen committed
85 86 87 88 89
(defgroup widget-faces nil
  "Faces used by the widget library."
  :group 'widgets
  :group 'faces)

90
(defvar widget-documentation-face 'widget-documentation
91
  "Face used for documentation strings in widgets.
92 93
This exists as a variable so it can be set locally in certain buffers.")

94 95 96 97 98 99 100
(defface widget-documentation '((((class color)
				  (background dark))
				 (:foreground "lime green"))
				(((class color)
				  (background light))
				 (:foreground "dark green"))
				(t nil))
Per Abrahamsen's avatar
Per Abrahamsen committed
101 102 103
  "Face used for documentation text."
  :group 'widget-documentation
  :group 'widget-faces)
104 105
(define-obsolete-face-alias 'widget-documentation-face
  'widget-documentation "22.1")
Per Abrahamsen's avatar
Per Abrahamsen committed
106

107
(defvar widget-button-face 'widget-button
108
  "Face used for buttons in widgets.
109 110
This exists as a variable so it can be set locally in certain buffers.")

111
(defface widget-button '((t (:weight bold)))
Per Abrahamsen's avatar
Per Abrahamsen committed
112
  "Face used for widget buttons."
Per Abrahamsen's avatar
Per Abrahamsen committed
113
  :group 'widget-faces)
114
(define-obsolete-face-alias 'widget-button-face 'widget-button "22.1")
Per Abrahamsen's avatar
Per Abrahamsen committed
115 116 117 118

(defcustom widget-mouse-face 'highlight
  "Face used for widget buttons when the mouse is above them."
  :type 'face
Per Abrahamsen's avatar
Per Abrahamsen committed
119
  :group 'widget-faces)
Per Abrahamsen's avatar
Per Abrahamsen committed
120

121 122 123
;; TTY gets special definitions here and in the next defface, because
;; the gray colors defined for other displays cause black text on a black
;; background, at least on light-background TTYs.
124 125 126 127 128 129 130 131 132 133 134
(defface widget-field '((((type tty))
			 :background "yellow3"
			 :foreground "black")
			(((class grayscale color)
			  (background light))
			 :background "gray85")
			(((class grayscale color)
			  (background dark))
			 :background "dim gray")
			(t
			 :slant italic))
Per Abrahamsen's avatar
Per Abrahamsen committed
135
  "Face used for editable fields."
Per Abrahamsen's avatar
Per Abrahamsen committed
136
  :group 'widget-faces)
137
(define-obsolete-face-alias 'widget-field-face 'widget-field "22.1")
138 139 140 141 142 143 144 145 146 147 148 149

(defface widget-single-line-field '((((type tty))
				     :background "green3"
				     :foreground "black")
				    (((class grayscale color)
				      (background light))
				     :background "gray85")
				    (((class grayscale color)
				      (background dark))
				     :background "dim gray")
				    (t
				     :slant italic))
Per Abrahamsen's avatar
Per Abrahamsen committed
150 151
  "Face used for editable fields spanning only a single line."
  :group 'widget-faces)
152 153
(define-obsolete-face-alias 'widget-single-line-field-face
  'widget-single-line-field "22.1")
Per Abrahamsen's avatar
Per Abrahamsen committed
154

155 156 157 158 159 160 161 162 163 164 165
;;; This causes display-table to be loaded, and not usefully.
;;;(defvar widget-single-line-display-table
;;;  (let ((table (make-display-table)))
;;;    (aset table 9  "^I")
;;;    (aset table 10 "^J")
;;;    table)
;;;  "Display table used for single-line editable fields.")

;;;(when (fboundp 'set-face-display-table)
;;;  (set-face-display-table 'widget-single-line-field-face
;;;			  widget-single-line-display-table))
Per Abrahamsen's avatar
Per Abrahamsen committed
166

Per Abrahamsen's avatar
Per Abrahamsen committed
167 168 169 170 171
;;; Utility functions.
;;
;; These are not really widget specific.

(defun widget-princ-to-string (object)
172 173 174 175 176
  "Return string representation of OBJECT, any Lisp object.
No quoting characters are used; no delimiters are printed around
the contents of strings."
  (with-output-to-string
      (princ object)))
Per Abrahamsen's avatar
Per Abrahamsen committed
177 178 179 180 181 182

(defun widget-clear-undo ()
  "Clear all undo information."
  (buffer-disable-undo (current-buffer))
  (buffer-enable-undo))

Per Abrahamsen's avatar
Per Abrahamsen committed
183 184 185 186 187 188
(defcustom widget-menu-max-size 40
  "Largest number of items allowed in a popup-menu.
Larger menus are read through the minibuffer."
  :group 'widgets
  :type 'integer)

189 190 191 192 193 194 195
(defcustom widget-menu-max-shortcuts 40
  "Largest number of items for which it works to choose one with a character.
For a larger number of items, the minibuffer is used."
  :group 'widgets
  :type 'integer)

(defcustom widget-menu-minibuffer-flag nil
Lute Kamstra's avatar
Lute Kamstra committed
196
  "Control how to ask for a choice from the keyboard.
197 198 199 200 201
Non-nil means use the minibuffer;
nil means read a single character."
  :group 'widgets
  :type 'boolean)

Per Abrahamsen's avatar
Per Abrahamsen committed
202 203 204 205
(defun widget-choose (title items &optional event)
  "Choose an item from a list.

First argument TITLE is the name of the list.
206
Second argument ITEMS is a list whose members are either
Per Abrahamsen's avatar
Per Abrahamsen committed
207 208
 (NAME . VALUE), to indicate selectable items, or just strings to
 indicate unselectable items.
Per Abrahamsen's avatar
Per Abrahamsen committed
209 210 211 212 213 214 215 216
Optional third argument EVENT is an input event.

The user is asked to choose between each NAME from the items alist,
and the VALUE of the chosen element will be returned.  If EVENT is a
mouse event, and the number of elements in items is less than
`widget-menu-max-size', a popup menu will be used, otherwise the
minibuffer."
  (cond ((and (< (length items) widget-menu-max-size)
217
	      event (display-popup-menus-p))
218
	 ;; Mouse click.
Per Abrahamsen's avatar
Per Abrahamsen committed
219 220
	 (x-popup-menu event
		       (list title (cons "" items))))
221 222
	((or widget-menu-minibuffer-flag
	     (> (length items) widget-menu-max-shortcuts))
223
	 ;; Read the choice of name from the minibuffer.
224
	 (setq items (widget-remove-if 'stringp items))
Per Abrahamsen's avatar
Per Abrahamsen committed
225 226 227 228 229
	 (let ((val (completing-read (concat title ": ") items nil t)))
	   (if (stringp val)
	       (let ((try (try-completion val items)))
		 (when (stringp try)
		   (setq val try))
230
		 (cdr (assoc val items))))))
231 232 233
	(t
	 ;; Construct a menu of the choices
	 ;; and then use it for prompting for a single character.
234 235 236
	 (let* ((overriding-terminal-local-map (make-sparse-keymap))
		(next-digit ?0)
		map choice some-choice-enabled value)
237 238 239
	   ;; Define SPC as a prefix char to get to this menu.
	   (define-key overriding-terminal-local-map " "
	     (setq map (make-sparse-keymap title)))
240
	   (with-current-buffer (get-buffer-create " widget-choose")
241 242 243 244 245 246 247 248
	     (erase-buffer)
	     (insert "Available choices:\n\n")
	     (while items
	       (setq choice (car items) items (cdr items))
	       (if (consp choice)
		   (let* ((name (car choice))
			 (function (cdr choice)))
		     (insert (format "%c = %s\n" next-digit name))
249 250
		     (define-key map (vector next-digit) function)
		     (setq some-choice-enabled t)))
251 252 253
	       ;; Allocate digits to disabled alternatives
	       ;; so that the digit of a given alternative never varies.
	       (setq next-digit (1+ next-digit)))
254 255 256
	     (insert "\nC-g = Quit")
	     (goto-char (point-min))
	     (forward-line))
257 258
	   (or some-choice-enabled
	       (error "None of the choices is currently meaningful"))
259
	   (define-key map [?\C-g] 'keyboard-quit)
260
	   (define-key map [t] 'keyboard-quit)
261 262
	   (define-key map [?\M-\C-v] 'scroll-other-window)
	   (define-key map [?\M--] 'negative-argument)
263 264 265
	   (setcdr map (nreverse (cdr map)))
	   ;; Read a char with the menu, and return the result
	   ;; that corresponds to it.
266
	   (save-window-excursion
267
	     (let ((buf (get-buffer " widget-choose")))
268
	       (fit-window-to-buffer (display-buffer buf))
269 270 271 272
	       (let ((cursor-in-echo-area t)
		     keys
		     (char 0)
		     (arg 1))
273 274
		 (while (not (or (and (integerp char)
				      (>= char ?0) (< char next-digit))
275 276
				 (eq value 'keyboard-quit)))
		   ;; Unread a SPC to lead to our new menu.
277
		   (setq unread-command-events (cons ?\s unread-command-events))
278
		   (setq keys (read-key-sequence title))
279 280
		   (setq value
			 (lookup-key overriding-terminal-local-map keys t)
281
			 char (aref keys 1))
282
		   (cond ((eq value 'scroll-other-window)
283 284
			  (let ((minibuffer-scroll-window
				 (get-buffer-window buf)))
285
			    (if (> 0 arg)
286 287
				(scroll-other-window-down
				 (window-height minibuffer-scroll-window))
288 289 290 291 292 293
			      (scroll-other-window))
			    (setq arg 1)))
			 ((eq value 'negative-argument)
			  (setq arg -1))
			 (t
			  (setq arg 1)))))))
294 295 296
	   (when (eq value 'keyboard-quit)
	     (error "Canceled"))
	   value))))
Per Abrahamsen's avatar
Per Abrahamsen committed
297

Paul Eggert's avatar
Paul Eggert committed
298
(defun widget-remove-if (predicate list)
299 300
  (let (result (tail list))
    (while tail
Paul Eggert's avatar
Paul Eggert committed
301
      (or (funcall predicate (car tail))
302 303 304 305
	  (setq result (cons (car tail) result)))
      (setq tail (cdr tail)))
    (nreverse result)))

Per Abrahamsen's avatar
Per Abrahamsen committed
306
;;; Widget text specifications.
307
;;
308
;; These functions are for specifying text properties.
Per Abrahamsen's avatar
Per Abrahamsen committed
309

310 311
;; We can set it to nil now that get_local_map uses get_pos_property.
(defconst widget-field-add-space nil
Per Abrahamsen's avatar
Per Abrahamsen committed
312 313
  "Non-nil means add extra space at the end of editable text fields.
If you don't add the space, it will become impossible to edit a zero
314
size field.")
Per Abrahamsen's avatar
Per Abrahamsen committed
315

316
(defvar widget-field-use-before-change t
Per Abrahamsen's avatar
Per Abrahamsen committed
317
  "Non-nil means use `before-change-functions' to track editable fields.
Glenn Morris's avatar
Glenn Morris committed
318 319
This enables the use of undo.  Using before hooks also means that
the :notify function can't know the new value.")
Per Abrahamsen's avatar
Per Abrahamsen committed
320

Per Abrahamsen's avatar
Per Abrahamsen committed
321
(defun widget-specify-field (widget from to)
Per Abrahamsen's avatar
Per Abrahamsen committed
322
  "Specify editable button for WIDGET between FROM and TO."
Per Abrahamsen's avatar
Per Abrahamsen committed
323 324 325 326 327
  ;; Terminating space is not part of the field, but necessary in
  ;; order for local-map to work.  Remove next sexp if local-map works
  ;; at the end of the overlay.
  (save-excursion
    (goto-char to)
Per Abrahamsen's avatar
Per Abrahamsen committed
328 329 330 331
    (cond ((null (widget-get widget :size))
	   (forward-char 1))
	  (widget-field-add-space
	   (insert-and-inherit " ")))
Per Abrahamsen's avatar
Per Abrahamsen committed
332
    (setq to (point)))
Miles Bader's avatar
Miles Bader committed
333
  (let ((keymap (widget-get widget :keymap))
334
	(face (or (widget-get widget :value-face) 'widget-field))
Miles Bader's avatar
Miles Bader committed
335
	(help-echo (widget-get widget :help-echo))
336
	(follow-link (widget-get widget :follow-link))
Miles Bader's avatar
Miles Bader committed
337 338
	(rear-sticky
	 (or (not widget-field-add-space) (widget-get widget :size))))
339
    (if (functionp help-echo)
340
      (setq help-echo 'widget-mouse-help))
341
    (when (= (char-before to) ?\n)
Miles Bader's avatar
Miles Bader committed
342 343 344
      ;; When the last character in the field is a newline, we want to
      ;; give it a `field' char-property of `boundary', which helps the
      ;; C-n/C-p act more naturally when entering/leaving the field.  We
345
     ;; do this by making a small secondary overlay to contain just that
Miles Bader's avatar
Miles Bader committed
346 347 348
      ;; one character.
      (let ((overlay (make-overlay (1- to) to nil t nil)))
	(overlay-put overlay 'field 'boundary)
349 350
        ;; We need the real field for tabbing.
	(overlay-put overlay 'real-field widget)
351 352 353
	;; Use `local-map' here, not `keymap', so that normal editing
	;; works in the field when, say, Custom uses `suppress-keymap'.
	(overlay-put overlay 'local-map keymap)
Miles Bader's avatar
Miles Bader committed
354
	(overlay-put overlay 'face face)
355
	(overlay-put overlay 'follow-link follow-link)
Miles Bader's avatar
Miles Bader committed
356 357 358 359 360 361 362
	(overlay-put overlay 'help-echo help-echo))
      (setq to (1- to))
      (setq rear-sticky t))
    (let ((overlay (make-overlay from to nil nil rear-sticky)))
      (widget-put widget :field-overlay overlay)
      ;;(overlay-put overlay 'detachable nil)
      (overlay-put overlay 'field widget)
363
      (overlay-put overlay 'local-map keymap)
Miles Bader's avatar
Miles Bader committed
364
      (overlay-put overlay 'face face)
365
      (overlay-put overlay 'follow-link follow-link)
Miles Bader's avatar
Miles Bader committed
366
      (overlay-put overlay 'help-echo help-echo)))
367 368 369 370 371 372 373 374 375
  (widget-specify-secret widget))

(defun widget-specify-secret (field)
  "Replace text in FIELD with value of `:secret', if non-nil."
  (let ((secret (widget-get field :secret))
	(size (widget-get field :size)))
    (when secret
      (let ((begin (widget-field-start field))
	    (end (widget-field-end field)))
376
	(when size
377
	  (while (and (> end begin)
378
		      (eq (char-after (1- end)) ?\s))
379 380 381 382 383 384 385
	    (setq end (1- end))))
	(while (< begin end)
	  (let ((old (char-after begin)))
	    (unless (eq old secret)
	      (subst-char-in-region begin (1+ begin) old secret)
	      (put-text-property begin (1+ begin) 'secret old))
	    (setq begin (1+ begin))))))))
Per Abrahamsen's avatar
Per Abrahamsen committed
386 387

(defun widget-specify-button (widget from to)
Per Abrahamsen's avatar
Per Abrahamsen committed
388
  "Specify button for WIDGET between FROM and TO."
389
  (let ((overlay (make-overlay from to nil t nil))
390
	(follow-link (widget-get widget :follow-link))
391
	(help-echo (widget-get widget :help-echo)))
Per Abrahamsen's avatar
Per Abrahamsen committed
392
    (widget-put widget :button-overlay overlay)
393 394
    (if (functionp help-echo)
      (setq help-echo 'widget-mouse-help))
Per Abrahamsen's avatar
Per Abrahamsen committed
395
    (overlay-put overlay 'button widget)
396
    (overlay-put overlay 'keymap (widget-get widget :keymap))
397
    (overlay-put overlay 'evaporate t)
398 399
    ;; We want to avoid the face with image buttons.
    (unless (widget-get widget :suppress-face)
400
      (overlay-put overlay 'face (widget-apply widget :button-face-get))
401
      (overlay-put overlay 'mouse-face
402 403 404 405 406 407 408 409 410 411 412
		   ;; Make new list structure for the mouse-face value
		   ;; so that different widgets will have
		   ;; different `mouse-face' property values
		   ;; and will highlight separately.
		   (let ((mouse-face-value
			  (widget-apply widget :mouse-face-get)))
		     ;; If it's a list, copy it.
		     (if (listp mouse-face-value)
			 (copy-sequence mouse-face-value)
		       ;; If it's a symbol, put it in a list.
		       (list mouse-face-value)))))
413
    (overlay-put overlay 'pointer 'hand)
414
    (overlay-put overlay 'follow-link follow-link)
415 416
    (overlay-put overlay 'help-echo help-echo)))

417
(defun widget-mouse-help (_window overlay _point)
418 419 420 421 422 423 424
  "Help-echo callback for widgets whose :help-echo is a function."
  (with-current-buffer (overlay-buffer overlay)
    (let* ((widget (widget-at (overlay-start overlay)))
	   (help-echo (if widget (widget-get widget :help-echo))))
      (if (functionp help-echo)
	  (funcall help-echo widget)
	help-echo))))
Per Abrahamsen's avatar
Per Abrahamsen committed
425 426

(defun widget-specify-sample (widget from to)
427
  "Specify sample for WIDGET between FROM and TO."
428 429
  (let ((overlay (make-overlay from to nil t nil)))
    (overlay-put overlay 'face (widget-apply widget :sample-face-get))
430
    (overlay-put overlay 'evaporate t)
Per Abrahamsen's avatar
Per Abrahamsen committed
431 432
    (widget-put widget :sample-overlay overlay)))

Per Abrahamsen's avatar
Per Abrahamsen committed
433
(defun widget-specify-doc (widget from to)
434
  "Specify documentation for WIDGET between FROM and TO."
Per Abrahamsen's avatar
Per Abrahamsen committed
435 436 437
  (let ((overlay (make-overlay from to nil t nil)))
    (overlay-put overlay 'widget-doc widget)
    (overlay-put overlay 'face widget-documentation-face)
438
    (overlay-put overlay 'evaporate t)
Per Abrahamsen's avatar
Per Abrahamsen committed
439
    (widget-put widget :doc-overlay overlay)))
Per Abrahamsen's avatar
Per Abrahamsen committed
440 441

(defmacro widget-specify-insert (&rest form)
442 443 444
  "Execute FORM without inheriting any text properties."
  `(save-restriction
    (let ((inhibit-read-only t)
445 446 447 448
	  (inhibit-modification-hooks t))
      (narrow-to-region (point) (point))
      (prog1 (progn ,@form)
	(goto-char (point-max))))))
Per Abrahamsen's avatar
Per Abrahamsen committed
449

450 451
(defface widget-inactive
  '((t :inherit shadow))
Per Abrahamsen's avatar
Per Abrahamsen committed
452
  "Face used for inactive widgets."
Per Abrahamsen's avatar
Per Abrahamsen committed
453
  :group 'widget-faces)
454 455
(define-obsolete-face-alias 'widget-inactive-face
  'widget-inactive "22.1")
Per Abrahamsen's avatar
Per Abrahamsen committed
456 457 458 459 460

(defun widget-specify-inactive (widget from to)
  "Make WIDGET inactive for user modifications."
  (unless (widget-get widget :inactive)
    (let ((overlay (make-overlay from to nil t nil)))
461
      (overlay-put overlay 'face 'widget-inactive)
Per Abrahamsen's avatar
Per Abrahamsen committed
462
      ;; This is disabled, as it makes the mouse cursor change shape.
463
      ;; (overlay-put overlay 'mouse-face 'widget-inactive)
Per Abrahamsen's avatar
Per Abrahamsen committed
464 465
      (overlay-put overlay 'evaporate t)
      (overlay-put overlay 'priority 100)
466
      (overlay-put overlay 'modification-hooks '(widget-overlay-inactive))
Per Abrahamsen's avatar
Per Abrahamsen committed
467 468
      (widget-put widget :inactive overlay))))

469
(defun widget-overlay-inactive (&rest _junk)
Per Abrahamsen's avatar
Per Abrahamsen committed
470 471
  "Ignoring the arguments, signal an error."
  (unless inhibit-read-only
472
    (error "The widget here is not active")))
Per Abrahamsen's avatar
Per Abrahamsen committed
473 474 475 476 477 478 479 480 481 482 483 484


(defun widget-specify-active (widget)
  "Make WIDGET active for user modifications."
  (let ((inactive (widget-get widget :inactive)))
    (when inactive
      (delete-overlay inactive)
      (widget-put widget :inactive nil))))

;;; Widget Properties.

(defsubst widget-type (widget)
Richard M. Stallman's avatar
Richard M. Stallman committed
485
  "Return the type of WIDGET.  The type is a symbol."
Per Abrahamsen's avatar
Per Abrahamsen committed
486 487
  (car widget))

488 489
;;;###autoload
(defun widgetp (widget)
490
  "Return non-nil if WIDGET is a widget."
491 492 493
  (if (symbolp widget)
      (get widget 'widget-type)
    (and (consp widget)
494 495
	 (symbolp (car widget))
	 (get (car widget) 'widget-type))))
496

Per Abrahamsen's avatar
Per Abrahamsen committed
497 498
(defun widget-get-indirect (widget property)
  "In WIDGET, get the value of PROPERTY.
499
If the value is a symbol, return its binding.
Per Abrahamsen's avatar
Per Abrahamsen committed
500 501 502 503 504 505
Otherwise, just return the value."
  (let ((value (widget-get widget property)))
    (if (symbolp value)
	(symbol-value value)
      value)))

Per Abrahamsen's avatar
Per Abrahamsen committed
506
(defun widget-member (widget property)
507
  "Non-nil if there is a definition in WIDGET for PROPERTY."
508
  (cond ((plist-member (cdr widget) property)
Per Abrahamsen's avatar
Per Abrahamsen committed
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
	 t)
	((car widget)
	 (widget-member (get (car widget) 'widget-type) property))
	(t nil)))

(defun widget-value (widget)
  "Extract the current value of WIDGET."
  (widget-apply widget
		:value-to-external (widget-apply widget :value-get)))

(defun widget-value-set (widget value)
  "Set the current value of WIDGET to VALUE."
  (widget-apply widget
		:value-set (widget-apply widget
					 :value-to-internal value)))

525
(defun widget-default-get (widget)
Per Abrahamsen's avatar
Per Abrahamsen committed
526
  "Extract the default external value of WIDGET."
527
  (widget-apply widget :value-to-external
Per Abrahamsen's avatar
Per Abrahamsen committed
528
		(or (widget-get widget :value)
529 530
		    (progn
		      (when (widget-get widget :args)
531
			(setq widget (widget-copy widget))
532 533 534 535 536 537 538 539
			(let (args)
			  (dolist (arg (widget-get widget :args))
			    (setq args (append args
					       (if (widget-get arg :inline)
						   (widget-get arg :args)
						 (list arg)))))
			  (widget-put widget :args args)))
		      (widget-apply widget :default-get)))))
540

Per Abrahamsen's avatar
Per Abrahamsen committed
541
(defun widget-match-inline (widget vals)
542
  "In WIDGET, match the start of VALS."
Per Abrahamsen's avatar
Per Abrahamsen committed
543 544
  (cond ((widget-get widget :inline)
	 (widget-apply widget :match-inline vals))
545
	((and (listp vals)
Per Abrahamsen's avatar
Per Abrahamsen committed
546 547 548 549 550 551
	      (widget-apply widget :match (car vals)))
	 (cons (list (car vals)) (cdr vals)))
	(t nil)))

(defun widget-apply-action (widget &optional event)
  "Apply :action in WIDGET in response to EVENT."
Per Abrahamsen's avatar
Per Abrahamsen committed
552 553 554
  (if (widget-apply widget :active)
      (widget-apply widget :action event)
    (error "Attempt to perform action on inactive widget")))
Per Abrahamsen's avatar
Per Abrahamsen committed
555

Per Abrahamsen's avatar
Per Abrahamsen committed
556 557 558 559 560 561 562 563 564 565 566 567 568 569
;;; Helper functions.
;;
;; These are widget specific.

;;;###autoload
(defun widget-prompt-value (widget prompt &optional value unbound)
  "Prompt for a value matching WIDGET, using PROMPT.
The current value is assumed to be VALUE, unless UNBOUND is non-nil."
  (unless (listp widget)
    (setq widget (list widget)))
  (setq prompt (format "[%s] %s" (widget-type widget) prompt))
  (setq widget (widget-convert widget))
  (let ((answer (widget-apply widget :prompt-value prompt value unbound)))
    (unless (widget-apply widget :match answer)
570
      (error "Value does not match %S type" (car widget)))
Per Abrahamsen's avatar
Per Abrahamsen committed
571 572 573 574 575
    answer))

(defun widget-get-sibling (widget)
  "Get the item WIDGET is assumed to toggle.
This is only meaningful for radio buttons or checkboxes in a list."
576
  (let* ((children (widget-get (widget-get widget :parent) :children))
Per Abrahamsen's avatar
Per Abrahamsen committed
577 578 579 580 581 582 583 584 585
	 child)
    (catch 'child
      (while children
	(setq child (car children)
	      children (cdr children))
	(when (eq (widget-get child :button) widget)
	  (throw 'child child)))
      nil)))

Per Abrahamsen's avatar
Per Abrahamsen committed
586 587 588 589
(defun widget-map-buttons (function &optional buffer maparg)
  "Map FUNCTION over the buttons in BUFFER.
FUNCTION is called with the arguments WIDGET and MAPARG.

Paul Eggert's avatar
Paul Eggert committed
590
If FUNCTION returns non-nil, the walk is canceled.
Per Abrahamsen's avatar
Per Abrahamsen committed
591 592 593 594 595 596

The arguments MAPARG, and BUFFER default to nil and (current-buffer),
respectively."
  (let ((cur (point-min))
	(widget nil)
	(overlays (if buffer
597
		      (with-current-buffer buffer (overlay-lists))
Per Abrahamsen's avatar
Per Abrahamsen committed
598 599 600 601 602 603 604
		    (overlay-lists))))
    (setq overlays (append (car overlays) (cdr overlays)))
    (while (setq cur (pop overlays))
      (setq widget (overlay-get cur 'button))
      (if (and widget (funcall function widget maparg))
	  (setq overlays nil)))))

605
;;; Images.
Per Abrahamsen's avatar
Per Abrahamsen committed
606

607
(defcustom widget-image-directory (file-name-as-directory
608
				   (expand-file-name "images/custom" data-directory))
609
  "Where widget button images are located.
Per Abrahamsen's avatar
Per Abrahamsen committed
610
If this variable is nil, widget will try to locate the directory
Per Abrahamsen's avatar
Per Abrahamsen committed
611
automatically."
Per Abrahamsen's avatar
Per Abrahamsen committed
612 613 614
  :group 'widgets
  :type 'directory)

615
(defcustom widget-image-enable t
616
  "If non-nil, use image buttons in widgets when available."
617
  :version "21.1"
Per Abrahamsen's avatar
Per Abrahamsen committed
618 619 620
  :group 'widgets
  :type 'boolean)

Per Abrahamsen's avatar
Per Abrahamsen committed
621 622 623 624 625 626 627 628 629 630
(defcustom widget-image-conversion
  '((xpm ".xpm") (gif ".gif") (png ".png") (jpeg ".jpg" ".jpeg")
    (xbm ".xbm"))
  "Conversion alist from image formats to file name suffixes."
  :group 'widgets
  :type '(repeat (cons :format "%v"
		       (symbol :tag "Image Format" unknown)
		       (repeat :tag "Suffixes"
			       (string :format "%v")))))

631 632 633
(defun widget-image-find (image)
  "Create a graphical button from IMAGE.
IMAGE should either already be an image, or be a file name sans
Per Abrahamsen's avatar
Per Abrahamsen committed
634
extension (xpm, xbm, gif, jpg, or png) located in
635 636 637
`widget-image-directory' or otherwise where `find-image' will find it."
  (cond ((not (and image widget-image-enable (display-graphic-p)))
	 ;; We don't want or can't use images.
Per Abrahamsen's avatar
Per Abrahamsen committed
638
	 nil)
639 640 641
	((and (consp image)
	      (eq 'image (car image)))
	 ;; Already an image spec.  Use it.
Per Abrahamsen's avatar
Per Abrahamsen committed
642
	 image)
Per Abrahamsen's avatar
Per Abrahamsen committed
643 644
	((stringp image)
	 ;; A string.  Look it up in relevant directories.
645 646 647 648
	 (let* ((load-path (cons widget-image-directory load-path))
		specs)
	   (dolist (elt widget-image-conversion)
	     (dolist (ext (cdr elt))
649 650
	       (push (list :type (car elt) :file (concat image ext))
		     specs)))
651
 	   (find-image (nreverse specs))))
Per Abrahamsen's avatar
Per Abrahamsen committed
652
	(t
Per Abrahamsen's avatar
Per Abrahamsen committed
653
	 ;; Oh well.
Per Abrahamsen's avatar
Per Abrahamsen committed
654 655
	 nil)))

656
(defvar widget-button-pressed-face 'widget-button-pressed
657 658 659 660
  "Face used for pressed buttons in widgets.
This exists as a variable so it can be set locally in certain
buffers.")

661
(defun widget-image-insert (widget tag image &optional _down _inactive)
Per Abrahamsen's avatar
Per Abrahamsen committed
662
  "In WIDGET, insert the text TAG or, if supported, IMAGE.
663 664 665 666 667
IMAGE should either be an image or an image file name sans extension
\(xpm, xbm, gif, jpg, or png) located in `widget-image-directory'.

Optional arguments DOWN and INACTIVE are used instead of IMAGE when the
button is pressed or inactive, respectively.  These are currently ignored."
668
  (if (and (featurep 'image)
669 670
	   (setq image (widget-image-find image)))
      (progn (widget-put widget :suppress-face t)
671
	     (insert-image image tag))
672
    (insert tag)))
Per Abrahamsen's avatar
Per Abrahamsen committed
673

674 675 676 677
(defun widget-move-and-invoke (event)
  "Move to where you click, and if it is an active field, invoke it."
  (interactive "e")
  (mouse-set-point event)
678 679 680
  (let ((pos (widget-event-point event)))
    (if (and pos (get-char-property pos 'button))
	(widget-button-click event))))
681

Per Abrahamsen's avatar
Per Abrahamsen committed
682 683 684 685 686 687 688 689 690
;;; Buttons.

(defgroup widget-button nil
  "The look of various kinds of buttons."
  :group 'widgets)

(defcustom widget-button-prefix ""
  "String used as prefix for buttons."
  :type 'string
Per Abrahamsen's avatar
Per Abrahamsen committed
691
  :group 'widget-button)
Per Abrahamsen's avatar
Per Abrahamsen committed
692 693 694 695

(defcustom widget-button-suffix ""
  "String used as suffix for buttons."
  :type 'string
Per Abrahamsen's avatar
Per Abrahamsen committed
696
  :group 'widget-button)
Per Abrahamsen's avatar
Per Abrahamsen committed
697

Per Abrahamsen's avatar
Per Abrahamsen committed
698 699 700 701
;;; Creating Widgets.

;;;###autoload
(defun widget-create (type &rest args)
702
  "Create widget of TYPE.
Per Abrahamsen's avatar
Per Abrahamsen committed
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
The optional ARGS are additional keyword arguments."
  (let ((widget (apply 'widget-convert type args)))
    (widget-apply widget :create)
    widget))

(defun widget-create-child-and-convert (parent type &rest args)
  "As part of the widget PARENT, create a child widget TYPE.
The child is converted, using the keyword arguments ARGS."
  (let ((widget (apply 'widget-convert type args)))
    (widget-put widget :parent parent)
    (unless (widget-get widget :indent)
      (widget-put widget :indent (+ (or (widget-get parent :indent) 0)
				    (or (widget-get widget :extra-offset) 0)
				    (widget-get parent :offset))))
    (widget-apply widget :create)
    widget))

(defun widget-create-child (parent type)
  "Create widget of TYPE."
Per Abrahamsen's avatar
Per Abrahamsen committed
722
  (let ((widget (widget-copy type)))
Per Abrahamsen's avatar
Per Abrahamsen committed
723 724 725 726 727 728 729 730 731 732
    (widget-put widget :parent parent)
    (unless (widget-get widget :indent)
      (widget-put widget :indent (+ (or (widget-get parent :indent) 0)
				    (or (widget-get widget :extra-offset) 0)
				    (widget-get parent :offset))))
    (widget-apply widget :create)
    widget))

(defun widget-create-child-value (parent type value)
  "Create widget of TYPE with value VALUE."
Per Abrahamsen's avatar
Per Abrahamsen committed
733
  (let ((widget (widget-copy type)))
Per Abrahamsen's avatar
Per Abrahamsen committed
734 735 736 737 738 739 740 741 742 743 744 745 746 747
    (widget-put widget :value (widget-apply widget :value-to-internal value))
    (widget-put widget :parent parent)
    (unless (widget-get widget :indent)
      (widget-put widget :indent (+ (or (widget-get parent :indent) 0)
				    (or (widget-get widget :extra-offset) 0)
				    (widget-get parent :offset))))
    (widget-apply widget :create)
    widget))

;;;###autoload
(defun widget-delete (widget)
  "Delete WIDGET."
  (widget-apply widget :delete))

Per Abrahamsen's avatar
Per Abrahamsen committed
748 749 750 751
(defun widget-copy (widget)
  "Make a deep copy of WIDGET."
  (widget-apply (copy-sequence widget) :copy))

Per Abrahamsen's avatar
Per Abrahamsen committed
752
(defun widget-convert (type &rest args)
753
  "Convert TYPE to a widget without inserting it in the buffer.
Per Abrahamsen's avatar
Per Abrahamsen committed
754 755
The optional ARGS are additional keyword arguments."
  ;; Don't touch the type.
756
  (let* ((widget (if (symbolp type)
Per Abrahamsen's avatar
Per Abrahamsen committed
757
		     (list type)
758
		   (copy-sequence type)))
Per Abrahamsen's avatar
Per Abrahamsen committed
759
	 (current widget)
760
	 done
Per Abrahamsen's avatar
Per Abrahamsen committed
761 762 763
	 (keys args))
    ;; First set the :args keyword.
    (while (cdr current)		;Look in the type.
764 765 766 767 768 769 770 771 772 773
      (if (and (keywordp (cadr current))
	       ;; If the last element is a keyword,
	       ;; it is still the :args element,
	       ;; even though it is a keyword.
	       (cddr current))
	  (if (eq (cadr current) :args)
	      ;; If :args is explicitly specified, obey it.
	      (setq current nil)
	    ;; Some other irrelevant keyword.
	    (setq current (cdr (cdr current))))
774 775
	(setcdr current (list :args (cdr current)))
	(setq current nil)))
776 777 778 779 780 781 782 783 784 785
    (while (and args (not done))	;Look in ARGS.
      (cond ((eq (car args) :args)
	     ;; Handle explicit specification of :args.
	     (setq args (cadr args)
		   done t))
	    ((keywordp (car args))
	     (setq args (cddr args)))
	    (t (setq done t))))
    (when done
      (widget-put widget :args args))
Per Abrahamsen's avatar
Per Abrahamsen committed
786 787 788 789 790 791 792 793
    ;; Then Convert the widget.
    (setq type widget)
    (while type
      (let ((convert-widget (plist-get (cdr type) :convert-widget)))
	(if convert-widget
	    (setq widget (funcall convert-widget widget))))
      (setq type (get (car type) 'widget-type)))
    ;; Finally set the keyword args.
794
    (while keys
Per Abrahamsen's avatar
Per Abrahamsen committed
795
      (let ((next (nth 0 keys)))
796 797
	(if (keywordp next)
	    (progn
Per Abrahamsen's avatar
Per Abrahamsen committed
798 799 800 801 802
	      (widget-put widget next (nth 1 keys))
	      (setq keys (nthcdr 2 keys)))
	  (setq keys nil))))
    ;; Convert the :value to internal format.
    (if (widget-member widget :value)
803 804 805 806
	(widget-put widget
		    :value (widget-apply widget
					 :value-to-internal
					 (widget-get widget :value))))
Per Abrahamsen's avatar
Per Abrahamsen committed
807 808 809
    ;; Return the newly create widget.
    widget))

810
;;;###autoload
Per Abrahamsen's avatar
Per Abrahamsen committed
811
(defun widget-insert (&rest args)
812
  "Call `insert' with ARGS even if surrounding text is read only."
Per Abrahamsen's avatar
Per Abrahamsen committed
813
  (let ((inhibit-read-only t)
814
	(inhibit-modification-hooks t))
Per Abrahamsen's avatar
Per Abrahamsen committed
815
    (apply 'insert args)))
Per Abrahamsen's avatar
Per Abrahamsen committed
816

Per Abrahamsen's avatar
Per Abrahamsen committed
817 818 819
(defun widget-convert-text (type from to
				 &optional button-from button-to
				 &rest args)
Per Abrahamsen's avatar
Per Abrahamsen committed
820
  "Return a widget of type TYPE with endpoint FROM TO.
821 822
No text will be inserted to the buffer, instead the text between FROM
and TO will be used as the widgets end points.  If optional arguments
Per Abrahamsen's avatar
Per Abrahamsen committed
823
BUTTON-FROM and BUTTON-TO are given, these will be used as the widgets
Per Abrahamsen's avatar
Per Abrahamsen committed
824 825 826
button end points.
Optional ARGS are extra keyword arguments for TYPE."
  (let ((widget (apply 'widget-convert type :delete 'widget-leave-text args))
Per Abrahamsen's avatar
Per Abrahamsen committed
827
	(from (copy-marker from))
828
	(to (copy-marker to)))
Per Abrahamsen's avatar
Per Abrahamsen committed
829 830 831 832 833 834 835 836
    (set-marker-insertion-type from t)
    (set-marker-insertion-type to nil)
    (widget-put widget :from from)
    (widget-put widget :to to)
    (when button-from
      (widget-specify-button widget button-from button-to))
    widget))

Per Abrahamsen's avatar
Per Abrahamsen committed
837
(defun widget-convert-button (type from to &rest args)
Per Abrahamsen's avatar
Per Abrahamsen committed
838
  "Return a widget of type TYPE with endpoint FROM TO.
Per Abrahamsen's avatar
Per Abrahamsen committed
839
Optional ARGS are extra keyword arguments for TYPE.
Per Abrahamsen's avatar
Per Abrahamsen committed
840 841 842
No text will be inserted to the buffer, instead the text between FROM
and TO will be used as the widgets end points, as well as the widgets
button end points."
Per Abrahamsen's avatar
Per Abrahamsen committed
843 844 845 846
  (apply 'widget-convert-text type from to from to args))

(defun widget-leave-text (widget)
  "Remove markers and overlays from WIDGET and its children."
847
  (let ((button (widget-get widget :button-overlay))
Per Abrahamsen's avatar
Per Abrahamsen committed
848
	(sample (widget-get widget :sample-overlay))
Per Abrahamsen's avatar
Per Abrahamsen committed
849
	(doc (widget-get widget :doc-overlay))
850 851 852
	(field (widget-get widget :field-overlay)))
    (set-marker (widget-get widget :from) nil)
    (set-marker (widget-get widget :to) nil)
Per Abrahamsen's avatar
Per Abrahamsen committed
853 854
    (when button
      (delete-overlay button))
Per Abrahamsen's avatar
Per Abrahamsen committed
855 856
    (when sample
      (delete-overlay sample))
Per Abrahamsen's avatar
Per Abrahamsen committed
857 858
    (when doc
      (delete-overlay doc))
Per Abrahamsen's avatar
Per Abrahamsen committed
859 860
    (when field
      (delete-overlay field))
861
    (mapc 'widget-leave-text (widget-get widget :children))))
Per Abrahamsen's avatar
Per Abrahamsen committed
862

Per Abrahamsen's avatar
Per Abrahamsen committed
863 864
;;; Keymap and Commands.

865 866 867
;; This alias exists only so that one can choose in doc-strings (e.g.
;; Custom-mode) which key-binding of widget-keymap one wants to refer to.
;; http://lists.gnu.org/archive/html/emacs-devel/2008-11/msg00480.html
868 869
(define-obsolete-function-alias 'advertised-widget-backward
  'widget-backward "23.2")
870

871
;;;###autoload
872 873 874
(defvar widget-keymap
  (let ((map (make-sparse-keymap)))
    (define-key map "\t" 'widget-forward)
875
    (define-key map "\e\t" 'widget-backward)
876 877
    (define-key map [(shift tab)] 'widget-backward)
    (put 'widget-backward :advertised-binding [(shift tab)])
878 879
    (define-key map [backtab] 'widget-backward)
    (define-key map [down-mouse-2] 'widget-button-click)
880
    (define-key map [down-mouse-1] 'widget-button-click)
Jason Rumney's avatar
Jason Rumney committed
881 882 883
    ;; The following definition needs to avoid using escape sequences that
    ;; might get converted to ^M when building loaddefs.el
    (define-key map [(control ?m)] 'widget-button-press)
884
    map)
Per Abrahamsen's avatar
Per Abrahamsen committed
885
  "Keymap containing useful binding for buffers containing widgets.
Glenn Morris's avatar
Glenn Morris committed
886 887
Recommended as a parent keymap for modes using widgets.
Note that such modes will need to require wid-edit.")
Per Abrahamsen's avatar
Per Abrahamsen committed
888 889

(defvar widget-global-map global-map
Dave Love's avatar
Don't  
Dave Love committed
890
  "Keymap used for events a widget does not handle itself.")
Per Abrahamsen's avatar
Per Abrahamsen committed
891 892
(make-variable-buffer-local 'widget-global-map)

893 894 895 896 897
(defvar widget-field-keymap
  (let ((map (copy-keymap widget-keymap)))
    (define-key map "\C-k" 'widget-kill-line)
    (define-key map "\M-\t" 'widget-complete)
    (define-key map "\C-m" 'widget-field-activate)
898
    ;; Since the widget code uses a `field' property to identify fields,
899
    ;; ordinary beginning-of-line does the right thing.
900
    ;;  (define-key map "\C-a" 'widget-beginning-of-line)
901
    (define-key map "\C-e" 'widget-end-of-line)
902
    map)
Per Abrahamsen's avatar
Per Abrahamsen committed
903 904
  "Keymap used inside an editable field.")

905 906
(defvar widget-text-keymap
  (let ((map (copy-keymap widget-keymap)))
907
    ;; Since the widget code uses a `field' property to identify fields,
908
    ;; ordinary beginning-of-line does the right thing.
909
    ;;  (define-key map "\C-a" 'widget-beginning-of-line)
910
    (define-key map "\C-e" 'widget-end-of-line)
911
    map)
Per Abrahamsen's avatar
Per Abrahamsen committed
912 913 914
  "Keymap used inside a text field.")

(defun widget-field-activate (pos &optional event)
Dave Love's avatar
Dave Love committed
915
  "Invoke the editable field at point."
Per Abrahamsen's avatar
Per Abrahamsen committed
916
  (interactive "@d")
Miles Bader's avatar
Miles Bader committed
917
  (let ((field (widget-field-at pos)))
Per Abrahamsen's avatar
Per Abrahamsen committed
918 919 920 921 922
    (if field
	(widget-apply-action field event)
      (call-interactively
       (lookup-key widget-global-map (this-command-keys))))))

923