Here is a (rather artificial) example of using GNU readline in C (also compiles g ++)
(and here is the link to it for windows )
The program analyzes the read line and if it contains a word beginning with V:
then it is substituted for the input of the next line.
#include <stdio.h> #include <stdlib.h> #include <readline/readline.h> #include <readline/history.h> static char *ins; int f() { if (ins && ins[0]) { rl_insert_text(ins); rl_redisplay(); } } int main (int ac, char *av[]) { char *line = 0, txt[1000] = "", *p; rl_pre_input_hook = f; // readline() вызовет нашу функцию перед чтением ввода (после вывода промпта) rl_bind_key('\t', rl_insert); // для вставки символа табуляции (иначе он работает как поиск дополнения имени файла) ins = txt; while (line = readline("> ")) { printf("line: %s\n", *line ? line : ""); txt[0] = 0; if (p = strstr(line, "V:")) sscanf(p, "%s", txt); if (line[0]) add_history(line); free(line); } return puts("End") == EOF; }
Since nested functions are not supported in C ++, the f()
function (readline hook) and the char txt[]
array (or a pointer to it, as in this example) have to be moved to an external level.
Call example:
avp@avp-ubu1:hashcode$ g++ t-readline.c -lreadline avp@avp-ubu1:hashcode$ ./a.out > ksdkk line: ksdkk > ueru V:444 line: ueru V:444 > V:444 kksk line: V:444 kksk > End
In line 5 (the third call to readline), the text V:444
at the beginning of the input area is substituted from the previously entered line.