Reputation: 53
I am writing a small shell in Rust on Linux as an exercise and I wanted to implement command history as well as cursor moving (i.e. moving back the cursor to edit a typo in the command).
I did not find a way in the Rust standard library to handle arrow key events, but I found the Termion crate which handles key events.
However, handling key events with Termion means entering "raw mode" for stdout, which overrides "legacy" functionalities, as described in this article about the crate:
Without raw mode, you cannot write a proper interactive TTY application. Raw mode gives you complete control over the TTY:
- It disables the line buffering: As you might notice, your command-line application tends to behave like the command-line. The programs will first get the input when the user types \n. Raw mode makes the program get the input after every key stroke.
- It disables displaying the input: Without raw mode, the things you type appear on the screen, making it insufficient for most interactive TTY applications, where keys can represent controls and not textual input.
- It disables canonicalization of the output: For example, \n represents “go one cell down” not “break the line”, for line breaks \n\r is needed.
- It disables scrolling.
I find this solution a bit overkill, as I want to retain most of the "legacy" I/O functionalities. Is there another way to handle arrow key input, or will I need to use the raw mode?
Upvotes: 5
Views: 5509
Reputation: 28025
There are several crates that provide line editing features for interactive programs. Here are a few that I found by searching crates.io for "readline" (the name of a C library):
I haven't used any of them, so this list is not a recommendation. Take a look at a few of them and choose one that suits your needs.
Upvotes: 4