-
Notifications
You must be signed in to change notification settings - Fork 0
/
auto-complete.cpp
95 lines (71 loc) · 1.88 KB
/
auto-complete.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>
static char** my_completion(const char*, int ,int);
char* my_generator(const char*,int);
char * dupstr (char*);
void *xmalloc (int);
char* cmd [] ={ "hello", "world", "hell" ,"word", "quit", " ", "\r" };
int main()
{
char *buf;
rl_completion_append_character = '\0';
rl_ignore_completion_duplicates = 1;
rl_attempted_completion_function = my_completion;
while((buf = readline("\n >> "))!=NULL) {
//enable auto-complete
rl_bind_key('\t',rl_complete);
printf("cmd [%s]\n",buf);
printf("value of duplicates: %d\n", rl_ignore_completion_duplicates);
if (strcmp(buf,"quit")==0)
break;
if (buf[0]!=0)
add_history(buf);
}
free(buf);
return 0;
}
static char** my_completion( const char * text , int start, int end)
{
char **matches;
matches = (char **)NULL;
if (start == 0)
matches = completion_matches ((char*)text, &my_generator);
else
rl_bind_key('\t',rl_insert);
return (matches);
}
char* my_generator(const char* text, int state)
{
static int list_index, len;
char *name;
if (!state) {
list_index = 0;
len = strlen (text);
}
while ((name = cmd[list_index]) && strncmp(cmd[list_index], "\r", 1) != 0) {
list_index++;
if (strncmp (name, text, len) == 0)
return (dupstr(name));
}
/* If no names matched, then return NULL. */
return ((char *)NULL);
}
char * dupstr (char* s) {
char *r;
r = (char*) xmalloc ((strlen (s) + 1));
strcpy (r, s);
return (r);
}
void * xmalloc (int size)
{
void *buf;
buf = malloc (size);
if (!buf) {
fprintf (stderr, "Error: Out of memory. Exiting.'n");
exit (1);
}
return buf;
}