]> diplodocus.org Git - nmh/blob - sbr/read_switch_multiword.c
d13ae7a1df1432f83e4186c5f87638ca68d4e515
[nmh] / sbr / read_switch_multiword.c
1 /* read_switch_multiword.c -- get an answer from the user and return a string array
2 *
3 * This code is Copyright (c) 2002, 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 "brkstring.h"
10 #include "ambigsw.h"
11 #include "print_sw.h"
12 #include "h/signals.h"
13 #include <setjmp.h>
14
15 static char ansbuf[BUFSIZ];
16 static sigjmp_buf sigenv;
17
18 /*
19 * static prototypes
20 */
21 static void intrser (int);
22
23
24 char **
25 read_switch_multiword (const char *prompt, const struct swit *ansp)
26 {
27 int i;
28 SIGNAL_HANDLER istat = NULL;
29 char *cp, **cpp;
30
31 if (sigsetjmp(sigenv, 1)) {
32 SIGNAL (SIGINT, istat);
33 return NULL;
34 }
35 istat = SIGNAL (SIGINT, intrser);
36
37 for (;;) {
38 fputs(prompt, stdout);
39 fflush (stdout);
40 cp = ansbuf;
41 while ((i = getchar ()) != '\n') {
42 if (i == EOF) {
43 /*
44 * If we get an EOF, return
45 */
46 if (feof(stdin))
47 siglongjmp (sigenv, 1);
48
49 /*
50 * For errors, if we get an EINTR that means that we got
51 * a signal and we should retry. If we get another error,
52 * then just return.
53 */
54
55 if (ferror(stdin)) {
56 if (errno == EINTR) {
57 clearerr(stdin);
58 continue;
59 }
60 fprintf(stderr, "\nError %s during read\n",
61 strerror(errno));
62 siglongjmp (sigenv, 1);
63 }
64
65 /* Just for completeness's sake... */
66 fprintf(stderr, "\nUnknown problem in getchar()\n");
67 siglongjmp(sigenv, 1);
68 }
69 if (cp < &ansbuf[sizeof ansbuf - 1])
70 *cp++ = i;
71 }
72 *cp = '\0';
73 if (ansbuf[0] == '?' || cp == ansbuf) {
74 puts("Options are:");
75 print_sw (ALL, ansp, "", stdout);
76 continue;
77 }
78 cpp = brkstring (ansbuf, " ", NULL);
79 switch (smatch (*cpp, ansp)) {
80 case AMBIGSW:
81 ambigsw (*cpp, ansp);
82 continue;
83 case UNKWNSW:
84 printf (" -%s unknown. Hit <CR> for help.\n", *cpp);
85 continue;
86 default:
87 SIGNAL (SIGINT, istat);
88 return cpp;
89 }
90 }
91 }
92
93
94 static void
95 intrser (int i)
96 {
97 NMH_UNUSED (i);
98
99 siglongjmp (sigenv, 1);
100 }