Determine escape sequence independent from terminal type
-
27-06-2021 - |
Question
My app reading escape sequences from terminal in raw mode. And when it's running on xterm I got F2 like "\eOQ". But when it's running in linux tty terminal (Switching by Ctrl-Alt-F1) I got "\e[[[B".
What is the correct way to determine that I got F2 independent from terminal type application running on?
Solution
If you're wanting to read terminal keypresses, you likely want to look at something like libtermkey , which abstracts the general problem away for you. Internally it uses a combination of terminfo
lookups, or hardcoded knowledge of the extended xterm
-like model for modified keypresses, so it can understand things like Ctrl-Up
, which a regular curses/etc... cannot.
while((ret = termkey_waitkey(tk, &key)) != TERMKEY_RES_EOF) {
termkey_strfkey(tk, buffer, sizeof buffer, &key, TERMKEY_FORMAT_VIM);
printf("You pressed key %s\n", buffer);
if(key.type == TERMKEY_TYPE_FUNCTION &&
!key.modifiers &&
key.code.number = 2)
printf("Got F2\n");
}
OTHER TIPS
Ok, as I got the best way to use [n]curses library. It is read terminfo (termcap) database and determine what mean escape sequence you got depend on terminal type.
It is not necessary using it's terminal graphics functions. To get correct escape sequences using curses you may do the following:
newterm(NULL, stdout, stdin);
Also, it is probably possibly do it manually by reading terminfo database in you app.
raw();
noecho();
keypad();
ch = getch();
if (ch == KEY_F(2)) printf("Got F2");
endwin();