Revert "Backport HTTPS proxy fix"
[emacs.git] / lisp / xt-mouse.el
blobe52095789baedd6ae856b6e63149696c0edcfc99
1 ;;; xt-mouse.el --- support the mouse when emacs run in an xterm
3 ;; Copyright (C) 1994, 2000-2016 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) event)
74 vec)
75 (is-move vec)
77 (let* ((down (terminal-parameter nil 'xterm-mouse-last-down))
78 (down-data (nth 1 down))
79 (down-where (nth 1 down-data)))
80 (setf (terminal-parameter nil 'xterm-mouse-last-down) nil)
81 (cond
82 ((null down)
83 ;; This is an "up-only" event. Pretend there was an up-event
84 ;; right before and keep the up-event for later.
85 (push event unread-command-events)
86 (vector (cons (intern (replace-regexp-in-string
87 "\\`\\([ACMHSs]-\\)*" "\\&down-"
88 (symbol-name ev-command) t))
89 (cdr event))))
90 ((equal ev-where down-where) vec)
92 (let ((drag (if (symbolp ev-where)
93 0 ;FIXME: Why?!?
94 (list (intern (replace-regexp-in-string
95 "\\`\\([ACMHSs]-\\)*" "\\&drag-"
96 (symbol-name ev-command) t))
97 down-data ev-data))))
98 (if (null track-mouse)
99 (vector drag)
100 (push drag unread-command-events)
101 (vector (list 'mouse-movement ev-data))))))))))))
103 ;; These two variables have been converted to terminal parameters.
105 ;;(defvar xterm-mouse-x 0
106 ;; "Position of last xterm mouse event relative to the frame.")
108 ;;(defvar xterm-mouse-y 0
109 ;; "Position of last xterm mouse event relative to the frame.")
111 (defvar xt-mouse-epoch nil)
113 ;; Indicator for the xterm-mouse mode.
115 (defun xterm-mouse-position-function (pos)
116 "Bound to `mouse-position-function' in XTerm mouse mode."
117 (when (terminal-parameter nil 'xterm-mouse-x)
118 (setcdr pos (cons (terminal-parameter nil 'xterm-mouse-x)
119 (terminal-parameter nil 'xterm-mouse-y))))
120 pos)
122 (defun xterm-mouse-truncate-wrap (f)
123 "Truncate with wrap-around."
124 (condition-case nil
125 ;; First try the built-in truncate, in case there's no overflow.
126 (truncate f)
127 ;; In case of overflow, do wraparound by hand.
128 (range-error
129 ;; In our case, we wrap around every 3 days or so, so if we assume
130 ;; a maximum of 65536 wraparounds, we're safe for a couple years.
131 ;; Using a power of 2 makes rounding errors less likely.
132 (let* ((maxwrap (* 65536 2048))
133 (dbig (truncate (/ f maxwrap)))
134 (fdiff (- f (* 1.0 maxwrap dbig))))
135 (+ (truncate fdiff) (* maxwrap dbig))))))
137 (defcustom xterm-mouse-utf-8 nil
138 "Non-nil if UTF-8 coordinates should be used to read mouse coordinates.
139 Set this to non-nil if you are sure that your terminal
140 understands UTF-8 coordinates, but not SGR coordinates."
141 :version "25.1"
142 :type 'boolean
143 :risky t
144 :group 'xterm)
146 (defun xterm-mouse--read-coordinate ()
147 "Read a mouse coordinate from the current terminal.
148 If `xterm-mouse-utf-8' was non-nil when
149 `turn-on-xterm-mouse-tracking-on-terminal' was called, reads the
150 coordinate as an UTF-8 code unit sequence; otherwise, reads a
151 single byte."
152 (let ((previous-keyboard-coding-system (keyboard-coding-system)))
153 (unwind-protect
154 (progn
155 (set-keyboard-coding-system
156 (if (terminal-parameter nil 'xterm-mouse-utf-8)
157 'utf-8-unix
158 ;; Use Latin-1 instead of no-conversion to avoid flicker
159 ;; due to `set-keyboard-coding-system' changing the meta
160 ;; mode.
161 'latin-1))
162 ;; Wait only a little; we assume that the entire escape sequence
163 ;; has already been sent when this function is called.
164 (read-char nil nil 0.1))
165 (set-keyboard-coding-system previous-keyboard-coding-system))))
167 ;; In default mode, each numeric parameter of XTerm's mouse report is
168 ;; a single char, possibly encoded as utf-8. The actual numeric
169 ;; parameter then is obtained by subtracting 32 from the character
170 ;; code. In extended mode the parameters are returned as decimal
171 ;; string delimited either by semicolons or for the last parameter by
172 ;; one of the characters "m" or "M". If the last character is a "m",
173 ;; then the mouse event was a button release, else it was a button
174 ;; press or a mouse motion. Return value is a cons cell with
175 ;; (NEXT-NUMERIC-PARAMETER . LAST-CHAR)
176 (defun xterm-mouse--read-number-from-terminal (extension)
177 (let (c)
178 (if extension
179 (let ((n 0))
180 (while (progn
181 (setq c (read-char))
182 (<= ?0 c ?9))
183 (setq n (+ (* 10 n) c (- ?0))))
184 (cons n c))
185 (cons (- (setq c (xterm-mouse--read-coordinate)) 32) c))))
187 ;; XTerm reports mouse events as
188 ;; <EVENT-CODE> <X> <Y> in default mode, and
189 ;; <EVENT-CODE> ";" <X> ";" <Y> <"M" or "m"> in extended mode.
190 ;; The macro read-number-from-terminal takes care of reading
191 ;; the response parameters appropriately. The EVENT-CODE differs
192 ;; slightly between default and extended mode.
193 ;; Return a list (EVENT-TYPE-SYMBOL X Y).
194 (defun xterm-mouse--read-event-sequence (&optional extension)
195 (pcase-let*
196 ((`(,code . ,_) (xterm-mouse--read-number-from-terminal extension))
197 (`(,x . ,_) (xterm-mouse--read-number-from-terminal extension))
198 (`(,y . ,c) (xterm-mouse--read-number-from-terminal extension))
199 (wheel (/= (logand code 64) 0))
200 (move (/= (logand code 32) 0))
201 (ctrl (/= (logand code 16) 0))
202 (meta (/= (logand code 8) 0))
203 (shift (/= (logand code 4) 0))
204 (down (and (not wheel)
205 (not move)
206 (if extension
207 (eq c ?M)
208 (/= (logand code 3) 3))))
209 (btn (cond
210 ((or extension down wheel)
211 (+ (logand code 3) (if wheel 4 1)))
212 ;; The default mouse protocol does not report the button
213 ;; number in release events: extract the button number
214 ;; from last button-down event.
215 ((terminal-parameter nil 'xterm-mouse-last-down)
216 (string-to-number
217 (substring
218 (symbol-name
219 (car (terminal-parameter nil 'xterm-mouse-last-down)))
220 -1)))
221 ;; Spurious release event without previous button-down
222 ;; event: assume, that the last button was button 1.
223 (t 1)))
224 (sym (if move 'mouse-movement
225 (intern (concat (if ctrl "C-" "")
226 (if meta "M-" "")
227 (if shift "S-" "")
228 (if down "down-" "")
229 "mouse-"
230 (number-to-string btn))))))
231 (list sym (1- x) (1- y))))
233 (defun xterm-mouse--set-click-count (event click-count)
234 (setcdr (cdr event) (list click-count))
235 (let ((name (symbol-name (car event))))
236 (when (string-match "\\(.*?\\)\\(\\(?:down-\\)?mouse-.*\\)" name)
237 (setcar event
238 (intern (concat (match-string 1 name)
239 (if (= click-count 2)
240 "double-" "triple-")
241 (match-string 2 name)))))))
243 (defun xterm-mouse-event (&optional extension)
244 "Convert XTerm mouse event to Emacs mouse event.
245 EXTENSION, if non-nil, means to use an extension to the usual
246 terminal mouse protocol; we currently support the value 1006,
247 which is the \"1006\" extension implemented in Xterm >= 277."
248 (let ((click (cond ((memq extension '(1006 nil))
249 (xterm-mouse--read-event-sequence extension))
251 (error "Unsupported XTerm mouse protocol")))))
252 (when click
253 (let* ((type (nth 0 click))
254 (x (nth 1 click))
255 (y (nth 2 click))
256 ;; Emulate timestamp information. This is accurate enough
257 ;; for default value of mouse-1-click-follows-link (450msec).
258 (timestamp (xterm-mouse-truncate-wrap
259 (* 1000
260 (- (float-time)
261 (or xt-mouse-epoch
262 (setq xt-mouse-epoch (float-time)))))))
263 (w (window-at x y))
264 (ltrb (window-edges w))
265 (left (nth 0 ltrb))
266 (top (nth 1 ltrb))
267 (posn (if w
268 (posn-at-x-y (- x left) (- y top) w t)
269 (append (list nil 'menu-bar)
270 (nthcdr 2 (posn-at-x-y x y)))))
271 (event (list type posn)))
272 (setcar (nthcdr 3 posn) timestamp)
274 ;; Try to handle double/triple clicks.
275 (let* ((last-click (terminal-parameter nil 'xterm-mouse-last-click))
276 (last-type (nth 0 last-click))
277 (last-name (symbol-name last-type))
278 (last-time (nth 1 last-click))
279 (click-count (nth 2 last-click))
280 (this-time (float-time))
281 (name (symbol-name type)))
282 (cond
283 ((not (string-match "down-" name))
284 ;; For up events, make the up side match the down side.
285 (setq this-time last-time)
286 (when (and click-count (> click-count 1)
287 (string-match "down-" last-name)
288 (equal name (replace-match "" t t last-name)))
289 (xterm-mouse--set-click-count event click-count)))
290 ((not last-time) nil)
291 ((and (> double-click-time (* 1000 (- this-time last-time)))
292 (equal last-name (replace-match "" t t name)))
293 (setq click-count (1+ click-count))
294 (xterm-mouse--set-click-count event click-count))
295 (t (setq click-count 1)))
296 (set-terminal-parameter nil 'xterm-mouse-last-click
297 (list type this-time click-count)))
299 (set-terminal-parameter nil 'xterm-mouse-x x)
300 (set-terminal-parameter nil 'xterm-mouse-y y)
301 (setq last-input-event event)))))
303 ;;;###autoload
304 (define-minor-mode xterm-mouse-mode
305 "Toggle XTerm mouse mode.
306 With a prefix argument ARG, enable XTerm mouse mode if ARG is
307 positive, and disable it otherwise. If called from Lisp, enable
308 the mode if ARG is omitted or nil.
310 Turn it on to use Emacs mouse commands, and off to use xterm mouse commands.
311 This works in terminal emulators compatible with xterm. It only
312 works for simple uses of the mouse. Basically, only non-modified
313 single clicks are supported. When turned on, the normal xterm
314 mouse functionality for such clicks is still available by holding
315 down the SHIFT key while pressing the mouse button."
316 :global t :group 'mouse
317 (funcall (if xterm-mouse-mode 'add-hook 'remove-hook)
318 'terminal-init-xterm-hook
319 'turn-on-xterm-mouse-tracking-on-terminal)
320 (if xterm-mouse-mode
321 ;; Turn it on
322 (progn
323 (setq mouse-position-function #'xterm-mouse-position-function)
324 (mapc #'turn-on-xterm-mouse-tracking-on-terminal (terminal-list)))
325 ;; Turn it off
326 (mapc #'turn-off-xterm-mouse-tracking-on-terminal (terminal-list))
327 (setq mouse-position-function nil)))
329 (defun xterm-mouse-tracking-enable-sequence ()
330 "Return a control sequence to enable XTerm mouse tracking.
331 The returned control sequence enables basic mouse tracking, mouse
332 motion events and finally extended tracking on terminals that
333 support it. The following escape sequences are understood by
334 modern xterms:
336 \"\\e[?1000h\" \"Basic mouse mode\": Enables reports for mouse
337 clicks. There is a limit to the maximum row/column
338 position (<= 223), which can be reported in this
339 basic mode.
341 \"\\e[?1002h\" \"Mouse motion mode\": Enables reports for mouse
342 motion events during dragging operations.
344 \"\\e[?1005h\" \"UTF-8 coordinate extension\": Enables an
345 extension to the basic mouse mode, which uses UTF-8
346 characters to overcome the 223 row/column limit.
347 This extension may conflict with non UTF-8
348 applications or non UTF-8 locales. It is only
349 enabled when the option `xterm-mouse-utf-8' is
350 non-nil.
352 \"\\e[?1006h\" \"SGR coordinate extension\": Enables a newer
353 alternative extension to the basic mouse mode, which
354 overcomes the 223 row/column limit without the
355 drawbacks of the UTF-8 coordinate extension.
357 The two extension modes are mutually exclusive, where the last
358 given escape sequence takes precedence over the former."
359 (apply #'concat (xterm-mouse--tracking-sequence ?h)))
361 (defconst xterm-mouse-tracking-enable-sequence
362 "\e[?1000h\e[?1002h\e[?1005h\e[?1006h"
363 "Control sequence to enable xterm mouse tracking.
364 Enables basic mouse tracking, mouse motion events and finally
365 extended tracking on terminals that support it. The following
366 escape sequences are understood by modern xterms:
368 \"\\e[?1000h\" \"Basic mouse mode\": Enables reports for mouse
369 clicks. There is a limit to the maximum row/column
370 position (<= 223), which can be reported in this
371 basic mode.
373 \"\\e[?1002h\" \"Mouse motion mode\": Enables reports for mouse
374 motion events during dragging operations.
376 \"\\e[?1005h\" \"UTF-8 coordinate extension\": Enables an extension
377 to the basic mouse mode, which uses UTF-8
378 characters to overcome the 223 row/column limit. This
379 extension may conflict with non UTF-8 applications or
380 non UTF-8 locales.
382 \"\\e[?1006h\" \"SGR coordinate extension\": Enables a newer
383 alternative extension to the basic mouse mode, which
384 overcomes the 223 row/column limit without the
385 drawbacks of the UTF-8 coordinate extension.
387 The two extension modes are mutually exclusive, where the last
388 given escape sequence takes precedence over the former.")
390 (make-obsolete-variable
391 'xterm-mouse-tracking-enable-sequence
392 "use the function `xterm-mouse-tracking-enable-sequence' instead."
393 "25.1")
395 (defun xterm-mouse-tracking-disable-sequence ()
396 "Return a control sequence to disable XTerm mouse tracking.
397 The control sequence resets the modes set by
398 `xterm-mouse-tracking-enable-sequence'."
399 (apply #'concat (nreverse (xterm-mouse--tracking-sequence ?l))))
401 (defconst xterm-mouse-tracking-disable-sequence
402 "\e[?1006l\e[?1005l\e[?1002l\e[?1000l"
403 "Reset the modes set by `xterm-mouse-tracking-enable-sequence'.")
405 (make-obsolete-variable
406 'xterm-mouse-tracking-disable-sequence
407 "use the function `xterm-mouse-tracking-disable-sequence' instead."
408 "25.1")
410 (defun xterm-mouse--tracking-sequence (suffix)
411 "Return a control sequence to enable or disable mouse tracking.
412 SUFFIX is the last character of each escape sequence (?h to
413 enable, ?l to disable)."
414 (mapcar
415 (lambda (code) (format "\e[?%d%c" code suffix))
416 `(1000 1002 ,@(when xterm-mouse-utf-8 '(1005)) 1006)))
418 (defun turn-on-xterm-mouse-tracking-on-terminal (&optional terminal)
419 "Enable xterm mouse tracking on TERMINAL."
420 (when (and xterm-mouse-mode (eq t (terminal-live-p terminal))
421 ;; Avoid the initial terminal which is not a termcap device.
422 ;; FIXME: is there more elegant way to detect the initial
423 ;; terminal?
424 (not (string= (terminal-name terminal) "initial_terminal")))
425 (unless (terminal-parameter terminal 'xterm-mouse-mode)
426 ;; Simulate selecting a terminal by selecting one of its frames
427 ;; so that we can set the terminal-local `input-decode-map'.
428 (with-selected-frame (car (frames-on-display-list terminal))
429 (define-key input-decode-map "\e[M" 'xterm-mouse-translate)
430 (define-key input-decode-map "\e[<" 'xterm-mouse-translate-extended))
431 (let ((enable (xterm-mouse-tracking-enable-sequence))
432 (disable (xterm-mouse-tracking-disable-sequence)))
433 (condition-case err
434 (send-string-to-terminal enable terminal)
435 ;; FIXME: This should use a dedicated error signal.
436 (error (if (equal (cadr err) "Terminal is currently suspended")
437 nil ; The sequence will be sent upon resume.
438 (signal (car err) (cdr err)))))
439 (push enable (terminal-parameter nil 'tty-mode-set-strings))
440 (push disable (terminal-parameter nil 'tty-mode-reset-strings))
441 (set-terminal-parameter terminal 'xterm-mouse-mode t)
442 (set-terminal-parameter terminal 'xterm-mouse-utf-8
443 xterm-mouse-utf-8)))))
445 (defun turn-off-xterm-mouse-tracking-on-terminal (terminal)
446 "Disable xterm mouse tracking on TERMINAL."
447 ;; Only send the disable command to those terminals to which we've already
448 ;; sent the enable command.
449 (when (and (terminal-parameter terminal 'xterm-mouse-mode)
450 (eq t (terminal-live-p terminal)))
451 ;; We could remove the key-binding and unset the `xterm-mouse-mode'
452 ;; terminal parameter, but it seems less harmful to send this escape
453 ;; command too many times (or to catch an unintended key sequence), than
454 ;; to send it too few times (or to fail to let xterm-mouse events
455 ;; pass by untranslated).
456 (condition-case err
457 (send-string-to-terminal xterm-mouse-tracking-disable-sequence
458 terminal)
459 ;; FIXME: This should use a dedicated error signal.
460 (error (if (equal (cadr err) "Terminal is currently suspended")
462 (signal (car err) (cdr err)))))
463 (setf (terminal-parameter nil 'tty-mode-set-strings)
464 (remq xterm-mouse-tracking-enable-sequence
465 (terminal-parameter nil 'tty-mode-set-strings)))
466 (setf (terminal-parameter nil 'tty-mode-reset-strings)
467 (remq xterm-mouse-tracking-disable-sequence
468 (terminal-parameter nil 'tty-mode-reset-strings)))
469 (set-terminal-parameter terminal 'xterm-mouse-mode nil)))
471 (provide 'xt-mouse)
473 ;;; xt-mouse.el ends here