Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

text auto complete using Tab in command line

I wonder how to implement a program in C that can automatically complete the command or text that you are entering in command line.For example, say your program is prompting user for a file name. Mostly one would use scanf() or else to do this. And then in the command line user would be prompt likeplease input the file name:_.

Let's say there is a shakespeare.txt in the same directory. And now I have entered shakes, and then I want the computer to auto-complete the shakespeare.txt for me, as it does for most programs when user hitting Tab. How to implement that?

Edit:to make it more clear, another example:

if you use grep in your command line, like grep -i "shakespeare" shakespeare.txt, before you complete shakespeare.txt yourself, if you simply use Tab, there would be some candidates show up.

How can I implement my program to make it possess this utilities when I try to prompt the user for input when using function like scanf()?

like image 737
Alex Avatar asked Jun 26 '15 13:06

Alex


1 Answers

If you consider using an existing utility, take a look at the GNU readline library which provides a pretty neat implementation of what you're looking for.
There some other helpful features like moving the cursor in your input, providing an input history and an input shell-like prompt.

This library's functionality works identical on different platforms.

As this example from Wikipedia shows, the key to indicate the completion can be set easily:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>

int main()
{
    char* input, shell_prompt[100];

    // Configure readline to auto-complete paths when the tab key is hit.
    rl_bind_key('\t', rl_complete);

    for(;;) {
        // Create prompt string from user name and current working directory.
        snprintf(shell_prompt, sizeof(shell_prompt), "%s:%s $ ", getenv("USER"), getcwd(NULL, 1024));

        // Display prompt and read input (NB: input must be freed after use)...
        input = readline(shell_prompt);

        // Check for EOF.
        if (!input)
            break;

        // Add input to history.
        add_history(input);

        // Do stuff...

        // Free input.
        free(input);
    }
    return 0;
}
like image 145
johabu Avatar answered Sep 27 '22 22:09

johabu