This is the code in OCaml to detect keys using the Unix module and raw mode in the linux terminal.
The only key I can’t detect is ESC. There could be others, but my main goal is to detect ESC key.
Here is the code of the function:
(* Function to read a character and recognize special keys *)
let read_character () =
let in_chan = in_channel_of_descr stdin in
let c = input_char in_chan in
if c = '27' then
let next1 = input_char in_chan in
let next2 = input_char in_chan in
match (next1, next2) with
| ('[', 'A') -> "Up Arrow"
| ('[', 'B') -> "Down Arrow"
| ('[', 'C') -> "Right Arrow"
| ('[', 'D') -> "Left Arrow"
| ('[', 'H') -> "Home"
| ('[', 'F') -> "End"
| ('[', '3') when input_char in_chan = '~' -> "Delete"
| ('[', '2') when input_char in_chan = '~' -> "Insert"
| ('[', '5') when input_char in_chan = '~' -> "Page Up"
| ('[', '6') when input_char in_chan = '~' -> "Page Down"
| _ -> "Ignore"
else
match c with
| 'n' -> "Enter" (* Handle Enter key *)
| '127' -> "Backspace" (* Handle Backspace (DEL) *)
| _ -> String.make 1 c (* Return single character *)
Please, take into account that C/curses works, but it is very slow to initialize/finish and it clears the screen, so it is not an optimal option.
It is kind of a challenge. AI suggested me using Lwt/Async, but none of that worked, since I didn’t have success installing that in Arch Linux.
Enio Lecoder is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
The Esc key generates the single ESC byte (octal 027), whereas other special keys generate an escape sequence beginning with this byte.
Therefore, there is no fully reliable way of detecting the Esc keypress in terminals.
One possibility, done probably most notably by the vi
family, is to check for the ESC byte without any other byte immediately available. This works pretty well in practice, although strictly speaking there could be cases when depending on the timing of events can go wrong. A variation to this is to allow for a bit of additional delay while waiting for followup bytes.
Another possibility, also often seen in terminal based applications, is to expect the user to press the Esc key twice. This is straightforward to detect without heuristics, but results in a less pleasant user experience.