Reverse control-code look up for terminals

escape-characterskeyboard shortcutsterminal

My understanding is that terminals often use ANSI control-codes to represent non-alphanumeric character sequences. For example, when editing .inputrc for Bash in Linux, it's easy to find code sequences that look as follows:

"\e[A": history-search-backward
"\e[B": history-search-forward
"\e[C": forward-char
"\e[D": backward-char
"\e[1~": beginning-of-line
"\e[4~": end-of-line
"\e[3~": delete-char
"\e[2~": quoted-insert
"\e[5C": forward-word
"\e[5D": backward-word

The commands above define key bindings for the Bash commands history-search-backward, etc..

Now, in bash, I can use read to see how characters typed in my keyboard are mapped to ANSI control codes. E.g. For example, if I run read, and then enter Ctrl-P, I get: ^P. Similarly, if I enter Alt-W, I get: ^[W.

My question is: Is there a program, tool or website that does the opposite? I.e. a tool that outputs or shows the sequence of keyboard keys that I need to type on my keyboard to obtain a given ANSI control-code sequence. For example, entering ^[W should output: Alt-W

Thanks!

Best Answer

infocmp can help. It writes escape as \E rather than \e or ^[.

For example, to find \e[A, which is your history-search-backward:

$ infocmp -1x | grep -F '=\E[A,'
       cuu1=\E[A,
$ man 5 terminfo | grep '  cuu1  '
       cursor_up                     cuu1       up       up one line

Which tells you to press cursor up, a.k.a. up arrow.

Note that you will need the -x flag (shown above) to display some combinations, e.g. Ctrl+<-.

These extended keys are not part of the standard, so they aren't listed in the terminfo man page, but they are documented in the terminfo file.

Also note that the control sequences vary depending on which terminal you use.

You can get information about a different terminal by using infocmp -1x <terminal>, e.g. infocmp -1x rxvt, infocmp -1x putty, etc.

Once you figure out which one terminfo thinks you have, things will be easier if you set your TERM variable to match.

Related Question