开发者

How would one implement bash-like tab completion?

I'm trying to determine how the system prints characters to standard input -- that is, how it prints characters which the user can delete and whi开发者_开发技巧ch are considered input if the user hits "Enter."

I happen to be using C, but I would be very surprised if the solution were language-dependent.

Thanks for any insights! : D


As iny says, bash uses readline for its input. The source is available here, and there's a file called complete.c.

To answer your question, I don't think they're actually printed to standard input. Readline contains some kind of buffer for the contents of the line the user is editing, and completion prints into this. When the user presses enter, the contents of the buffer are sent to whatever program wanted to read a line, and in the case of bash, passed along into standard input. (Readline doesn't do this - other programs which use readline might simply store the value into a string for later use.)


Several people have pointed out that bash uses readline, which is true, but I think what you're really asking is how is it able to see what you've typed before you hit enter.

The answer is that ttys (ie: terminals) can be switched into "raw mode", where input processing of the terminal is disabled, and then you'll see every character as it comes in. This also disables automatic echoing of typed characters.

See this guide on Reading a single character from a file or a terminal for more info.


It uses readline library to handle the input and readline provides the history and the completion.

To actually implement completion, access to the keyboard input handling is needed. The completion must be able to modify the buffer used by it. After that it is just about looking at the current input and checking what completions is found. The actual completion logic can work in many ways.


Here's a C snippet that implements tab completion via readline:

http://github.com/rupa/el

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