mouse.el 94.3 KB
Newer Older
Richard M. Stallman's avatar
Richard M. Stallman committed
1
;;; mouse.el --- window system-independent mouse support
Eric S. Raymond's avatar
Eric S. Raymond committed
2

3
;; Copyright (C) 1993, 1994, 1995, 1999, 2000, 2001, 2002, 2003,
Glenn Morris's avatar
Glenn Morris committed
4
;;   2004, 2005, 2006, 2007 Free Software Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
5

Eric S. Raymond's avatar
Eric S. Raymond committed
6
;; Maintainer: FSF
7
;; Keywords: hardware, mouse
Eric S. Raymond's avatar
Eric S. Raymond committed
8

Richard M. Stallman's avatar
Richard M. Stallman committed
9
;; This file is part of GNU Emacs.
Richard M. Stallman's avatar
Richard M. Stallman committed
10

Richard M. Stallman's avatar
Richard M. Stallman committed
11 12 13 14
;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
Richard M. Stallman's avatar
Richard M. Stallman committed
15

Richard M. Stallman's avatar
Richard M. Stallman committed
16 17 18 19
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
Richard M. Stallman's avatar
Richard M. Stallman committed
20

Richard M. Stallman's avatar
Richard M. Stallman committed
21
;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs; see the file COPYING.  If not, write to the
Lute Kamstra's avatar
Lute Kamstra committed
23 24
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.
Richard M. Stallman's avatar
Richard M. Stallman committed
25

26 27 28 29 30 31 32 33
;;; Commentary:

;; This package provides various useful commands (including help
;; system access) through the mouse.  All this code assumes that mouse
;; interpretation has been abstracted into Emacs input events.
;;
;; The code is rather X-dependent.

34 35
;;; Code:

Jim Blandy's avatar
Jim Blandy committed
36
;;; Utility functions.
Richard M. Stallman's avatar
Richard M. Stallman committed
37

Jim Blandy's avatar
Jim Blandy committed
38 39
;;; Indent track-mouse like progn.
(put 'track-mouse 'lisp-indent-function 0)
Richard M. Stallman's avatar
Richard M. Stallman committed
40

Richard M. Stallman's avatar
Richard M. Stallman committed
41 42 43 44
(defcustom mouse-yank-at-point nil
  "*If non-nil, mouse yank commands yank at point instead of at click."
  :type 'boolean
  :group 'mouse)
45 46 47 48

(defcustom mouse-drag-copy-region t
  "*If non-nil, mouse drag copies region to kill-ring."
  :type 'boolean
49
  :version "22.1"
50 51
  :group 'mouse)

52
(defcustom mouse-1-click-follows-link 450
53
  "Non-nil means that clicking Mouse-1 on a link follows the link.
54

55 56
With the default setting, an ordinary Mouse-1 click on a link
performs the same action as Mouse-2 on that link, while a longer
57
Mouse-1 click \(hold down the Mouse-1 button for more than 450
58
milliseconds) performs the original Mouse-1 binding \(which
59 60 61 62
typically sets point where you click the mouse).

If value is an integer, the time elapsed between pressing and
releasing the mouse button determines whether to follow the link
63
or perform the normal Mouse-1 action (typically set point).
64 65 66
The absolute numeric value specifices the maximum duration of a
\"short click\" in milliseconds.  A positive value means that a
short click follows the link, and a longer click performs the
67
normal action.  A negative value gives the opposite behavior.
68 69 70

If value is `double', a double click follows the link.

71
Otherwise, a single Mouse-1 click unconditionally follows the link.
72 73 74 75 76 77

Note that dragging the mouse never follows the link.

This feature only works in modes that specifically identify
clickable text as links, so it may not work with some external
packages.  See `mouse-on-link-p' for details."
78
  :version "22.1"
79 80
  :type '(choice (const :tag "Disabled" nil)
		 (const :tag "Double click" double)
81
                 (number :tag "Single click time limit" :value 450)
82 83 84
                 (other :tag "Single click" t))
  :group 'mouse)

85 86 87 88 89 90 91 92 93 94 95
(defcustom mouse-1-click-in-non-selected-windows t
  "*If non-nil, a Mouse-1 click also follows links in non-selected windows.

If nil, a Mouse-1 click on a link in a non-selected window performs
the normal mouse-1 binding, typically selects the window and sets
point at the click position."
  :type 'boolean
  :version "22.1"
  :group 'mouse)


Jim Blandy's avatar
Jim Blandy committed
96

97 98
;; Provide a mode-specific menu on a mouse button.

Stefan Monnier's avatar
Stefan Monnier committed
99 100
(defun popup-menu (menu &optional position prefix)
  "Popup the given menu and call the selected option.
101 102
MENU can be a keymap, an easymenu-style menu or a list of keymaps as for
`x-popup-menu'.
Stefan Monnier's avatar
Stefan Monnier committed
103 104 105
POSITION can be a click event or ((XOFFSET YOFFSET) WINDOW) and defaults to
  the current mouse position.
PREFIX is the prefix argument (if any) to pass to the command."
106 107 108 109
  (let* ((map (cond
	       ((keymapp menu) menu)
	       ((and (listp menu) (keymapp (car menu))) menu)
	       (t (let* ((map (easy-menu-create-menu (car menu) (cdr menu)))
Stefan Monnier's avatar
Stefan Monnier committed
110 111 112
			 (filter (when (symbolp map)
				   (plist-get (get map 'menu-prop) :filter))))
		    (if filter (funcall filter (symbol-function map)) map)))))
113
	 event cmd)
114
    (unless position
Dave Love's avatar
Dave Love committed
115
      (let ((mp (mouse-pixel-position)))
116
	(setq position (list (list (cadr mp) (cddr mp)) (car mp)))))
Stefan Monnier's avatar
Stefan Monnier committed
117
    ;; The looping behavior was taken from lmenu's popup-menu-popup
118 119 120 121
    (while (and map (setq event
			  ;; map could be a prefix key, in which case
			  ;; we need to get its function cell
			  ;; definition.
Dave Love's avatar
Dave Love committed
122
			  (x-popup-menu position (indirect-function map))))
Stefan Monnier's avatar
Stefan Monnier committed
123 124 125
      ;; Strangely x-popup-menu returns a list.
      ;; mouse-major-mode-menu was using a weird:
      ;; (key-binding (apply 'vector (append '(menu-bar) menu-prefix events)))
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
      (setq cmd
	    (if (and (not (keymapp map)) (listp map))
		;; We were given a list of keymaps.  Search them all
		;; in sequence until a first binding is found.
		(let ((mouse-click (apply 'vector event))
		      binding)
		  (while (and map (null binding))
		    (setq binding (lookup-key (car map) mouse-click))
		    (if (numberp binding) ; `too long'
			(setq binding nil))
		    (setq map (cdr map)))
		  binding)
	      ;; We were given a single keymap.
	      (lookup-key map (apply 'vector event))))
      ;; Clear out echoing, which perhaps shows a prefix arg.
      (message "")
      ;; Maybe try again but with the submap.
      (setq map (if (keymapp cmd) cmd)))
144 145 146
    ;; If the user did not cancel by refusing to select,
    ;; and if the result is a command, run it.
    (when (and (null map) (commandp cmd))
147 148 149 150 151
      (setq prefix-arg prefix)
      ;; `setup-specified-language-environment', for instance,
      ;; expects this to be set from a menu keymap.
      (setq last-command-event (car (last event)))
      ;; mouse-major-mode-menu was using `command-execute' instead.
Miles Bader's avatar
Miles Bader committed
152
      (call-interactively cmd))))
