Initial Commit
[packages] / xemacs-packages / fsf-compat / button.el
1 ;;; button.el --- clickable buttons
2 ;;
3 ;; Copyright (C) 2001-2014 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Miles Bader <miles@gnu.org>
6 ;; Keywords: extensions
7 ;; Package: emacs
8 ;;
9 ;; This file is part of XEmacs.
10 ;;
11 ;; XEmacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25 ;;
26 ;; This package defines functions for inserting and manipulating
27 ;; clickable buttons in Emacs buffers, such as might be used for help
28 ;; hyperlinks, etc.
29 ;;
30 ;; In some ways it duplicates functionality also offered by the
31 ;; `widget' package, but the button package has the advantage that it
32 ;; is (1) much faster, (2) much smaller, and (3) much, much, simpler
33 ;; (the code, that is, not the interface).
34 ;;
35 ;; Buttons can either use extents, in which case the button is
36 ;; represented by the extent itself, or text-properties, in which case
37 ;; the button is represented by a marker or buffer-position pointing
38 ;; somewhere in the button.  In the latter case, no markers into the
39 ;; buffer are retained, which is important for speed if there are are
40 ;; extremely large numbers of buttons.  Note however that if there is
41 ;; an existing face text-property at the site of the button, the
42 ;; button face may not be visible.  Using extents avoids this.
43 ;;
44 ;; Using `define-button-type' to define default properties for buttons
45 ;; is not necessary, but it is encouraged, since doing so makes the
46 ;; resulting code clearer and more efficient.
47 ;;
48
49 ;;; Code:
50
51 \f
52 ;; Globals
53
54 (defface button '((t (:underline t)))
55   "Default face used for buttons."
56   :group 'faces)
57
58 (defvar button-map
59   (let ((map (make-sparse-keymap 'button-map)))
60     ;; The following definition needs to avoid using escape sequences that
61     ;; might get converted to ^M when building loaddefs.el
62     (define-key map [(control ?m)] 'push-button)
63     (define-key map [button2] 'push-button)
64     map)
65   "Keymap used by buttons.")
66
67 (defvar button-buffer-map
68   (let ((map (make-sparse-keymap 'button-buffer-map)))
69     (define-key map [?\t] 'forward-button)
70     (define-key map "\e\t" 'backward-button)
71     (define-key map [backtab] 'backward-button)
72     map)
73   "Keymap useful for buffers containing buttons.
74 Mode-specific keymaps may want to use this as their parent keymap.")
75
76 ;; Default properties for buttons
77 (put 'default-button 'face 'button)
78 (put 'default-button 'mouse-face 'highlight)
79 (put 'default-button 'keymap button-map)
80 (put 'default-button 'type 'button)
81 ;; action may be either a function to call, or a marker to go to
82 (put 'default-button 'action 'ignore)
83 (put 'default-button 'help-echo "mouse-2, RET: Push this button")
84 ;; Make extent buttons go away if their underlying text is deleted.
85 (put 'default-button 'detachable t)
86 ;; Prevent insertions adjacent to the text-property buttons from
87 ;; inheriting its properties.
88 (put 'default-button 'rear-nonsticky t)
89
90 ;; A `category-symbol' property for the default button type
91 (put 'button 'button-category-symbol 'default-button)
92
93 \f
94 ;; Button types (which can be used to hold default properties for buttons)
95
96 ;; Because button-type properties are inherited by buttons using the
97 ;; special `category' property (implemented by both extents and
98 ;; text-properties), we need to store them on a symbol to which the
99 ;; `category' properties can point.  Instead of using the symbol that's
100 ;; the name of each button-type, however, we use a separate symbol (with
101 ;; `-button' appended, and uninterned) to store the properties.  This is
102 ;; to avoid name clashes.
103
104 ;; [this is an internal function]
105 (defsubst button-category-symbol (type)
106   "Return the symbol used by button-type TYPE to store properties.
107 Buttons inherit them by setting their `category' property to that symbol."
108   (or (get type 'button-category-symbol)
109       (error "Unknown button type `%s'" type)))
110
111 ;;;###autoload
112 (defun define-button-type (name &rest properties)
113   "Define a `button type' called NAME (a symbol).
114 The remaining arguments form a sequence of PROPERTY VALUE pairs,
115 specifying properties to use as defaults for buttons with this type
116 \(a button's type may be set by giving it a `type' property when
117 creating the button, using the :type keyword argument).
118
119 In addition, the keyword argument :supertype may be used to specify a
120 button-type from which NAME inherits its default property values
121 \(however, the inheritance happens only when NAME is defined; subsequent
122 changes to a supertype are not reflected in its subtypes)."
123   (let ((catsym (make-symbol (concat (symbol-name name) "-button")))
124         (super-catsym
125          (button-category-symbol
126           (or (plist-get properties 'supertype)
127               (plist-get properties :supertype)
128               'button))))
129     ;; Provide a link so that it's easy to find the real symbol.
130     (put name 'button-category-symbol catsym)
131     ;; Initialize NAME's properties using the global defaults.
132     (let ((default-props (symbol-plist super-catsym)))
133       (while default-props
134         (put catsym (pop default-props) (pop default-props))))
135     ;; Add NAME as the `type' property, which will then be returned as
136     ;; the type property of individual buttons.
137     (put catsym 'type name)
138     ;; Add the properties in PROPERTIES to the real symbol.
139     (while properties
140       (let ((prop (pop properties)))
141         (when (eq prop :supertype)
142           (setq prop 'supertype))
143         (put catsym prop (pop properties))))
144     ;; Make sure there's a `supertype' property
145     (unless (get catsym 'supertype)
146       (put catsym 'supertype 'button))
147     name))
148
149 (defun button-type-put (type prop val)
150   "Set the button-type TYPE's PROP property to VAL."
151   (put (button-category-symbol type) prop val))
152
153 (defun button-type-get (type prop)
154   "Get the property of button-type TYPE named PROP."
155   (get (button-category-symbol type) prop))
156
157 (defun button-type-subtype-p (type supertype)
158   "Return t if button-type TYPE is a subtype of SUPERTYPE."
159   (or (eq type supertype)
160       (and type
161            (button-type-subtype-p (button-type-get type 'supertype)
162                                   supertype))))
163
164 \f
165 ;; Button properties and other attributes
166
167 (defun button-start (button)
168   "Return the position at which BUTTON starts."
169   (if (extentp button)
170       (extent-start-position button)
171     ;; Must be a text-property button.
172     (or (previous-single-property-change (1+ button) 'button)
173         (point-min))))
174
175 (defun button-end (button)
176   "Return the position at which BUTTON ends."
177   (if (extentp button)
178       (extent-end-position button)
179     ;; Must be a text-property button.
180     (or (next-single-property-change button 'button)
181         (point-max))))
182
183 (defun button-get (button prop)
184   "Get the property of button BUTTON named PROP."
185   (cond ((extentp button)
186          (or (extent-property button prop)
187              (let ((category (extent-property button 'category)))
188                (when category
189                  (get category prop)))))
190         ((button--area-button-p button)
191          (get-text-property (cdr button)
192                             prop (button--area-button-string button)))
193         (t ; Must be a text-property button.
194          (get-text-property button prop))))
195
196 (defun button-put (button prop val)
197   "Set BUTTON's PROP property to VAL."
198   ;; Treat some properties specially.
199   (cond ((memq prop '(type :type))
200          ;; We translate a `type' property a `category' property, since
201          ;; that's what's actually used by extents/text-properties for
202          ;; inheriting properties.
203          (setq prop 'category)
204          (setq val (button-category-symbol val)))
205         ((eq prop 'category)
206          ;; Disallow updating the `category' property directly.
207          (error "Button `category' property may not be set directly")))
208   ;; Add the property.
209   (cond ((extentp button)
210          (set-extent-property button prop val))
211         ((button--area-button-p button)
212          (setq button (button--area-button-string button))
213          (put-text-property 0 (length button) prop val button))
214         (t ; Must be a text-property button.
215          (put-text-property
216           (or (previous-single-property-change (1+ button) 'button)
217               (point-min))
218           (or (next-single-property-change button 'button)
219               (point-max))
220           prop val))))
221
222 ;;;###autoload
223 (defun button-activate (button &optional use-mouse-action)
224   "Call BUTTON's action property.
225 If USE-MOUSE-ACTION is non-nil, invoke the button's mouse-action
226 instead of its normal action; if the button has no mouse-action,
227 the normal action is used instead.
228
229 The action can either be a marker or a function.  If it's a
230 marker then goto it.  Otherwise if it is a function then it is
231 called with BUTTON as only argument.  BUTTON is either an
232 extent, a buffer position, or (for buttons in the mode-line or
233 header-line) a string."
234   (let ((action (or (and use-mouse-action (button-get button 'mouse-action))
235                     (button-get button 'action))))
236     (if (markerp action)
237         (save-selected-window
238           (select-window (display-buffer (marker-buffer action)))
239           (goto-char action)
240           (recenter 0))
241       (funcall action button))))
242
243 (defun button-label (button)
244   "Return BUTTON's text label."
245   (if (button--area-button-p button)
246       (substring-no-properties (button--area-button-string button))
247     (buffer-substring-no-properties (button-start button)
248                                     (button-end button))))
249
250 (defsubst button-type (button)
251   "Return BUTTON's button-type."
252   (button-get button 'type))
253
254 (defun button-has-type-p (button type)
255   "Return t if BUTTON has button-type TYPE, or one of TYPE's subtypes."
256   (button-type-subtype-p (button-get button 'type) type))
257
258 (defun button--area-button-p (b)
259   "Return non-nil if BUTTON is an area button.
260 Such area buttons are used for buttons in the mode-line and header-line."
261   (stringp (car-safe b)))
262
263 (defalias 'button--area-button-string #'car)
264 \f
265 ;; Creating extent buttons
266
267 ;;;###autoload
268 (defun make-button (beg end &rest properties)
269   "Make a button from BEG to END in the current buffer.
270 The remaining arguments form a sequence of PROPERTY VALUE pairs,
271 specifying properties to add to the button.
272 In addition, the keyword argument :type may be used to specify a
273 button-type from which to inherit other properties; see
274 `define-button-type'.
275
276 Also see `make-text-button', `insert-button'."
277   (when (> beg end)
278     (setq beg (prog1 end (setq end beg))))
279   (let ((extent (make-extent beg end)))
280     (set-extent-property extent 'start-open t)
281     (while properties
282       (button-put extent (pop properties) (pop properties)))
283     ;; Put a pointer to the button in the extent, so it's easy to get
284     ;; when we don't actually have a reference to the extent.
285     (set-extent-property extent 'button extent)
286     ;; If the user didn't specify a type, use the default.
287     (unless (extent-property extent 'category)
288       (set-extent-property extent 'category 'default-button))
289     ;; EXTENT is the button, so return it
290     extent))
291
292 ;;;###autoload
293 (defun insert-button (label &rest properties)
294   "Insert a button with the label LABEL.
295 The remaining arguments form a sequence of PROPERTY VALUE pairs,
296 specifying properties to add to the button.
297 In addition, the keyword argument :type may be used to specify a
298 button-type from which to inherit other properties; see
299 `define-button-type'.
300
301 Also see `insert-text-button', `make-button'."
302   (apply #'make-button
303          (prog1 (point) (insert label))
304          (point)
305          properties))
306
307 \f
308 ;; Creating text-property buttons
309
310 ;;;###autoload
311 (defun make-text-button (beg end &rest properties)
312   "Make a button from BEG to END in the current buffer.
313 The remaining arguments form a sequence of PROPERTY VALUE pairs,
314 specifying properties to add to the button.
315 In addition, the keyword argument :type may be used to specify a
316 button-type from which to inherit other properties; see
317 `define-button-type'.
318
319 This function is like `make-button', except that the button is actually
320 part of the text instead of being a property of the buffer.  That is,
321 this function uses text properties, the other uses extents.
322 Creating large numbers of buttons can also be somewhat faster
323 using `make-text-button'.  Note, however, that if there is an existing
324 face property at the site of the button, the button face may not be visible.
325 You may want to use `make-button' in that case.
326
327 BEG can also be a string, in which case it is made into a button.
328
329 Also see `insert-text-button'."
330   (let ((object nil)
331         (type-entry
332          (or (plist-member properties 'type)
333              (plist-member properties :type))))
334     (when (stringp beg)
335       (setq object beg beg 0 end (length object)))
336     ;; Disallow setting the `category' property directly.
337     (when (plist-get properties 'category)
338       (error "Button `category' property may not be set directly"))
339     (if (null type-entry)
340         ;; The user didn't specify a `type' property, use the default.
341         (setq properties (cons 'category (cons 'default-button properties)))
342       ;; The user did specify a `type' property.  Translate it into a
343       ;; `category' property, which is what's actually used by
344       ;; text-properties for inheritance.
345       (setcar type-entry 'category)
346       (setcar (cdr type-entry)
347               (button-category-symbol (car (cdr type-entry)))))
348     ;; Now add all the text properties at once
349     (add-text-properties beg end
350                          ;; Each button should have a non-eq `button'
351                          ;; property so that next-single-property-change can
352                          ;; detect boundaries reliably.
353                          (cons 'button (cons (list t) properties))
354                          object)
355     ;; Return something that can be used to get at the button.
356     (or object beg)))
357
358 (defun insert-text-button (label &rest properties)
359   "Insert a button with the label LABEL.
360 The remaining arguments form a sequence of PROPERTY VALUE pairs,
361 specifying properties to add to the button.
362 In addition, the keyword argument :type may be used to specify a
363 button-type from which to inherit other properties; see
364 `define-button-type'.
365
366 This function is like `insert-button', except that the button is
367 actually part of the text instead of being a property of the buffer.
368 Creating large numbers of buttons can also be somewhat faster using
369 `insert-text-button'.
370
371 Also see `make-text-button'."
372   (apply #'make-text-button
373          (prog1 (point) (insert label))
374          (point)
375          properties))
376
377 \f
378 ;; Finding buttons in a buffer
379
380 ;;;###autoload
381 (defun button-at (pos)
382   "Return the button at position POS in the current buffer, or nil.
383 If the button at POS is a text property button, the return value
384 is a marker pointing to POS."
385   (let ((button (get-char-property pos 'button)))
386     (if (or (extentp button) (null button))
387         button
388       ;; Must be a text-property button; return a marker pointing to it.
389       (copy-marker pos t))))
390
391 ;;;###autoload
392 (defun next-button (pos &optional count-current)
393   "Return the next button after position POS in the current buffer.
394 If COUNT-CURRENT is non-nil, count any button at POS in the search,
395 instead of starting at the next button."
396     (unless count-current
397       ;; Search for the next button boundary.
398       (setq pos (next-single-char-property-change pos 'button)))
399     (and (< pos (point-max))
400          (or (button-at pos)
401              ;; We must have originally been on a button, and are now in
402              ;; the inter-button space.  Recurse to find a button.
403              (next-button pos))))
404
405 ;;;###autoload
406 (defun previous-button (pos &optional count-current)
407   "Return the previous button before position POS in the current buffer.
408 If COUNT-CURRENT is non-nil, count any button at POS in the search,
409 instead of starting at the next button."
410   (let ((button (button-at pos)))
411     (if button
412         (if count-current
413             button
414           ;; We started out on a button, so move to its start and look
415           ;; for the previous button boundary.
416           (setq pos (previous-single-char-property-change
417                      (button-start button) 'button))
418           (let ((new-button (button-at pos)))
419             (if new-button
420                 ;; We are in a button again; this can happen if there
421                 ;; are adjacent buttons (or at bob).
422                 (unless (= pos (button-start button)) new-button)
423               ;; We are now in the space between buttons.
424               (previous-button pos))))
425       ;; We started out in the space between buttons.
426       (setq pos (previous-single-char-property-change pos 'button))
427       (or (button-at pos)
428           (and (> pos (point-min))
429                (button-at (1- pos)))))))
430
431 \f
432 ;; User commands
433
434 ;;;###autoload
435 (defun push-button (&optional pos use-mouse-action)
436   "Perform the action specified by a button at location POS.
437 POS may be either a buffer position or a mouse-event.  If
438 USE-MOUSE-ACTION is non-nil, invoke the button's mouse-action
439 instead of its normal action; if the button has no mouse-action,
440 the normal action is used instead.  The action may be either a
441 function to call or a marker to display and is invoked using
442 `button-activate' (which see).
443
444 POS defaults to point, except when `push-button' is invoked
445 interactively as the result of a mouse-event, in which case, the
446 mouse event is used.
447 If there's no button at POS, do nothing and return nil, otherwise
448 return t."
449   (interactive
450    (list (if (mouse-event-p last-command-event) last-command-event (point))))
451   (if (and (not (integerp pos)) (eventp pos))
452       ;; POS is a mouse event; switch to the proper window/buffer
453       (with-current-buffer (event-buffer pos)
454         (if (event-over-text-area-p pos)
455             (push-button (event-point pos) t)
456           (button-activate (event-point pos) t)))
457     ;; POS is just normal position
458     (let ((button (button-at (or pos (point)))))
459       (when button
460         (button-activate button use-mouse-action)
461         t))))
462
463 ;;;###autoload
464 (defun forward-button (n &optional wrap display-message)
465   "Move to the Nth next button, or Nth previous button if N is negative.
466 If N is 0, move to the start of any button at point.
467 If WRAP is non-nil, moving past either end of the buffer continues from the
468 other end.
469 If DISPLAY-MESSAGE is non-nil, the button's help-echo string is displayed.
470 Any button with a non-nil `skip' property is skipped over.
471 Returns the button found."
472   (interactive "p\nd\nd")
473   (let (button)
474     (if (zerop n)
475         ;; Move to start of current button
476         (if (setq button (button-at (point)))
477             (goto-char (button-start button)))
478       ;; Move to Nth next button
479       (let ((iterator (if (> n 0) #'next-button #'previous-button))
480             (wrap-start (if (> n 0) (point-min) (point-max)))
481             opoint fail)
482         (setq n (abs n))
483         (setq button t)                 ; just to start the loop
484         (while (and (null fail) (> n 0) button)
485           (setq button (funcall iterator (point)))
486           (when (and (not button) wrap)
487             (setq button (funcall iterator wrap-start t)))
488           (when button
489             (goto-char (button-start button))
490             ;; Avoid looping forever (e.g., if all the buttons have
491             ;; the `skip' property).
492             (cond ((null opoint)
493                    (setq opoint (point)))
494                   ((= opoint (point))
495                    (setq fail t)))
496             (unless (button-get button 'skip)
497               (setq n (1- n)))))))
498     (if (null button)
499         (error (if wrap "No buttons!" "No more buttons"))
500       (let ((msg (and display-message (button-get button 'help-echo))))
501         (when msg
502           (message "%s" msg)))
503       button)))
504
505 ;;;###autoload
506 (defun backward-button (n &optional wrap display-message)
507   "Move to the Nth previous button, or Nth next button if N is negative.
508 If N is 0, move to the start of any button at point.
509 If WRAP is non-nil, moving past either end of the buffer continues from the
510 other end.
511 If DISPLAY-MESSAGE is non-nil, the button's help-echo string is displayed.
512 Any button with a non-nil `skip' property is skipped over.
513 Returns the button found."
514   (interactive "p\nd\nd")
515   (forward-button (- n) wrap display-message))
516
517
518 (provide 'button)
519
520 ;;; button.el ends here