Improve responsiveness while in 'replace-buffer-contents'
[emacs.git] / lisp / xt-mouse.el
blob8fb65d5bfa79896a4df5901d3e4960f5f78ed73c
1 ;;; xt-mouse.el --- support the mouse when emacs run in an xterm -*- lexical-binding: t -*-
3 ;; Copyright (C) 1994, 2000-2018 Free Software Foundation, Inc.
5 ;; Author: Per Abrahamsen <abraham@dina.kvl.dk>
6 ;; Keywords: mouse, terminals
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; Enable mouse support when running inside an xterm.
27 ;; This is actually useful when you are running X11 locally, but is
28 ;; working on remote machine over a modem line or through a gateway.
30 ;; It works by translating xterm escape codes into generic emacs mouse
31 ;; events so it should work with any package that uses the mouse.
33 ;; You don't have to turn off xterm mode to use the normal xterm mouse
34 ;; functionality, it is still available by holding down the SHIFT key
35 ;; when you press the mouse button.
37 ;;; Todo:
39 ;; Support multi-click -- somehow.
41 ;;; Code:
43 (defvar xterm-mouse-debug-buffer nil)
45 (defun xterm-mouse-translate (_event)
46 "Read a click and release event from XTerm."
47 (xterm-mouse-translate-1))
49 (defun xterm-mouse-translate-extended (_event)
50 "Read a click and release event from XTerm.
51 Similar to `xterm-mouse-translate', but using the \"1006\"
52 extension, which supports coordinates >= 231 (see
53 http://invisible-island.net/xterm/ctlseqs/ctlseqs.html)."
54 (xterm-mouse-translate-1 1006))
56 (defun xterm-mouse-translate-1 (&optional extension)
57 (save-excursion
58 (let* ((event (xterm-mouse-event extension))
59 (ev-command (nth 0 event))
60 (ev-data (nth 1 event))
61 (ev-where (nth 1 ev-data))
62 (vec (vector event))
63 (is-move (eq 'mouse-movement ev-command))
64 (is-down (string-match "down-" (symbol-name ev-command))))
66 ;; Mouse events symbols must have an 'event-kind property with
67 ;; the value 'mouse-click.
68 (when ev-command (put ev-command 'event-kind 'mouse-click))
70 (cond
71 ((null event) nil) ;Unknown/bogus byte sequence!
72 (is-down
73 (setf (terminal-parameter nil 'xterm-mouse-last-down)
74 ;; EVENT might be handed back to the input queue, which
75 ;; might modify it. Copy it into the terminal parameter
76 ;; to guard against that.
77 (copy-sequence event))
78 vec)
79 (is-move vec)
81 (let* ((down (terminal-parameter nil 'xterm-mouse-last-down))
82 (down-data (nth 1 down))
83 (down-where (nth 1 down-data)))
84 (setf (terminal-parameter nil 'xterm-mouse-last-down) nil)
85 (cond
86 ((null down)
87 ;; This is an "up-only" event. Pretend there was an up-event
88 ;; right before and keep the up-event for later.
89 (push event unread-command-events)
90 (vector (cons (intern (replace-regexp-in-string
91 "\\`\\([ACMHSs]-\\)*" "\\&down-"
92 (symbol-name ev-command) t))
93 (cdr event))))
94 ((equal ev-where down-where) vec)
96 (let ((drag (if (symbolp ev-where)
97 0 ;FIXME: Why?!?
98 (list (intern (replace-regexp-in-string
99 "\\`\\([ACMHSs]-\\)*" "\\&drag-"
100 (symbol-name ev-command) t))
101 down-data ev-data))))
102 (if (null track-mouse)
103 (vector drag)
104 (push drag unread-command-events)
105 (vector (list 'mouse-movement ev-data))))))))))))
107 ;; These two variables have been converted to terminal parameters.
109 ;;(defvar xterm-mouse-x 0
110 ;; "Position of last xterm mouse event relative to the frame.")
112 ;;(defvar xterm-mouse-y 0
113 ;; "Position of last xterm mouse event relative to the frame.")
115 (defvar xt-mouse-epoch nil)
117 ;; Indicator for the xterm-mouse mode.
119 (defun xterm-mouse-position-function (pos)
120 "Bound to `mouse-position-function' in XTerm mouse mode."
121 (when (terminal-parameter nil 'xterm-mouse-x)
122 (setcdr pos (cons (terminal-parameter nil 'xterm-mouse-x)
123 (terminal-parameter nil 'xterm-mouse-y))))
124 pos)
126 (defun xterm-mouse-truncate-wrap (f)
127 "Truncate with wrap-around."
128 (condition-case nil
129 ;; First try the built-in truncate, in case there's no overflow.
130 (truncate f)
131 ;; In case of overflow, do wraparound by hand.
132 (range-error
133 ;; In our case, we wrap around every 3 days or so, so if we assume
134 ;; a maximum of 65536 wraparounds, we're safe for a couple years.
135 ;; Using a power of 2 makes rounding errors less likely.
136 (let* ((maxwrap (* 65536 2048))
137 (dbig (truncate (/ f maxwrap)))
138 (fdiff (- f (* 1.0 maxwrap dbig))))
139 (+ (truncate fdiff) (* maxwrap dbig))))))
141 (defcustom xterm-mouse-utf-8 nil
142 "Non-nil if UTF-8 coordinates should be used to read mouse coordinates.
143 Set this to non-nil if you are sure that your terminal
144 understands UTF-8 coordinates, but not SGR coordinates."
145 :version "25.1"
146 :type 'boolean
147 :risky t
148 :group 'xterm)
150 (defun xterm-mouse--read-coordinate ()
151 "Read a mouse coordinate from the current terminal.
152 If `xterm-mouse-utf-8' was non-nil when
153 `turn-on-xterm-mouse-tracking-on-terminal' was called, reads the
154 coordinate as an UTF-8 code unit sequence; otherwise, reads a
155 single byte."
156 (let ((previous-keyboard-coding-system (keyboard-coding-system)))
157 (unwind-protect
158 (progn
159 (set-keyboard-coding-system
160 (if (terminal-parameter nil 'xterm-mouse-utf-8)
161 'utf-8-unix
162 'no-conversion))
163 ;; Wait only a little; we assume that the entire escape sequence
164 ;; has already been sent when this function is called.
165 (read-char nil nil 0.1))
166 (set-keyboard-coding-system previous-keyboard-coding-system))))
168 ;; In default mode, each numeric parameter of XTerm's mouse report is
169 ;; a single char, possibly encoded as utf-8. The actual numeric
170 ;; parameter then is obtained by subtracting 32 from the character
171 ;; code. In extended mode the parameters are returned as decimal
172 ;; string delimited either by semicolons or for the last parameter by
173 ;; one of the characters "m" or "M". If the last character is a "m",
174 ;; then the mouse event was a button release, else it was a button
175 ;; press or a mouse motion. Return value is a cons cell with
176 ;; (NEXT-NUMERIC-PARAMETER . LAST-CHAR)
177 (defun xterm-mouse--read-number-from-terminal (extension)
178 (let (c)
179 (if extension
180 (let ((n 0))
181 (while (progn
182 (setq c (read-char))
183 (<= ?0 c ?9))
184 (setq n (+ (* 10 n) c (- ?0))))
185 (cons n c))
186 (cons (- (setq c (xterm-mouse--read-coordinate)) 32) c))))
188 ;; XTerm reports mouse events as
189 ;; <EVENT-CODE> <X> <Y> in default mode, and
190 ;; <EVENT-CODE> ";" <X> ";" <Y> <"M" or "m"> in extended mode.
191 ;; The macro read-number-from-terminal takes care of reading
192 ;; the response parameters appropriately. The EVENT-CODE differs
193 ;; slightly between default and extended mode.
194 ;; Return a list (EVENT-TYPE-SYMBOL X Y).
195 (defun xterm-mouse--read-event-sequence (&optional extension)
196 (pcase-let*
197 ((`(,code . ,_) (xterm-mouse--read-number-from-terminal extension))
198 (`(,x . ,_) (xterm-mouse--read-number-from-terminal extension))
199 (`(,y . ,c) (xterm-mouse--read-number-from-terminal extension))
200 (wheel (/= (logand code 64) 0))
201 (move (/= (logand code 32) 0))
202 (ctrl (/= (logand code 16) 0))
203 (meta (/= (logand code 8) 0))
204 (shift (/= (logand code 4) 0))
205 (down (and (not wheel)
206 (not move)
207 (if extension
208 (eq c ?M)
209 (/= (logand code 3) 3))))
210 (btn (cond
211 ((or extension down wheel)
212 (+ (logand code 3) (if wheel 4 1)))
213 ;; The default mouse protocol does not report the button
214 ;; number in release events: extract the button number
215 ;; from last button-down event.
216 ((terminal-parameter nil 'xterm-mouse-last-down)
217 (string-to-number
218 (substring
219 (symbol-name
220 (car (terminal-parameter nil 'xterm-mouse-last-down)))
221 -1)))
222 ;; Spurious release event without previous button-down
223 ;; event: assume, that the last button was button 1.
224 (t 1)))
225 (sym (if move 'mouse-movement
226 (intern (concat (if ctrl "C-" "")
227 (if meta "M-" "")
228 (if shift "S-" "")
229 (if down "down-" "")
230 "mouse-"
231 (number-to-string btn))))))
232 (list sym (1- x) (1- y))))
234 (defun xterm-mouse--set-click-count (event click-count)
235 (setcdr (cdr event) (list click-count))
236 (let ((name (symbol-name (car event))))
237 (when (string-match "\\(.*?\\)\\(\\(?:down-\\)?mouse-.*\\)" name)
238 (setcar event
239 (intern (concat (match-string 1 name)
240 (if (= click-count 2)
241 "double-" "triple-")
242 (match-string 2 name)))))))
244 (defun xterm-mouse-event (&optional extension)
245 "Convert XTerm mouse event to Emacs mouse event.
246 EXTENSION, if non-nil, means to use an extension to the usual
247 terminal mouse protocol; we currently support the value 1006,
248 which is the \"1006\" extension implemented in Xterm >= 277."
249 (let ((click (cond ((memq extension '(1006 nil))
250 (xterm-mouse--read-event-sequence extension))
252 (error "Unsupported XTerm mouse protocol")))))
253 (when click
254 (let* ((type (nth 0 click))
255 (x (nth 1 click))
256 (y (nth 2 click))
257 ;; Emulate timestamp information. This is accurate enough
258 ;; for default value of mouse-1-click-follows-link (450msec).
259 (timestamp (xterm-mouse-truncate-wrap
260 (* 1000
261 (- (float-time)
262 (or xt-mouse-epoch
263 (setq xt-mouse-epoch (float-time)))))))
264 (w (window-at x y))
265 (ltrb (window-edges w))
266 (left (nth 0 ltrb))
267 (top (nth 1 ltrb))
268 (posn (if w
269 (posn-at-x-y (- x left) (- y top) w t)
270 (append (list nil 'menu-bar)
271 (nthcdr 2 (posn-at-x-y x y)))))
272 (event (list type posn)))
273 (setcar (nthcdr 3 posn) timestamp)
275 ;; Try to handle double/triple clicks.
276 (let* ((last-click (terminal-parameter nil 'xterm-mouse-last-click))
277 (last-type (nth 0 last-click))
278 (last-name (symbol-name last-type))
279 (last-time (nth 1 last-click))
280 (click-count (nth 2 last-click))
281 (last-x (nth 3 last-click))
282 (last-y (nth 4 last-click))
283 (this-time (float-time))
284 (name (symbol-name type)))
285 (cond
286 ((not (string-match "down-" name))
287 ;; For up events, make the up side match the down side.
288 (setq this-time last-time)
289 (when (and click-count (> click-count 1)
290 (string-match "down-" last-name)
291 (equal name (replace-match "" t t last-name)))
292 (xterm-mouse--set-click-count event click-count)))
293 ((and last-time
294 double-click-time
295 (or (eq double-click-time t)
296 (> double-click-time (* 1000 (- this-time last-time))))
297 (<= (abs (- x last-x))
298 (/ double-click-fuzz 8))
299 (<= (abs (- y last-y))
300 (/ double-click-fuzz 8))
301 (equal last-name (replace-match "" t t name)))
302 (setq click-count (1+ click-count))
303 (xterm-mouse--set-click-count event click-count))
304 (t (setq click-count 1)))
305 (set-terminal-parameter nil 'xterm-mouse-last-click
306 (list type this-time click-count x y)))
308 (set-terminal-parameter nil 'xterm-mouse-x x)
309 (set-terminal-parameter nil 'xterm-mouse-y y)
310 (setq last-input-event event)))))
312 ;;;###autoload
313 (define-minor-mode xterm-mouse-mode
314 "Toggle XTerm mouse mode.
315 With a prefix argument ARG, enable XTerm mouse mode if ARG is
316 positive, and disable it otherwise. If called from Lisp, enable
317 the mode if ARG is omitted or nil.
319 Turn it on to use Emacs mouse commands, and off to use xterm mouse commands.
320 This works in terminal emulators compatible with xterm. It only
321 works for simple uses of the mouse. Basically, only non-modified
322 single clicks are supported. When turned on, the normal xterm
323 mouse functionality for such clicks is still available by holding
324 down the SHIFT key while pressing the mouse button."
325 :global t :group 'mouse
326 (funcall (if xterm-mouse-mode 'add-hook 'remove-hook)
327 'terminal-init-xterm-hook
328 'turn-on-xterm-mouse-tracking-on-terminal)
329 (if xterm-mouse-mode
330 ;; Turn it on
331 (progn
332 (setq mouse-position-function #'xterm-mouse-position-function)
333 (mapc #'turn-on-xterm-mouse-tracking-on-terminal (terminal-list)))
334 ;; Turn it off
335 (mapc #'turn-off-xterm-mouse-tracking-on-terminal (terminal-list))
336 (setq mouse-position-function nil)))
338 (defun xterm-mouse-tracking-enable-sequence ()
339 "Return a control sequence to enable XTerm mouse tracking.
340 The returned control sequence enables basic mouse tracking, mouse
341 motion events and finally extended tracking on terminals that
342 support it. The following escape sequences are understood by
343 modern xterms:
345 \"\\e[?1000h\" \"Basic mouse mode\": Enables reports for mouse
346 clicks. There is a limit to the maximum row/column
347 position (<= 223), which can be reported in this
348 basic mode.
350 \"\\e[?1002h\" \"Mouse motion mode\": Enables reports for mouse
351 motion events during dragging operations.
353 \"\\e[?1005h\" \"UTF-8 coordinate extension\": Enables an
354 extension to the basic mouse mode, which uses UTF-8
355 characters to overcome the 223 row/column limit.
356 This extension may conflict with non UTF-8
357 applications or non UTF-8 locales. It is only
358 enabled when the option `xterm-mouse-utf-8' is
359 non-nil.
361 \"\\e[?1006h\" \"SGR coordinate extension\": Enables a newer
362 alternative extension to the basic mouse mode, which
363 overcomes the 223 row/column limit without the
364 drawbacks of the UTF-8 coordinate extension.
366 The two extension modes are mutually exclusive, where the last
367 given escape sequence takes precedence over the former."
368 (apply #'concat (xterm-mouse--tracking-sequence ?h)))
370 (defconst xterm-mouse-tracking-enable-sequence
371 "\e[?1000h\e[?1002h\e[?1005h\e[?1006h"
372 "Control sequence to enable xterm mouse tracking.
373 Enables basic mouse tracking, mouse motion events and finally
374 extended tracking on terminals that support it. The following
375 escape sequences are understood by modern xterms:
377 \"\\e[?1000h\" \"Basic mouse mode\": Enables reports for mouse
378 clicks. There is a limit to the maximum row/column
379 position (<= 223), which can be reported in this
380 basic mode.
382 \"\\e[?1002h\" \"Mouse motion mode\": Enables reports for mouse
383 motion events during dragging operations.
385 \"\\e[?1005h\" \"UTF-8 coordinate extension\": Enables an extension
386 to the basic mouse mode, which uses UTF-8
387 characters to overcome the 223 row/column limit. This
388 extension may conflict with non UTF-8 applications or
389 non UTF-8 locales.
391 \"\\e[?1006h\" \"SGR coordinate extension\": Enables a newer
392 alternative extension to the basic mouse mode, which
393 overcomes the 223 row/column limit without the
394 drawbacks of the UTF-8 coordinate extension.
396 The two extension modes are mutually exclusive, where the last
397 given escape sequence takes precedence over the former.")
399 (make-obsolete-variable
400 'xterm-mouse-tracking-enable-sequence
401 "use the function `xterm-mouse-tracking-enable-sequence' instead."
402 "25.1")
404 (defun xterm-mouse-tracking-disable-sequence ()
405 "Return a control sequence to disable XTerm mouse tracking.
406 The control sequence resets the modes set by
407 `xterm-mouse-tracking-enable-sequence'."
408 (apply #'concat (nreverse (xterm-mouse--tracking-sequence ?l))))
410 (defconst xterm-mouse-tracking-disable-sequence
411 "\e[?1006l\e[?1005l\e[?1002l\e[?1000l"
412 "Reset the modes set by `xterm-mouse-tracking-enable-sequence'.")
414 (make-obsolete-variable
415 'xterm-mouse-tracking-disable-sequence
416 "use the function `xterm-mouse-tracking-disable-sequence' instead."
417 "25.1")
419 (defun xterm-mouse--tracking-sequence (suffix)
420 "Return a control sequence to enable or disable mouse tracking.
421 SUFFIX is the last character of each escape sequence (?h to
422 enable, ?l to disable)."
423 (mapcar
424 (lambda (code) (format "\e[?%d%c" code suffix))
425 `(1000 1002 ,@(when xterm-mouse-utf-8 '(1005)) 1006)))
427 (defun turn-on-xterm-mouse-tracking-on-terminal (&optional terminal)
428 "Enable xterm mouse tracking on TERMINAL."
429 (when (and xterm-mouse-mode (eq t (terminal-live-p terminal))
430 ;; Avoid the initial terminal which is not a termcap device.
431 ;; FIXME: is there more elegant way to detect the initial
432 ;; terminal?
433 (not (string= (terminal-name terminal) "initial_terminal")))
434 (unless (terminal-parameter terminal 'xterm-mouse-mode)
435 ;; Simulate selecting a terminal by selecting one of its frames
436 ;; so that we can set the terminal-local `input-decode-map'.
437 (with-selected-frame (car (frames-on-display-list terminal))
438 (define-key input-decode-map "\e[M" 'xterm-mouse-translate)
439 (define-key input-decode-map "\e[<" 'xterm-mouse-translate-extended))
440 (let ((enable (xterm-mouse-tracking-enable-sequence))
441 (disable (xterm-mouse-tracking-disable-sequence)))
442 (condition-case err
443 (send-string-to-terminal enable terminal)
444 ;; FIXME: This should use a dedicated error signal.
445 (error (if (equal (cadr err) "Terminal is currently suspended")
446 nil ; The sequence will be sent upon resume.
447 (signal (car err) (cdr err)))))
448 (push enable (terminal-parameter nil 'tty-mode-set-strings))
449 (push disable (terminal-parameter nil 'tty-mode-reset-strings))
450 (set-terminal-parameter terminal 'xterm-mouse-mode t)
451 (set-terminal-parameter terminal 'xterm-mouse-utf-8
452 xterm-mouse-utf-8)))))
454 (defun turn-off-xterm-mouse-tracking-on-terminal (terminal)
455 "Disable xterm mouse tracking on TERMINAL."
456 ;; Only send the disable command to those terminals to which we've already
457 ;; sent the enable command.
458 (when (and (terminal-parameter terminal 'xterm-mouse-mode)
459 (eq t (terminal-live-p terminal)))
460 ;; We could remove the key-binding and unset the `xterm-mouse-mode'
461 ;; terminal parameter, but it seems less harmful to send this escape
462 ;; command too many times (or to catch an unintended key sequence), than
463 ;; to send it too few times (or to fail to let xterm-mouse events
464 ;; pass by untranslated).
465 (condition-case err
466 (send-string-to-terminal xterm-mouse-tracking-disable-sequence
467 terminal)
468 ;; FIXME: This should use a dedicated error signal.
469 (error (if (equal (cadr err) "Terminal is currently suspended")
471 (signal (car err) (cdr err)))))
472 (setf (terminal-parameter nil 'tty-mode-set-strings)
473 (remq xterm-mouse-tracking-enable-sequence
474 (terminal-parameter nil 'tty-mode-set-strings)))
475 (setf (terminal-parameter nil 'tty-mode-reset-strings)
476 (remq xterm-mouse-tracking-disable-sequence
477 (terminal-parameter nil 'tty-mode-reset-strings)))
478 (set-terminal-parameter terminal 'xterm-mouse-mode nil)))
480 (provide 'xt-mouse)
482 ;;; xt-mouse.el ends here