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