Search code examples
ctabsreadlinelibreadline

Tab Completion in C (readline library)


I have been trying to get tab completion working.. I am very confused and don't know what to do. Could you please take a look at my code and tell me how I could possibly fix it.

By the way I used rl_attempted_completion_function since I got it from an online tutorial but it is an C++ function. What function can I use to replace it without making changes.

Thanks

   static char** completion( const char * text , int start,  int end){
            char **matches;
            matches = (char **)NULL;

            if (start == 0)
                    matches = rl_completion_matches ((char*)text, &generator);

            return (matches);
    }

    char* generator(const char* text, int state) {
            int index, len;
            char *comm;
            if (!state) {
                    index = 0;
                    len = (int)strlen (text);
            }

            while ( (*comm = newEnv[index])) {
                    index++;
                    if (strncmp (comm, text, len) == 0)
                            return ((comm));
            }
            return NULL;
    }

    int main (int argc,  char * argv[]) {

            using_history();
            rl_readline_name = basename(argv[0]);

            rl_attempted_completion_function = completion;

            while ( readline(">> ")!= NULL )  
                    rl_bind_key('\t',rl_complete);

            return 0;
    }

Solution

  • I notice this:

    char *comm;
    ...
    while ( (*comm = newEnv[index])) {
    

    I don't know what the return type of newEnv is, but you probably want to put it in comm, not *comm, because you didn't point comm at anything.