问题
I want to implement auto-completion feature for my CLI application. The default behavior of getc() is returning only when the following list of characters are entered: NEW_LINE or EOF. I want to add TAB to this list so that I can trigger my auto-completion algorithm.
Is there a way to do it, for instance, using termios? The editline library (http://www.thrysoee.dk/editline/) can do it but I could not figure how it does?
回答1:
Handling of terminal IO takes about 40 pages in the second edition of "Advanced Programming in the UNIX Environment"... Rapidly, you can set the eol and eol2 (termios.c_cc[EOL] and termios.c_cc[EOL2]) characters to have additional characters behaving like \n.
You can even try this with stty
$ cat -
abc\tdef
abc\tdef
^d
$stty eol ^i
abc\tabc\tdef
def
^d
Example of how to do it in a program (in practice, don't forget error handling and restoring the original state at end, when suspended, when signaled, and so on... that's why using a packaged library to do it is better, there are a lot of details to get right for a robust application).
struct termios term;
tcgetattr(STDIN_FILENO, &term);
term.c_cc[EOL] = '\t';
tcsetattr(STDION_FILENO, TCSAFLUSH, &term);
回答2:
The easiest approach, which doesn't require tcsetattr()
or tcgetattr()
at all, is to use cbreak()
to put the terminal into "cbreak" mode, which does not buffering or processing of control characters, and then to use nocbreak()
when you're done to reset it.
The man page for cbreak
documents various related functions, including raw()
and noecho()
that you can use to control the terminal without having to fully understand termios.
If you want finer control, you'll need to use termios directly. I wrote a blog post a little while ago that should get you started.
回答3:
you should be using gnu readline isntead of killing yourself with getc()... ;)
来源:https://stackoverflow.com/questions/4163405/how-to-change-termios-configuration-so-that-getc-immediately-returns-when-use