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