Merge branch 'master' into comment-cache
[emacs.git] / lisp / xt-mouse.el
blobacb30187a8e821be7814f8182b5cb6ed1bc372cd
1 ;;; xt-mouse.el --- support the mouse when emacs run in an xterm -*- lexical-binding: t -*-
3 ;; Copyright (C) 1994, 2000-2017 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 <http://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 (this-time (float-time))
282 (name (symbol-name type)))
283 (cond
284 ((not (string-match "down-" name))
285 ;; For up events, make the up side match the down side.
286 (setq this-time last-time)
287 (when (and click-count (> click-count 1)
288 (string-match "down-" last-name)
289 (equal name (replace-match "" t t last-name)))
290 (xterm-mouse--set-click-count event click-count)))
291 ((not last-time) nil)
292 ((and (> double-click-time (* 1000 (- this-time last-time)))
293 (equal last-name (replace-match "" t t name)))
294 (setq click-count (1+ click-count))
295 (xterm-mouse--set-click-count event click-count))
296 (t (setq click-count 1)))
297 (set-terminal-parameter nil 'xterm-mouse-last-click
298 (list type this-time click-count)))
300 (set-terminal-parameter nil 'xterm-mouse-x x)
301 (set-terminal-parameter nil 'xterm-mouse-y y)
302 (setq last-input-event event)))))
304 ;;;###autoload
305 (define-minor-mode xterm-mouse-mode
306 "Toggle XTerm mouse mode.
307 With a prefix argument ARG, enable XTerm mouse mode if ARG is
308 positive, and disable it otherwise. If called from Lisp, enable
309 the mode if ARG is omitted or nil.
311 Turn it on to use Emacs mouse commands, and off to use xterm mouse commands.
312 This works in terminal emulators compatible with xterm. It only
313 works for simple uses of the mouse. Basically, only non-modified
314 single clicks are supported. When turned on, the normal xterm
315 mouse functionality for such clicks is still available by holding
316 down the SHIFT key while pressing the mouse button."
317 :global t :group 'mouse
318 (funcall (if xterm-mouse-mode 'add-hook 'remove-hook)
319 'terminal-init-xterm-hook
320 'turn-on-xterm-mouse-tracking-on-terminal)
321 (if xterm-mouse-mode
322 ;; Turn it on
323 (progn
324 (setq mouse-position-function #'xterm-mouse-position-function)
325 (mapc #'turn-on-xterm-mouse-tracking-on-terminal (terminal-list)))
326 ;; Turn it off
327 (mapc #'turn-off-xterm-mouse-tracking-on-terminal (terminal-list))
328 (setq mouse-position-function nil)))
330 (defun xterm-mouse-tracking-enable-sequence ()
331 "Return a control sequence to enable XTerm mouse tracking.
332 The returned control sequence enables basic mouse tracking, mouse
333 motion events and finally extended tracking on terminals that
334 support it. The following escape sequences are understood by
335 modern xterms:
337 \"\\e[?1000h\" \"Basic mouse mode\": Enables reports for mouse
338 clicks. There is a limit to the maximum row/column
339 position (<= 223), which can be reported in this
340 basic mode.
342 \"\\e[?1002h\" \"Mouse motion mode\": Enables reports for mouse
343 motion events during dragging operations.
345 \"\\e[?1005h\" \"UTF-8 coordinate extension\": Enables an
346 extension to the basic mouse mode, which uses UTF-8
347 characters to overcome the 223 row/column limit.
348 This extension may conflict with non UTF-8
349 applications or non UTF-8 locales. It is only
350 enabled when the option `xterm-mouse-utf-8' is
351 non-nil.
353 \"\\e[?1006h\" \"SGR coordinate extension\": Enables a newer
354 alternative extension to the basic mouse mode, which
355 overcomes the 223 row/column limit without the
356 drawbacks of the UTF-8 coordinate extension.
358 The two extension modes are mutually exclusive, where the last
359 given escape sequence takes precedence over the former."
360 (apply #'concat (xterm-mouse--tracking-sequence ?h)))
362 (defconst xterm-mouse-tracking-enable-sequence
363 "\e[?1000h\e[?1002h\e[?1005h\e[?1006h"
364 "Control sequence to enable xterm mouse tracking.
365 Enables basic mouse tracking, mouse motion events and finally
366 extended tracking on terminals that support it. The following
367 escape sequences are understood by modern xterms:
369 \"\\e[?1000h\" \"Basic mouse mode\": Enables reports for mouse
370 clicks. There is a limit to the maximum row/column
371 position (<= 223), which can be reported in this
372 basic mode.
374 \"\\e[?1002h\" \"Mouse motion mode\": Enables reports for mouse
375 motion events during dragging operations.
377 \"\\e[?1005h\" \"UTF-8 coordinate extension\": Enables an extension
378 to the basic mouse mode, which uses UTF-8
379 characters to overcome the 223 row/column limit. This
380 extension may conflict with non UTF-8 applications or
381 non UTF-8 locales.
383 \"\\e[?1006h\" \"SGR coordinate extension\": Enables a newer
384 alternative extension to the basic mouse mode, which
385 overcomes the 223 row/column limit without the
386 drawbacks of the UTF-8 coordinate extension.
388 The two extension modes are mutually exclusive, where the last
389 given escape sequence takes precedence over the former.")
391 (make-obsolete-variable
392 'xterm-mouse-tracking-enable-sequence
393 "use the function `xterm-mouse-tracking-enable-sequence' instead."
394 "25.1")
396 (defun xterm-mouse-tracking-disable-sequence ()
397 "Return a control sequence to disable XTerm mouse tracking.
398 The control sequence resets the modes set by
399 `xterm-mouse-tracking-enable-sequence'."
400 (apply #'concat (nreverse (xterm-mouse--tracking-sequence ?l))))
402 (defconst xterm-mouse-tracking-disable-sequence
403 "\e[?1006l\e[?1005l\e[?1002l\e[?1000l"
404 "Reset the modes set by `xterm-mouse-tracking-enable-sequence'.")
406 (make-obsolete-variable
407 'xterm-mouse-tracking-disable-sequence
408 "use the function `xterm-mouse-tracking-disable-sequence' instead."
409 "25.1")
411 (defun xterm-mouse--tracking-sequence (suffix)
412 "Return a control sequence to enable or disable mouse tracking.
413 SUFFIX is the last character of each escape sequence (?h to
414 enable, ?l to disable)."
415 (mapcar
416 (lambda (code) (format "\e[?%d%c" code suffix))
417 `(1000 1002 ,@(when xterm-mouse-utf-8 '(1005)) 1006)))
419 (defun turn-on-xterm-mouse-tracking-on-terminal (&optional terminal)
420 "Enable xterm mouse tracking on TERMINAL."
421 (when (and xterm-mouse-mode (eq t (terminal-live-p terminal))
422 ;; Avoid the initial terminal which is not a termcap device.
423 ;; FIXME: is there more elegant way to detect the initial
424 ;; terminal?
425 (not (string= (terminal-name terminal) "initial_terminal")))
426 (unless (terminal-parameter terminal 'xterm-mouse-mode)
427 ;; Simulate selecting a terminal by selecting one of its frames
428 ;; so that we can set the terminal-local `input-decode-map'.
429 (with-selected-frame (car (frames-on-display-list terminal))
430 (define-key input-decode-map "\e[M" 'xterm-mouse-translate)
431 (define-key input-decode-map "\e[<" 'xterm-mouse-translate-extended))
432 (let ((enable (xterm-mouse-tracking-enable-sequence))
433 (disable (xterm-mouse-tracking-disable-sequence)))
434 (condition-case err
435 (send-string-to-terminal enable terminal)
436 ;; FIXME: This should use a dedicated error signal.
437 (error (if (equal (cadr err) "Terminal is currently suspended")
438 nil ; The sequence will be sent upon resume.
439 (signal (car err) (cdr err)))))
440 (push enable (terminal-parameter nil 'tty-mode-set-strings))
441 (push disable (terminal-parameter nil 'tty-mode-reset-strings))
442 (set-terminal-parameter terminal 'xterm-mouse-mode t)
443 (set-terminal-parameter terminal 'xterm-mouse-utf-8
444 xterm-mouse-utf-8)))))
446 (defun turn-off-xterm-mouse-tracking-on-terminal (terminal)
447 "Disable xterm mouse tracking on TERMINAL."
448 ;; Only send the disable command to those terminals to which we've already
449 ;; sent the enable command.
450 (when (and (terminal-parameter terminal 'xterm-mouse-mode)
451 (eq t (terminal-live-p terminal)))
452 ;; We could remove the key-binding and unset the `xterm-mouse-mode'
453 ;; terminal parameter, but it seems less harmful to send this escape
454 ;; command too many times (or to catch an unintended key sequence), than
455 ;; to send it too few times (or to fail to let xterm-mouse events
456 ;; pass by untranslated).
457 (condition-case err
458 (send-string-to-terminal xterm-mouse-tracking-disable-sequence
459 terminal)
460 ;; FIXME: This should use a dedicated error signal.
461 (error (if (equal (cadr err) "Terminal is currently suspended")
463 (signal (car err) (cdr err)))))
464 (setf (terminal-parameter nil 'tty-mode-set-strings)
465 (remq xterm-mouse-tracking-enable-sequence
466 (terminal-parameter nil 'tty-mode-set-strings)))
467 (setf (terminal-parameter nil 'tty-mode-reset-strings)
468 (remq xterm-mouse-tracking-disable-sequence
469 (terminal-parameter nil 'tty-mode-reset-strings)))
470 (set-terminal-parameter terminal 'xterm-mouse-mode nil)))
472 (provide 'xt-mouse)
474 ;;; xt-mouse.el ends here