c42c8aa2f06c56541d95ca2bfca2129483f1600b
[chise/xemacs-chise.git.1] / lisp / mouse.el
1 ;;; mouse.el --- window system-independent mouse support.
2
3 ;; Copyright (C) 1988, 1992-4, 1997 Free Software Foundation, Inc.
4 ;; Copyright (C) 1995 Tinker Systems
5 ;; Copyright (C) 1995, 1996 Ben Wing.
6
7 ;; Maintainer: XEmacs Development Team
8 ;; Keywords: mouse, dumped
9
10 ;; This file is part of XEmacs.
11
12 ;; XEmacs is free software; you can redistribute it and/or modify it
13 ;; under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; XEmacs is distributed in the hope that it will be useful, but
18 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with XEmacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Synched up with: Not synched with FSF.  Almost completely divergent.
28
29 ;;; Commentary:
30
31 ;; This file is dumped with XEmacs (when window system support is compiled in).
32
33 ;;; Code:
34
35 (provide 'mouse)
36
37 (global-set-key 'button1 'mouse-track)
38 (global-set-key '(shift button1) 'mouse-track-adjust)
39 (global-set-key '(control button1) 'mouse-track-insert)
40 (global-set-key '(control shift button1) 'mouse-track-delete-and-insert)
41 (global-set-key '(meta button1) 'mouse-track-do-rectangle)
42
43 ;; drops are now handled in dragdrop.el (ograf@fga.de)
44
45 ;; enable drag regions (ograf@fga.de)
46 ;; if button2 is dragged from within a region, this becomes a drop
47 ;;
48 ;; this must be changed to the new api
49 (if (featurep '(or offix cde mswindows))
50     (global-set-key 'button2 'mouse-drag-or-yank)
51   (global-set-key 'button2 'mouse-yank))
52
53 (defgroup mouse nil
54   "Window system-independent mouse support."
55   :group 'editing)
56
57 (defcustom mouse-track-rectangle-p nil
58   "*If true, then dragging out a region with the mouse selects rectangles
59 instead of simple start/end regions."
60   :type 'boolean
61   :group 'mouse)
62
63 (defcustom mouse-yank-at-point nil
64   "*If non-nil, the function `mouse-yank' will yank text at the cursor location.
65 Otherwise, the cursor will be moved to the location of the pointer click before
66 text is inserted."
67   :type 'boolean
68   :group 'mouse)
69
70 (defcustom mouse-highlight-text 'context
71   "*Choose the default double-click highlighting behavior.
72 If set to `context', double-click will highlight words when the mouse
73  is at a word character, or a symbol if the mouse is at a symbol
74  character.
75 If set to `word', double-click will always attempt to highlight a word.
76 If set to `symbol', double-click will always attempt to highlight a
77  symbol (the default behavior in previous XEmacs versions)."
78   :type '(choice (const context)
79                  (const word)
80                  (const symbol))
81   :group 'mouse)
82
83 (defvar mouse-yank-function 'mouse-consolidated-yank
84   "Function that is called upon by `mouse-yank' to actually insert text.")
85
86 (defun mouse-consolidated-yank ()
87   "Insert the current selection or, if there is none under X insert the X cutbuffer.
88 A mark is pushed, so that the inserted text lies between point and mark."
89   (interactive)
90   (if (not (console-on-window-system-p))
91       (yank)
92     (push-mark)
93     (if (region-active-p)
94         (if (consp zmacs-region-extent)
95             ;; pirated code from insert-rectangle in rect.el
96             ;; perhaps that code should be modified to handle a list of extents
97             ;; as the rectangle to be inserted?
98             (let ((lines zmacs-region-extent)
99                   (insertcolumn (current-column))
100                   (first t))
101               (push-mark)
102               (while lines
103                 (or first
104                     (progn
105                       (forward-line 1)
106                       (or (bolp) (insert ?\n))
107                       (move-to-column insertcolumn t)))
108                 (setq first nil)
109                 (insert (extent-string (car lines)))
110                 (setq lines (cdr lines))))
111           (insert (extent-string zmacs-region-extent)))
112       (insert-selection t))))
113
114 (defun insert-selection (&optional check-cutbuffer-p move-point-event)
115   "Insert the current selection into buffer at point."
116   (interactive "P")
117   (let ((text (if check-cutbuffer-p
118                   (or (condition-case () (get-selection) (error ()))
119                       (get-cutbuffer)
120                       (error "No selection or cut buffer available"))
121                 (get-selection))))
122     (cond (move-point-event
123            (mouse-set-point move-point-event)
124            (push-mark (point)))
125           ((interactive-p)
126            (push-mark (point))))
127     (insert text)
128     ))
129
130 \f
131 (defun mouse-select ()
132   "Select Emacs window the mouse is on."
133   (interactive "@"))
134
135 (defun mouse-delete-window ()
136   "Delete the Emacs window the mouse is on."
137   (interactive "@")
138   (delete-window))
139
140 (defun mouse-keep-one-window ()
141   "Select Emacs window mouse is on, then kill all other Emacs windows."
142   (interactive "@")
143   (delete-other-windows))
144
145 (defun mouse-select-and-split ()
146   "Select Emacs window mouse is on, then split it vertically in half."
147   (interactive "@")
148   (split-window-vertically nil))
149
150 (defun mouse-set-point (event)
151   "Select Emacs window mouse is on, and move point to mouse position."
152   (interactive "@e")
153   (let ((window (event-window event))
154         (pos (event-point event))
155         (close-pos (event-closest-point event)))
156     (or window (error "not in a window"))
157     (select-window window)
158     (if (and pos (> pos 0))
159         ;; If the event was over a text char, it's easy.
160         (goto-char (max (min pos (point-max)) (point-min)))
161       (if (and close-pos (> close-pos 0))
162           (goto-char (max (min close-pos (point-max)) (point-min)))
163         ;; When the event occurs outside of the frame directly to the
164         ;; left or right of a modeline, close-point is nil, but
165         ;; event-over-modeline is also nil.  That will drop us to this
166         ;; point.  So instead of erroring, just return nil.
167         nil))))
168
169 (defun mouse-yank (event)
170   "Paste text with the mouse.
171 If the variable `mouse-yank-at-point' is nil, then pasting occurs at the
172 location of the click; otherwise, pasting occurs at the current cursor
173 location."
174   (interactive "e")
175   (and (not mouse-yank-at-point)
176        (mouse-set-point event))
177   (funcall mouse-yank-function))
178
179 (defun click-inside-extent-p (click extent)
180   "Return non-nil if the button event is within the primary selection-extent.
181 Return nil otherwise."
182   ;; stig@hackvan.com
183   (let ((ewin (event-window click))
184         (epnt (event-point click)))
185     (and ewin
186          epnt
187          extent
188          (eq (window-buffer ewin)
189              (extent-object extent))
190          (extent-start-position extent)
191          (> epnt (extent-start-position extent))
192          (> (extent-end-position extent) epnt))))
193
194 (defun click-inside-selection-p (click)
195   (or (click-inside-extent-p click primary-selection-extent)
196       (click-inside-extent-p click zmacs-region-extent)
197       ))
198
199 (defun point-inside-extent-p (extent)
200   "Return t if point is within the bounds of the primary selection extent.
201 Return t is point is at the end position of the extent.
202 Return nil otherwise."
203   ;; stig@hackvan.com
204   (and extent
205        (eq (current-buffer)
206            (extent-object extent))
207        (> (point) (extent-start-position extent))
208        (>= (extent-end-position extent) (point))))
209
210 (defun point-inside-selection-p ()
211   ;; by Stig@hackvan.com
212   (or (point-inside-extent-p primary-selection-extent)
213       (point-inside-extent-p zmacs-region-extent)))
214
215 (defun mouse-drag-or-yank (event)
216   "Either drag or paste the current selection.
217 If the variable `mouse-yank-at-point' is non-nil,
218 move the cursor to the location of the click before pasting.
219 This functions has to be improved.  Currently it is just a (working) test."
220   ;; by Oliver Graf <ograf@fga.de>
221   (interactive "e")
222   (if (click-inside-extent-p event zmacs-region-extent)
223       ;; okay, this is a drag
224       (cond ((featurep 'offix)
225              (offix-start-drag-region event
226                                       (extent-start-position zmacs-region-extent)
227                                       (extent-end-position zmacs-region-extent)))
228             ((featurep 'cde)
229              ;; should also work with CDE
230              (cde-start-drag-region event
231                                     (extent-start-position zmacs-region-extent)
232                                     (extent-end-position zmacs-region-extent)))
233             (t (error "No offix or CDE support compiled in")))
234     ;; no drag, call region-funct
235     (and (not mouse-yank-at-point)
236          (mouse-set-point event))
237     (funcall mouse-yank-function))
238   )
239
240 (defun mouse-eval-sexp (click force-window)
241   "Evaluate the sexp under the mouse.  Usually, this is the last sexp before
242 the click, but if you click on a left paren, then it is the sexp beginning
243 with the paren that is evaluated.  Also, since strings evaluate to themselves,
244 they're fed to re-search-forward and the matched region is highlighted until
245 the mouse button is released.
246
247 Perhaps the most useful thing about this function is that the evaluation of
248 the expression which is clicked upon is relative not to the window where you
249 click, but to the current window and the current position of point.  Thus,
250 you can use `mouse-eval-sexp' to interactively test code that acts upon a
251 buffer...something you cannot do with the standard `eval-last-sexp' function.
252 It's also fantastic for debugging regular expressions."
253   ;; by Stig@hackvan.com
254   (interactive "e\nP")
255   (let (exp val result-str)
256     (setq exp (save-window-excursion
257                 (save-excursion
258                   (mouse-set-point click)
259                   (save-excursion
260                     (or (looking-at "(") (forward-sexp -1))
261                     (read (point-marker))))))
262     (cond ((stringp exp)
263            (if (setq val (re-search-forward exp nil t))
264                (let* ((oo (make-extent (match-beginning 0) (match-end 0))))
265                  (set-extent-face oo 'highlight)
266                  (set-extent-priority oo 1000)
267                  ;; wait for button release...
268                  (setq unread-command-event (next-command-event))
269                  (delete-extent oo))
270              (message "Regex \"%s\" not found" exp)
271              (ding nil 'quiet)))
272           (t (setq val (if (fboundp 'eval-interactive)
273                            (eval-interactive exp)
274                          (eval exp)))))
275     (setq result-str (prin1-to-string val))
276     ;; #### -- need better test
277     (if (and (not force-window)
278              (<= (length result-str) (window-width (selected-window))))
279         (message "%s" result-str)
280       (with-output-to-temp-buffer "*Mouse-Eval*"
281         (condition-case nil
282             (pprint val)
283           (error (prin1 val))))
284       )))
285
286 (defun mouse-line-length (event)
287   "Print the length of the line indicated by the pointer."
288   (interactive "@e")
289   (save-excursion
290     (mouse-set-point event)
291     (message "Line length: %d" (- (point-at-eol) (point-at-bol))))
292   (sleep-for 1))
293
294 (defun mouse-set-mark (event)
295   "Select Emacs window mouse is on, and set mark at mouse position.
296 Display cursor at that position for a second."
297   (interactive "@e")
298   (let ((point-save (point)))
299     (unwind-protect
300         (progn (mouse-set-point event)
301                (push-mark nil t)
302                (sit-for 1))
303       (goto-char point-save))))
304
305 (defun mouse-scroll (event)
306   "Scroll point to the mouse position."
307   (interactive "@e")
308   (save-excursion
309     (mouse-set-point event)
310     (recenter 0)
311     (scroll-right (event-x event))))
312
313 (defun mouse-del-char (event)
314   "Delete the char pointed to by the mouse."
315   (interactive "@e")
316   (save-excursion
317     (mouse-set-point event)
318     (delete-char 1 nil)))
319
320 (defun mouse-kill-line (event)
321   "Kill the line pointed to by the mouse."
322   (interactive "@e")
323   (save-excursion
324     (mouse-set-point event)
325     (kill-line nil)))
326
327 (defun mouse-bury-buffer (event)
328   "Bury the buffer pointed to by the mouse, thus selecting the next one."
329   (interactive "e")
330   (save-selected-window
331     (select-window (event-window event))
332     (bury-buffer)))
333
334 (defun mouse-unbury-buffer (event)
335   "Unbury and select the most recently buried buffer."
336   (interactive "e")
337   (save-selected-window
338     (select-window (event-window event))
339     (let* ((bufs (buffer-list))
340            (entry (1- (length bufs)))
341            val)
342       (while (not (setq val (nth entry bufs)
343                         val (and (/= (aref (buffer-name val) 0)
344                                      ? )
345                                  val)))
346         (setq entry (1- entry)))
347       (switch-to-buffer val))))
348
349 (defun narrow-window-to-region (m n)
350   "Narrow window to region between point and last mark"
351   (interactive "r")
352   (save-excursion
353     (save-restriction
354       (if (eq (selected-window) (next-window))
355           (split-window))
356       (goto-char m)
357       (recenter 0)
358       (if (eq (selected-window)
359               (if (zerop (minibuffer-depth))
360                   (next-window)))
361           ()
362         (shrink-window (- (- (window-height) (count-lines m n)) 1))))))
363
364 (defun mouse-window-to-region (event)
365   "Narrow window to region between cursor and mouse pointer."
366   (interactive "@e")
367   (let ((point-save (point)))
368     (unwind-protect
369         (progn (mouse-set-point event)
370                (push-mark nil t)
371                (sit-for 1))
372       (goto-char point-save)
373       (narrow-window-to-region (region-beginning) (region-end)))))
374
375 (defun mouse-ignore ()
376   "Don't do anything."
377   (interactive))
378
379 \f
380 ;;; mouse/selection tracking
381 ;;; generalized mouse-track
382
383 (defvar default-mouse-track-normalize-point-function
384   'default-mouse-track-normalize-point
385   "Function called to normalize position of point.
386 Called with two arguments: TYPE depends on the number of times that the
387 mouse has been clicked and is a member of `default-mouse-track-type-list',
388 FORWARDP determines the direction in which the point should be moved.")
389
390 (defvar mouse-track-down-hook nil
391   "Function or functions called when the user presses the mouse.
392 This hook is invoked by `mouse-track'; thus, it will not be called
393 for any buttons with a different binding.  The functions will be
394 called with two arguments: the button-press event and a click
395 count (see `mouse-track-click-hook').
396
397 If any function returns non-nil, the remaining functions will not be
398 called.
399
400 Note that most applications should take action when the mouse is
401 released, not when it is pressed.'")
402
403 (defvar mouse-track-drag-hook nil
404   "Function or functions called when the user drags the mouse.
405 This hook is invoked by `mouse-track'; thus, it will not be called
406 for any buttons with a different binding.  The functions will be
407 called with three arguments: the mouse-motion event, a click
408 count (see `mouse-track-click-hook'), and whether the call to
409 this hook occurred as a result of a drag timeout (see
410 `mouse-track-scroll-delay').
411
412 If any function returns non-nil, the remaining functions will not be
413 called.
414
415 Note that no calls to this function will be made until the user
416 initiates a drag (i.e. moves the mouse more than a certain
417 threshold in either the X or the Y direction, as defined by
418 `mouse-track-x-threshold' and `mouse-track-y-threshold').
419
420 See also `mouse-track-drag-up-hook'.")
421
422 (defvar mouse-track-drag-up-hook nil
423   "Function or functions called when the user finishes a drag.
424 This hook is invoked by `mouse-track'; thus, it will not be called
425 for any buttons with a different binding.  The functions will be
426 called with two arguments: the button-press event and a click
427 count (see `mouse-track-click-hook').
428
429 If any function returns non-nil, the remaining functions will not be
430 called.
431
432 Note that this hook will not be invoked unless the user has
433 initiated a drag, i.e. moved the mouse more than a certain threshold
434 (see `mouse-track-drag-hook').  When this function is invoked,
435 `mouse-track-drag-hook' will have been invoked at least once.
436
437 See also `mouse-track-click-hook'.")
438
439 (defvar mouse-track-click-hook nil
440   "Function or functions called when the user clicks the mouse.
441 `Clicking' means pressing and releasing the mouse without having
442 initiated a drag (i.e. without having moved more than a certain
443 threshold -- see `mouse-track-drag-hook').
444
445 This hook is invoked by `mouse-track'; thus, it will not be called
446 for any buttons with a different binding.  The functions will be
447 called with two arguments: the button-release event and a click
448 count, which specifies the number of times that the mouse has been
449 clicked in a series of clicks, each of which is separated by at most
450 `mouse-track-multi-click-time'.  This can be used to implement actions
451 that are called on double clicks, triple clicks, etc.
452
453 If any function returns non-nil, the remaining functions will not be
454 called.
455
456 See also `mouse-track-drag-up-hook.")
457
458 (defvar mouse-track-up-hook nil
459   "Function or functions called when the user releases the mouse.
460 This hook is invoked by `mouse-track'; thus, it will not be called
461 for any buttons with a different binding.  The functions will be
462 called with two arguments: the button-release event and a click
463 count (see `mouse-track-click-hook').
464
465 For many applications, it is more appropriate to use one or both
466 of `mouse-track-click-hook' and `mouse-track-drag-up-hook'.")
467
468 (defvar mouse-track-cleanup-hook nil
469   "Function or functions called when `mouse-track' terminates.
470 This hook will be called in all circumstances, even upon a
471 non-local exit out of `mouse-track', and so is useful for
472 doing cleanup work such as removing extents that may have
473 been created during the operation of `mouse-track'.
474
475 Unlike all of the other mouse-track hooks, this is a \"normal\"
476 hook: the hook functions are called with no arguments, and
477 all hook functions are called regardless of their return
478 values.")
479
480 (defcustom mouse-track-multi-click-time 400
481   "*Maximum number of milliseconds allowed between clicks for a multi-click.
482 See `mouse-track-click-hook'."
483   :type 'integer
484   :group 'mouse)
485
486 (defcustom mouse-track-scroll-delay 100
487   "Maximum of milliseconds between calls to `mouse-track-drag-hook'.
488 If the user is dragging the mouse (i.e. the button is held down and
489 a drag has been initiated) and does not move the mouse for this many
490 milliseconds, the hook will be called with t as the value of the
491 WAS-TIMEOUT parameter.  This can be used to implement scrolling
492 in a selection when the user drags the mouse out the window it
493 was in.
494
495 A value of nil disables the timeout feature."
496   :type '(choice integer (const :tag "Disabled" nil))
497   :group 'mouse)
498
499 (defvar mouse-track-x-threshold '(face-width 'default)
500   "Minimum number of pixels in the X direction for a drag to be initiated.
501 If the mouse is moved more than either the X or Y threshold while the
502 button is held down (see also `mouse-track-y-threshold'), then a drag
503 is initiated; otherwise the gesture is considered to be a click.
504 See `mouse-track'.
505
506 The value should be either a number of a form to be evaluated to
507 produce a number.")
508
509 (defvar mouse-track-y-threshold '(face-height 'default)
510   "Minimum number of pixels in the Y direction for a drag to be initiated.
511 If the mouse is moved more than either the X or Y threshold while the
512 button is held down (see also `mouse-track-x-threshold'), then a drag
513 is initiated; otherwise the gesture is considered to be a click.
514 See `mouse-track'.
515
516 The value should be either a number of a form to be evaluated to
517 produce a number.")
518
519 ;; these variables are private to mouse-track.
520 (defvar mouse-track-up-time nil)
521 (defvar mouse-track-up-x nil)
522 (defvar mouse-track-up-y nil)
523 (defvar mouse-track-timeout-id nil)
524 (defvar mouse-track-click-count nil)
525
526 (defun mouse-track-set-timeout (event)
527   (if mouse-track-timeout-id
528       (disable-timeout mouse-track-timeout-id))
529   (if mouse-track-scroll-delay
530       (setq mouse-track-timeout-id
531             (add-timeout (/ mouse-track-scroll-delay 1000.0)
532                          'mouse-track-scroll-undefined
533                          (copy-event event)))))
534
535 (defun mouse-track-run-hook (hook event &rest args)
536   ;; ugh, can't use run-hook-with-args-until-success because we have
537   ;; to get the value using symbol-value-in-buffer.  Doing a
538   ;; save-excursion/set-buffer is wrong because the hook might want to
539   ;; change the buffer, but just doing a set-buffer is wrong because
540   ;; the hook might not want to change the buffer.
541   ;; #### What we need here is a Lisp interface to
542   ;; run_hook_with_args_in_buffer.  Here is a poor man's version.
543   (let ((buffer (event-buffer event)))
544     (and mouse-grabbed-buffer (setq buffer mouse-grabbed-buffer))
545     (when buffer
546       (let ((value (symbol-value-in-buffer hook buffer nil)))
547         (if (and (listp value) (not (eq (car value) 'lambda)))
548             ;; List of functions.
549             (let (retval)
550               (while (and value (null retval))
551                 ;; Found `t': should process default value.  We could
552                 ;; splice it into the buffer-local value, but that
553                 ;; would cons, which is not a good thing for
554                 ;; mouse-track hooks.
555                 (if (eq (car value) t)
556                     (let ((global (default-value hook)))
557                       (if (and (listp global) (not (eq (car global) 'lambda)))
558                           ;; List of functions.
559                           (while (and global
560                                       (null (setq retval
561                                                   (apply (car global) event args))))
562                             (pop global))
563                         ;; lambda
564                         (setq retval (apply (car global) event args))))
565                   (setq retval (apply (car value) event args)))
566                 (pop value))
567               retval)
568           ;; lambda
569           (apply value event args))))))
570
571 (defun mouse-track-scroll-undefined (random)
572   ;; the old implementation didn't actually define this function,
573   ;; and in normal use it won't ever be called because the timeout
574   ;; will either be removed before it fires or will be picked off
575   ;; with next-event and not dispatched.  However, if you're
576   ;; attempting to debug a click-hook (which is pretty damn
577   ;; difficult to do), this function may get called.
578 )
579
580 (defun mouse-track (event)
581   "Make a selection with the mouse.  This should be bound to a mouse button.
582 The behavior of XEmacs during mouse selection is customizable using various
583 hooks and variables: see `mouse-track-click-hook', `mouse-track-drag-hook',
584 `mouse-track-drag-up-hook', `mouse-track-down-hook', `mouse-track-up-hook',
585 `mouse-track-cleanup-hook', `mouse-track-multi-click-time',
586 `mouse-track-scroll-delay', `mouse-track-x-threshold', and
587 `mouse-track-y-threshold'.
588
589 Default handlers are provided to implement standard selecting/positioning
590 behavior.  You can explicitly request this default behavior, and override
591 any custom-supplied handlers, by using the function `mouse-track-default'
592 instead of `mouse-track'.
593
594 Default behavior is as follows:
595
596 If you click-and-drag, the selection will be set to the region between the
597 point of the initial click and the point at which you release the button.
598 These positions need not be ordered.
599
600 If you click-and-release without moving the mouse, then the point is moved
601 and the selection is disowned (there will be no selection owner).  The mark
602 will be set to the previous position of point.
603
604 If you double-click, the selection will extend by symbols instead of by
605 characters.  If you triple-click, the selection will extend by lines.
606
607 If you drag the mouse off the top or bottom of the window, you can select
608 pieces of text which are larger than the visible part of the buffer; the
609 buffer will scroll as necessary.
610
611 The selected text becomes the current X Selection.  The point will be left
612 at the position at which you released the button, and the mark will be left
613 at the initial click position."
614   (interactive "e")
615   (let ((mouse-down t)
616         (xthresh (eval mouse-track-x-threshold))
617         (ythresh (eval mouse-track-y-threshold))
618         (orig-x (event-x-pixel event))
619         (orig-y (event-y-pixel event))
620         (buffer (event-buffer event))
621         (mouse-grabbed-buffer (event-buffer event))
622         mouse-moved)
623     (if (or (not mouse-track-up-x)
624             (not mouse-track-up-y)
625             (not mouse-track-up-time)
626             (> (- (event-timestamp event) mouse-track-up-time)
627                mouse-track-multi-click-time)
628             (> (abs (- mouse-track-up-x orig-x)) xthresh)
629             (> (abs (- mouse-track-up-y orig-y)) ythresh))
630         (setq mouse-track-click-count 1)
631       (setq mouse-track-click-count (1+ mouse-track-click-count)))
632     (if (not (event-window event))
633         (error "Not over a window."))
634     (mouse-track-run-hook 'mouse-track-down-hook
635                           event mouse-track-click-count)
636     (unwind-protect
637         (while mouse-down
638           (setq event (next-event event))
639           (cond ((motion-event-p event)
640                  (if (and (not mouse-moved)
641                           (or (> (abs (- (event-x-pixel event) orig-x))
642                                  xthresh)
643                               (> (abs (- (event-y-pixel event) orig-y))
644                                  ythresh)))
645                      (setq mouse-moved t))
646                  (if mouse-moved
647                      (mouse-track-run-hook 'mouse-track-drag-hook
648                       event mouse-track-click-count nil))
649                  (mouse-track-set-timeout event))
650                 ((and (timeout-event-p event)
651                       (eq (event-function event)
652                           'mouse-track-scroll-undefined))
653                  (if mouse-moved
654                      (mouse-track-run-hook 'mouse-track-drag-hook
655                       (event-object event) mouse-track-click-count t))
656                  (mouse-track-set-timeout (event-object event)))
657                 ((button-release-event-p event)
658                  (setq mouse-track-up-time (event-timestamp event))
659                  (setq mouse-track-up-x (event-x-pixel event))
660                  (setq mouse-track-up-y (event-y-pixel event))
661                  (setq mouse-down nil)
662                  (mouse-track-run-hook 'mouse-track-up-hook
663                   event mouse-track-click-count)
664                  (if mouse-moved
665                      (mouse-track-run-hook 'mouse-track-drag-up-hook
666                       event mouse-track-click-count)
667                    (mouse-track-run-hook 'mouse-track-click-hook
668                     event mouse-track-click-count)))
669                 ((or (key-press-event-p event)
670                      (and (misc-user-event-p event)
671                           (eq (event-function event) 'cancel-mode-internal)))
672                  (error "Selection aborted"))
673                 (t
674                  (dispatch-event event))))
675       ;; protected
676       (if mouse-track-timeout-id
677           (disable-timeout mouse-track-timeout-id))
678       (setq mouse-track-timeout-id nil)
679       (and buffer
680            (save-excursion
681              (set-buffer buffer)
682              (run-hooks 'mouse-track-cleanup-hook))))))
683
684 \f
685 ;;;;;;;;;;;; default handlers: new version of mouse-track
686
687 (defvar default-mouse-track-type nil)
688 (defvar default-mouse-track-type-list '(char word line))
689 (defvar default-mouse-track-window nil)
690 (defvar default-mouse-track-extent nil)
691 (defvar default-mouse-track-adjust nil)
692 (defvar default-mouse-track-min-anchor nil)
693 (defvar default-mouse-track-max-anchor nil)
694 (defvar default-mouse-track-result nil)
695 (defvar default-mouse-track-down-event nil)
696
697 ;; D. Verna Feb. 17 1998
698 ;; This function used to assume that when (event-window event) differs from
699 ;; window, we have to scroll. This is WRONG, for instance when there are
700 ;; toolbars on the side, in which case window-event returns nil.
701 (defun default-mouse-track-set-point-in-window (event window)
702   (if (event-over-modeline-p event)
703       nil ;; Scroll
704     ;; Not over a modeline
705     (if (eq (event-window event) window)
706         (let ((p (event-closest-point event)))
707           (if  (or (not p) (not (pos-visible-in-window-p p window)))
708               nil ;; Scroll
709             (mouse-set-point event)
710             t))
711       ;; Not over a modeline, not the same window. Check if the Y position
712       ;; is still overlapping the original window.
713       (let* ((edges (window-pixel-edges window))
714              (row (event-y-pixel event))
715              (text-start (nth 1 edges))
716              (text-end (+ (nth 3 edges))))
717         (if (or (< row text-start)
718                 (> row text-end))
719             nil ;; Scroll
720           ;; The Y pos in overlapping the original window. Check however if
721           ;; the position is really visible, because there could be a
722           ;; scrollbar or a modeline at this place.
723           ;; Find the mean line height (height / lines nb), and approximate
724           ;; the line number for Y pos.
725           (select-window window)
726           (let ((line (/ (* (- row text-start) (window-height))
727                          (- text-end text-start))))
728             (if (not (save-excursion
729                        (goto-char (window-start))
730                        (pos-visible-in-window-p
731                         (point-at-bol (+ 1 line)))))
732                 nil ;; Scroll
733               ;; OK, we can go to that position
734               (goto-char (window-start))
735               (forward-line line)
736               ;; On the right side: go to end-of-line.
737               (when (>= (event-x-pixel event) (nth 2 edges))
738                 (goto-char (point-at-eol)))
739               t))))
740       )))
741
742
743 (defun default-mouse-track-scroll-and-set-point (event window)
744   (select-window window)
745   (let ((edges (window-pixel-edges window))
746         (row (event-y-pixel event))
747         (height (face-height 'default)))
748     (cond ((< (abs (- row (nth 1 edges))) (abs (- row (nth 3 edges))))
749            ;; closer to window's top than to bottom, so move up
750            (let ((delta (max 1 (/ (- (nth 1 edges) row) height))))
751              (condition-case () (scroll-down delta) (error))
752              (goto-char (window-start))))
753           ((>= (point) (point-max)))
754           (t
755            ;; scroll by one line if over the modeline or a clipped line
756            (let ((delta (if (or (event-over-modeline-p event)
757                                 (< row (nth 3 edges)))
758                             1
759                           (+ (/ (- row (nth 3 edges)) height) 1)))
760                  (close-pos (event-closest-point event)))
761              (condition-case () (scroll-up delta) (error))
762              (if (and close-pos (pos-visible-in-window-p close-pos))
763                  (goto-char close-pos)
764                (goto-char (window-end))
765                (vertical-motion delta)
766                ;; window-end reports the end of the clipped line, even if
767                ;; scroll-on-clipped-lines is t.  compensate.
768                ;; (If window-end gets fixed this can be removed.)
769                (if (not (pos-visible-in-window-p (max (1- (point))
770                                                       (point-min))))
771                    (vertical-motion -1))
772                (condition-case () (backward-char 1)
773                  (error (end-of-line)))))))))
774
775
776 ;; This remembers the last position at which the user clicked, for the
777 ;; benefit of mouse-track-adjust (for example, button1; scroll until the
778 ;; position of the click is off the frame; then Sh-button1 to select the
779 ;; new region.
780 (defvar default-mouse-track-previous-point nil)
781
782 (defun default-mouse-track-set-point (event window)
783   (if (default-mouse-track-set-point-in-window event window)
784       nil
785     (default-mouse-track-scroll-and-set-point event window)))
786
787 (defsubst default-mouse-track-beginning-of-word (symbolp)
788   (let ((word-constituent (cond ((eq symbolp t) "\\w\\|\\s_\\|\\s'")
789                                 ((null symbolp) "\\w")
790                                 (t "[^ \t\n]")))
791         (white-space "[ \t]"))
792     (cond ((bobp) nil)
793           ((looking-at word-constituent)
794            (backward-char)
795            (while (and (not (bobp)) (looking-at word-constituent))
796              (backward-char))
797            (if (or (not (bobp)) (not (looking-at word-constituent)))
798                (forward-char)))
799           ((looking-at white-space)
800            (backward-char)
801            (while (looking-at white-space)
802              (backward-char))
803            (forward-char)))))
804
805 (defun default-mouse-track-end-of-word (symbolp)
806   (let ((word-constituent (cond ((eq symbolp t) "\\w\\|\\s_\\|\\s'")
807                                 ((null symbolp) "\\w")
808                                 (t "[^ \t\n]")))
809         (white-space "[ \t]"))
810     (cond ((looking-at word-constituent) ; word or symbol constituent
811            (while (looking-at word-constituent)
812              (forward-char)))
813           ((looking-at white-space) ; word or symbol constituent
814            (while (looking-at white-space)
815              (forward-char))))))
816
817 ;; Decide what will be the SYMBOLP argument to
818 ;; default-mouse-track-{beginning,end}-of-word, according to the
819 ;; syntax of the current character and value of mouse-highlight-text.
820 (defsubst default-mouse-track-symbolp (syntax)
821   (cond ((eq mouse-highlight-text 'context)
822          (eq syntax ?_))
823         ((eq mouse-highlight-text 'symbol)
824          t)
825         (t
826          nil)))
827
828 ;; Return t if point is at an opening quote character.  This is
829 ;; determined by testing whether the syntax of the following character
830 ;; is `string', which will always be true for opening quotes and
831 ;; always false for closing quotes.
832 (defun default-mouse-track-point-at-opening-quote-p ()
833   (save-excursion
834     (forward-char 1)
835     (eq (buffer-syntactic-context) 'string)))
836
837 (defun default-mouse-track-normalize-point (type forwardp)
838   (cond ((eq type 'word)
839          ;; trap the beginning and end of buffer errors
840          (ignore-errors
841            (setq type (char-syntax (char-after (point))))
842            (if forwardp
843                (if (or (= type ?\()
844                        (and (= type ?\")
845                             (default-mouse-track-point-at-opening-quote-p)))
846                    (goto-char (scan-sexps (point) 1))
847                  (default-mouse-track-end-of-word
848                    (default-mouse-track-symbolp type)))
849              (if (or (= type ?\))
850                      (and (= type ?\")
851                           (not (default-mouse-track-point-at-opening-quote-p))))
852                  (goto-char (scan-sexps (1+ (point)) -1))
853                (default-mouse-track-beginning-of-word
854                  (default-mouse-track-symbolp type))))))
855         ((eq type 'line)
856          (if forwardp (end-of-line) (beginning-of-line)))
857         ((eq type 'buffer)
858          (if forwardp (end-of-buffer) (beginning-of-buffer)))))
859
860 (defun default-mouse-track-next-move (min-anchor max-anchor extent)
861   (let ((anchor (if (<= (point) min-anchor) max-anchor min-anchor)))
862     (funcall default-mouse-track-normalize-point-function
863              default-mouse-track-type (> (point) anchor))
864     (if (consp extent)
865         (default-mouse-track-next-move-rect anchor (point) extent)
866       (if extent
867           (if (<= anchor (point))
868               (set-extent-endpoints extent anchor (point))
869             (set-extent-endpoints extent (point) anchor))))))
870
871 (defun default-mouse-track-next-move-rect (start end extents &optional pad-p)
872   (if (< end start)
873       (let ((tmp start)) (setq start end end tmp)))
874   (cond
875    ((= start end)               ; never delete the last remaining extent
876     (mapcar 'delete-extent (cdr extents))
877     (setcdr extents nil)
878     (set-extent-endpoints (car extents) start start))
879    (t
880     (let ((indent-tabs-mode nil)        ; if pad-p, don't use tabs
881           (rest extents)
882           left right last p)
883       (save-excursion
884         (save-restriction
885           (goto-char end)
886           (setq right (current-column))
887           (goto-char start)
888           (setq left (current-column))
889           (if (< right left)
890               (let ((tmp left))
891                 (setq left right right tmp)
892                 (setq start (- start (- right left))
893                       end (+ end (- right left)))))
894           ;; End may have been set to a value greater than point-max if drag
895           ;; or movement extends to end of buffer, so reset it.
896           (setq end (min end (point-max)))
897           (beginning-of-line)
898           (narrow-to-region (point) end)
899           (goto-char start)
900           (while (and rest (not (eobp)))
901             (setq p (point))
902             (move-to-column right pad-p)
903             (set-extent-endpoints (car rest) p (point))
904             ;; this code used to look at the return value
905             ;; of forward-line, but that doesn't work because
906             ;; forward-line has bogus behavior: If you're on
907             ;; the last line of a buffer but not at the very
908             ;; end, forward-line will move you to the very
909             ;; end and return 0 instead of 1, like it should.
910             ;; the result was frequent infinite loops here,
911             ;; creating very large numbers of extents at
912             ;; the same position.  There was an N^2 sorting
913             ;; algorithm in extents.c for extents at a
914             ;; particular position, and the result was very
915             ;; bad news.
916             (forward-line 1)
917             (if (not (eobp))
918                 (move-to-column left pad-p))
919             (setq last rest
920                   rest (cdr rest)))
921           (cond (rest
922                  (mapcar 'delete-extent rest)
923                  (setcdr last nil))
924                 ((not (eobp))
925                  (while (not (eobp))
926                    (setq p (point))
927                    (move-to-column right pad-p)
928                    (let ((e (make-extent p (point))))
929                      (set-extent-face e (extent-face (car extents)))
930                      (set-extent-priority e (extent-priority (car extents)))
931                      (setcdr last (cons e nil))
932                      (setq last (cdr last)))
933                    (forward-line 1)
934                    (if (not (eobp))
935                        (move-to-column left pad-p))
936                    )))))
937       ))))
938
939 (defun default-mouse-track-has-selection-p (buffer)
940   (and (selection-owner-p)
941        (extent-live-p primary-selection-extent)
942        (not (extent-detached-p primary-selection-extent))
943        (eq buffer (extent-object primary-selection-extent))))
944
945 (defun default-mouse-track-anchor (adjust previous-point)
946   (if adjust
947       (if (default-mouse-track-has-selection-p (current-buffer))
948           (let ((start (extent-start-position primary-selection-extent))
949                 (end (extent-end-position primary-selection-extent)))
950             (cond ((< (point) start) end)
951                   ((> (point) end) start)
952                   ((> (- (point) start) (- end (point))) start)
953                   (t end)))
954         previous-point)
955     (point)))
956
957 (defun default-mouse-track-maybe-own-selection (pair type)
958   (let ((start (car pair))
959         (end (cdr pair)))
960     (or (= start end) (push-mark (if (= (point) start) end start)))
961     (cond (zmacs-regions
962            (if (= start end)
963                nil
964              ;; #### UTTER KLUDGE.
965              ;; If we don't have this sit-for here, then triple-clicking
966              ;; will result in the line not being highlighted as it
967              ;; should.  What appears to be happening is this:
968              ;;
969              ;; -- each time the button goes down, the selection is
970              ;;    disowned (see comment "remove the existing selection
971              ;;    to unclutter the display", below).
972              ;; -- this causes a SelectionClear event to be sent to
973              ;;    XEmacs.
974              ;; -- each time the button goes up except the first, the
975              ;;    selection is owned again.
976              ;; -- later, XEmacs processes the SelectionClear event.
977              ;;    The selection code attempts to keep track of the
978              ;;    time that it last asserted the selection, and
979              ;;    compare it to the time of the SelectionClear event,
980              ;;    to see if it's a bogus notification or not (as
981              ;;    is the case here).  However, for some unknown
982              ;;    reason this doesn't work in the triple-clicking
983              ;;    case, and the selection code bogusly thinks this
984              ;;    SelectionClear event is the real thing.
985              ;; -- putting the sit-for in causes the pending
986              ;;    SelectionClear events to get processed before
987              ;;    the selection is reasserted, so everything works
988              ;;    out OK.
989              ;;
990              ;; Presumably(?) this means there is a weird timing bug
991              ;; in the selection code, but there's not a chance in hell
992              ;; that I have the patience to track it down.  Blame the
993              ;; designers of X for fucking everything up so badly.
994              ;;
995              ;; This was originally a sit-for 0 but that wasn't
996              ;; sufficient to make things work.  Even this isn't
997              ;; always sufficient but it seems to give something
998              ;; approaching a 99% success rate.  Making it higher yet
999              ;; would help guarantee success with the price that the
1000              ;; delay would start to become noticeable.
1001              ;;
1002              (and (eq (console-type) 'x)
1003                   (sit-for 0.15 t))
1004              (zmacs-activate-region)))
1005           ((console-on-window-system-p)
1006            (if (= start end)
1007                (disown-selection type)
1008              (if (consp default-mouse-track-extent)
1009                  ;; own the rectangular region
1010                  ;; this is a hack
1011                  (let ((r default-mouse-track-extent))
1012                    (save-excursion
1013                      (set-buffer (get-buffer-create " *rect yank temp buf*"))
1014                      (while r
1015                        (insert (extent-string (car r)) "\n")
1016                        (setq r (cdr r)))
1017                      (own-selection (buffer-substring (point-min) (point-max)))
1018                      (kill-buffer (current-buffer))))
1019                (own-selection (cons (set-marker (make-marker) start)
1020                                     (set-marker (make-marker) end))
1021                               type)))))
1022     (if (and (eq 'x (console-type))
1023              (not (= start end)))
1024         ;; I guess cutbuffers should do something with rectangles too.
1025         ;; does anybody use them?
1026         (x-store-cutbuffer (buffer-substring start end)))))
1027
1028 (defun default-mouse-track-deal-with-down-event (click-count)
1029   (let ((event default-mouse-track-down-event))
1030     (if (null event) nil
1031       (select-frame (event-frame event))
1032       (let ((adjust default-mouse-track-adjust)
1033             ;; ####When you click on the splash-screen,
1034             ;; event-{closest-,}point can be out of bounds.  Should
1035             ;; event-closest-point really be allowed to return a bad
1036             ;; position like that?  Maybe pixel_to_glyph_translation
1037             ;; needs to invalidate its cache when the buffer changes.
1038             ;; -dkindred@cs.cmu.edu
1039             (close-pos  (save-excursion
1040                           (set-buffer (event-buffer event))
1041                           (let ((p (event-closest-point event)))
1042                             (and p (min (max p (point-min)) (point-max))))))
1043             extent previous-point)
1044
1045         (if (not (event-window event))
1046             (error "not over window?"))
1047         (setq default-mouse-track-type
1048               (nth (mod (1- click-count)
1049                         (length default-mouse-track-type-list))
1050                    default-mouse-track-type-list))
1051         (setq default-mouse-track-window (event-window event))
1052         ;; Note that the extent used here is NOT the extent which
1053         ;; ends up as the value of zmacs-region-extent - this one is used
1054         ;; just during mouse-dragging.
1055         (setq default-mouse-track-extent
1056               (make-extent close-pos close-pos (event-buffer event)))
1057         (setq extent default-mouse-track-extent)
1058         (set-extent-face extent 'zmacs-region)
1059         ;; While the selection is being dragged out, give the selection extent
1060         ;; slightly higher priority than any mouse-highlighted extent, so that
1061         ;; the exact endpoints of the selection will be visible while the mouse
1062         ;; is down.  Normally, the selection and mouse highlighting have the
1063         ;; same priority, so that conflicts between the two of them are
1064         ;; resolved by the usual size-and-endpoint-comparison method.
1065         (set-extent-priority extent (1+ mouse-highlight-priority))
1066         (if mouse-track-rectangle-p
1067             (setq default-mouse-track-extent
1068                   (list default-mouse-track-extent)))
1069
1070         (setq previous-point
1071               (if (and adjust
1072                        (markerp default-mouse-track-previous-point)
1073                        (eq (current-buffer)
1074                            (marker-buffer default-mouse-track-previous-point)))
1075                   (marker-position default-mouse-track-previous-point)
1076                 (point)))
1077         (default-mouse-track-set-point event default-mouse-track-window)
1078         (if (not adjust)
1079             (if (markerp default-mouse-track-previous-point)
1080                 (set-marker default-mouse-track-previous-point (point))
1081               (setq default-mouse-track-previous-point (point-marker))))
1082         ;;
1083         ;; adjust point to a word or line boundary if appropriate
1084         (let ((anchor (default-mouse-track-anchor adjust previous-point)))
1085           (setq default-mouse-track-min-anchor
1086                 (save-excursion (goto-char anchor)
1087                                 (funcall
1088                                  default-mouse-track-normalize-point-function
1089                                  default-mouse-track-type nil)
1090                                 (point)))
1091           (setq default-mouse-track-max-anchor
1092                 (save-excursion (goto-char anchor)
1093                                 (funcall
1094                                  default-mouse-track-normalize-point-function
1095                                  default-mouse-track-type t)
1096                                 (point))))
1097         ;;
1098         ;; remove the existing selection to unclutter the display
1099         (if (not adjust)
1100             (cond (zmacs-regions
1101                    (zmacs-deactivate-region))
1102                   ((console-on-window-system-p)
1103                    (disown-selection)))))
1104       (setq default-mouse-track-down-event nil))))
1105
1106 (defun default-mouse-track-down-hook (event click-count)
1107   (setq default-mouse-track-down-event (copy-event event))
1108   nil)
1109
1110 (defun default-mouse-track-cleanup-extents-hook ()
1111   (remove-hook 'pre-command-hook 'default-mouse-track-cleanup-extents-hook)
1112   (let ((extent default-mouse-track-extent))
1113     (if (consp extent) ; rectangle-p
1114         (mapcar 'delete-extent extent)
1115       (if extent
1116           (delete-extent extent)))))
1117
1118 (defun default-mouse-track-cleanup-hook ()
1119   (if zmacs-regions
1120       (funcall 'default-mouse-track-cleanup-extents-hook)
1121     (let ((extent default-mouse-track-extent)
1122           (func #'(lambda (e)
1123                     (and (extent-live-p e)
1124                          (set-extent-face e 'primary-selection)))))
1125       (add-hook 'pre-command-hook 'default-mouse-track-cleanup-extents-hook)
1126       (if (consp extent)                ; rectangle-p
1127           (mapcar func extent)
1128         (if extent
1129             (funcall func extent))))))
1130
1131 (defun default-mouse-track-cleanup-extent ()
1132   (let ((dead-func
1133          (function (lambda (x)
1134                      (or (not (extent-live-p x))
1135                          (extent-detached-p x)))))
1136         (extent default-mouse-track-extent))
1137     (if (consp extent)
1138         (if (funcall dead-func extent)
1139             (let (newval)
1140               (mapcar (function (lambda (x)
1141                                   (if (not (funcall dead-func x))
1142                                       (setq newval (cons x newval)))))
1143                       extent)
1144               (setq default-mouse-track-extent (nreverse newval))))
1145       (if (funcall dead-func extent)
1146           (setq default-mouse-track-extent nil)))))
1147
1148 (defun default-mouse-track-drag-hook (event click-count was-timeout)
1149   (default-mouse-track-deal-with-down-event click-count)
1150   (default-mouse-track-set-point event default-mouse-track-window)
1151   (default-mouse-track-cleanup-extent)
1152   (default-mouse-track-next-move default-mouse-track-min-anchor
1153     default-mouse-track-max-anchor
1154     default-mouse-track-extent)
1155   t)
1156
1157 (defun default-mouse-track-return-dragged-selection (event)
1158   (default-mouse-track-cleanup-extent)
1159   (let ((extent default-mouse-track-extent)
1160         result)
1161     (default-mouse-track-set-point-in-window event default-mouse-track-window)
1162     (default-mouse-track-next-move default-mouse-track-min-anchor
1163                            default-mouse-track-max-anchor
1164                            extent)
1165     (cond ((consp extent) ; rectangle-p
1166            (let ((first (car extent))
1167                  (last (car (setq extent (nreverse extent)))))
1168              ;; nreverse is destructive so we need to reset this
1169              (setq default-mouse-track-extent extent)
1170              (setq result (cons (extent-start-position first)
1171                                 (extent-end-position last)))
1172              ;; kludge to fix up region when dragging backwards...
1173              (if (and (/= (point) (extent-start-position first))
1174                       (/= (point) (extent-end-position last))
1175                       (= (point) (extent-end-position first)))
1176                  (goto-char (car result)))))
1177           (extent
1178            (setq result (cons (extent-start-position extent)
1179                               (extent-end-position extent)))))
1180     ;; Minor kludge: if we're selecting in line-mode, include the
1181     ;; final newline.  It's hard to do this in *-normalize-point.
1182     (if (and result (eq default-mouse-track-type 'line))
1183         (let ((end-p (= (point) (cdr result))))
1184           (goto-char (cdr result))
1185           (if (not (eobp))
1186               (setcdr result (1+ (cdr result))))
1187           (goto-char (if end-p (cdr result) (car result)))))
1188 ;;;       ;; Minor kludge sub 2.  If in char mode, and we drag the
1189 ;;;       ;; mouse past EOL, include the newline.
1190 ;;;       ;;
1191 ;;;       ;; Major problem: can't easily distinguish between being
1192 ;;;       ;; just past the last char on a line, and well past it,
1193 ;;;       ;; to determine whether or not to include it in the region
1194 ;;;       ;;
1195 ;;;       (if nil ; (eq default-mouse-track-type 'char)
1196 ;;;           (let ((after-end-p (and (not (eobp))
1197 ;;;                                   (eolp)
1198 ;;;                                   (> (point) (car result)))))
1199 ;;;             (if after-end-p
1200 ;;;                 (progn
1201 ;;;                   (setcdr result (1+ (cdr result)))
1202 ;;;                   (goto-char (cdr result))))))
1203     result))
1204
1205 (defun default-mouse-track-drag-up-hook (event click-count)
1206   (let ((result (default-mouse-track-return-dragged-selection event)))
1207     (if result
1208         (default-mouse-track-maybe-own-selection result 'PRIMARY)))
1209   t)
1210
1211 (defun default-mouse-track-click-hook (event click-count)
1212   (default-mouse-track-drag-hook event click-count nil)
1213   (default-mouse-track-drag-up-hook event click-count)
1214   t)
1215
1216 (add-hook 'mouse-track-down-hook 'default-mouse-track-down-hook)
1217 (add-hook 'mouse-track-drag-hook 'default-mouse-track-drag-hook)
1218 (add-hook 'mouse-track-drag-up-hook 'default-mouse-track-drag-up-hook)
1219 (add-hook 'mouse-track-click-hook 'default-mouse-track-click-hook)
1220 (add-hook 'mouse-track-cleanup-hook 'default-mouse-track-cleanup-hook)
1221
1222 \f
1223 ;;;;;;;;;;;; other mouse-track stuff (mostly associated with the
1224 ;;;;;;;;;;;; default handlers)
1225
1226 (defun mouse-track-default (event)
1227   "Invoke `mouse-track' with only the default handlers active."
1228   (interactive "e")
1229   (let ((mouse-track-down-hook 'default-mouse-track-down-hook)
1230         (mouse-track-drag-hook 'default-mouse-track-drag-hook)
1231         (mouse-track-drag-up-hook 'default-mouse-track-drag-up-hook)
1232         (mouse-track-click-hook 'default-mouse-track-click-hook)
1233         (mouse-track-cleanup-hook 'default-mouse-track-cleanup-hook))
1234     (mouse-track event)))
1235
1236 (defun mouse-track-do-rectangle (event)
1237   "Like `mouse-track' but selects rectangles instead of regions."
1238   (interactive "e")
1239   (let ((mouse-track-rectangle-p t))
1240         (mouse-track event)))
1241
1242 (defun mouse-track-adjust (event)
1243   "Extend the existing selection.  This should be bound to a mouse button.
1244 The selection will be enlarged or shrunk so that the point of the mouse
1245 click is one of its endpoints.  This function in fact behaves fairly
1246 similarly to `mouse-track', but begins by extending the existing selection
1247 (or creating a new selection from the previous text cursor position to
1248 the current mouse position) instead of creating a new, empty selection.
1249
1250 The mouse-track handlers are run from this command just like from
1251 `mouse-track'.  Therefore, do not call this command from a mouse-track
1252 handler!"
1253   (interactive "e")
1254   (let ((default-mouse-track-adjust t))
1255     (mouse-track event)))
1256
1257 (defun mouse-track-adjust-default (event)
1258   "Extend the existing selection, using only the default handlers.
1259 This is just like `mouse-track-adjust' but will override any
1260 custom mouse-track handlers that the user may have installed."
1261   (interactive "e")
1262   (let ((default-mouse-track-adjust t))
1263     (mouse-track-default event)))
1264
1265 (defvar mouse-track-insert-selected-region nil)
1266
1267 (defun mouse-track-insert-drag-up-hook (event click-count)
1268   (setq mouse-track-insert-selected-region
1269         (default-mouse-track-return-dragged-selection event)))
1270
1271 (defun mouse-track-insert (event &optional delete)
1272   "Make a selection with the mouse and insert it at point.
1273 This is exactly the same as the `mouse-track' command on \\[mouse-track],
1274 except that point is not moved; the selected text is immediately inserted
1275 after being selected\; and the selection is immediately disowned afterwards."
1276   (interactive "*e")
1277   (setq mouse-track-insert-selected-region nil)
1278   (let ((mouse-track-drag-up-hook 'mouse-track-insert-drag-up-hook)
1279         (mouse-track-click-hook 'mouse-track-insert-click-hook)
1280         s)
1281     (save-excursion
1282       (save-window-excursion
1283         (mouse-track event)
1284         (if (consp mouse-track-insert-selected-region)
1285             (let ((pair mouse-track-insert-selected-region))
1286               (setq s (prog1
1287                           (buffer-substring (car pair) (cdr pair))
1288                         (if delete
1289                             (kill-region (car pair) (cdr pair)))))))))
1290         (or (null s) (equal s "") (insert s))))
1291
1292 (defun mouse-track-insert-click-hook (event click-count)
1293   (default-mouse-track-drag-hook event click-count nil)
1294   (mouse-track-insert-drag-up-hook event click-count)
1295   t)
1296
1297 (defun mouse-track-delete-and-insert (event)
1298   "Make a selection with the mouse and insert it at point.
1299 This is exactly the same as the `mouse-track' command on \\[mouse-track],
1300 except that point is not moved; the selected text is immediately inserted
1301 after being selected\; and the text of the selection is deleted."
1302   (interactive "*e")
1303   (mouse-track-insert event t))
1304
1305 ;;;;;;;;;;;;;;;;;;;;;;;;
1306
1307
1308 (defvar inhibit-help-echo nil
1309   "Inhibits display of `help-echo' extent properties in the minibuffer.")
1310 (defvar last-help-echo-object nil)
1311 (defvar help-echo-owns-message nil)
1312
1313 (defun clear-help-echo (&optional ignored-frame)
1314   (if help-echo-owns-message
1315       (progn
1316         (setq help-echo-owns-message nil
1317               last-help-echo-object nil)
1318         (clear-message 'help-echo))))
1319
1320 (defun show-help-echo (mess)
1321   ;; (clear-help-echo)
1322   (setq help-echo-owns-message t)
1323   (display-message 'help-echo mess))
1324
1325 (add-hook 'mouse-leave-frame-hook 'clear-help-echo)
1326
1327 ;; It may be a good idea to move this to C, for better performance of
1328 ;; extent highlighting and pointer changes.
1329 (defun default-mouse-motion-handler (event)
1330   "For use as the value of `mouse-motion-handler'.
1331 This implements the various pointer-shape variables,
1332 as well as extent highlighting, help-echo, toolbar up/down,
1333 and `mode-motion-hook'."
1334   (let* ((frame (or (event-frame event) (selected-frame)))
1335          (window (event-window event))
1336          (buffer (event-buffer event))
1337          (modeline-point (and buffer (event-modeline-position event)))
1338          (modeline-string (and modeline-point
1339                                (symbol-value-in-buffer
1340                                 'generated-modeline-string buffer)))
1341          ;; point must be invalidated by modeline-point.
1342          (point (and buffer (not modeline-point)
1343                      (event-point event)))
1344          (extent (or (and point
1345                           (extent-at point buffer 'mouse-face))
1346                      (and modeline-point
1347                           (extent-at modeline-point modeline-string
1348                                      ;; Modeline extents don't have a
1349                                      ;; mouse-face property set.
1350                                      'help-echo))))
1351          (glyph-extent1 (event-glyph-extent event))
1352          (glyph-extent (and glyph-extent1
1353                             (extent-live-p glyph-extent1)
1354                             glyph-extent1))
1355          ;; This is an extent:
1356          (user-pointer1 (or (and glyph-extent
1357                                  (extent-property glyph-extent 'pointer)
1358                                  glyph-extent)
1359                             (and point (extent-at point buffer 'pointer))
1360                             (and modeline-point
1361                                  (extent-at modeline-point modeline-string
1362                                             'pointer))))
1363          ;; And this should be a glyph:
1364          (user-pointer (and user-pointer1 (extent-live-p user-pointer1)
1365                             (extent-property user-pointer1 'pointer)))
1366          (button (event-toolbar-button event))
1367          (help (or (and glyph-extent (extent-property glyph-extent 'help-echo)
1368                         glyph-extent)
1369                    (and button (not (null (toolbar-button-help-string button)))
1370                         button)
1371                    (and point
1372                         (extent-at point buffer 'help-echo))
1373                    (and modeline-point
1374                         (extent-at modeline-point modeline-string
1375                                    'help-echo))))
1376          ;; vars is a list of glyph variables to check for a pointer
1377          ;; value.
1378          (vars (cond
1379                 ;; Checking if button is non-nil is not sufficent
1380                 ;; since the pointer could be over a blank portion
1381                 ;; of the toolbar.
1382                 ((event-over-toolbar-p event)
1383                  '(toolbar-pointer-glyph nontext-pointer-glyph
1384                                          text-pointer-glyph))
1385                 ((or extent glyph-extent)
1386                  '(selection-pointer-glyph text-pointer-glyph))
1387                 ((event-over-modeline-p event)
1388                  '(modeline-pointer-glyph nontext-pointer-glyph
1389                                           text-pointer-glyph))
1390                 ((and (event-over-vertical-divider-p event)
1391                       ;; #### I disagree with the check below.
1392                       ;; Discuss it with Kirill for 21.1.  --hniksic
1393                       (specifier-instance vertical-divider-always-visible-p
1394                                           (event-window event)))
1395                  '(divider-pointer-glyph nontext-pointer-glyph
1396                                          text-pointer-glyph))
1397                 (point '(text-pointer-glyph))
1398                 (buffer '(nontext-pointer-glyph text-pointer-glyph))
1399                 (t '(nontext-pointer-glyph text-pointer-glyph))))
1400          pointer)
1401     (and user-pointer (glyphp user-pointer)
1402          (push 'user-pointer vars))
1403     (while (and vars (not (pointer-image-instance-p pointer)))
1404       (setq pointer (glyph-image-instance (symbol-value (car vars))
1405                                           (or window frame))
1406             vars (cdr vars)))
1407
1408     (if (pointer-image-instance-p pointer)
1409         (set-frame-pointer frame pointer))
1410
1411     ;; If last-pressed-toolbar-button is not nil, then check and see
1412     ;; if we have moved to a new button and adjust the down flags
1413     ;; accordingly.
1414     (when (and (featurep 'toolbar) toolbar-active)
1415       (unless (eq last-pressed-toolbar-button button)
1416         (release-previous-toolbar-button event)
1417         (and button (press-toolbar-button event))))
1418
1419     (cond (extent (highlight-extent extent t))
1420           (glyph-extent (highlight-extent glyph-extent t))
1421           (t (highlight-extent nil nil)))
1422     (cond ((extentp help)
1423            (or inhibit-help-echo
1424                (eq help last-help-echo-object) ;save some time
1425                (eq (selected-window) (minibuffer-window))
1426                (let ((hprop (extent-property help 'help-echo)))
1427                  (setq last-help-echo-object help)
1428                  (or (stringp hprop)
1429                      (setq hprop (funcall hprop help)))
1430                  (and hprop (show-help-echo hprop)))))
1431           ((and (featurep 'toolbar)
1432                 (toolbar-button-p help)
1433                 (toolbar-button-enabled-p help))
1434            (or (not toolbar-help-enabled)
1435                (eq help last-help-echo-object) ;save some time
1436                (eq (selected-window) (minibuffer-window))
1437                (let ((hstring (toolbar-button-help-string button)))
1438                  (setq last-help-echo-object help)
1439                  (or (stringp hstring)
1440                      (setq hstring (funcall hstring help)))
1441                  (and hstring (show-help-echo hstring)))))
1442           (last-help-echo-object
1443            (clear-help-echo)))
1444     (if mouse-grabbed-buffer (setq buffer mouse-grabbed-buffer))
1445     (if (and buffer (symbol-value-in-buffer 'mode-motion-hook buffer nil))
1446         (with-current-buffer buffer
1447           (run-hook-with-args 'mode-motion-hook event)
1448
1449           ;; If the mode-motion-hook created a highlightable extent around
1450           ;; the mouse-point, highlight it right away.  Otherwise it wouldn't
1451           ;; be highlighted until the *next* motion event came in.
1452           (if (and point
1453                    (null extent)
1454                    (setq extent (extent-at point
1455                                            (event-buffer event) ; not buffer
1456                                            'mouse-face)))
1457               (highlight-extent extent t)))))
1458   nil)
1459
1460 (setq mouse-motion-handler 'default-mouse-motion-handler)
1461 \f
1462 ;;
1463 ;; Vertical divider dragging
1464 ;;
1465 (defun drag-window-divider (event)
1466   "Handle resizing windows by dragging window dividers.
1467 This is an intenal function, normally bound to button1 event in
1468 window-divider-map. You would not call it, but you may bind it to
1469 other mouse buttons."
1470   (interactive "e")
1471   ;; #### I disagree with the check below.
1472   ;; Discuss it with Kirill for 21.1.  --hniksic
1473   (if (not (specifier-instance vertical-divider-always-visible-p
1474                                (event-window event)))
1475       (error "Not over a window"))
1476   (let-specifier ((vertical-divider-shadow-thickness
1477                    (- (specifier-instance vertical-divider-shadow-thickness
1478                                           (event-window event)))
1479                    (event-window event)))
1480     (let* ((window (event-window event))
1481            (frame (event-channel event))
1482            (last-timestamp (event-timestamp event))
1483            done)
1484       (while (not done)
1485         (let* ((edges (window-pixel-edges window))
1486                (old-right (caddr edges))
1487                (old-left (car edges))
1488                (backup-conf (current-window-configuration frame))
1489                (old-edges-all-windows (mapcar 'window-pixel-edges
1490                                               (window-list))))
1491
1492           ;; This is borrowed from modeline.el:
1493           ;; requeue event and quit if this is a misc-user, eval or
1494           ;;   keypress event.
1495           ;; quit if this is a button press or release event, or if the event
1496           ;;   occurred in some other frame.
1497           ;; drag if this is a mouse motion event and the time
1498           ;;   between this event and the last event is greater than
1499           ;;   drag-divider-event-lag.
1500           ;; do nothing if this is any other kind of event.
1501           (setq event (next-event event))
1502           (cond ((or (misc-user-event-p event)
1503                      (key-press-event-p event))
1504                  (setq unread-command-events (nconc unread-command-events
1505                                                     (list event))
1506                        done t))
1507                 ((button-release-event-p event)
1508                  (setq done t))
1509                 ((button-event-p event)
1510                  (setq done t))
1511                 ((not (motion-event-p event))
1512                  (dispatch-event event))
1513                 ((not (eq frame (event-frame event)))
1514                  (setq done t))
1515                 ((< (abs (- (event-timestamp event) last-timestamp))
1516                     drag-divider-event-lag))
1517                 (t
1518                  (setq last-timestamp (event-timestamp event))
1519                  ;; Enlarge the window, calculating change in characters
1520                  ;; of default font. Do not let the window to become
1521                  ;; less than alolwed minimum (not because that's critical
1522                  ;; for the code performance, just the visual effect is
1523                  ;; better: when cursor goes to the left of the next left
1524                  ;; divider, the vindow being resized shrinks to minimal
1525                  ;; size.
1526                  (enlarge-window (max (- window-min-width (window-width window))
1527                                       (/ (- (event-x-pixel event) old-right)
1528                                          (face-width 'default window)))
1529                                  t window)
1530                  ;; Backout the change if some windows got deleted, or
1531                  ;; if the change caused more than two windows to resize
1532                  ;; (shifting the whole stack right is ugly), or if the
1533                  ;; left window side has slipped (right side cannot be
1534                  ;; moved any funrther to the right, so enlarge-window
1535                  ;; plays bad games with the left edge.
1536                  (if (or (/= (count-windows) (length old-edges-all-windows))
1537                          (/= old-left (car (window-pixel-edges window)))
1538                          ;; This check is very hairy. We allow any number
1539                          ;; of left edges to change, but only to the same
1540                          ;; new value. Similar procedure is for the right edges.
1541                          (let ((all-that-bad nil)
1542                                (new-left-ok nil)
1543                                (new-right-ok nil))
1544                            (mapcar* (lambda (window old-edges)
1545                                       (let ((new (car (window-pixel-edges window))))
1546                                         (if (/= new (car old-edges))
1547                                             (if (and new-left-ok
1548                                                      (/= new-left-ok new))
1549                                                 (setq all-that-bad t)
1550                                               (setq new-left-ok new)))))
1551                                     (window-list) old-edges-all-windows)
1552                            (mapcar* (lambda (window old-edges)
1553                                       (let ((new (caddr (window-pixel-edges window))))
1554                                         (if (/= new (caddr old-edges))
1555                                             (if (and new-right-ok
1556                                                      (/= new-right-ok new))
1557                                                 (setq all-that-bad t)
1558                                               (setq new-right-ok new)))))
1559                                     (window-list) old-edges-all-windows)
1560                            all-that-bad))
1561                      (set-window-configuration backup-conf)))))))))
1562
1563 (setq vertical-divider-map (make-keymap))
1564 (define-key vertical-divider-map 'button1 'drag-window-divider)
1565
1566 ;;; mouse.el ends here