]> diplodocus.org Git - nmh/blob - sbr/read_switch_multiword_via_readline.c
Alter mh-chart(7)'s NAME to be lowercase.
[nmh] / sbr / read_switch_multiword_via_readline.c
1
2 /*
3 * read_switch_multiword_via_readline.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
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 cpp = brkstring(ansbuf, " ", NULL);
55 switch (smatch(*cpp, ansp)) {
56 case AMBIGSW:
57 ambigsw(*cpp, ansp);
58 continue;
59 case UNKWNSW:
60 printf(" -%s unknown. Hit <CR> for help.\n", *cpp);
61 continue;
62 default:
63 free(ans);
64 return cpp;
65 }
66 free(ans);
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 char **matches;
81
82 NMH_UNUSED (end);
83
84 matches = (char **) NULL;
85
86 if (start == 0)
87 matches = rl_completion_matches(text, nmh_command_generator);
88
89 return matches;
90 }
91
92 static char *
93 nmh_command_generator(const char *text, int state)
94 {
95 static int list_index, len;
96 char *name, *p;
97 char buf[256];
98
99 if (!state) {
100 list_index = 0;
101 len = strlen(text);
102 }
103
104 while ((name = rl_cmds[list_index].sw)) {
105 list_index++;
106 strncpy(buf, name, sizeof(buf));
107 buf[sizeof(buf) - 1] = '\0';
108 p = *brkstring(buf, " ", NULL);
109 if (strncmp(p, text, len) == 0)
110 return strdup(p);
111 }
112
113 return NULL;
114 }
115 #endif /* READLINE_SUPPORT */
116