1

I'm trying to write my own terminal shell in C and want to know how I can register arrow-up and arrow-down presses to populate the current input line with a previously entered line? I'd like to do this without pressing enter.

I wrote my shell to save every entered line to a history.txt file, so I'm thinking my approach will be to have the shell take inputs like ^[[A or ^[[B and automatically replace it with the last recorded command, and somehow iterate through the lines of the history.txt file with each successive key press. Since I've read that implementation of this can be platform-specific, I'm hoping for this to work on any GNU/Linux distribution, or at least Debian 12.

Once I figure this out I'd also like to use the left and right keys to scroll through text that I've already typed, instead of adding ^[[D and ^[[C after what's been typed, and eventually add autocomplete using Tab, but for the sake of having a more specific question, for now I'm asking for help primarily with the up and down keys scrolling through previous commands the same way it works in Bash on Debian and similar Linux/POSIX systems I've used.

I haven't been able to think of a way to implement this so far, and wasn't sure what to search for to find any examples of other people implementing this behavior in their own code, I could only see discussions of people who weren't seeing this behavior as they expected to in their OS's provided shell.

6
  • 2
    Check tiswww.case.edu/php/chet/readline/rltop.html Commented Mar 15 at 21:19
  • 2
    You might like to use termios or ncurses (Linux), or conio (Windows) if you don't want the prehistoric line-oriented input, and respond to keystrokes as they happen. Commented Mar 15 at 21:30
  • 2
    What have you tried so far? Please see: How to create a Minimal, Reproducible Example, How do I ask a good question? Commented Mar 16 at 4:06
  • 4
    Take a look at the GNU Readline library. Commented Mar 16 at 6:45
  • 2
    What Jonathan said. If you use GNU readline() it's just about as simple as replacing all calls to fgets() (or whatever line-reading function you used to use) with readline(). Or, you could roll your own, and you'd learn a lot, but it'd be a lot of work. Commented Mar 16 at 10:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.