]> diplodocus.org Git - nmh/blob - sbr/getansreadline.c
Removed export of most of the variables in test/common.sh.in. The
[nmh] / sbr / getansreadline.c
1
2 /*
3 * getansreadline.c -- get an answer from the user, with readline
4 *
5 * This code is Copyright (c) 2012, by the authors of nmh. See the
6 * COPYRIGHT file in the root directory of the nmh distribution for
7 * complete copyright information.
8 */
9
10 #include <h/mh.h>
11 #include <h/signals.h>
12
13 #ifdef READLINE_SUPPORT
14 #include <readline/readline.h>
15 #include <readline/history.h>
16
17 static struct swit *rl_cmds;
18
19 static char *nmh_command_generator(const char *, int);
20 static char **nmh_completion(const char *, int, int);
21 static void initialize_readline(void);
22
23 static char ansbuf[BUFSIZ];
24
25 /*
26 * getans, but with readline support
27 */
28
29 char **
30 getans_via_readline(char *prompt, struct swit *ansp)
31 {
32 char *ans, **cpp;
33
34 initialize_readline();
35 rl_cmds = ansp;
36
37 for (;;) {
38 ans = readline(prompt);
39 /*
40 * If we get an EOF, return
41 */
42
43 if (ans == NULL)
44 return NULL;
45
46 if (ans[0] == '?' || ans[0] == '\0') {
47 printf("Options are:\n");
48 print_sw(ALL, ansp, "", stdout);
49 free(ans);
50 continue;
51 }
52 add_history(ans);
53 strncpy(ansbuf, ans, sizeof(ansbuf));
54 ansbuf[sizeof(ansbuf) - 1] = '\0';
55 cpp = brkstring(ansbuf, " ", NULL);
56 switch (smatch(*cpp, ansp)) {
57 case AMBIGSW:
58 ambigsw(*cpp, ansp);
59 continue;
60 case UNKWNSW:
61 printf(" -%s unknown. Hit <CR> for help.\n", *cpp);
62 continue;
63 default:
64 free(ans);
65 return cpp;
66 }
67 free(ans);
68 }
69 }
70
71 static void
72 initialize_readline(void)
73 {
74 rl_readline_name = "Nmh";
75 rl_attempted_completion_function = nmh_completion;
76 }
77
78 static char **
79 nmh_completion(const char *text, int start, int end)
80 {
81 char **matches;
82
83 NMH_UNUSED (end);
84
85 matches = (char **) NULL;
86
87 if (start == 0)
88 matches = rl_completion_matches(text, nmh_command_generator);
89
90 return matches;
91 }
92
93 static char *
94 nmh_command_generator(const char *text, int state)
95 {
96 static int list_index, len;
97 char *name, *p;
98 char buf[256];
99
100 if (!state) {
101 list_index = 0;
102 len = strlen(text);
103 }
104
105 while ((name = rl_cmds[list_index].sw)) {
106 list_index++;
107 strncpy(buf, name, sizeof(buf));
108 buf[sizeof(buf) - 1] = '\0';
109 p = *brkstring(buf, " ", NULL);
110 if (strncmp(p, text, len) == 0)
111 return strdup(p);
112 }
113
114 return NULL;
115 }
116 #endif /* READLINE_SUPPORT */
117