As an exercise in understanding my computer better, and as a tool, I'm writing my own shell in C++. Stephen Brennan's article on writing a simple shell was very helpful.
However, what has me flummoxed is how to handle pressing up-arrow and down-arrow to scroll through my command history.
I tried
ncurses
, but that replaces the entire screen, whereas the system-provided shell seems to just continue writing into the Terminal.I tried using
tcgetattr
to turn off canonical mode, but while that lets me get arrow key presses as they are typed, it also turns off all processing of left/right arrow keys for text navigation, and the backspace key, and Ctrl-C... While I could probably send a signal myself in response to Ctr-C, I have no idea how to get the Terminal to move the cursor back (apart from outputting a "return" and re-writing the start of the line). It also seems to give me different escape sequences for the keys, depending on whether I'm running in Xcode's "dumb" Terminal or in my Mac's Terminal.app.I looked at the sources for
fish
Shell andbash
, but there just seems to be so much going on that I can't find the relevant parts.
How do the standard shells handle receiving keypresses? How do they handle moving the cursor and doing backspace? How do they re-write parts of a line without having to take over the screen? Is there a standard somewhere that defines what a shell needs to do?
PS - I know how to record the previous commands. It's the actually getting the keypresses while they are being typed, as opposed to after someone presses return, that I can't get to work.