Skip to content

Instantly share code, notes, and snippets.

@algal
Created May 5, 2024 22:33
Show Gist options
  • Save algal/93334ddd3b6801e2aac022c299dde1d0 to your computer and use it in GitHub Desktop.
Save algal/93334ddd3b6801e2aac022c299dde1d0 to your computer and use it in GitHub Desktop.
Make emacs see all keystrokes in TTY mode with iTerm2
;; This package makes changes to how emacs interprets CSI escape codes, so that
;; it better understands "CSI u"-style codes, so that more key chords pass
;; through to emacs in terminal mode.
;;
;; It is intended to work with the following terminal confugration:
;;
;; - iTerm2 / Keys / Report modifiers using CSI u: enabled
;; - iTerm2 / Keys / xterm control sequences can enable modifyOtherKeys mode: enabled
;; - iTerm2 / Terminal / Report Terminal Type: xterm-direct
;;
;; It needs to be REQUIRED early during init
;;
;; As of iTerm2 3.4.23, with tmux 3.3a, it does not work within tmux
;; windows, using iTerm2's tmux command code (tmux -CC) or with plain
;; tmux.
;;
;; based on:
;; - https://gitlab.com/gnachman/iterm2/-/issues/8382
;; - https://gist.github.com/gnachman/b4fb1e643e7e82a546bc9f86f30360e4
(defun bsc-eval-after-load-xterm ()
"Updates xterm-function-map with many CSI u "
(unless (display-graphic-p)
(xterm--init-modify-other-keys)
(when (and (boundp 'xterm-extra-capabilities) (boundp 'xterm-function-map))
(message "Updating xterm-function-map to add some CSI u code")
;; fix M-S-ret for org mode
(define-key xterm-function-map "\e\[13;4u" [(control meta shift ?\r)])
(define-key xterm-function-map "\e\[27;4;13~" [(control meta shift ?\r)])
;; manually create keymap for shift-space
(define-key xterm-function-map
"\e\[32;2u"
(vector (append '(shift) (cons 32 '()))))
(cl-loop
for c from 32 to 126
do
(cl-loop
for code in
'(;; with ?.VT100.formatOtherKeys: 0
("\e\[27;3;%d~" meta)
("\e\[27;4;%d~" meta shift)
("\e\[27;5;%d~" control)
("\e\[27;6;%d~" control shift)
("\e\[27;7;%d~" control meta)
("\e\[27;8;%d~" control meta shift)
;; with ?.VT100.formatOtherKeys: 1
("\e\[%d;3u" meta)
("\e\[%d;4u" meta shift)
("\e\[%d;5u" control)
("\e\[%d;6u" control shift)
("\e\[%d;7u" control meta)
("\e\[%d;8u" control meta shift))
do
;; define-key can take a vector that wraps a list of
;; events, e.g. [(control shift ?a)] for C-S-a
(define-key xterm-function-map
(format (car code) c)
(vector (append (cdr code) (cons c '())))))))))
(when (and
(equal (getenv-internal "TERM" initial-environment) "xterm-direct")
(equal (getenv-internal "LC_TERMINAL" initial-environment) "iTerm2"))
(eval-after-load "xterm" '(bsc-eval-after-load-xterm)))
(provide 'term-iterm2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment