Terminal – Control and Up/Down Keys for Emacs

emacskeyboardterminal

Is it possible to use C-up and C-down when running emacs in the terminal window (when starting emacs from the command line with the -nw flag)? What should my terminal send when I press C-up and C-down for these keys to work in emacs?

I'm on Mac OSX, using iterm2 to ssh into a remote linux server, where I start the emacs session from bash.

Best Answer

Terminals know characters, not keys, so keys with no corresponding character need to be translated into escape sequences and back.

You can pick any control sequences that doesn't cause any conflict and that iterm2 and Emacs agree on. Unfortunately, these control sequences aren't standardized. \e[1;5A and \e[1;5B are popular choices (where \e is an escape character).

Emacs has a fairly complex system to translate escape sequences into keys. See translation keymaps in the manual. Use input-decode-map unless you have an old version of Emacs that doesn't have it.

(define-key input-decode-map "\e[1;5A" [C-up])
(define-key input-decode-map "\e[1;5B" [C-down])

In iterm2, set the corresponding key sequences in the “Keys” tab in your profile. See How can I get control+left arrow to go back one word in iTerm2? for an illustrated guide.

See also Emacs + paredit under terminal (Terminal.app, iTerm, iTerm2).

Related Question