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