Output alists with dotted pair notation in .dir-locals.el
[emacs.git] / lisp / xt-mouse.el
blobda4af32e5e952854f269480fb9c23fef1efe29e3
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.
316 Turn it on to use Emacs mouse commands, and off to use xterm mouse commands.
317 This works in terminal emulators compatible with xterm. It only
318 works for simple uses of the mouse. Basically, only non-modified
319 single clicks are supported. When turned on, the normal xterm
320 mouse functionality for such clicks is still available by holding
321 down the SHIFT key while pressing the mouse button."
322 :global t :group 'mouse
323 (funcall (if xterm-mouse-mode 'add-hook 'remove-hook)
324 'terminal-init-xterm-hook
325 'turn-on-xterm-mouse-tracking-on-terminal)
326 (if xterm-mouse-mode
327 ;; Turn it on
328 (progn
329 (setq mouse-position-function #'xterm-mouse-position-function)
330 (mapc #'turn-on-xterm-mouse-tracking-on-terminal (terminal-list)))
331 ;; Turn it off
332 (mapc #'turn-off-xterm-mouse-tracking-on-terminal (terminal-list))
333 (setq mouse-position-function nil)))
335 (defun xterm-mouse-tracking-enable-sequence ()
336 "Return a control sequence to enable XTerm mouse tracking.
337 The returned control sequence enables basic mouse tracking, mouse
338 motion events and finally extended tracking on terminals that
339 support it. The following escape sequences are understood by
340 modern xterms:
342 \"\\e[?1000h\" \"Basic mouse mode\": Enables reports for mouse
343 clicks. There is a limit to the maximum row/column
344 position (<= 223), which can be reported in this
345 basic mode.
347 \"\\e[?1002h\" \"Mouse motion mode\": Enables reports for mouse
348 motion events during dragging operations.
350 \"\\e[?1005h\" \"UTF-8 coordinate extension\": Enables an
351 extension to the basic mouse mode, which uses UTF-8
352 characters to overcome the 223 row/column limit.
353 This extension may conflict with non UTF-8
354 applications or non UTF-8 locales. It is only
355 enabled when the option `xterm-mouse-utf-8' is
356 non-nil.
358 \"\\e[?1006h\" \"SGR coordinate extension\": Enables a newer
359 alternative extension to the basic mouse mode, which
360 overcomes the 223 row/column limit without the
361 drawbacks of the UTF-8 coordinate extension.
363 The two extension modes are mutually exclusive, where the last
364 given escape sequence takes precedence over the former."
365 (apply #'concat (xterm-mouse--tracking-sequence ?h)))
367 (defconst xterm-mouse-tracking-enable-sequence
368 "\e[?1000h\e[?1002h\e[?1005h\e[?1006h"
369 "Control sequence to enable xterm mouse tracking.
370 Enables basic mouse tracking, mouse motion events and finally
371 extended tracking on terminals that support it. The following
372 escape sequences are understood by modern xterms:
374 \"\\e[?1000h\" \"Basic mouse mode\": Enables reports for mouse
375 clicks. There is a limit to the maximum row/column
376 position (<= 223), which can be reported in this
377 basic mode.
379 \"\\e[?1002h\" \"Mouse motion mode\": Enables reports for mouse
380 motion events during dragging operations.
382 \"\\e[?1005h\" \"UTF-8 coordinate extension\": Enables an extension
383 to the basic mouse mode, which uses UTF-8
384 characters to overcome the 223 row/column limit. This
385 extension may conflict with non UTF-8 applications or
386 non UTF-8 locales.
388 \"\\e[?1006h\" \"SGR coordinate extension\": Enables a newer
389 alternative extension to the basic mouse mode, which
390 overcomes the 223 row/column limit without the
391 drawbacks of the UTF-8 coordinate extension.
393 The two extension modes are mutually exclusive, where the last
394 given escape sequence takes precedence over the former.")
396 (make-obsolete-variable
397 'xterm-mouse-tracking-enable-sequence
398 "use the function `xterm-mouse-tracking-enable-sequence' instead."
399 "25.1")
401 (defun xterm-mouse-tracking-disable-sequence ()
402 "Return a control sequence to disable XTerm mouse tracking.
403 The control sequence resets the modes set by
404 `xterm-mouse-tracking-enable-sequence'."
405 (apply #'concat (nreverse (xterm-mouse--tracking-sequence ?l))))
407 (defconst xterm-mouse-tracking-disable-sequence
408 "\e[?1006l\e[?1005l\e[?1002l\e[?1000l"
409 "Reset the modes set by `xterm-mouse-tracking-enable-sequence'.")
411 (make-obsolete-variable
412 'xterm-mouse-tracking-disable-sequence
413 "use the function `xterm-mouse-tracking-disable-sequence' instead."
414 "25.1")
416 (defun xterm-mouse--tracking-sequence (suffix)
417 "Return a control sequence to enable or disable mouse tracking.
418 SUFFIX is the last character of each escape sequence (?h to
419 enable, ?l to disable)."
420 (mapcar
421 (lambda (code) (format "\e[?%d%c" code suffix))
422 `(1000 1002 ,@(when xterm-mouse-utf-8 '(1005)) 1006)))
424 (defun turn-on-xterm-mouse-tracking-on-terminal (&optional terminal)
425 "Enable xterm mouse tracking on TERMINAL."
426 (when (and xterm-mouse-mode (eq t (terminal-live-p terminal))
427 ;; Avoid the initial terminal which is not a termcap device.
428 ;; FIXME: is there more elegant way to detect the initial
429 ;; terminal?
430 (not (string= (terminal-name terminal) "initial_terminal")))
431 (unless (terminal-parameter terminal 'xterm-mouse-mode)
432 ;; Simulate selecting a terminal by selecting one of its frames
433 ;; so that we can set the terminal-local `input-decode-map'.
434 (with-selected-frame (car (frames-on-display-list terminal))
435 (define-key input-decode-map "\e[M" 'xterm-mouse-translate)
436 (define-key input-decode-map "\e[<" 'xterm-mouse-translate-extended))
437 (let ((enable (xterm-mouse-tracking-enable-sequence))
438 (disable (xterm-mouse-tracking-disable-sequence)))
439 (condition-case err
440 (send-string-to-terminal enable terminal)
441 ;; FIXME: This should use a dedicated error signal.
442 (error (if (equal (cadr err) "Terminal is currently suspended")
443 nil ; The sequence will be sent upon resume.
444 (signal (car err) (cdr err)))))
445 (push enable (terminal-parameter nil 'tty-mode-set-strings))
446 (push disable (terminal-parameter nil 'tty-mode-reset-strings))
447 (set-terminal-parameter terminal 'xterm-mouse-mode t)
448 (set-terminal-parameter terminal 'xterm-mouse-utf-8
449 xterm-mouse-utf-8)))))
451 (defun turn-off-xterm-mouse-tracking-on-terminal (terminal)
452 "Disable xterm mouse tracking on TERMINAL."
453 ;; Only send the disable command to those terminals to which we've already
454 ;; sent the enable command.
455 (when (and (terminal-parameter terminal 'xterm-mouse-mode)
456 (eq t (terminal-live-p terminal)))
457 ;; We could remove the key-binding and unset the `xterm-mouse-mode'
458 ;; terminal parameter, but it seems less harmful to send this escape
459 ;; command too many times (or to catch an unintended key sequence), than
460 ;; to send it too few times (or to fail to let xterm-mouse events
461 ;; pass by untranslated).
462 (condition-case err
463 (send-string-to-terminal xterm-mouse-tracking-disable-sequence
464 terminal)
465 ;; FIXME: This should use a dedicated error signal.
466 (error (if (equal (cadr err) "Terminal is currently suspended")
468 (signal (car err) (cdr err)))))
469 (setf (terminal-parameter nil 'tty-mode-set-strings)
470 (remq xterm-mouse-tracking-enable-sequence
471 (terminal-parameter nil 'tty-mode-set-strings)))
472 (setf (terminal-parameter nil 'tty-mode-reset-strings)
473 (remq xterm-mouse-tracking-disable-sequence
474 (terminal-parameter nil 'tty-mode-reset-strings)))
475 (set-terminal-parameter terminal 'xterm-mouse-mode nil)))
477 (provide 'xt-mouse)
479 ;;; xt-mouse.el ends here