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