153 154 155

(defvar mouse-major-mode-menu-prefix)	; dynamically bound

156
(defun mouse-major-mode-menu (event &optional prefix)
157 158
  "Pop up a mode-specific menu of mouse commands.
Default to the Edit menu if the major mode doesn't define a menu."
159 160
  ;; Switch to the window clicked on, because otherwise
  ;; the mode's commands may not make sense.
161
  (interactive "@e\nP")
162
  ;; Let the mode update its menus first.
163
  (run-hooks 'activate-menubar-hook 'menu-bar-update-hook)
164 165 166 167 168 169 170
  (let* (;; This is where mouse-major-mode-menu-prefix
	 ;; returns the prefix we should use (after menu-bar).
	 ;; It is either nil or (SOME-SYMBOL).
	 (mouse-major-mode-menu-prefix nil)
	 ;; Keymap from which to inherit; may be null.
	 (ancestor (mouse-major-mode-menu-1
		    (and (current-local-map)
171
			 (local-key-binding [menu-bar]))))
172 173 174 175
	 ;; Make a keymap in which our last command leads to a menu or
	 ;; default to the edit menu.
	 (newmap (if ancestor
		     (make-sparse-keymap (concat mode-name " Mode"))
176
		   menu-bar-edit-menu)))
177 178 179 180
    (if ancestor
	;; Make our menu inherit from the desired keymap which we want
	;; to display as the menu now.
	(set-keymap-parent newmap ancestor))
Stefan Monnier's avatar
Stefan Monnier committed
181 182
    (popup-menu newmap event prefix)))

183 184

