]> diplodocus.org Git - nmh/blob - sbr/read_switch_multiword_via_readline.c
2320ccbf1ce0268fc0c0bdbd96f55eb33e59864f
[nmh] / sbr / read_switch_multiword_via_readline.c
1 /* read_switch_multiword_via_readline.c -- get an answer from the user, with readline
2 *
3 * This code is Copyright (c) 2012, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include "h/mh.h"
9 #include "smatch.h"
10 #include "brkstring.h"
11 #include "ambigsw.h"
12 #include "print_sw.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 read_switch_multiword_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 puts("Options are:");
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 free(ans);
57
58 cpp = brkstring(ansbuf, " ", NULL);
59 switch (smatch(*cpp, ansp)) {
60 case AMBIGSW:
61 ambigsw(*cpp, ansp);
62 continue;
63 case UNKWNSW:
64 printf(" -%s unknown. Hit <CR> for help.\n", *cpp);
65 continue;
66 default:
67 return cpp;
68 }
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 NMH_UNUSED (end);
83
84 if (start == 0)
85 return rl_completion_matches(text, nmh_command_generator);
86
87 return NULL;
88 }
89
90 static char *
91 nmh_command_generator(const char *text, int state)
92 {
93 static int list_index, len;
94 char *name, *p;
95 char buf[256];
96
97 if (!state) {
98 list_index = 0;
99 len = strlen(text);
100 }
101
102 while ((name = rl_cmds[list_index].sw)) {
103 list_index++;
104 strncpy(buf, name, sizeof(buf));
105 buf[sizeof(buf) - 1] = '\0';
106 p = *brkstring(buf, " ", NULL);
107 if (strncmp(p, text, len) == 0)
108 return strdup(p);
109 }
110
111 return NULL;
112 }
113 #endif /* READLINE_SUPPORT */