6

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!

7

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.

  • infocmp won't help if you use a combination not in the terminal description. – Thomas Dickey Nov 3 '16 at 0:37
1

The cat function is the usual way to do this, since you can use it to show what your keyboard actually sends. bash doesn't use any of the extended information in the terminal database (it uses a subset of the conventional termcap capabilities).

The drawback to using cat, of course, is determining whether

^[[A

is ^[A or escapeA (noting that bash provides a printable \e to represent the escape character).

In practice, you can ignore the former: essentially no one sends the three literal characters, "everyone" send that ^[ as the escape character).

Further reading:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.