;; Compute and cache the equivalent keys in MENU and all its submenus.
185 186 187 188 189 190 191 192 193 194 195 196 197
;;;(defun mouse-major-mode-menu-compute-equiv-keys (menu)
;;;  (and (eq (car menu) 'keymap)
;;;       (x-popup-menu nil menu))
;;;  (while menu
;;;    (and (consp (car menu))
;;;	 (consp (cdr (car menu)))
;;;	 (let ((tail (cdr (car menu))))
;;;	   (while (and (consp tail)
;;;		       (not (eq (car tail) 'keymap)))
;;;	     (setq tail (cdr tail)))
;;;	   (if (consp tail)
;;;	       (mouse-major-mode-menu-compute-equiv-keys tail))))
;;;    (setq menu (cdr menu))))
198 199 200 201 202 203 204 205 206 207 208 209 210

;; Given a mode's menu bar keymap,
;; if it defines exactly one menu bar menu,
;; return just that menu.
;; Otherwise return a menu for all of them.
(defun mouse-major-mode-menu-1 (menubar)
  (if menubar
      (let ((tail menubar)
	    submap)
	(while tail
	  (if (consp (car tail))
	      (if submap
		  (setq submap t)
211
		(setq submap (car tail))))
212
	  (setq tail (cdr tail)))
213
	(if (eq submap t)
214
	    menubar
215
	  (setq mouse-major-mode-menu-prefix (list (car submap)))
216
	  (lookup-key menubar (vector (car submap)))))))
217 218

(defun mouse-popup-menubar (event prefix)
219
  "Pop up a menu equivalent to the menu bar for keyboard EVENT with PREFIX.
220 221 222
The contents are the items that would be in the menu bar whether or
not it is actually displayed."
  (interactive "@e \nP")
223
  (run-hooks 'activate-menubar-hook 'menu-bar-update-hook)
224 225 226
  (let* ((local-menu (and (current-local-map)
			  (lookup-key (current-local-map) [menu-bar])))
	 (global-menu (lookup-key global-map [menu-bar]))
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
	 ;; If a keymap doesn't have a prompt string (a lazy
	 ;; programmer didn't bother to provide one), create it and
	 ;; insert it into the keymap; each keymap gets its own
	 ;; prompt.  This is required for non-toolkit versions to
	 ;; display non-empty menu pane names.
	 (minor-mode-menus
	  (mapcar
	   (function
	    (lambda (menu)
	      (let* ((minor-mode (car menu))
		     (menu (cdr menu))
		     (title-or-map (cadr menu)))
		(or (stringp title-or-map)
		    (setq menu
			  (cons 'keymap
				(cons (concat
				       (capitalize (subst-char-in-string
244
						    ?- ?\s (symbol-name
245 246 247 248 249
							    minor-mode)))
				       " Menu")
				      (cdr menu)))))
		menu)))
	   (minor-mode-key-binding [menu-bar])))
250 251 252 253 254 255 256 257 258 259 260
	 (local-title-or-map (and local-menu (cadr local-menu)))
	 (global-title-or-map (cadr global-menu)))
    (or (null local-menu)
	(stringp local-title-or-map)
	(setq local-menu (cons 'keymap
			       (cons (concat mode-name " Mode Menu")
				     (cdr local-menu)))))
    (or (stringp global-title-or-map)
	(setq global-menu (cons 'keymap
			        (cons "Global Menu"
				      (cdr global-menu)))))
261
    ;; Supplying the list is faster than making a new map.
262 263 264 265
    (popup-menu (append (list global-menu)
			(if local-menu
			    (list local-menu))
			minor-mode-menus)
266
		event prefix)))
267 268 269 270 271 272 273 274

(defun mouse-popup-menubar-stuff (event prefix)
  "Popup a menu like either `mouse-major-mode-menu' or `mouse-popup-menubar'.
Use the former if the menu bar is showing, otherwise the latter."
  (interactive "@e \nP")
  (if (zerop (assoc-default 'menu-bar-lines (frame-parameters) 'eq 0))
      (mouse-popup-menubar event prefix)
    (mouse-major-mode-menu event prefix)))
275

276 277
;; Commands that operate on windows.

278 279 280 281
(defun mouse-minibuffer-check (event)
  (let ((w (posn-window (event-start event))))
    (and (window-minibuffer-p w)
	 (not (minibuffer-window-active-p w))
282 283 284
	 (error "Minibuffer window is not active")))
  ;; Give temporary modes such as isearch a chance to turn off.
  (run-hooks 'mouse-leave-buffer-hook))
285

Jim Blandy's avatar
Jim Blandy committed
286
(defun mouse-delete-window (click)
287
  "Delete the window you click on.
288
Do nothing if the frame has just one window.
289
This command must be bound to a mouse click."
Jim Blandy's avatar
Jim Blandy committed
290
  (interactive "e")
291
  (unless (one-window-p t)
292 293
    (mouse-minibuffer-check click)
    (delete-window (posn-window (event-start click)))))
Jim Blandy's avatar
Jim Blandy committed
294

295 296 297
(defun mouse-select-window (click)
  "Select the window clicked on; don't move point."
  (interactive "e")
298
  (mouse-minibuffer-check click)
299 300 301 302 303 304
  (let ((oframe (selected-frame))
	(frame (window-frame (posn-window (event-start click)))))
    (select-window (posn-window (event-start click)))
    (raise-frame frame)
    (select-frame frame)
    (or (eq frame oframe)
305
	(set-mouse-position (selected-frame) (1- (frame-width)) 0))))
306

307 308 309
(defun mouse-tear-off-window (click)
  "Delete the window clicked on, and create a new frame displaying its buffer."
  (interactive "e")
310
  (mouse-minibuffer-check click)
311 312
  (let* ((window (posn-window (event-start click)))
	 (buf (window-buffer window))
313
	 (frame (make-frame)))
314 315 316 317
    (select-frame frame)
    (switch-to-buffer buf)
    (delete-window window)))

318
(defun mouse-delete-other-windows ()
319
  "Delete all windows except the one you click on."
320
  (interactive "@")
Jim Blandy's avatar
Jim Blandy committed
321
  (delete-other-windows))
Richard M. Stallman's avatar
Richard M. Stallman committed
322

Jim Blandy's avatar
Jim Blandy committed
323 324 325 326
(defun mouse-split-window-vertically (click)
  "Select Emacs window mouse is on, then split it vertically in half.
The window is split at the line clicked on.
This command must be bound to a mouse click."
327
  (interactive "@e")
328
  (mouse-minibuffer-check click)
329 330
  (let ((start (event-start click)))
    (select-window (posn-window start))
331
    (let ((new-height (1+ (cdr (posn-col-row (event-end click)))))
332 333 334
	  (first-line window-min-height)
	  (last-line (- (window-height) window-min-height)))
      (if (< last-line first-line)
335
	  (error "Window too short to split")
336 337
	(split-window-vertically
	 (min (max new-height first-line) last-line))))))
Jim Blandy's avatar
Jim Blandy committed
338

339 340 341 342 343
(defun mouse-split-window-horizontally (click)
  "Select Emacs window mouse is on, then split it horizontally in half.
The window is split at the column clicked on.
This command must be bound to a mouse click."
  (interactive "@e")
344
  (mouse-minibuffer-check click)
345 346 347 348 349 350
  (let ((start (event-start click)))
    (select-window (posn-window start))
    (let ((new-width (1+ (car (posn-col-row (event-end click)))))
	  (first-col window-min-width)
	  (last-col (- (window-width) window-min-width)))
      (if (< last-col first-col)
351
	  (error "Window too narrow to split")
352 353
	(split-window-horizontally
	 (min (max new-width first-col) last-col))))))
354

355 356 357
(defun mouse-drag-window-above (window)
  "Return the (or a) window directly above WINDOW.
That means one whose bottom edge is at the same height as WINDOW's top edge."
358 359 360
  (let ((start-top   (nth 1 (window-edges window)))
        (start-left  (nth 0 (window-edges window)))
        (start-right (nth 2 (window-edges window)))
361 362 363 364
	(start-window window)
	above-window)
    (setq window (previous-window window 0))
    (while (and (not above-window) (not (eq window start-window)))
365 366 367 368 369 370 371 372
      (let ((left  (nth 0 (window-edges window)))
            (right (nth 2 (window-edges window))))
        (when (and (= (+ (window-height window) (nth 1 (window-edges window)))
                      start-top)
                   (or (and (<= left start-left)  (<= start-right right))
                       (and (<= start-left left)  (<= left start-right))
                       (and (<= start-left right) (<= right start-right))))
          (setq above-window window)))
373 374 375 376 377 378 379 380
      (setq window (previous-window window)))
    above-window))

(defun mouse-drag-move-window-bottom (window growth)
  "Move the bottom of WINDOW up or down by GROWTH lines.
Move it down if GROWTH is positive, or up if GROWTH is negative.
If this would make WINDOW too short,
shrink the window or windows above it to make room."
381 382 383
  (condition-case nil
      (adjust-window-trailing-edge window growth nil)
    (error nil)))
384

385 386 387 388 389 390 391 392 393 394 395
(defsubst mouse-drag-move-window-top (window growth)
  "Move the top of WINDOW up or down by GROWTH lines.
Move it down if GROWTH is positive, or up if GROWTH is negative.
If this would make WINDOW too short, shrink the window or windows
above it to make room."
  ;; Moving the top of WINDOW is actually moving the bottom of the
  ;; window above.
  (let ((window-above (mouse-drag-window-above window)))
    (and window-above
	 (mouse-drag-move-window-bottom window-above (- growth)))))

396 397 398
(defun mouse-drag-mode-line-1 (start-event mode-line-p)
  "Change the height of a window by dragging on the mode or header line.
START-EVENT is the starting mouse-event of the drag action.
399
MODE-LINE-P non-nil means dragging a mode line; nil means a header line."
400 401
  ;; Give temporary modes such as isearch a chance to turn off.
  (run-hooks 'mouse-leave-buffer-hook)
402 403 404 405 406 407 408 409
  (let* ((done nil)
	 (echo-keystrokes 0)
	 (start (event-start start-event))
	 (start-event-window (posn-window start))
	 (start-event-frame (window-frame start-event-window))
	 (start-nwindows (count-windows t))
	 (minibuffer (frame-parameter nil 'minibuffer))
	 should-enlarge-minibuffer event mouse y top bot edges wconfig growth)
410 411 412 413 414 415
    (track-mouse
      (progn
	;; if this is the bottommost ordinary window, then to
	;; move its modeline the minibuffer must be enlarged.
	(setq should-enlarge-minibuffer
	      (and minibuffer
416
		   mode-line-p
417 418
		   (not (one-window-p t))
		   (= (nth 1 (window-edges minibuffer))
419
		      (nth 3 (window-edges start-event-window)))))
420

421 422 423 424 425
	;; loop reading events and sampling the position of
	;; the mouse.
	(while (not done)
	  (setq event (read-event)
		mouse (mouse-position))
426

427 428 429 430 431 432 433 434 435
	  ;; do nothing if
	  ;;   - there is a switch-frame event.
	  ;;   - the mouse isn't in the frame that we started in
	  ;;   - the mouse isn't in any Emacs frame
	  ;; drag if
	  ;;   - there is a mouse-movement event
	  ;;   - there is a scroll-bar-movement event
	  ;;     (same as mouse movement for our purposes)
	  ;; quit if
436 437
	  ;;   - there is a keyboard event or some other unknown event.
	  (cond ((not (consp event))
438
		 (setq done t))
439

440
		((memq (car event) '(switch-frame select-window))
441
		 nil)
442

443 444
		((not (memq (car event) '(mouse-movement scroll-bar-movement)))
		 (when (consp event)
445 446 447 448 449
		   ;; Do not unread a drag-mouse-1 event since it will cause the
		   ;; selection of the window above when dragging the modeline
		   ;; above the selected window.
		   (unless (eq (car event) 'drag-mouse-1)
		     (push event unread-command-events)))
450
		 (setq done t))
451

452 453
		((not (eq (car mouse) start-event-frame))
		 nil)
454

455 456
		((null (car (cdr mouse)))
		 nil)
457

458 459
		(t
		 (setq y (cdr (cdr mouse))
460
		       edges (window-edges start-event-window)
461 462
		       top (nth 1 edges)
		       bot (nth 3 edges))
463

464
		 ;; compute size change needed
465 466
		 (cond (mode-line-p
			(setq growth (- y bot -1)))
467 468 469 470 471
		       (t	; header line
			(when (< (- bot y) window-min-height)
			  (setq y (- bot window-min-height)))
			;; The window's top includes the header line!
			(setq growth (- top y))))
472
		 (setq wconfig (current-window-configuration))
473

474
		 ;; Check for an error case.
475 476 477 478
		 (when (and (/= growth 0)
			    (not minibuffer)
			    (one-window-p t))
		   (error "Attempt to resize sole window"))
479

480 481
		 ;; grow/shrink minibuffer?
		 (if should-enlarge-minibuffer
482 483
		     (unless resize-mini-windows
		       (mouse-drag-move-window-bottom start-event-window growth))
484
		   ;; no.  grow/shrink the selected window
485
		   ;(message "growth = %d" growth)
486 487 488
		   (if mode-line-p
		       (mouse-drag-move-window-bottom start-event-window growth)
		     (mouse-drag-move-window-top start-event-window growth)))
489

490 491 492 493 494 495
		 ;; if this window's growth caused another
		 ;; window to be deleted because it was too
		 ;; short, rescind the change.
		 ;;
		 ;; if size change caused space to be stolen
		 ;; from a window above this one, rescind the
496
		 ;; change, but only if we didn't grow/shrink
497 498 499
		 ;; the minibuffer.  minibuffer size changes
		 ;; can cause all windows to shrink... no way
		 ;; around it.
500 501
		 (when (or (/= start-nwindows (count-windows t))
			   (and (not should-enlarge-minibuffer)
502
				(> growth 0)
503
				mode-line-p
504 505 506 507
				(/= top
				    (nth 1 (window-edges
					    ;; Choose right window.
					    start-event-window)))))
508
		   (set-window-configuration wconfig)))))))))
509 510 511 512 513 514 515

(defun mouse-drag-mode-line (start-event)
  "Change the height of a window by dragging on the mode line."
  (interactive "e")
  (mouse-drag-mode-line-1 start-event t))

(defun mouse-drag-header-line (start-event)
516 517 518
  "Change the height of a window by dragging on the header line.
Windows whose header-lines are at the top of the frame cannot be
resized by dragging their header-line."
519
  (interactive "e")
520 521 522 523 524 525 526
  ;; Changing the window's size by dragging its header-line when the
  ;; header-line is at the top of the frame is somewhat strange,
  ;; because the header-line doesn't move, so don't do it.
  (let* ((start (event-start start-event))
	 (window (posn-window start))
	 (frame (window-frame window))
	 (first-window (frame-first-window frame)))
Chong Yidong's avatar
Chong Yidong committed
527 528 529 530
    (unless (or (eq window first-window)
		(= (nth 1 (window-edges window))
		   (nth 1 (window-edges first-window))))
      (mouse-drag-mode-line-1 start-event nil))))
531

532

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
(defun mouse-drag-vertical-line-rightward-window (window)
  "Return a window that is immediately to the right of WINDOW, or nil."
  (let ((bottom (nth 3 (window-inside-edges window)))
	(left (nth 0 (window-inside-edges window)))
	best best-right
	(try (previous-window window)))
    (while (not (eq try window))
      (let ((try-top (nth 1 (window-inside-edges try)))
	    (try-bottom (nth 3 (window-inside-edges try)))
	    (try-right (nth 2 (window-inside-edges try))))
	(if (and (< try-top bottom)
		 (>= try-bottom bottom)
		 (< try-right left)
		 (or (null best-right) (> try-right best-right)))
	    (setq best-right try-right best try)))
      (setq try (previous-window try)))
    best))

551 552 553 554 555
(defun mouse-drag-vertical-line (start-event)
  "Change the width of a window by dragging on the vertical line."
  (interactive "e")
  ;; Give temporary modes such as isearch a chance to turn off.
  (run-hooks 'mouse-leave-buffer-hook)
556 557 558 559
  (let* ((done nil)
	 (echo-keystrokes 0)
	 (start-event-frame (window-frame (car (car (cdr start-event)))))
	 (start-event-window (car (car (cdr start-event))))
560
	 event mouse x left right edges growth
561 562 563
	 (which-side
	  (or (cdr (assq 'vertical-scroll-bars (frame-parameters start-event-frame)))
	      'right)))
564 565 566 567 568 569 570 571 572 573
    (cond
     ((one-window-p t)
      (error "Attempt to resize sole ordinary window"))
     ((and (eq which-side 'right)
	   (>= (nth 2 (window-inside-edges start-event-window))
	       (frame-width start-event-frame)))
      (error "Attempt to drag rightmost scrollbar"))
     ((and (eq which-side 'left)
	   (= (nth 0 (window-inside-edges start-event-window)) 0))
      (error "Attempt to drag leftmost scrollbar")))
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    (track-mouse
      (progn
	;; loop reading events and sampling the position of
	;; the mouse.
	(while (not done)
	  (setq event (read-event)
		mouse (mouse-position))
	  ;; do nothing if
	  ;;   - there is a switch-frame event.
	  ;;   - the mouse isn't in the frame that we started in
	  ;;   - the mouse isn't in any Emacs frame
	  ;; drag if
	  ;;   - there is a mouse-movement event
	  ;;   - there is a scroll-bar-movement event
	  ;;     (same as mouse movement for our purposes)
	  ;; quit if
	  ;;   - there is a keyboard event or some other unknown event
	  ;;     unknown event.
	  (cond ((integerp event)
		 (setq done t))
594
		((memq (car event) '(switch-frame select-window))
595 596 597 598 599 600 601 602 603 604 605 606
		 nil)
		((not (memq (car event)
			    '(mouse-movement scroll-bar-movement)))
		 (if (consp event)
		     (setq unread-command-events
			   (cons event unread-command-events)))
		 (setq done t))
		((not (eq (car mouse) start-event-frame))
		 nil)
		((null (car (cdr mouse)))
		 nil)
		(t
607 608 609 610
		 (let ((window
			;; If the scroll bar is on the window's left,
			;; adjust the window on the left.
			(if (eq which-side 'right)
611
			    start-event-window
612
			  (mouse-drag-vertical-line-rightward-window
613
			   start-event-window))))
614
		   (setq x (- (car (cdr mouse))
Karl Heuer's avatar
Karl Heuer committed
615
			      (if (eq which-side 'right) 0 2))
616
			 edges (window-edges window)
617 618 619 620 621 622 623
			 left (nth 0 edges)
			 right (nth 2 edges))
		   ;; scale back a move that would make the
		   ;; window too thin.
		   (if (< (- x left -1) window-min-width)
		       (setq x (+ left window-min-width -1)))
		   ;; compute size change needed
624 625 626 627
		   (setq growth (- x right -1))
		   (condition-case nil
		       (adjust-window-trailing-edge window growth t)
		     (error nil))))))))))
628

629
(defun mouse-set-point (event)
Jim Blandy's avatar
Jim Blandy committed
630
  "Move point to the position clicked on with the mouse.
631
This should be bound to a mouse click event type."
Jim Blandy's avatar
Jim Blandy committed
632
  (interactive "e")
633
  (mouse-minibuffer-check event)
634 635
  ;; Use event-end in case called from mouse-drag-region.
  ;; If EVENT is a click, event-end and event-start give same value.
Stefan Monnier's avatar
Stefan Monnier committed
636
  (posn-set-point (event-end event)))
Jim Blandy's avatar
Jim Blandy committed
637

638 639 640 641 642 643 644 645 646 647 648
(defvar mouse-last-region-beg nil)
(defvar mouse-last-region-end nil)
(defvar mouse-last-region-tick nil)

(defun mouse-region-match ()
  "Return non-nil if there's an active region that was set with the mouse."
  (and (mark t) mark-active
       (eq mouse-last-region-beg (region-beginning))
       (eq mouse-last-region-end (region-end))
       (eq mouse-last-region-tick (buffer-modified-tick))))

649
(defun mouse-set-region (click)
650
  "Set the region to the text dragged over, and copy to kill ring.
651
This should be bound to a mouse drag event."
652
  (interactive "e")
653
  (mouse-minibuffer-check click)
654 655 656 657 658
  (let ((posn (event-start click))
	(end (event-end click)))
    (select-window (posn-window posn))
    (if (numberp (posn-point posn))
	(goto-char (posn-point posn)))
659
    ;; If mark is highlighted, no need to bounce the cursor.
660 661
    ;; On X, we highlight while dragging, thus once again no need to bounce.
    (or transient-mark-mode
662
	(memq (framep (selected-frame)) '(x pc w32 mac))
663
	(sit-for 1))
664
    (push-mark)
665
    (set-mark (point))
666
    (if (numberp (posn-point end))
667 668 669
	(goto-char (posn-point end)))
    ;; Don't set this-command to kill-region, so that a following
    ;; C-w will not double the text in the kill ring.
670
    ;; Ignore last-command so we don't append to a preceding kill.
671 672 673
    (when mouse-drag-copy-region
      (let (this-command last-command deactivate-mark)
	(copy-region-as-kill (mark) (point))))
674 675 676
    (mouse-set-region-1)))

(defun mouse-set-region-1 ()
677
  ;; Set transient-mark-mode for a little while.
678 679
  (if (memq transient-mark-mode '(nil identity))
      (setq transient-mark-mode 'only))
680 681 682
  (setq mouse-last-region-beg (region-beginning))
  (setq mouse-last-region-end (region-end))
  (setq mouse-last-region-tick (buffer-modified-tick)))
683

Richard M. Stallman's avatar
Richard M. Stallman committed
684
(defcustom mouse-scroll-delay 0.25
685 686 687 688 689 690
  "*The pause between scroll steps caused by mouse drags, in seconds.
If you drag the mouse beyond the edge of a window, Emacs scrolls the
window to bring the text beyond that edge into view, with a delay of
this many seconds between scroll steps.  Scrolling stops when you move
the mouse back into the window, or release the button.
This variable's value may be non-integral.
Richard M. Stallman's avatar
Richard M. Stallman committed
691 692 693
Setting this to zero causes Emacs to scroll as fast as it can."
  :type 'number
  :group 'mouse)
694

Richard M. Stallman's avatar
Richard M. Stallman committed
695
(defcustom mouse-scroll-min-lines 1
696 697 698 699 700
  "*The minimum number of lines scrolled by dragging mouse out of window.
Moving the mouse out the top or bottom edge of the window begins
scrolling repeatedly.  The number of lines scrolled per repetition
is normally equal to the number of lines beyond the window edge that
the mouse has moved.  However, it always scrolls at least the number
Richard M. Stallman's avatar
Richard M. Stallman committed
701 702 703
of lines specified by this variable."
  :type 'integer
  :group 'mouse)
704

705 706
(defun mouse-scroll-subr (window jump &optional overlay start)
  "Scroll the window WINDOW, JUMP lines at a time, until new input arrives.
707 708 709
If OVERLAY is an overlay, let it stretch from START to the far edge of
the newly visible text.
Upon exit, point is at the far edge of the newly visible text."
710 711 712 713 714
  (cond
   ((and (> jump 0) (< jump mouse-scroll-min-lines))
    (setq jump mouse-scroll-min-lines))
   ((and (< jump 0) (< (- jump) mouse-scroll-min-lines))
    (setq jump (- mouse-scroll-min-lines))))
715 716 717 718 719 720 721
  (let ((opoint (point)))
    (while (progn
	     (goto-char (window-start window))
	     (if (not (zerop (vertical-motion jump window)))
		 (progn
		   (set-window-start window (point))
		   (if (natnump jump)
722 723 724 725 726 727 728
		       (if (window-end window)
			   (progn
			     (goto-char (window-end window))
			     ;; window-end doesn't reflect the window's new
			     ;; start position until the next redisplay.
			     (vertical-motion (1- jump) window))
			 (vertical-motion (- (window-height window) 2)))
729 730 731 732 733 734 735 736
		     (goto-char (window-start window)))
		   (if overlay
		       (move-overlay overlay start (point)))
		   ;; Now that we have scrolled WINDOW properly,
		   ;; put point back where it was for the redisplay
		   ;; so that we don't mess up the selected window.
		   (or (eq window (selected-window))
		       (goto-char opoint))
737
		   (sit-for mouse-scroll-delay)))))
738 739
    (or (eq window (selected-window))
	(goto-char opoint))))
740

741
;; Create an overlay and immediately delete it, to get "overlay in no buffer".
742 743 744 745 746
(defconst mouse-drag-overlay
  (let ((ol (make-overlay (point-min) (point-min))))
    (delete-overlay ol)
    (overlay-put ol 'face 'region)
    ol))
747

748
(defvar mouse-selection-click-count 0)
749

750 751
(defvar mouse-selection-click-count-buffer nil)

752
(defun mouse-drag-region (start-event)
753
  "Set the region to the text that the mouse is dragged over.
754 755
Highlight the drag area as you move the mouse.
This must be bound to a button-down mouse event.
756
In Transient Mark mode, the highlighting remains as long as the mark
757 758 759
remains active.  Otherwise, it remains until the next input event.

If the click is in the echo area, display the `*Messages*' buffer."
760
  (interactive "e")
761 762 763
  (let ((w (posn-window (event-start start-event))))
    (if (and (window-minibuffer-p w)
	     (not (minibuffer-window-active-p w)))
764
	(save-excursion
Richard M. Stallman's avatar
Richard M. Stallman committed
765
	  ;; Swallow the up-event.
766
	  (read-event)
767
	  (set-buffer (get-buffer-create "*Messages*"))
768 769 770 771
	  (goto-char (point-max))
	  (display-buffer (current-buffer)))
      ;; Give temporary modes such as isearch a chance to turn off.
      (run-hooks 'mouse-leave-buffer-hook)
772
      (mouse-drag-track start-event t))))
773

774

775
(defun mouse-posn-property (pos property)
776 777
  "Look for a property at click position.
POS may be either a buffer position or a click position like
778
those returned from `event-start'.  If the click position is on
779 780 781 782 783
a string, the text property PROPERTY is examined.
If this is nil or the click is not on a string, then
the corresponding buffer position is searched for PROPERTY.
If PROPERTY is encountered in one of those places,
its value is returned."
784 785 786 787 788 789 790 791 792
  (if (consp pos)
      (let ((w (posn-window pos)) (pt (posn-point pos))
	    (str (posn-string pos)))
	(or (and str
		 (get-text-property (cdr str) property (car str)))
	    (and pt
		 (get-char-property pt property w))))
    (get-char-property pos property)))

793 794
(defun mouse-on-link-p (pos)
  "Return non-nil if POS is on a link in the current buffer.
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
795 796
POS must be a buffer position in the current buffer or a mouse
event location in the selected window (see `event-start').
797 798
However, if `mouse-1-click-in-non-selected-windows' is non-nil,
POS may be a mouse event location in any window.
799 800 801

A clickable link is identified by one of the following methods:

Kim F. Storm's avatar
Kim F. Storm committed
802
- If the character at POS has a non-nil `follow-link' text or
803
overlay property, the value of that property determines what to do.
804

Kim F. Storm's avatar
Kim F. Storm committed
805 806 807
- If there is a local key-binding or a keybinding at position POS
for the `follow-link' event, the binding of that event determines
what to do.
808

Kim F. Storm's avatar
Kim F. Storm committed
809 810 811
The resulting value determine whether POS is inside a link:

- If the value is `mouse-face', POS is inside a link if there
812 813
is a non-nil `mouse-face' property at POS.  Return t in this case.

Kim F. Storm's avatar
Kim F. Storm committed
814
- If the value is a function, FUNC, POS is inside a link if
815
the call \(FUNC POS) returns non-nil.  Return the return value
Thien-Thi Nguyen's avatar
Thien-Thi Nguyen committed
816
from that call.  Arg is \(posn-point POS) if POS is a mouse event.
817

Kim F. Storm's avatar
Kim F. Storm committed
818
- Otherwise, return the value itself.
819 820 821 822 823 824 825 826 827 828 829 830 831

The return value is interpreted as follows:

- If it is a string, the mouse-1 event is translated into the
first character of the string, i.e. the action of the mouse-1
click is the local or global binding of that character.

- If it is a vector, the mouse-1 event is translated into the
first element of that vector, i.e. the action of the mouse-1
click is the local or global binding of that event.

- Otherwise, the mouse-1 event is translated into a mouse-2 event
at the same position."
832 833 834 835 836 837 838 839 840 841
  (let ((action
	 (and (or (not (consp pos))
		  mouse-1-click-in-non-selected-windows
		  (eq (selected-window) (posn-window pos)))
	      (or (mouse-posn-property pos 'follow-link)
		  (key-binding [follow-link] nil t pos)))))
    (cond
     ((eq action 'mouse-face)
      (and (mouse-posn-property pos 'mouse-face) t))
     ((functionp action)
842
      ;; FIXME: This seems questionable if the click is not in a buffer.
843
      ;; Should we instead decide that `action' takes a `posn'?
844 845
      (if (consp pos)
	  (with-current-buffer (window-buffer (posn-window pos))
846
	    (funcall action (posn-point pos)))
847
	(funcall action pos)))
848
     (t action))))
849

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
(defun mouse-fixup-help-message (msg)
  "Fix help message MSG for `mouse-1-click-follows-link'."
  (let (mp pos)
    (if (and mouse-1-click-follows-link
	     (stringp msg)
	     (save-match-data
	       (string-match "^mouse-2" msg))
	     (setq mp (mouse-pixel-position))
	     (consp (setq pos (cdr mp)))
	     (car pos) (>= (car pos) 0)
	     (cdr pos) (>= (cdr pos) 0)
	     (setq pos (posn-at-x-y (car pos) (cdr pos) (car mp)))
	     (windowp (posn-window pos)))
	(with-current-buffer (window-buffer (posn-window pos))
	  (if (mouse-on-link-p pos)
	      (setq msg (concat
		    (cond
		     ((eq mouse-1-click-follows-link 'double) "double-")
		     ((and (integerp mouse-1-click-follows-link)
			   (< mouse-1-click-follows-link 0)) "Long ")
		     (t ""))
		    "mouse-1" (substring msg 7)))))))
  msg)
873

874 875 876 877 878 879 880 881 882 883
(defun mouse-move-drag-overlay (ol start end mode)
  (unless (= start end)
    ;; Go to START first, so that when we move to END, if it's in the middle
    ;; of intangible text, point jumps in the direction away from START.
    ;; Don't do it if START=END otherwise a single click risks selecting
    ;; a region if it's on intangible text.  This exception was originally
    ;; only applied on entry to mouse-drag-region, which had the problem
    ;; that a tiny move during a single-click would cause the intangible
    ;; text to be selected.
    (goto-char start)
884 885 886
    (goto-char end)
    (setq end (point)))
  (let ((range (mouse-start-end start end mode)))
887 888
    (move-overlay ol (car range) (nth 1 range))))

889
(defun mouse-drag-track (start-event  &optional
890 891 892 893 894
				      do-mouse-drag-region-post-process)
    "Track mouse drags by highlighting area between point and cursor.
The region will be defined with mark and point, and the overlay
will be deleted after return.  DO-MOUSE-DRAG-REGION-POST-PROCESS
should only be used by mouse-drag-region."
895
  (mouse-minibuffer-check start-event)
896 897 898 899 900 901 902
  (setq mouse-selection-click-count-buffer (current-buffer))
  (let* ((original-window (selected-window))
         ;; We've recorded what we needed from the current buffer and
         ;; window, now let's jump to the place of the event, where things
         ;; are happening.
         (_ (mouse-set-point start-event))
         (echo-keystrokes 0)
903
	 (start-posn (event-start start-event))
904 905
	 (start-point (posn-point start-posn))
	 (start-window (posn-window start-posn))
906
	 (start-window-start (window-start start-window))
907
	 (start-hscroll (window-hscroll start-window))
908
	 (bounds (window-edges start-window))
909
	 (make-cursor-line-fully-visible nil)
910 911 912 913
	 (top (nth 1 bounds))
	 (bottom (if (window-minibuffer-p start-window)
		     (nth 3 bounds)
		   ;; Don't count the mode line.
914
		   (1- (nth 3 bounds))))
915
	 (on-link (and mouse-1-click-follows-link
916
		       (or mouse-1-click-in-non-selected-windows
917 918 919 920
			   (eq start-window original-window))
                       ;; Use start-point before the intangibility
                       ;; treatment, in case we click on a link inside an
                       ;; intangible text.
921
                       (mouse-on-link-p start-posn)))
922 923 924
	 (click-count (1- (event-click-count start-event)))
	 (remap-double-click (and on-link
				  (eq mouse-1-click-follows-link 'double)
925 926 927 928 929
				  (= click-count 1)))
	 ;; Suppress automatic hscrolling, because that is a nuisance
	 ;; when setting point near the right fringe (but see below).
	 (automatic-hscrolling-saved automatic-hscrolling)
	 (automatic-hscrolling nil))
930
    (setq mouse-selection-click-count click-count)
931 932 933 934 935
    ;; In case the down click is in the middle of some intangible text,
    ;; use the end of that text, and put it in START-POINT.
    (if (< (point) start-point)
	(goto-char start-point))
    (setq start-point (point))
936
    (if remap-double-click ;; Don't expand mouse overlay in links
937
	(setq click-count 0))
938 939 940
    (mouse-move-drag-overlay mouse-drag-overlay start-point start-point
                             click-count)
    (overlay-put mouse-drag-overlay 'window start-window)
941
    (deactivate-mark)
942
    (let (event end end-point last-end-point)
943
      (track-mouse
944
	(while (progn
945
		 (setq event (read-event))
946 947 948
                 (or (mouse-movement-p event)
                     (memq (car-safe event) '(switch-frame select-window))))
          (if (memq (car-safe event) '(switch-frame select-window))
949
	      nil
950 951 952 953 954
	    ;; Automatic hscrolling did not occur during the call to
	    ;; `read-event'; but if the user subsequently drags the
	    ;; mouse, go ahead and hscroll.
	    (let ((automatic-hscrolling automatic-hscrolling-saved))
	      (