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