问题描述:

Here's a simple program that uses libedit or GNU readlines to generate autocompletion options

#include <readline/readline.h>

#include <stdlib.h>

#include <string.h>

char *command_generator(char *word, int state) {

char *options[] = {"I_love_math", "he_love_math", "she_loves_math", "they_love_math", NULL};

return options[state] ? strdup(options[state]) : NULL;

}

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

rl_readline_name = "rl_example";

rl_completion_entry_function = (void*)command_generator;

rl_initialize();

rl_parse_and_bind("TAB: menu-complete");

while (1) {

char *line = readline("rl> ");

if (line == NULL) break;

printf("echo %s\n", line);

free(line);

}

return 0;

}

This program works, in the sense it displays the completion options, however it does not actually complete them. That is, it will only display the available options

$ gcc -ggdb3 -ledit example.c && ./a.out

rl> a

he_love_math I_love_math she_loves_math they_love_math

rl> a

Even after I press tab, it does not relace "a" with "he_love_math", it just shows the options.

From a small internet search, I found out that one needs to bind the TAB key to menu-complete, however as you can see, neither running

rl_parse_and_bind("TAB: menu-complete");

not putting "TAB: menu-complete" in my home directory helps here.

How can I make completion work? How can I cause libedit to replace the current word with the completion suggestion?

网友答案:

readline on OSx is implemented via routines in libedit aka editline. Unfortunately the compatibility does not extend as far as the configuration commands.

Change your binding line to:

rl_parse_and_bind("bind ^I rl_complete");

or put this in ~/.editrc

bind ^I rl_complete

Read the man page for editline and editrc; but they don't have information on the rl_* routines in the library libedit

相关阅读:
Top