xt-mouse.el 20 KB

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