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