Do some error checking in puthead()
[s-mailx.git] / lex_input.c
blob152087b326aafa86c933107cf1e5bc53129339dc
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Command input, lexing and evaluation, resource file loading and `source'ing.
3 *@ TODO PS_ROBOT requires yet PS_SOURCING, which REALLY sucks.
4 *@ TODO Commands and ghosts deserve a hashmap. Or so.
6 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
7 * Copyright (c) 2012 - 2016 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
8 */
9 /*
10 * Copyright (c) 1980, 1993
11 * The Regents of the University of California. All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
37 #undef n_FILE
38 #define n_FILE lex_input
40 #ifndef HAVE_AMALGAMATION
41 # include "nail.h"
42 #endif
44 enum a_lex_input_flags{
45 a_LEX_NONE,
46 a_LEX_FREE = 1<<0, /* Structure was allocated, free() it */
47 a_LEX_PIPE = 1<<1, /* Open on a pipe */
48 a_LEX_MACRO = 1<<2, /* Running a macro */
49 a_LEX_MACRO_FREE_DATA = 1<<3, /* Lines are allocated, free(3) once done */
50 a_LEX_MACRO_X_OPTION = 1<<4, /* Macro indeed command line -X option */
51 a_LEX_MACRO_CMD = 1<<5, /* Macro indeed single-line: ~:COMMAND */
53 a_LEX_SUPER_MACRO = 1<<16 /* *Not* inheriting PS_SOURCING state */
56 struct a_lex_cmd{
57 char const *lc_name; /* Name of command */
58 int (*lc_func)(void*); /* Implementor of command */
59 enum argtype lc_argtype; /* Arglist type (see below) */
60 si16_t lc_msgflag; /* Required flags of msgs */
61 si16_t lc_msgmask; /* Relevant flags of msgs */
62 #ifdef HAVE_DOCSTRINGS
63 char const *lc_doc; /* One line doc for command */
64 #endif
66 /* Yechh, can't initialize unions */
67 #define lc_minargs lc_msgflag /* Minimum argcount for RAWLIST */
68 #define lc_maxargs lc_msgmask /* Max argcount for RAWLIST */
70 struct a_lex_ghost{
71 struct a_lex_ghost *lg_next;
72 struct str lg_cmd; /* Data follows after .lg_name */
73 char lg_name[n_VFIELD_SIZE(0)];
76 struct a_lex_eval_ctx{
77 struct str le_line; /* The terminated data to _evaluate() */
78 ui32_t le_line_size; /* May be used to store line memory size */
79 bool_t le_is_recursive; /* Evaluation in evaluation? (collect ~:) */
80 ui8_t __dummy[3];
81 bool_t le_add_history; /* Add command to history (TRUM1=gabby)? */
82 char const *le_new_content; /* History: reenter line, start with this */
85 struct a_lex_input_stack{
86 struct a_lex_input_stack *li_outer;
87 FILE *li_file; /* File we were in */
88 void *li_cond; /* Saved state of conditional stack */
89 ui32_t li_flags; /* enum a_lex_input_flags */
90 ui32_t li_loff; /* Pseudo (macro): index in .li_lines */
91 char **li_lines; /* Pseudo content, lines unfolded */
92 char li_autorecmem[n_MEMORY_AUTOREC_TYPE_SIZEOF];
93 char li_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
95 n_CTA(n_MEMORY_AUTOREC_TYPE_SIZEOF % sizeof(void*) == 0,
96 "Inacceptible size of structure buffer");
98 static sighandler_type a_lex_oldpipe;
99 static struct a_lex_ghost *a_lex_ghosts;
100 /* a_lex_cmd_tab[] after fun protos */
102 /* */
103 static struct a_lex_input_stack *a_lex_input;
105 /* Isolate the command from the arguments */
106 static char *a_lex_isolate(char const *comm);
108 /* Command ghost handling */
109 static int a_lex_c_ghost(void *v);
110 static int a_lex_c_unghost(void *v);
112 /* Print a list of all commands */
113 static int a_lex_c_list(void *v);
115 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
117 /* `help' / `?' command */
118 static int a_lex_c_help(void *v);
120 /* `quit' command */
121 static int a_lex_c_quit(void *v);
123 /* Print the binaries version number */
124 static int a_lex_c_version(void *v);
126 static int a_lex__version_cmp(void const *s1, void const *s2);
128 /* PS_STATE_PENDMASK requires some actions */
129 static void a_lex_update_pstate(void);
131 /* Evaluate a single command.
132 * .le_add_history and .le_new_content will be updated upon success.
133 * Command functions return 0 for success, 1 for error, and -1 for abort.
134 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
135 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
137 /* Get first-fit, or NULL */
138 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
140 /* Branch here on hangup signal and simulate "exit" */
141 static void a_lex_hangup(int s);
143 /* The following gets called on receipt of an interrupt. Close all open files
144 * except 0, 1, 2, and the temporary. Also, unstack all source files */
145 static void a_lex_onintr(int s);
147 /* Pop the current input back to the previous level. Update the program state.
148 * If the argument is TRUM1 then we don't alert and error out if the stack
149 * doesn't exist at all */
150 static void a_lex_unstack(bool_t eval_error);
152 /* `source' and `source_if' (if silent_error: no pipes allowed, then) */
153 static bool_t a_lex_source_file(char const *file, bool_t silent_error);
155 /* System resource file load()ing or -X command line option array traversal */
156 static bool_t a_lex_load(struct a_lex_input_stack *lip);
158 /* A simplified command loop for recursed state machines */
159 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
161 /* List of all commands, and list of commands which are specially treated
162 * and deduced in _evaluate(), but we need a list for _c_list() and
163 * print_comm_docstr() */
164 #ifdef HAVE_DOCSTRINGS
165 # define DS(S) , S
166 #else
167 # define DS(S)
168 #endif
169 static struct a_lex_cmd const a_lex_cmd_tab[] = {
170 #include "cmd_tab.h"
172 a_lex_special_cmd_tab[] = {
173 { "#", NULL, 0, 0, 0
174 DS(N_("Comment command: ignore remaining (continuable) line")) },
175 { "-", NULL, 0, 0, 0
176 DS(N_("Print out the preceding message")) }
178 #undef DS
180 static char *
181 a_lex_isolate(char const *comm){
182 NYD2_ENTER;
183 while(*comm != '\0' &&
184 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
185 ++comm;
186 NYD2_LEAVE;
187 return n_UNCONST(comm);
190 static int
191 a_lex_c_ghost(void *v){
192 struct a_lex_ghost *lgp, *gp;
193 size_t i, cl, nl;
194 char *cp;
195 char const **argv;
196 NYD_ENTER;
198 argv = v;
200 /* Show the list? */
201 if(*argv == NULL){
202 FILE *fp;
204 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
205 fp = stdout;
207 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
208 fprintf(fp, "wysh ghost %s %s\n",
209 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
211 if(fp != stdout){
212 page_or_print(fp, i);
213 Fclose(fp);
215 goto jleave;
218 /* Verify the ghost name is a valid one */
219 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0'){
220 n_err(_("`ghost': can't canonicalize %s\n"),
221 n_shexp_quote_cp(argv[0], FAL0));
222 v = NULL;
223 goto jleave;
226 /* Show command of single ghost? */
227 if(argv[1] == NULL){
228 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
229 if(!strcmp(argv[0], gp->lg_name)){
230 printf("wysh ghost %s %s\n",
231 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
232 goto jleave;
234 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
235 v = NULL;
236 goto jleave;
239 /* Define command for ghost: verify command content */
240 for(cl = 0, i = 1; (cp = n_UNCONST(argv[i])) != NULL; ++i)
241 if(*cp != '\0')
242 cl += strlen(cp) +1; /* SP or NUL */
243 if(cl == 0){
244 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
245 v = NULL;
246 goto jleave;
249 /* If the ghost already exists, recreate */
250 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
251 if(!strcmp(gp->lg_name, argv[0])){
252 if(lgp != NULL)
253 lgp->lg_next = gp->lg_next;
254 else
255 a_lex_ghosts = gp->lg_next;
256 free(gp);
257 break;
260 nl = strlen(argv[0]) +1;
261 gp = smalloc(sizeof(*gp) - n_VFIELD_SIZEOF(struct a_lex_ghost, lg_name) +
262 nl + cl);
263 gp->lg_next = a_lex_ghosts;
264 a_lex_ghosts = gp;
265 memcpy(gp->lg_name, argv[0], nl);
266 cp = gp->lg_cmd.s = gp->lg_name + nl;
267 gp->lg_cmd.l = --cl;
269 while(*++argv != NULL)
270 if((i = strlen(*argv)) > 0){
271 memcpy(cp, *argv, i);
272 cp += i;
273 *cp++ = ' ';
275 *--cp = '\0';
276 jleave:
277 NYD_LEAVE;
278 return v == NULL;
281 static int
282 a_lex_c_unghost(void *v){
283 struct a_lex_ghost *lgp, *gp;
284 char const **argv, *cp;
285 int rv;
286 NYD_ENTER;
288 rv = 0;
289 argv = v;
291 while((cp = *argv++) != NULL){
292 if(cp[0] == '*' && cp[1] == '\0'){
293 while((gp = a_lex_ghosts) != NULL){
294 a_lex_ghosts = gp->lg_next;
295 free(gp);
297 }else{
298 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
299 lgp = gp, gp = gp->lg_next)
300 if(!strcmp(gp->lg_name, cp)){
301 if(lgp != NULL)
302 lgp->lg_next = gp->lg_next;
303 else
304 a_lex_ghosts = gp->lg_next;
305 free(gp);
306 goto jouter;
308 n_err(_("`unghost': no such alias: %s\n"),
309 n_shexp_quote_cp(cp, FAL0));
310 rv = 1;
311 jouter: ;
314 NYD_LEAVE;
315 return rv;
318 static int
319 a_lex_c_list(void *v){
320 FILE *fp;
321 struct a_lex_cmd const **cpa, *cp, **cursor;
322 size_t l, i;
323 NYD_ENTER;
325 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
326 cpa = salloc(sizeof(cp) * i);
328 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
329 cpa[i] = &a_lex_cmd_tab[i];
330 /* C99 */{
331 size_t j;
333 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
334 cpa[i] = &a_lex_special_cmd_tab[j];
336 cpa[i] = NULL;
338 /* C99 */{
339 char const *xcp = v;
341 if(*xcp == '\0')
342 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
345 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
346 fp = stdout;
348 fprintf(fp, _("Commands are:\n"));
349 l = 1;
350 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
351 if(cp->lc_func == &c_cmdnotsupp)
352 continue;
353 if(options & OPT_D_V){
354 char const *argt;
356 switch(cp->lc_argtype & ARG_ARGMASK){
357 case ARG_MSGLIST: argt = N_("message-list"); break;
358 case ARG_STRLIST: argt = N_("a \"string\""); break;
359 case ARG_RAWLIST: argt = N_("old-style quoting"); break;
360 case ARG_NOLIST: argt = N_("no arguments"); break;
361 case ARG_NDMLIST: argt = N_("message-list (without a default)"); break;
362 case ARG_WYSHLIST: argt = N_("sh(1)ell-style quoting"); break;
363 default: argt = N_("`wysh' for sh(1)ell-style quoting"); break;
365 #ifdef HAVE_DOCSTRINGS
366 fprintf(fp, _("`%s'. Argument type: %s.\n\t%s\n"),
367 cp->lc_name, V_(argt), V_(cp->lc_doc));
368 l += 2;
369 #else
370 fprintf(fp, "`%s' (%s)\n", cp->lc_name, argt);
371 ++l;
372 #endif
373 }else{
374 size_t j = strlen(cp->lc_name) + 2;
376 if((i += j) > 72){
377 i = j;
378 fprintf(fp, "\n");
379 ++l;
381 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
385 if(fp != stdout){
386 page_or_print(fp, l);
387 Fclose(fp);
389 NYD_LEAVE;
390 return 0;
393 static int
394 a_lex__pcmd_cmp(void const *s1, void const *s2){
395 struct a_lex_cmd const * const *cp1, * const *cp2;
396 int rv;
397 NYD2_ENTER;
399 cp1 = s1;
400 cp2 = s2;
401 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
402 NYD2_LEAVE;
403 return rv;
406 static int
407 a_lex_c_help(void *v){
408 int rv;
409 char *arg;
410 NYD_ENTER;
412 /* Help for a single command? */
413 if((arg = *(char**)v) != NULL){
414 struct a_lex_ghost const *gp;
415 struct a_lex_cmd const *cp, *cpmax;
417 /* Ghosts take precedence */
418 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
419 if(!strcmp(arg, gp->lg_name)){
420 printf("%s -> ", arg);
421 arg = gp->lg_cmd.s;
422 break;
425 cpmax = &(cp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
426 jredo:
427 for(; PTRCMP(cp, <, cpmax); ++cp){
428 #ifdef HAVE_DOCSTRINGS
429 # define a_DS V_(cp->lc_doc)
430 #else
431 # define a_DS n_empty
432 #endif
433 if(!strcmp(arg, cp->lc_name))
434 printf("%s: %s", arg, a_DS);
435 else if(is_prefix(arg, cp->lc_name))
436 printf("%s (%s): %s", arg, cp->lc_name, a_DS);
437 else
438 continue;
440 if(options & OPT_D_V){
441 char const *atp;
443 switch(cp->lc_argtype & ARG_ARGMASK){
444 case ARG_MSGLIST: atp = N_("message-list"); break;
445 case ARG_STRLIST: atp = N_("a \"string\""); break;
446 case ARG_RAWLIST: atp = N_("old-style quoting"); break;
447 case ARG_NOLIST: atp = N_("no arguments"); break;
448 case ARG_NDMLIST: atp = N_("message-list (no default)"); break;
449 case ARG_WYSHLIST: atp = N_("sh(1)ell-style quoting"); break;
450 default: atp = N_("`wysh' for sh(1)ell-style quoting"); break;
452 #ifdef HAVE_DOCSTRINGS
453 printf(_("\n\tArgument type: %s"), V_(atp));
454 #else
455 printf(_("argument type: %s"), V_(atp));
456 #endif
457 #undef a_DS
459 putchar('\n');
460 rv = 0;
461 goto jleave;
464 if(PTRCMP(cpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
465 cpmax = &(cp = a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
466 goto jredo;
469 if(gp != NULL){
470 printf("%s\n", n_shexp_quote_cp(arg, TRU1));
471 rv = 0;
472 }else{
473 n_err(_("Unknown command: `%s'\n"), arg);
474 rv = 1;
476 }else{
477 /* Very ugly, but take care for compiler supported string lengths :( */
478 fputs(progname, stdout);
479 fputs(_(
480 " commands -- <msglist> denotes message specifications,\n"
481 "e.g., 1-5, :n or ., separated by spaces:\n"), stdout);
482 fputs(_(
483 "\n"
484 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
485 "Type <msglist> like `type' but always show all headers\n"
486 "next goto and type next message\n"
487 "from <msglist> (search and) print header summary for the given list\n"
488 "headers header summary for messages surrounding \"dot\"\n"
489 "delete <msglist> delete messages (can be `undelete'd)\n"),
490 stdout);
492 fputs(_(
493 "\n"
494 "save <msglist> folder append messages to folder and mark as saved\n"
495 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
496 "write <msglist> file write message contents to file (prompts for parts)\n"
497 "Reply <msglist> reply to message senders only\n"
498 "reply <msglist> like `Reply', but address all recipients\n"
499 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
500 stdout);
502 fputs(_(
503 "\n"
504 "mail <recipients> compose a mail for the given recipients\n"
505 "file folder change to another mailbox\n"
506 "File folder like `file', but open readonly\n"
507 "quit quit and apply changes to the current mailbox\n"
508 "xit or exit like `quit', but discard changes\n"
509 "!shell command shell escape\n"
510 "list [<anything>] all available commands [in search order]\n"),
511 stdout);
513 rv = (ferror(stdout) != 0);
515 jleave:
516 NYD_LEAVE;
517 return rv;
520 static int
521 a_lex_c_quit(void *v){
522 NYD_ENTER;
523 n_UNUSED(v);
525 /* If we are PS_SOURCING, then return 1 so _evaluate() can handle it.
526 * Otherwise return -1 to abort command loop */
527 pstate |= PS_EXIT;
528 NYD_LEAVE;
529 return 0;
532 static int
533 a_lex_c_version(void *v){
534 int longest, rv;
535 char *iop;
536 char const *cp, **arr;
537 size_t i, i2;
538 NYD_ENTER;
539 n_UNUSED(v);
541 printf(_("%s version %s\nFeatures included (+) or not (-)\n"),
542 uagent, ok_vlook(version));
544 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
545 i = strlen(cp = &ok_vlook(features)[1]) +1;
546 iop = salloc(i);
547 memcpy(iop, cp, i);
549 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
550 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
551 arr[i] = cp;
552 i2 = strlen(cp);
553 longest = n_MAX(longest, (int)i2);
555 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
557 for(++longest, i2 = 0; i-- > 0;){
558 cp = *(arr++);
559 printf("%-*s ", longest, cp);
560 i2 += longest;
561 if(UICMP(z, ++i2 + longest, >=, scrnwidth) || i == 0){
562 i2 = 0;
563 putchar('\n');
567 if((rv = ferror(stdout) != 0))
568 clearerr(stdout);
569 NYD_LEAVE;
570 return rv;
573 static int
574 a_lex__version_cmp(void const *s1, void const *s2){
575 char const * const *cp1, * const *cp2;
576 int rv;
577 NYD2_ENTER;
579 cp1 = s1;
580 cp2 = s2;
581 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
582 NYD2_LEAVE;
583 return rv;
586 static void
587 a_lex_update_pstate(void){
588 NYD_ENTER;
590 if(pstate & PS_SIGWINCH_PEND){
591 char buf[32];
593 snprintf(buf, sizeof buf, "%d", scrnwidth);
594 ok_vset(COLUMNS, buf);
595 snprintf(buf, sizeof buf, "%d", scrnheight);
596 ok_vset(LINES, buf);
599 pstate &= ~PS_PSTATE_PENDMASK;
600 NYD_LEAVE;
603 static int
604 a_lex_evaluate(struct a_lex_eval_ctx *evp){
605 /* xxx old style(9), but also old code */
606 struct str line;
607 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
608 struct a_lex_ghost *gp;
609 struct a_lex_cmd const *cmd;
610 int c, e;
611 bool_t wysh;
612 NYD_ENTER;
614 wysh = FAL0;
615 e = 1;
616 cmd = NULL;
617 gp = NULL;
618 line = evp->le_line; /* XXX don't change original (buffer pointer) */
619 assert(line.s[line.l] == '\0');
620 evp->le_add_history = FAL0;
621 evp->le_new_content = NULL;
623 /* Command ghosts that refer to shell commands or macro expansion restart */
624 jrestart:
626 /* Strip the white space away from end and beginning of command */
627 if(line.l > 0){
628 size_t i = line.l;
630 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
631 --i;
632 line.l = i;
634 for(cp = line.s; spacechar(*cp); ++cp)
636 line.l -= PTR2SIZE(cp - line.s);
638 /* Ignore null commands (comments) */
639 if(*cp == '#')
640 goto jleave0;
642 /* Handle ! differently to get the correct lexical conventions */
643 arglist[0] = cp;
644 if(*cp == '!')
645 ++cp;
646 /* Isolate the actual command; since it may not necessarily be
647 * separated from the arguments (as in `p1') we need to duplicate it to
648 * be able to create a NUL terminated version.
649 * We must be aware of several special one letter commands here */
650 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
651 (*cp == '|' || *cp == '~' || *cp == '?'))
652 ++cp;
653 c = (int)PTR2SIZE(cp - arglist[0]);
654 line.l -= c;
655 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
656 memcpy(word, arglist[0], c);
657 word[c] = '\0';
659 /* Look up the command; if not found, bitch.
660 * Normally, a blank command would map to the first command in the
661 * table; while PS_SOURCING, however, we ignore blank lines to eliminate
662 * confusion; act just the same for ghosts */
663 if(*word == '\0'){
664 if((pstate & PS_ROBOT) || gp != NULL)
665 goto jleave0;
666 cmd = a_lex_cmd_tab + 0;
667 goto jexec;
670 /* XXX It may be the argument parse adjuster */
671 if(!wysh && c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
672 wysh = TRU1;
673 line.s = cp;
674 goto jrestart;
677 /* If this is the first evaluation, check command ghosts */
678 if(gp == NULL){
679 /* TODO relink list head, so it's sorted on usage over time?
680 * TODO in fact, there should be one hashmap over all commands and ghosts
681 * TODO so that the lookup could be made much more efficient than it is
682 * TODO now (two adjacent list searches! */
683 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
684 if(!strcmp(word, gp->lg_name)){
685 if(line.l > 0){
686 size_t i;
688 i = gp->lg_cmd.l;
689 line.s = salloc(i + line.l +1);
690 memcpy(line.s, gp->lg_cmd.s, i);
691 memcpy(line.s + i, cp, line.l);
692 line.s[i += line.l] = '\0';
693 line.l = i;
694 }else{
695 line.s = gp->lg_cmd.s;
696 line.l = gp->lg_cmd.l;
698 goto jrestart;
702 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
703 bool_t s;
705 if(!(s = condstack_isskip()) || (options & OPT_D_V))
706 n_err(_("Unknown command%s: `%s'\n"),
707 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
708 if(s)
709 goto jleave0;
710 if(cmd != NULL){
711 c_cmdnotsupp(NULL);
712 cmd = NULL;
714 goto jleave;
717 /* See if we should execute the command -- if a conditional we always
718 * execute it, otherwise, check the state of cond */
719 jexec:
720 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
721 goto jleave0;
723 /* Process the arguments to the command, depending on the type it expects */
724 if(!(cmd->lc_argtype & ARG_M) && (options & OPT_SENDMODE)){
725 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
726 goto jleave;
728 if((cmd->lc_argtype & ARG_S) && !(pstate & PS_STARTED)){
729 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
730 goto jleave;
732 if((cmd->lc_argtype & ARG_I) &&
733 !(options & (OPT_INTERACTIVE | OPT_BATCH_FLAG))){
734 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
735 cmd->lc_name);
736 goto jleave;
738 if((cmd->lc_argtype & ARG_R) && (pstate & PS_RECURSED)){
739 n_err(_("Cannot invoke `%s' when in recursed mode (e.g., composing)\n"),
740 cmd->lc_name);
741 goto jleave;
744 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
745 n_err(_("May not execute `%s' -- message file is read only\n"),
746 cmd->lc_name);
747 goto jleave;
749 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
750 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
751 goto jleave;
754 if(cmd->lc_argtype & ARG_O)
755 OBSOLETE2(_("this command will be removed"), cmd->lc_name);
756 if(cmd->lc_argtype & ARG_V)
757 temporary_arg_v_store = NULL;
759 if(wysh && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST)
760 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
761 /* TODO v15: strip PS_ARGLIST_MASK off, just in case the actual command
762 * TODO doesn't use any of those list commands which strip this mask,
763 * TODO and for now we misuse bits for checking relation to history;
764 * TODO argument state should be property of a per-command carrier instead */
765 pstate &= ~PS_ARGLIST_MASK;
766 switch(cmd->lc_argtype & ARG_ARGMASK){
767 case ARG_MSGLIST:
768 /* Message list defaulting to nearest forward legal message */
769 if(n_msgvec == NULL)
770 goto je96;
771 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
772 break;
773 if(c == 0){
774 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
775 n_msgvec[1] = 0;
777 if(n_msgvec[0] == 0){
778 if(!(pstate & PS_HOOK_MASK))
779 printf(_("No applicable messages\n"));
780 break;
782 e = (*cmd->lc_func)(n_msgvec);
783 break;
785 case ARG_NDMLIST:
786 /* Message list with no defaults, but no error if none exist */
787 if(n_msgvec == NULL){
788 je96:
789 n_err(_("Invalid use of message list\n"));
790 break;
792 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
793 break;
794 e = (*cmd->lc_func)(n_msgvec);
795 break;
797 case ARG_STRLIST:
798 /* Just the straight string, with leading blanks removed */
799 while(whitechar(*cp))
800 ++cp;
801 e = (*cmd->lc_func)(cp);
802 break;
804 case ARG_WYSHLIST:
805 c = 1;
806 if(0){
807 /* FALLTHRU */
808 case ARG_WYRALIST:
809 c = wysh ? 1 : 0;
810 if(0){
811 case ARG_RAWLIST:
812 c = 0;
816 if((c = getrawlist((c != 0), arglist, n_NELEM(arglist), cp, line.l)) < 0){
817 n_err(_("Invalid argument list\n"));
818 break;
820 if(c < cmd->lc_minargs){
821 n_err(_("`%s' requires at least %d arg(s)\n"),
822 cmd->lc_name, cmd->lc_minargs);
823 break;
825 #undef lc_minargs
826 if(c > cmd->lc_maxargs){
827 n_err(_("`%s' takes no more than %d arg(s)\n"),
828 cmd->lc_name, cmd->lc_maxargs);
829 break;
831 #undef lc_maxargs
832 e = (*cmd->lc_func)(arglist);
833 break;
835 case ARG_NOLIST:
836 /* Just the constant zero, for exiting, eg. */
837 e = (*cmd->lc_func)(0);
838 break;
840 default:
841 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
842 cmd->lc_argtype & ARG_ARGMASK); )
843 goto jleave0;
846 if(e == 0 && (cmd->lc_argtype & ARG_V) &&
847 (cp = temporary_arg_v_store) != NULL){
848 temporary_arg_v_store = NULL;
849 evp->le_new_content = cp;
850 goto jleave0;
852 if(!(cmd->lc_argtype & ARG_H))
853 evp->le_add_history = (((cmd->lc_argtype & ARG_G) ||
854 (pstate & PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
856 jleave:
857 /* C99 */{
858 bool_t reset = !(pstate & PS_ROOT);
860 pstate |= PS_ROOT;
861 ok_vset(_exit_status, (e == 0 ? "0" : "1")); /* TODO num=1 +real value! */
862 if(reset)
863 pstate &= ~PS_ROOT;
866 /* Exit the current source file on error TODO what a mess! */
867 if(e == 0)
868 pstate &= ~PS_EVAL_ERROR;
869 else{
870 pstate |= PS_EVAL_ERROR;
871 if(e < 0 || (pstate & PS_ROBOT)){ /* FIXME */
872 e = 1;
873 goto jret;
875 goto jret0;
878 if(cmd == NULL)
879 goto jret0;
880 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint))
881 if(visible(dot)){
882 line.s = savestr("type");
883 line.l = sizeof("type") -1;
884 gp = (struct a_lex_ghost*)-1; /* Avoid `ghost' interpretation */
885 goto jrestart;
888 if(!(pstate & (PS_SOURCING | PS_HOOK_MASK)) && !(cmd->lc_argtype & ARG_T))
889 pstate |= PS_SAW_COMMAND;
890 jleave0:
891 pstate &= ~PS_EVAL_ERROR;
892 jret0:
893 e = 0;
894 jret:
896 fprintf(stderr, "a_lex_evaluate returns %d for <%s>\n",e,line.s);
898 NYD_LEAVE;
899 return e;
902 static struct a_lex_cmd const *
903 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
904 struct a_lex_cmd const *cp;
905 NYD2_ENTER;
907 for(cp = a_lex_cmd_tab;
908 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
909 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
910 goto jleave;
911 cp = NULL;
912 jleave:
913 NYD2_LEAVE;
914 return cp;
917 static void
918 a_lex_hangup(int s){
919 NYD_X; /* Signal handler */
920 n_UNUSED(s);
921 /* nothing to do? */
922 exit(EXIT_ERR);
925 static void
926 a_lex_onintr(int s){ /* TODO block signals while acting */
927 NYD_X; /* Signal handler */
928 n_UNUSED(s);
930 safe_signal(SIGINT, a_lex_onintr);
932 termios_state_reset();
933 close_all_files(); /* FIXME .. of current level ONLU! */
934 if(image >= 0){
935 close(image);
936 image = -1;
939 a_lex_unstack(TRUM1);
941 if(interrupts != 1)
942 n_err_sighdl(_("Interrupt\n"));
943 safe_signal(SIGPIPE, a_lex_oldpipe);
944 siglongjmp(srbuf, 0); /* FIXME get rid */
947 static void
948 a_lex_unstack(bool_t eval_error){
949 struct a_lex_input_stack *lip;
950 NYD_ENTER;
952 if((lip = a_lex_input) == NULL){
953 n_memory_reset();
955 /* If called from a_lex_onintr(), be silent FIXME */
956 pstate &= ~(PS_SOURCING | PS_ROBOT);
957 if(eval_error == TRUM1 || !(pstate & PS_STARTED))
958 goto jleave;
959 goto jerr;
962 if(lip->li_flags & a_LEX_MACRO){
963 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
964 char **lp;
966 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
967 free(*lp);
968 ++lip->li_loff;
970 /* Part of lip's memory chunk, then */
971 if(!(lip->li_flags & a_LEX_MACRO_CMD))
972 free(lip->li_lines);
974 }else{
975 if(lip->li_flags & a_LEX_PIPE)
976 /* XXX command manager should -TERM then -KILL instead of hoping
977 * XXX for exit of provider due to EPIPE / SIGPIPE */
978 Pclose(lip->li_file, TRU1);
979 else
980 Fclose(lip->li_file);
983 if(!condstack_take(lip->li_cond)){
984 n_err(_("Unmatched `if' at end of %s %s\n"),
985 ((lip->li_flags & a_LEX_MACRO
986 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
987 : _("`source'd file"))),
988 lip->li_name);
989 eval_error = TRU1;
992 n_memory_autorec_pop(&lip->li_autorecmem[0]);
994 if((a_lex_input = lip->li_outer) == NULL){
995 pstate &= ~(PS_SOURCING | PS_ROBOT);
996 }else{
997 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
998 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
999 pstate &= ~PS_SOURCING;
1000 assert(pstate & PS_ROBOT);
1003 if(eval_error)
1004 goto jerr;
1005 jleave:
1006 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1007 free(lip);
1008 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1009 a_lex_unstack(TRUM1);
1010 NYD_LEAVE;
1011 return;
1013 jerr:
1014 if(lip != NULL){
1015 if(options & OPT_D_V)
1016 n_alert(_("Stopped %s %s due to errors%s"),
1017 (pstate & PS_STARTED
1018 ? (lip->li_flags & a_LEX_MACRO
1019 ? (lip->li_flags & a_LEX_MACRO_CMD
1020 ? _("evaluating command") : _("evaluating macro"))
1021 : (lip->li_flags & a_LEX_PIPE
1022 ? _("executing `source'd pipe")
1023 : _("loading `source'd file")))
1024 : (lip->li_flags & a_LEX_MACRO
1025 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1026 ? _("evaluating command line") : _("evaluating macro"))
1027 : _("loading initialization resource"))),
1028 lip->li_name,
1029 (options & OPT_DEBUG ? n_empty : _(" (enable *debug* for trace)")));
1032 if(!(options & OPT_INTERACTIVE) && !(pstate & PS_STARTED)){
1033 if(options & OPT_D_V)
1034 n_alert(_("Non-interactive, bailing out due to errors "
1035 "in startup load phase"));
1036 exit(EXIT_ERR);
1038 goto jleave;
1041 static bool_t
1042 a_lex_source_file(char const *file, bool_t silent_error){
1043 struct a_lex_input_stack *lip;
1044 size_t nlen;
1045 char *nbuf;
1046 bool_t ispipe;
1047 FILE *fip;
1048 NYD_ENTER;
1050 fip = NULL;
1052 /* Being a command argument file is space-trimmed *//* TODO v15 with
1053 * TODO WYRALIST this is no longer necessary true, and for that we
1054 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1055 #if 0
1056 ((ispipe = (!silent_error && (nlen = strlen(file)) > 0 &&
1057 file[--nlen] == '|')))
1058 #else
1059 ispipe = FAL0;
1060 if(!silent_error)
1061 for(nlen = strlen(file); nlen > 0;){
1062 char c;
1064 c = file[--nlen];
1065 if(!blankchar(c)){
1066 if(c == '|'){
1067 nbuf = savestrbuf(file, nlen);
1068 ispipe = TRU1;
1069 break;
1073 #endif
1075 if(ispipe){
1076 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1077 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL){
1078 if(!silent_error || (options & OPT_D_V))
1079 n_perr(nbuf, 0);
1080 goto jleave;
1082 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1083 goto jleave;
1084 else if((fip = Fopen(nbuf, "r")) == NULL){
1085 if(!silent_error || (options & OPT_D_V))
1086 n_perr(nbuf, 0);
1087 goto jleave;
1090 lip = smalloc(sizeof(*lip) -
1091 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1092 (nlen = strlen(nbuf) +1));
1093 lip->li_outer = a_lex_input;
1094 lip->li_file = fip;
1095 lip->li_cond = condstack_release();
1096 n_memory_autorec_push(&lip->li_autorecmem[0]);
1097 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1098 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1099 ? a_LEX_SUPER_MACRO : 0);
1100 memcpy(lip->li_name, nbuf, nlen);
1102 pstate |= PS_SOURCING | PS_ROBOT;
1103 a_lex_input = lip;
1104 a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC);
1105 /* FIXME return TRUM1 if file can't be opened, FAL0 on eval error */
1106 jleave:
1107 NYD_LEAVE;
1108 return silent_error ? TRU1 : (fip != NULL);
1111 static bool_t
1112 a_lex_load(struct a_lex_input_stack *lip){
1113 bool_t rv;
1114 NYD2_ENTER;
1116 assert(!(pstate & PS_STARTED));
1117 assert(a_lex_input == NULL);
1119 /* POSIX:
1120 * Any errors in the start-up file shall either cause mailx to terminate
1121 * with a diagnostic message and a non-zero status or to continue after
1122 * writing a diagnostic message, ignoring the remainder of the lines in
1123 * the start-up file. */
1124 lip->li_cond = condstack_release();
1125 n_memory_autorec_push(&lip->li_autorecmem[0]);
1127 /* FIXME won't work for now (PS_ROBOT needs PS_SOURCING anyway)
1128 pstate |= PS_ROBOT |
1129 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : PS_SOURCING);
1131 pstate |= PS_ROBOT | PS_SOURCING;
1132 if(options & OPT_D_V)
1133 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1134 a_lex_input = lip;
1135 if(!(rv = n_commands())){
1136 if(!(options & OPT_INTERACTIVE)){
1137 if(options & OPT_D_V)
1138 n_alert(_("Non-interactive program mode, forced exit"));
1139 exit(EXIT_ERR);
1142 /* PS_EXIT handled by callers */
1143 NYD2_LEAVE;
1144 return rv;
1147 static bool_t
1148 a_commands_recursive(enum n_lexinput_flags lif){
1149 struct a_lex_eval_ctx ev;
1150 bool_t rv;
1151 NYD2_ENTER;
1153 memset(&ev, 0, sizeof ev);
1155 /* FIXME sigkondom */
1156 n_COLOUR( n_colour_env_push(); )
1157 rv = TRU1;
1158 for(;;){
1159 int n;
1161 /* Read a line of commands and handle end of file specially */
1162 ev.le_line.l = ev.le_line_size;
1163 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l,
1164 ev.le_new_content);
1165 ev.le_line_size = (ui32_t)ev.le_line.l;
1166 ev.le_line.l = (ui32_t)n;
1168 if(n < 0)
1169 break;
1171 if(a_lex_evaluate(&ev)){
1172 rv = FAL0;
1173 break;
1175 n_memory_reset();
1177 if((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)){
1178 if(exit_status != EXIT_OK)
1179 break;
1182 a_lex_unstack(!rv);
1183 n_COLOUR( n_colour_env_pop(FAL0); )
1185 if(ev.le_line.s != NULL)
1186 free(ev.le_line.s);
1187 NYD2_LEAVE;
1188 return rv;
1191 FL bool_t
1192 n_commands(void){ /* FIXME */
1193 struct a_lex_eval_ctx ev;
1194 int n;
1195 bool_t volatile rv;
1196 NYD_ENTER;
1198 rv = TRU1;
1200 if (!(pstate & PS_SOURCING)) {
1201 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1202 safe_signal(SIGINT, &a_lex_onintr);
1203 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1204 safe_signal(SIGHUP, &a_lex_hangup);
1206 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1207 safe_signal(SIGPIPE, a_lex_oldpipe);
1209 memset(&ev, 0, sizeof ev);
1211 (void)sigsetjmp(srbuf, 1); /* FIXME get rid */
1212 for (;;) {
1213 char *temporary_orig_line; /* XXX eval_ctx.le_line not yet constant */
1215 n_COLOUR( n_colour_env_pop(TRU1); )
1217 /* TODO Unless we have our signal manager (or however we do it) child
1218 * TODO processes may have time slots where their execution isn't
1219 * TODO protected by signal handlers (in between start and setup
1220 * TODO completed). close_all_files() is only called from onintr()
1221 * TODO so those may linger possibly forever */
1222 if(!(pstate & PS_SOURCING))
1223 close_all_files();
1225 interrupts = 0;
1227 temporary_localopts_free(); /* XXX intermediate hack */
1229 n_memory_reset();
1231 if (!(pstate & PS_SOURCING)) {
1232 char *cp;
1234 /* TODO Note: this buffer may contain a password. We should redefine
1235 * TODO the code flow which has to do that */
1236 if ((cp = termios_state.ts_linebuf) != NULL) {
1237 termios_state.ts_linebuf = NULL;
1238 termios_state.ts_linesize = 0;
1239 free(cp); /* TODO pool give-back */
1241 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1242 if (ev.le_line.l > LINESIZE * 3) {
1243 free(ev.le_line.s); /* TODO pool! but what? */
1244 ev.le_line.s = NULL;
1245 ev.le_line.l = ev.le_line_size = 0;
1249 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1250 char *cp;
1252 cp = ok_vlook(newmail);
1253 if ((options & OPT_TTYIN) && cp != NULL) {
1254 struct stat st;
1256 /* FIXME TEST WITH NOPOLL ETC. !!! */
1257 n = (cp != NULL && strcmp(cp, "nopoll"));
1258 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1259 st.st_size > mailsize) ||
1260 (mb.mb_type == MB_MAILDIR && n != 0)) {
1261 size_t odot = PTR2SIZE(dot - message);
1262 ui32_t odid = (pstate & PS_DID_PRINT_DOT);
1264 if (setfile(mailname,
1265 FEDIT_NEWMAIL |
1266 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1267 exit_status |= EXIT_ERR;
1268 rv = FAL0;
1269 break;
1271 dot = message + odot;
1272 pstate |= odid;
1276 exit_status = EXIT_OK;
1279 /* Read a line of commands and handle end of file specially */
1280 jreadline:
1281 ev.le_line.l = ev.le_line_size;
1282 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1283 &ev.le_line.s, &ev.le_line.l, ev.le_new_content);
1284 ev.le_line_size = (ui32_t)ev.le_line.l;
1285 ev.le_line.l = (ui32_t)n;
1287 if (n < 0) {
1288 /* FIXME did unstack() when PS_SOURCING, only break with PS_LOADING*/
1289 if (!(pstate & PS_ROBOT) &&
1290 (options & OPT_INTERACTIVE) && ok_blook(ignoreeof)) {
1291 printf(_("*ignoreeof* set, use `quit' to quit.\n"));
1292 n_msleep(500, FAL0);
1293 continue;
1295 break;
1298 temporary_orig_line = ((pstate & PS_SOURCING) ||
1299 !(options & OPT_INTERACTIVE)) ? NULL
1300 : savestrbuf(ev.le_line.s, ev.le_line.l);
1301 pstate &= ~PS_HOOK_MASK;
1302 if (a_lex_evaluate(&ev)) {
1303 if (!(pstate & PS_STARTED)) /* TODO mess; join PS_EVAL_ERROR.. */
1304 rv = FAL0;
1305 break;
1308 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
1309 if (exit_status != EXIT_OK)
1310 break;
1311 if ((pstate & (PS_SOURCING | PS_EVAL_ERROR)) == PS_EVAL_ERROR) {
1312 exit_status = EXIT_ERR;
1313 break;
1316 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1317 if (ev.le_new_content != NULL)
1318 goto jreadline;
1319 /* *Can* happen since _evaluate() n_unstack()s on error! XXX no more */
1320 if (temporary_orig_line != NULL)
1321 n_tty_addhist(temporary_orig_line, (ev.le_add_history != TRU1));
1324 if(pstate & PS_EXIT)
1325 break;
1328 a_lex_unstack(!rv);
1330 if (ev.le_line.s != NULL)
1331 free(ev.le_line.s);
1332 NYD_LEAVE;
1333 return rv;
1336 FL int
1337 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1338 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1339 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1340 struct n_string xprompt;
1341 FILE *ifile;
1342 bool_t doprompt, dotty;
1343 char const *iftype;
1344 int n, nold;
1345 NYD2_ENTER;
1347 /* Special case macro mode: never need to prompt, lines have always been
1348 * unfolded already */
1349 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1350 if(*linebuf != NULL)
1351 free(*linebuf);
1353 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1354 *linesize = 0;
1355 n = -1;
1356 goto jleave;
1359 ++a_lex_input->li_loff;
1360 *linesize = strlen(*linebuf);
1361 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1362 *linebuf = sbufdup(*linebuf, *linesize);
1364 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1365 ? "-X OPTION" : "MACRO";
1366 n = (int)*linesize;
1367 pstate |= PS_READLINE_NL;
1368 goto jhave_dat;
1370 pstate &= ~PS_READLINE_NL;
1372 iftype = (!(pstate & PS_STARTED) ? "LOAD"
1373 : (pstate & PS_SOURCING) ? "SOURCE" : "READ");
1374 doprompt = ((pstate & (PS_STARTED | PS_ROBOT)) == PS_STARTED &&
1375 (options & OPT_INTERACTIVE));
1376 dotty = (doprompt && !ok_blook(line_editor_disable));
1377 if(!doprompt)
1378 lif |= n_LEXINPUT_PROMPT_NONE;
1379 else{
1380 if(!dotty)
1381 n_string_creat_auto(&xprompt);
1382 if(prompt == NULL)
1383 lif |= n_LEXINPUT_PROMPT_EVAL;
1386 /* Ensure stdout is flushed first anyway */
1387 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1388 fflush(stdout);
1390 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : stdin;
1391 assert(ifile != NULL);
1393 for(nold = n = 0;;){
1394 if(dotty){
1395 assert(ifile == stdin);
1396 if(string != NULL && (n = (int)strlen(string)) > 0){
1397 if(*linesize > 0)
1398 *linesize += n +1;
1399 else
1400 *linesize = (size_t)n + LINESIZE +1;
1401 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1402 memcpy(*linebuf, string, (size_t)n +1);
1404 string = NULL;
1405 /* TODO if nold>0, don't redisplay the entire line!
1406 * TODO needs complete redesign ... */
1407 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1408 n_MEMORY_DEBUG_ARGSCALL);
1409 }else{
1410 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1411 n_tty_create_prompt(&xprompt, prompt, lif);
1412 if(xprompt.s_len > 0){
1413 fwrite(xprompt.s_dat, 1, xprompt.s_len, stdout);
1414 fflush(stdout);
1418 n = (readline_restart)(ifile, linebuf, linesize, n
1419 n_MEMORY_DEBUG_ARGSCALL);
1421 if(n > 0 && nold > 0){
1422 int i = 0;
1423 char const *cp = *linebuf + nold;
1425 while(blankspacechar(*cp) && nold + i < n)
1426 ++cp, ++i;
1427 if(i > 0){
1428 memmove(*linebuf + nold, cp, n - nold - i);
1429 n -= i;
1430 (*linebuf)[n] = '\0';
1435 if(n <= 0)
1436 break;
1438 /* POSIX says:
1439 * An unquoted <backslash> at the end of a command line shall
1440 * be discarded and the next line shall continue the command */
1441 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1442 if(dotty)
1443 pstate |= PS_READLINE_NL;
1444 break;
1446 /* Definitely outside of quotes, thus the quoting rules are so that an
1447 * uneven number of successive backslashs at EOL is a continuation */
1448 if(n > 1){
1449 size_t i, j;
1451 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1452 if((*linebuf)[i] != '\\')
1453 break;
1454 if(!(j & 1))
1455 break;
1457 (*linebuf)[nold = --n] = '\0';
1458 lif |= n_LEXINPUT_NL_FOLLOW;
1461 if(n < 0)
1462 goto jleave;
1463 (*linebuf)[*linesize = n] = '\0';
1465 jhave_dat:
1466 #if 0
1467 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1468 char *cp, c;
1469 size_t i;
1471 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1472 c = *--cp;
1473 if(!blankspacechar(c))
1474 break;
1476 (*linebuf)[n = (int)i] = '\0';
1479 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1480 char *cp, c;
1481 size_t j, i;
1483 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1484 c = *cp++;
1485 if(!blankspacechar(c))
1486 break;
1488 if(i > 0){
1489 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1490 (*linebuf)[n = (int)j] = '\0';
1493 #endif /* 0 (notyet - must take care for backslash escaped space) */
1495 if(options & OPT_D_VV)
1496 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1497 jleave:
1498 if (pstate & PS_PSTATE_PENDMASK)
1499 a_lex_update_pstate();
1500 NYD2_LEAVE;
1501 return n;
1504 FL char *
1505 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1506 char const *string){
1507 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1508 size_t linesize;
1509 char *linebuf, *rv;
1510 int n;
1511 NYD2_ENTER;
1513 linesize = 0;
1514 linebuf = NULL;
1515 rv = NULL;
1517 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1518 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1519 (lif & n_LEXINPUT_HIST_ADD) && (options & OPT_INTERACTIVE))
1520 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1522 if(linebuf != NULL)
1523 free(linebuf);
1524 NYD2_LEAVE;
1525 return rv;
1528 FL void
1529 n_load(char const *name){
1530 struct a_lex_input_stack *lip;
1531 size_t i;
1532 FILE *fip;
1533 NYD_ENTER;
1535 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1536 goto jleave;
1538 i = strlen(name) +1;
1539 lip = scalloc(1, sizeof(*lip) -
1540 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) + i);
1541 lip->li_file = fip;
1542 lip->li_flags = a_LEX_FREE;
1543 memcpy(lip->li_name, name, i);
1545 a_lex_load(lip);
1546 pstate &= ~PS_EXIT;
1547 jleave:
1548 NYD_LEAVE;
1551 FL void
1552 n_load_Xargs(char const **lines, size_t cnt){
1553 static char const name[] = "-X";
1555 ui8_t buf[sizeof(struct a_lex_input_stack) + sizeof name];
1556 char const *srcp, *xsrcp;
1557 char *cp;
1558 size_t imax, i, len;
1559 struct a_lex_input_stack *lip;
1560 NYD_ENTER;
1562 memset(buf, 0, sizeof buf);
1563 lip = (void*)buf;
1564 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1565 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1566 memcpy(lip->li_name, name, sizeof name);
1568 /* The problem being that we want to support reverse solidus newline
1569 * escaping also within multiline -X, i.e., POSIX says:
1570 * An unquoted <backslash> at the end of a command line shall
1571 * be discarded and the next line shall continue the command
1572 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
1573 * entire lines array and set _MACRO_FREE_DATA */
1574 imax = cnt + 1;
1575 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
1577 /* For each of the input lines.. */
1578 for(i = len = 0, cp = NULL; cnt > 0;){
1579 bool_t keep;
1580 size_t j;
1582 if((j = strlen(srcp = *lines)) == 0){
1583 ++lines, --cnt;
1584 continue;
1587 /* Separate one line from a possible multiline input string */
1588 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1589 *lines = &xsrcp[1];
1590 j = PTR2SIZE(xsrcp - srcp);
1591 }else
1592 ++lines, --cnt;
1594 /* The (separated) string may itself indicate soft newline escaping */
1595 if((keep = (srcp[j - 1] == '\\'))){
1596 size_t xj, xk;
1598 /* Need an uneven number of reverse solidus */
1599 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1600 if(srcp[xj] != '\\')
1601 break;
1602 if(xk & 1)
1603 --j;
1604 else
1605 keep = FAL0;
1608 /* Strip any leading WS from follow lines, then */
1609 if(cp != NULL)
1610 while(j > 0 && blankspacechar(*srcp))
1611 ++srcp, --j;
1613 if(j > 0){
1614 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1615 imax += 4;
1616 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
1617 imax);
1619 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
1620 memcpy(&cp[len], srcp, j);
1621 cp[len += j] = '\0';
1623 if(!keep)
1624 ++i;
1626 if(!keep)
1627 cp = NULL, len = 0;
1629 if(cp != NULL){
1630 assert(i + 1 < imax);
1631 lip->li_lines[i++] = cp;
1633 lip->li_lines[i] = NULL;
1635 a_lex_load(lip);
1636 if(pstate & PS_EXIT)
1637 exit(EXIT_OK);
1638 NYD_LEAVE;
1641 FL int
1642 c_source(void *v){
1643 int rv;
1644 NYD_ENTER;
1646 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1647 NYD_LEAVE;
1648 return rv;
1651 FL int
1652 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1653 int rv;
1654 NYD_ENTER;
1656 rv = (a_lex_source_file(*(char**)v, TRU1) != FAL0) ? 0 : 1;
1657 NYD_LEAVE;
1658 return rv;
1661 FL bool_t
1662 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines){
1663 struct a_lex_input_stack *lip;
1664 size_t i;
1665 int rv;
1666 NYD_ENTER;
1668 lip = smalloc(sizeof(*lip) -
1669 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1670 (i = strlen(name) +1));
1671 lip->li_outer = a_lex_input;
1672 lip->li_file = NULL;
1673 lip->li_cond = condstack_release();
1674 n_memory_autorec_push(&lip->li_autorecmem[0]);
1675 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1676 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1677 ? a_LEX_SUPER_MACRO : 0);
1678 lip->li_loff = 0;
1679 lip->li_lines = lines;
1680 memcpy(lip->li_name, name, i);
1682 pstate |= PS_ROBOT;
1683 a_lex_input = lip;
1684 rv = a_commands_recursive(lif);
1685 NYD_LEAVE;
1686 return rv;
1689 FL bool_t
1690 n_source_command(enum n_lexinput_flags lif, char const *cmd){
1691 struct a_lex_input_stack *lip;
1692 size_t i, ial;
1693 bool_t rv;
1694 NYD_ENTER;
1696 i = strlen(cmd);
1697 cmd = sbufdup(cmd, i++);
1698 ial = n_ALIGN(i);
1700 lip = smalloc(sizeof(*lip) -
1701 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1702 ial + 2*sizeof(char*));
1703 lip->li_outer = a_lex_input;
1704 lip->li_file = NULL;
1705 lip->li_cond = condstack_release();
1706 n_memory_autorec_push(&lip->li_autorecmem[0]);
1707 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1708 a_LEX_MACRO_CMD |
1709 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1710 ? a_LEX_SUPER_MACRO : 0);
1711 lip->li_loff = 0;
1712 lip->li_lines = (void*)(lip->li_name + ial);
1713 lip->li_lines[0] = n_UNCONST(cmd); /* dup'ed above */
1714 lip->li_lines[1] = NULL;
1715 memcpy(lip->li_name, cmd, i);
1717 pstate |= PS_ROBOT;
1718 a_lex_input = lip;
1719 rv = a_commands_recursive(lif);
1720 NYD_LEAVE;
1721 return rv;
1724 FL bool_t
1725 n_source_may_yield_control(void){
1726 return ((options & OPT_INTERACTIVE) &&
1727 (pstate & PS_STARTED) &&
1728 (!(pstate & PS_ROBOT) || (pstate & PS_RECURSED)) && /* Ok for ~: */
1729 (a_lex_input == NULL || a_lex_input->li_outer == NULL));
1732 /* s-it-mode */