Copyright 2016
[s-mailx.git] / lex_input.c
blob9916212cb4e72227a7301008d05a8df4ca97d911
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[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; /* Enter (final) command in history? */
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_name[VFIELD_SIZE(0)]; /* Name of file or macro */
95 static sighandler_type a_lex_oldpipe;
96 static struct a_lex_ghost *a_lex_ghosts;
97 /* a_lex_cmd_tab[] after fun protos */
99 /* */
100 static struct a_lex_input_stack *a_lex_input;
102 /* Isolate the command from the arguments */
103 static char *a_lex_isolate(char const *comm);
105 /* Command ghost handling */
106 static int a_lex_c_ghost(void *v);
107 static int a_lex_c_unghost(void *v);
109 /* Print a list of all commands */
110 static int a_lex_c_list(void *v);
112 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
114 /* `quit' command */
115 static int a_lex_c_quit(void *v);
117 /* Print the binaries version number */
118 static int a_lex_c_version(void *v);
120 static int a_lex__version_cmp(void const *s1, void const *s2);
122 /* PS_STATE_PENDMASK requires some actions */
123 static void a_lex_update_pstate(void);
125 /* Evaluate a single command.
126 * .le_add_history and .le_new_content will be updated upon success.
127 * Command functions return 0 for success, 1 for error, and -1 for abort.
128 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
129 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
131 /* Get first-fit, or NULL */
132 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
134 /* Branch here on hangup signal and simulate "exit" */
135 static void a_lex_hangup(int s);
137 /* The following gets called on receipt of an interrupt. Close all open files
138 * except 0, 1, 2, and the temporary. Also, unstack all source files */
139 static void a_lex_onintr(int s);
141 /* Pop the current input back to the previous level. Update the program state.
142 * If the argument is TRUM1 then we don't alert and error out if the stack
143 * doesn't exist at all */
144 static void a_lex_unstack(bool_t eval_error);
146 /* `source' and `source_if' (if silent_error: no pipes allowed, then) */
147 static bool_t a_lex_source_file(char const *file, bool_t silent_error);
149 /* System resource file load()ing or -X command line option array traversal */
150 static bool_t a_lex_load(struct a_lex_input_stack *lip);
152 /* A simplified command loop for recursed state machines */
153 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
155 /* List of all commands, and list of commands which are specially treated
156 * and deduced in _evaluate(), but we need a list for _c_list() and
157 * print_comm_docstr() */
158 #ifdef HAVE_DOCSTRINGS
159 # define DS(S) , S
160 #else
161 # define DS(S)
162 #endif
163 static struct a_lex_cmd const a_lex_cmd_tab[] = {
164 #include "cmd_tab.h"
166 a_lex_special_cmd_tab[] = {
167 { "#", NULL, 0, 0, 0
168 DS(N_("Comment command: ignore remaining (continuable) line")) },
169 { "-", NULL, 0, 0, 0
170 DS(N_("Print out the preceding message")) }
172 #undef DS
174 static char *
175 a_lex_isolate(char const *comm){
176 NYD2_ENTER;
177 while(*comm != '\0' &&
178 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
179 ++comm;
180 NYD2_LEAVE;
181 return UNCONST(comm);
184 static int
185 a_lex_c_ghost(void *v){
186 struct a_lex_ghost *lgp, *gp;
187 size_t i, cl, nl;
188 char *cp;
189 char const **argv;
190 NYD_ENTER;
192 argv = v;
194 /* Show the list? */
195 if(*argv == NULL){
196 FILE *fp;
198 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
199 fp = stdout;
201 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
202 fprintf(fp, "wysh ghost %s %s\n",
203 gp->lg_name, n_shell_quote_cp(gp->lg_cmd.s, TRU1));
205 if(fp != stdout){
206 page_or_print(fp, i);
207 Fclose(fp);
209 goto jleave;
212 /* Verify the ghost name is a valid one */
213 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0'){
214 n_err(_("`ghost': can't canonicalize %s\n"),
215 n_shell_quote_cp(argv[0], FAL0));
216 v = NULL;
217 goto jleave;
220 /* Show command of single ghost? */
221 if(argv[1] == NULL){
222 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
223 if(!strcmp(argv[0], gp->lg_name)){
224 printf("wysh ghost %s %s\n",
225 gp->lg_name, n_shell_quote_cp(gp->lg_cmd.s, TRU1));
226 goto jleave;
228 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
229 v = NULL;
230 goto jleave;
233 /* Define command for ghost: verify command content */
234 for(cl = 0, i = 1; (cp = UNCONST(argv[i])) != NULL; ++i)
235 if(*cp != '\0')
236 cl += strlen(cp) +1; /* SP or NUL */
237 if(cl == 0){
238 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
239 v = NULL;
240 goto jleave;
243 /* If the ghost already exists, recreate */
244 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
245 if(!strcmp(gp->lg_name, argv[0])){
246 if(lgp != NULL)
247 lgp->lg_next = gp->lg_next;
248 else
249 a_lex_ghosts = gp->lg_next;
250 free(gp);
251 break;
254 nl = strlen(argv[0]) +1;
255 gp = smalloc(sizeof(*gp) - VFIELD_SIZEOF(struct a_lex_ghost, lg_name) +
256 nl + cl);
257 gp->lg_next = a_lex_ghosts;
258 a_lex_ghosts = gp;
259 memcpy(gp->lg_name, argv[0], nl);
260 cp = gp->lg_cmd.s = gp->lg_name + nl;
261 gp->lg_cmd.l = --cl;
263 while(*++argv != NULL)
264 if((i = strlen(*argv)) > 0){
265 memcpy(cp, *argv, i);
266 cp += i;
267 *cp++ = ' ';
269 *--cp = '\0';
270 jleave:
271 NYD_LEAVE;
272 return v == NULL;
275 static int
276 a_lex_c_unghost(void *v){
277 struct a_lex_ghost *lgp, *gp;
278 char const **argv, *cp;
279 int rv;
280 NYD_ENTER;
282 rv = 0;
283 argv = v;
285 while((cp = *argv++) != NULL){
286 if(cp[0] == '*' && cp[1] == '\0'){
287 while((gp = a_lex_ghosts) != NULL){
288 a_lex_ghosts = gp->lg_next;
289 free(gp);
291 }else{
292 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
293 lgp = gp, gp = gp->lg_next)
294 if(!strcmp(gp->lg_name, cp)){
295 if(lgp != NULL)
296 lgp->lg_next = gp->lg_next;
297 else
298 a_lex_ghosts = gp->lg_next;
299 free(gp);
300 goto jouter;
302 n_err(_("`unghost': no such alias: %s\n"),
303 n_shell_quote_cp(cp, FAL0));
304 rv = 1;
305 jouter: ;
308 NYD_LEAVE;
309 return rv;
312 static int
313 a_lex_c_list(void *v){
314 FILE *fp;
315 struct a_lex_cmd const **cpa, *cp, **cursor;
316 size_t l, i;
317 NYD_ENTER;
319 i = NELEM(a_lex_cmd_tab) + NELEM(a_lex_special_cmd_tab) +1;
320 cpa = salloc(sizeof(cp) * i);
322 for(i = 0; i < NELEM(a_lex_cmd_tab); ++i)
323 cpa[i] = &a_lex_cmd_tab[i];
324 /* C99 */{
325 size_t j;
327 for(j = 0; j < NELEM(a_lex_special_cmd_tab); ++i, ++j)
328 cpa[i] = &a_lex_special_cmd_tab[j];
330 cpa[i] = NULL;
332 /* C99 */{
333 char const *xcp = v;
335 if(*xcp == '\0')
336 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
339 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
340 fp = stdout;
342 fprintf(fp, _("Commands are:\n"));
343 l = 1;
344 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
345 if(cp->lc_func == &c_cmdnotsupp)
346 continue;
347 if(options & OPT_D_V){
348 char const *argt;
350 switch(cp->lc_argtype & ARG_ARGMASK){
351 case ARG_MSGLIST: argt = N_("message-list"); break;
352 case ARG_STRLIST: argt = N_("a \"string\""); break;
353 case ARG_RAWLIST: argt = N_("old-style quoting"); break;
354 case ARG_NOLIST: argt = N_("no arguments"); break;
355 case ARG_NDMLIST: argt = N_("message-list (without a default)"); break;
356 case ARG_WYSHLIST: argt = N_("sh(1)ell-style quoting"); break;
357 default: argt = N_("`wysh' for sh(1)ell-style quoting"); break;
359 #ifdef HAVE_DOCSTRINGS
360 fprintf(fp, _("`%s'. Argument type: %s.\n\t%s\n"),
361 cp->lc_name, V_(argt), V_(cp->lc_doc));
362 l += 2;
363 #else
364 fprintf(fp, "`%s' (%s)\n", cp->lc_name, argt);
365 ++l;
366 #endif
367 }else{
368 size_t j = strlen(cp->lc_name) + 2;
370 if((i += j) > 72){
371 i = j;
372 fprintf(fp, "\n");
373 ++l;
375 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
379 if(fp != stdout){
380 page_or_print(fp, l);
381 Fclose(fp);
383 NYD_LEAVE;
384 return 0;
387 static int
388 a_lex__pcmd_cmp(void const *s1, void const *s2){
389 struct a_lex_cmd const * const *cp1, * const *cp2;
390 int rv;
391 NYD2_ENTER;
393 cp1 = s1;
394 cp2 = s2;
395 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
396 NYD2_LEAVE;
397 return rv;
400 static int
401 a_lex_c_quit(void *v){
402 NYD_ENTER;
403 UNUSED(v);
405 /* If we are PS_SOURCING, then return 1 so _evaluate() can handle it.
406 * Otherwise return -1 to abort command loop */
407 pstate |= PS_EXIT;
408 NYD_LEAVE;
409 return 0;
412 static int
413 a_lex_c_version(void *v){
414 int longest, rv;
415 char *iop;
416 char const *cp, **arr;
417 size_t i, i2;
418 NYD_ENTER;
419 UNUSED(v);
421 printf(_("%s version %s\nFeatures included (+) or not (-)\n"),
422 uagent, ok_vlook(version));
424 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
425 i = strlen(cp = &ok_vlook(features)[1]);
426 i2 = strlen(&cp[i + 1]) +1;
427 iop = salloc(i + i2);
428 memcpy(iop, cp, i);
429 memcpy(&iop[i], &cp[++i], i2);
431 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
432 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
433 arr[i] = cp;
434 i2 = strlen(cp);
435 longest = MAX(longest, (int)i2);
437 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
439 for(++longest, i2 = 0; i-- > 0;){
440 cp = *(arr++);
441 printf("%-*s ", longest, cp);
442 i2 += longest;
443 if(UICMP(z, ++i2 + longest, >=, scrnwidth) || i == 0){
444 i2 = 0;
445 putchar('\n');
449 if((rv = ferror(stdout) != 0))
450 clearerr(stdout);
451 NYD_LEAVE;
452 return rv;
455 static int
456 a_lex__version_cmp(void const *s1, void const *s2){
457 char const * const *cp1, * const *cp2;
458 int rv;
459 NYD2_ENTER;
461 cp1 = s1;
462 cp2 = s2;
463 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
464 NYD2_LEAVE;
465 return rv;
468 static void
469 a_lex_update_pstate(void){
470 NYD_ENTER;
472 if(pstate & PS_SIGWINCH_PEND){
473 char buf[32];
475 snprintf(buf, sizeof buf, "%d", scrnwidth);
476 ok_vset(COLUMNS, buf);
477 snprintf(buf, sizeof buf, "%d", scrnheight);
478 ok_vset(LINES, buf);
481 pstate &= ~PS_PSTATE_PENDMASK;
482 NYD_LEAVE;
485 static int
486 a_lex_evaluate(struct a_lex_eval_ctx *evp){
487 /* xxx old style(9), but also old code */
488 struct str line;
489 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
490 struct a_lex_ghost *gp;
491 struct a_lex_cmd const *cmd;
492 int c, e;
493 bool_t wysh;
494 NYD_ENTER;
496 wysh = FAL0;
497 e = 1;
498 cmd = NULL;
499 gp = NULL;
500 line = evp->le_line; /* XXX don't change original (buffer pointer) */
501 assert(line.s[line.l] == '\0');
502 evp->le_add_history = FAL0;
503 evp->le_new_content = NULL;
505 /* Command ghosts that refer to shell commands or macro expansion restart */
506 jrestart:
508 /* Strip the white space away from end and beginning of command */
509 if(line.l > 0){
510 size_t i = line.l;
512 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
513 --i;
514 line.l = i;
516 for(cp = line.s; spacechar(*cp); ++cp)
518 line.l -= PTR2SIZE(cp - line.s);
520 /* Ignore null commands (comments) */
521 if(*cp == '#')
522 goto jleave0;
524 /* Handle ! differently to get the correct lexical conventions */
525 arglist[0] = cp;
526 if(*cp == '!')
527 ++cp;
528 /* Isolate the actual command; since it may not necessarily be
529 * separated from the arguments (as in `p1') we need to duplicate it to
530 * be able to create a NUL terminated version.
531 * We must be aware of several special one letter commands here */
532 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
533 (*cp == '|' || *cp == '~' || *cp == '?'))
534 ++cp;
535 c = (int)PTR2SIZE(cp - arglist[0]);
536 line.l -= c;
537 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
538 memcpy(word, arglist[0], c);
539 word[c] = '\0';
541 /* Look up the command; if not found, bitch.
542 * Normally, a blank command would map to the first command in the
543 * table; while PS_SOURCING, however, we ignore blank lines to eliminate
544 * confusion; act just the same for ghosts */
545 if(*word == '\0'){
546 if((pstate & PS_ROBOT) || gp != NULL)
547 goto jleave0;
548 cmd = a_lex_cmd_tab + 0;
549 goto jexec;
552 /* XXX It may be the argument parse adjuster */
553 if(!wysh && c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
554 wysh = TRU1;
555 line.s = cp;
556 goto jrestart;
559 /* If this is the first evaluation, check command ghosts */
560 if(gp == NULL){
561 /* TODO relink list head, so it's sorted on usage over time?
562 * TODO in fact, there should be one hashmap over all commands and ghosts
563 * TODO so that the lookup could be made much more efficient than it is
564 * TODO now (two adjacent list searches! */
565 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
566 if(!strcmp(word, gp->lg_name)){
567 if(line.l > 0){
568 size_t i;
570 i = gp->lg_cmd.l;
571 line.s = salloc(i + line.l +1);
572 memcpy(line.s, gp->lg_cmd.s, i);
573 memcpy(line.s + i, cp, line.l);
574 line.s[i += line.l] = '\0';
575 line.l = i;
576 }else{
577 line.s = gp->lg_cmd.s;
578 line.l = gp->lg_cmd.l;
580 goto jrestart;
584 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
585 bool_t s;
587 if(!(s = condstack_isskip()) || (options & OPT_D_V))
588 n_err(_("Unknown command%s: `%s'\n"),
589 (s ? _(" (ignored due to `if' condition)") : ""), word);
590 if(s)
591 goto jleave0;
592 if(cmd != NULL){
593 c_cmdnotsupp(NULL);
594 cmd = NULL;
596 goto jleave;
599 /* See if we should execute the command -- if a conditional we always
600 * execute it, otherwise, check the state of cond */
601 jexec:
602 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
603 goto jleave0;
605 /* Process the arguments to the command, depending on the type it expects */
606 if(!(cmd->lc_argtype & ARG_M) && (options & OPT_SENDMODE)){
607 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
608 goto jleave;
610 if((cmd->lc_argtype & ARG_S) && !(pstate & PS_STARTED)){
611 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
612 goto jleave;
614 if((cmd->lc_argtype & ARG_I) &&
615 !(options & (OPT_INTERACTIVE | OPT_BATCH_FLAG))){
616 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
617 cmd->lc_name);
618 goto jleave;
620 if((cmd->lc_argtype & ARG_R) && (pstate & PS_RECURSED)){
621 n_err(_("Cannot invoke `%s' when in recursed mode (e.g., composing)\n"),
622 cmd->lc_name);
623 goto jleave;
626 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
627 n_err(_("May not execute `%s' -- message file is read only\n"),
628 cmd->lc_name);
629 goto jleave;
631 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
632 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
633 goto jleave;
636 if(cmd->lc_argtype & ARG_O)
637 OBSOLETE2(_("this command will be removed"), cmd->lc_name);
638 if(cmd->lc_argtype & ARG_V)
639 temporary_arg_v_store = NULL;
641 if(wysh && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST)
642 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
643 switch(cmd->lc_argtype & ARG_ARGMASK){
644 case ARG_MSGLIST:
645 /* Message list defaulting to nearest forward legal message */
646 if(n_msgvec == NULL)
647 goto je96;
648 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
649 break;
650 if(c == 0){
651 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
652 n_msgvec[1] = 0;
654 if(n_msgvec[0] == 0){
655 if(!(pstate & PS_HOOK_MASK))
656 printf(_("No applicable messages\n"));
657 break;
659 e = (*cmd->lc_func)(n_msgvec);
660 break;
662 case ARG_NDMLIST:
663 /* Message list with no defaults, but no error if none exist */
664 if(n_msgvec == NULL){
665 je96:
666 n_err(_("Invalid use of message list\n"));
667 break;
669 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
670 break;
671 e = (*cmd->lc_func)(n_msgvec);
672 break;
674 case ARG_STRLIST:
675 /* Just the straight string, with leading blanks removed */
676 while(whitechar(*cp))
677 ++cp;
678 e = (*cmd->lc_func)(cp);
679 break;
681 case ARG_WYSHLIST:
682 c = 1;
683 if(0){
684 /* FALLTHRU */
685 case ARG_WYRALIST:
686 c = wysh ? 1 : 0;
687 if(0){
688 case ARG_RAWLIST:
689 c = 0;
693 if((c = getrawlist((c != 0), arglist, NELEM(arglist), cp, line.l)) < 0){
694 n_err(_("Invalid argument list\n"));
695 break;
697 if(c < cmd->lc_minargs){
698 n_err(_("`%s' requires at least %d arg(s)\n"),
699 cmd->lc_name, cmd->lc_minargs);
700 break;
702 #undef lc_minargs
703 if(c > cmd->lc_maxargs){
704 n_err(_("`%s' takes no more than %d arg(s)\n"),
705 cmd->lc_name, cmd->lc_maxargs);
706 break;
708 #undef lc_maxargs
709 e = (*cmd->lc_func)(arglist);
710 break;
712 case ARG_NOLIST:
713 /* Just the constant zero, for exiting, eg. */
714 e = (*cmd->lc_func)(0);
715 break;
717 default:
718 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
719 cmd->lc_argtype & ARG_ARGMASK); )
720 goto jleave0;
723 if(e == 0 && (cmd->lc_argtype & ARG_V) &&
724 (cp = temporary_arg_v_store) != NULL){
725 temporary_arg_v_store = NULL;
726 evp->le_new_content = cp;
727 goto jleave0;
729 if(!(cmd->lc_argtype & ARG_H) && !(pstate & PS_MSGLIST_SAW_NO))
730 evp->le_add_history = TRU1;
732 jleave:
733 /* Exit the current source file on error TODO what a mess! */
734 if(e == 0)
735 pstate &= ~PS_EVAL_ERROR;
736 else{
737 pstate |= PS_EVAL_ERROR;
738 if(e < 0 || (pstate & PS_ROBOT)){ /* FIXME */
739 e = 1;
740 goto jret;
742 goto jret0;
745 if(cmd == NULL)
746 goto jret0;
747 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint))
748 if(visible(dot)){
749 line.s = savestr("type");
750 line.l = sizeof("type") -1;
751 gp = (struct a_lex_ghost*)-1; /* Avoid `ghost' interpretation */
752 goto jrestart;
755 if(!(pstate & (PS_SOURCING | PS_HOOK_MASK)) && !(cmd->lc_argtype & ARG_T))
756 pstate |= PS_SAW_COMMAND;
757 jleave0:
758 pstate &= ~PS_EVAL_ERROR;
759 jret0:
760 e = 0;
761 jret:
763 fprintf(stderr, "a_lex_evaluate returns %d for <%s>\n",e,line.s);
765 NYD_LEAVE;
766 return e;
769 static struct a_lex_cmd const *
770 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
771 struct a_lex_cmd const *cp;
772 NYD2_ENTER;
774 for(cp = a_lex_cmd_tab; PTRCMP(cp, <, &a_lex_cmd_tab[NELEM(a_lex_cmd_tab)]);
775 ++cp)
776 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
777 goto jleave;
778 cp = NULL;
779 jleave:
780 NYD2_LEAVE;
781 return cp;
784 static void
785 a_lex_hangup(int s){
786 NYD_X; /* Signal handler */
787 UNUSED(s);
788 /* nothing to do? */
789 exit(EXIT_ERR);
792 static void
793 a_lex_onintr(int s){
794 NYD_X; /* Signal handler */
796 safe_signal(SIGINT, a_lex_onintr);
797 noreset = 0;
798 a_lex_unstack(TRUM1);
800 termios_state_reset();
801 close_all_files(); /* FIXME .. to outer level ONLU! */
803 if(image >= 0){
804 close(image);
805 image = -1;
807 if(interrupts != 1)
808 n_err_sighdl(_("Interrupt\n"));
809 safe_signal(SIGPIPE, a_lex_oldpipe);
810 siglongjmp(srbuf, 0); /* FIXME get rid */
813 static void
814 a_lex_unstack(bool_t eval_error){
815 struct a_lex_input_stack *lip;
816 NYD_ENTER;
818 if((lip = a_lex_input) == NULL){
819 /* If called from a_lex_onintr(), be silent FIXME */
820 pstate &= ~(PS_SOURCING | PS_ROBOT);
821 if(eval_error == TRUM1 || !(pstate & PS_STARTED))
822 goto jleave;
823 goto jerr;
826 if(lip->li_flags & a_LEX_MACRO){
827 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
828 char **lp;
830 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
831 free(*lp);
832 ++lip->li_loff;
834 /* Part of lip's memory chunk, then */
835 if(!(lip->li_flags & a_LEX_MACRO_CMD))
836 free(lip->li_lines);
838 }else{
839 if(lip->li_flags & a_LEX_PIPE)
840 /* XXX command manager should -TERM then -KILL instead of hoping
841 * XXX for exit of provider due to EPIPE / SIGPIPE */
842 Pclose(lip->li_file, TRU1);
843 else
844 Fclose(lip->li_file);
847 if(!condstack_take(lip->li_cond)){
848 n_err(_("Unmatched `if' at end of %s %s\n"),
849 ((lip->li_flags & a_LEX_MACRO
850 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
851 : _("`source'd file"))),
852 lip->li_name);
853 eval_error = TRU1;
856 if((a_lex_input = lip->li_outer) == NULL){
857 pstate &= ~(PS_SOURCING | PS_ROBOT);
858 }else{
859 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
860 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
861 pstate &= ~PS_SOURCING;
862 assert(pstate & PS_ROBOT);
865 if(eval_error)
866 goto jerr;
867 if(lip->li_flags & a_LEX_FREE)
868 free(lip);
869 jleave:
870 if(UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
871 a_lex_unstack(TRUM1);
872 NYD_LEAVE;
873 return;
875 jerr:
876 if(lip != NULL){
877 if(options & OPT_D_V)
878 n_alert(_("Stopped %s %s due to errors%s"),
879 (pstate & PS_STARTED
880 ? (lip->li_flags & a_LEX_MACRO
881 ? (lip->li_flags & a_LEX_MACRO_CMD
882 ? _("evaluating command") : _("evaluating macro"))
883 : (lip->li_flags & a_LEX_PIPE
884 ? _("executing `source'd pipe")
885 : _("loading `source'd file")))
886 : (lip->li_flags & a_LEX_MACRO
887 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
888 ? _("evaluating command line") : _("evaluating macro"))
889 : _("loading initialization resource"))),
890 lip->li_name,
891 (options & OPT_DEBUG ? "" : _(" (enable *debug* for trace)")));
892 if(lip->li_flags & a_LEX_FREE)
893 free(lip);
896 if(!(options & OPT_INTERACTIVE) && !(pstate & PS_STARTED)){
897 if(options & OPT_D_V)
898 n_alert(_("Non-interactive, bailing out due to errors "
899 "in startup load phase"));
900 exit(EXIT_ERR);
902 goto jleave;
905 static bool_t
906 a_lex_source_file(char const *file, bool_t silent_error){
907 struct a_lex_input_stack *lip;
908 size_t nlen;
909 char *nbuf;
910 bool_t ispipe;
911 FILE *fip;
912 NYD_ENTER;
914 fip = NULL;
916 /* Being a command argument file is space-trimmed */
917 if((ispipe = (!silent_error && (nlen = strlen(file)) > 0 &&
918 file[--nlen] == '|'))){
919 if((fip = Popen(nbuf = savestrbuf(file, nlen), "r",
920 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL){
921 if(!silent_error || (options & OPT_D_V))
922 n_perr(nbuf, 0);
923 goto jleave;
925 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
926 goto jleave;
927 else if((fip = Fopen(nbuf, "r")) == NULL){
928 if(!silent_error || (options & OPT_D_V))
929 n_perr(nbuf, 0);
930 goto jleave;
933 lip = smalloc(sizeof(*lip) -
934 VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
935 (nlen = strlen(nbuf) +1));
936 lip->li_outer = a_lex_input;
937 lip->li_file = fip;
938 lip->li_cond = condstack_release();
939 lip->li_flags = (ispipe ? a_LEX_PIPE : a_LEX_NONE) |
940 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
941 ? a_LEX_SUPER_MACRO : 0);
942 memcpy(lip->li_name, nbuf, nlen);
944 pstate |= PS_SOURCING | PS_ROBOT;
945 a_lex_input = lip;
946 a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC);
947 /* FIXME return TRUM1 if file can't be opened, FAL0 on eval error */
948 jleave:
949 NYD_LEAVE;
950 return silent_error ? TRU1 : (fip != NULL);
953 static bool_t
954 a_lex_load(struct a_lex_input_stack *lip){
955 bool_t rv;
956 NYD2_ENTER;
958 assert(!(pstate & PS_STARTED));
959 assert(a_lex_input == NULL);
961 /* POSIX:
962 * Any errors in the start-up file shall either cause mailx to terminate
963 * with a diagnostic message and a non-zero status or to continue after
964 * writing a diagnostic message, ignoring the remainder of the lines in
965 * the start-up file. */
966 lip->li_cond = condstack_release();
968 /* FIXME won't work for now (PS_ROBOT needs PS_SOURCING anyway)
969 pstate |= PS_ROBOT |
970 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : PS_SOURCING);
972 pstate |= PS_ROBOT | PS_SOURCING;
973 if(options & OPT_D_V)
974 n_err(_("Loading %s\n"), n_shell_quote_cp(lip->li_name, FAL0));
975 a_lex_input = lip;
976 if(!(rv = n_commands())){
977 if(!(options & OPT_INTERACTIVE)){
978 if(options & OPT_D_V)
979 n_alert(_("Non-interactive program mode, forced exit"));
980 exit(EXIT_ERR);
983 /* PS_EXIT handled by callers */
984 NYD2_LEAVE;
985 return rv;
988 static bool_t
989 a_commands_recursive(enum n_lexinput_flags lif){
990 struct a_lex_eval_ctx ev;
991 bool_t rv;
992 NYD2_ENTER;
994 memset(&ev, 0, sizeof ev);
996 /* FIXME sigkondom */
997 n_COLOUR( n_colour_env_push(); )
998 rv = TRU1;
999 for(;;){
1000 int n;
1002 /* Read a line of commands and handle end of file specially */
1003 ev.le_line.l = ev.le_line_size;
1004 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l,
1005 ev.le_new_content);
1006 ev.le_line_size = (ui32_t)ev.le_line.l;
1007 ev.le_line.l = (ui32_t)n;
1009 if(n < 0)
1010 break;
1012 if(a_lex_evaluate(&ev)){
1013 rv = FAL0;
1014 break;
1017 if((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)){
1018 if(exit_status != EXIT_OK)
1019 break;
1022 a_lex_unstack(!rv);
1023 n_COLOUR( n_colour_env_pop(FAL0); )
1025 if(ev.le_line.s != NULL)
1026 free(ev.le_line.s);
1027 NYD2_LEAVE;
1028 return rv;
1031 #ifdef HAVE_DOCSTRINGS
1032 FL bool_t
1033 n_print_comm_docstr(char const *comm){
1034 struct a_lex_ghost const *gp;
1035 struct a_lex_cmd const *cp, *cpmax;
1036 bool_t rv = FAL0;
1037 NYD_ENTER;
1039 /* Ghosts take precedence */
1040 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
1041 if(!strcmp(comm, gp->lg_name)){
1042 printf("%s -> ", comm);
1043 comm = gp->lg_cmd.s;
1044 break;
1047 cpmax = &(cp = a_lex_cmd_tab)[NELEM(a_lex_cmd_tab)];
1048 jredo:
1049 for(; PTRCMP(cp, <, cpmax); ++cp){
1050 if(!strcmp(comm, cp->lc_name))
1051 printf("%s: %s\n", comm, V_(cp->lc_doc));
1052 else if(is_prefix(comm, cp->lc_name))
1053 printf("%s (%s): %s\n", comm, cp->lc_name, V_(cp->lc_doc));
1054 else
1055 continue;
1056 rv = TRU1;
1057 break;
1059 if(!rv && PTRCMP(cpmax, ==, &a_lex_cmd_tab[NELEM(a_lex_cmd_tab)])){
1060 cpmax = &(cp = a_lex_special_cmd_tab)[NELEM(a_lex_special_cmd_tab)];
1061 goto jredo;
1064 if(!rv && gp != NULL){
1065 printf("%s\n", n_shell_quote_cp(comm, TRU1));
1066 rv = TRU1;
1068 NYD_LEAVE;
1069 return rv;
1071 #endif /* HAVE_DOCSTRINGS */
1073 FL bool_t
1074 n_commands(void){ /* FIXME */
1075 struct a_lex_eval_ctx ev;
1076 int n;
1077 bool_t volatile rv = TRU1;
1078 NYD_ENTER;
1080 if (!(pstate & PS_SOURCING)) {
1081 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1082 safe_signal(SIGINT, &a_lex_onintr);
1083 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1084 safe_signal(SIGHUP, &a_lex_hangup);
1086 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1087 safe_signal(SIGPIPE, a_lex_oldpipe);
1089 memset(&ev, 0, sizeof ev);
1091 (void)sigsetjmp(srbuf, 1); /* FIXME get rid */
1092 for (;;) {
1093 char *temporary_orig_line; /* XXX eval_ctx.le_line not yet constant */
1095 n_COLOUR( n_colour_env_pop(TRU1); )
1097 /* TODO Unless we have our signal manager (or however we do it) child
1098 * TODO processes may have time slots where their execution isn't
1099 * TODO protected by signal handlers (in between start and setup
1100 * TODO completed). close_all_files() is only called from onintr()
1101 * TODO so those may linger possibly forever */
1102 if(!(pstate & PS_SOURCING))
1103 close_all_files();
1105 interrupts = 0;
1107 temporary_localopts_free(); /* XXX intermediate hack */
1108 sreset((pstate & PS_SOURCING) != 0);
1109 if (!(pstate & PS_SOURCING)) {
1110 char *cp;
1112 /* TODO Note: this buffer may contain a password. We should redefine
1113 * TODO the code flow which has to do that */
1114 if ((cp = termios_state.ts_linebuf) != NULL) {
1115 termios_state.ts_linebuf = NULL;
1116 termios_state.ts_linesize = 0;
1117 free(cp); /* TODO pool give-back */
1119 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1120 if (ev.le_line.l > LINESIZE * 3) {
1121 free(ev.le_line.s); /* TODO pool! but what? */
1122 ev.le_line.s = NULL;
1123 ev.le_line.l = ev.le_line_size = 0;
1127 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1128 char *cp;
1130 cp = ok_vlook(newmail);
1131 if ((options & OPT_TTYIN) && cp != NULL) {
1132 struct stat st;
1134 /* FIXME TEST WITH NOPOLL ETC. !!! */
1135 n = (cp != NULL && strcmp(cp, "nopoll"));
1136 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1137 st.st_size > mailsize) ||
1138 (mb.mb_type == MB_MAILDIR && n != 0)) {
1139 size_t odot = PTR2SIZE(dot - message);
1140 ui32_t odid = (pstate & PS_DID_PRINT_DOT);
1142 if (setfile(mailname,
1143 FEDIT_NEWMAIL |
1144 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1145 exit_status |= EXIT_ERR;
1146 rv = FAL0;
1147 break;
1149 dot = message + odot;
1150 pstate |= odid;
1154 exit_status = EXIT_OK;
1157 /* Read a line of commands and handle end of file specially */
1158 jreadline:
1159 ev.le_line.l = ev.le_line_size;
1160 n = n_lex_input(n_LEXINPUT_CTX_BASE | n_LEXINPUT_NL_ESC, NULL,
1161 &ev.le_line.s, &ev.le_line.l, ev.le_new_content);
1162 ev.le_line_size = (ui32_t)ev.le_line.l;
1163 ev.le_line.l = (ui32_t)n;
1165 if (n < 0) {
1166 /* FIXME did unstack() when PS_SOURCING, only break with PS_LOADING*/
1167 if (!(pstate & PS_ROBOT) &&
1168 (options & OPT_INTERACTIVE) && ok_blook(ignoreeof)) {
1169 printf(_("*ignoreeof* set, use `quit' to quit.\n"));
1170 n_msleep(500, FAL0);
1171 continue;
1173 break;
1176 temporary_orig_line = ((pstate & PS_SOURCING) ||
1177 !(options & OPT_INTERACTIVE)) ? NULL
1178 : savestrbuf(ev.le_line.s, ev.le_line.l);
1179 pstate &= ~PS_HOOK_MASK;
1180 if (a_lex_evaluate(&ev)) {
1181 if (!(pstate & PS_STARTED)) /* TODO mess; join PS_EVAL_ERROR.. */
1182 rv = FAL0;
1183 break;
1186 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
1187 if (exit_status != EXIT_OK)
1188 break;
1189 if ((pstate & (PS_SOURCING | PS_EVAL_ERROR)) == PS_EVAL_ERROR) {
1190 exit_status = EXIT_ERR;
1191 break;
1194 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1195 if (ev.le_new_content != NULL)
1196 goto jreadline;
1197 /* *Can* happen since _evaluate() n_unstack()s on error! XXX no more */
1198 if (temporary_orig_line != NULL)
1199 n_tty_addhist(temporary_orig_line, !ev.le_add_history);
1202 if(pstate & PS_EXIT)
1203 break;
1205 a_lex_unstack(!rv);
1207 if (ev.le_line.s != NULL)
1208 free(ev.le_line.s);
1209 if (pstate & PS_SOURCING)
1210 sreset(FAL0);
1211 NYD_LEAVE;
1212 return rv;
1215 FL int
1216 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1217 size_t *linesize, char const *string SMALLOC_DEBUG_ARGS){
1218 /* TODO readline: linebuf pool! */
1219 FILE *ifile;
1220 bool_t doprompt, dotty;
1221 char const *iftype;
1222 int n, nold;
1223 NYD2_ENTER;
1225 /* Special case macro mode: never need to prompt, lines have always been
1226 * unfolded already */
1227 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1228 char **lp = &a_lex_input->li_lines[a_lex_input->li_loff];
1230 if(*linebuf != NULL)
1231 free(*linebuf);
1233 if((*linebuf = *lp) == NULL){
1234 *linesize = 0;
1235 n = -1;
1236 goto jleave;
1239 ++a_lex_input->li_loff;
1240 *linesize = strlen(*linebuf);
1241 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1242 *linebuf = sbufdup(*linebuf, *linesize);
1243 pstate |= PS_READLINE_NL;
1245 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1246 ? "-X OPTION" : "MACRO";
1247 goto jhave_dat;
1249 pstate &= ~PS_READLINE_NL;
1251 iftype = (!(pstate & PS_STARTED) ? "LOAD"
1252 : (pstate & PS_SOURCING) ? "SOURCE" : "READ");
1253 doprompt = ((pstate & (PS_STARTED | PS_ROBOT)) == PS_STARTED &&
1254 (options & OPT_INTERACTIVE));
1255 dotty = (doprompt && !ok_blook(line_editor_disable));
1256 if(!doprompt)
1257 prompt = NULL;
1258 else if(prompt == NULL)
1259 prompt = getprompt();
1261 /* Ensure stdout is flushed first anyway */
1262 if(!dotty && prompt == NULL)
1263 fflush(stdout);
1265 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : stdin;
1266 assert(ifile != NULL);
1268 for(nold = n = 0;;){
1269 if(dotty){
1270 assert(ifile == stdin);
1271 if(string != NULL && (n = (int)strlen(string)) > 0){
1272 if(*linesize > 0)
1273 *linesize += n +1;
1274 else
1275 *linesize = (size_t)n + LINESIZE +1;
1276 *linebuf = (srealloc)(*linebuf, *linesize SMALLOC_DEBUG_ARGSCALL);
1277 memcpy(*linebuf, string, (size_t)n +1);
1279 string = NULL;
1280 /* TODO if nold>0, don't redisplay the entire line!
1281 * TODO needs complete redesign ... */
1282 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1283 SMALLOC_DEBUG_ARGSCALL);
1284 }else{
1285 if(prompt != NULL) {
1286 if(*prompt != '\0')
1287 fputs(prompt, stdout);
1288 fflush(stdout);
1291 n = (readline_restart)(ifile, linebuf, linesize, n
1292 SMALLOC_DEBUG_ARGSCALL);
1294 if(n > 0 && nold > 0){
1295 int i = 0;
1296 char const *cp = *linebuf + nold;
1298 while(blankspacechar(*cp) && nold + i < n)
1299 ++cp, ++i;
1300 if(i > 0){
1301 memmove(*linebuf + nold, cp, n - nold - i);
1302 n -= i;
1303 (*linebuf)[n] = '\0';
1308 if(n <= 0)
1309 break;
1311 /* POSIX says:
1312 * An unquoted <backslash> at the end of a command line shall
1313 * be discarded and the next line shall continue the command */
1314 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1315 if(dotty)
1316 pstate |= PS_READLINE_NL;
1317 break;
1319 /* Definitely outside of quotes, thus the quoting rules are so that an
1320 * uneven number of successive backslashs at EOL is a continuation */
1321 if(n > 1){
1322 size_t i, j;
1324 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1325 if((*linebuf)[i] != '\\')
1326 break;
1327 if(!(j & 1))
1328 break;
1330 (*linebuf)[nold = --n] = '\0';
1331 if(prompt != NULL && *prompt != '\0')
1332 prompt = ".. "; /* XXX PS2 .. */
1335 if(n < 0)
1336 goto jleave;
1337 (*linebuf)[*linesize = n] = '\0';
1339 jhave_dat:
1340 #if 0
1341 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1342 char *cp, c;
1343 size_t i;
1345 for(cp = &(*linebuf)[i = *linesize];; --i){
1346 c = *--cp;
1347 if(!blankspacechar(c))
1348 break;
1350 (*linebuf)[*linesize = i] = '\0';
1353 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1354 char *cp, c;
1355 size_t j, i;
1357 for(cp = &(*linebuf)[0], j = *linesize, i = 0; i < j; ++i){
1358 c = *cp++;
1359 if(!blankspacechar(c))
1360 break;
1362 if(i > 0){
1363 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1364 (*linebuf)[*linesize = j] = '\0';
1367 #endif /* 0 (notyet - must take care for backslash escaped space) */
1369 if(options & OPT_D_VV)
1370 n_err(_("%s %" PRIuZ " bytes <%s>\n"), iftype, *linesize, *linebuf);
1371 n = (int)*linesize; /* XXX si64_t */
1372 jleave:
1373 if (pstate & PS_PSTATE_PENDMASK)
1374 a_lex_update_pstate();
1375 NYD2_LEAVE;
1376 return n;
1379 FL char *
1380 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1381 char const *string){
1382 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1383 size_t linesize;
1384 char *linebuf, *rv;
1385 int n;
1386 NYD2_ENTER;
1388 linesize = 0;
1389 linebuf = NULL;
1390 rv = NULL;
1392 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1393 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1394 (lif & n_LEXINPUT_HIST_ADD) && (options & OPT_INTERACTIVE))
1395 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1397 if(linebuf != NULL)
1398 free(linebuf);
1399 NYD2_LEAVE;
1400 return rv;
1403 FL void
1404 n_load(char const *name){
1405 struct a_lex_input_stack *lip;
1406 size_t i;
1407 FILE *fip;
1408 NYD_ENTER;
1410 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1411 goto jleave;
1413 i = strlen(name) +1;
1414 lip = scalloc(1, sizeof(*lip) -
1415 VFIELD_SIZEOF(struct a_lex_input_stack, li_name) + i);
1416 lip->li_file = fip;
1417 lip->li_flags = a_LEX_FREE;
1418 memcpy(lip->li_name, name, i);
1420 a_lex_load(lip);
1421 pstate &= ~PS_EXIT;
1422 jleave:
1423 NYD_LEAVE;
1426 FL void
1427 n_load_Xargs(char const **lines){
1428 static char const name[] = "-X";
1430 ui8_t buf[sizeof(struct a_lex_input_stack) + sizeof name];
1431 struct a_lex_input_stack *lip;
1432 NYD_ENTER;
1434 memset(buf, 0, sizeof buf);
1435 lip = (void*)buf;
1436 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1437 lip->li_lines = UNCONST(lines);
1438 memcpy(lip->li_name, name, sizeof name);
1440 a_lex_load(lip);
1441 if(pstate & PS_EXIT)
1442 exit(EXIT_OK);
1443 NYD_LEAVE;
1446 FL int
1447 c_source(void *v){
1448 int rv;
1449 NYD_ENTER;
1451 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1452 NYD_LEAVE;
1453 return rv;
1456 FL int
1457 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1458 int rv;
1459 NYD_ENTER;
1461 rv = (a_lex_source_file(*(char**)v, TRU1) != FAL0) ? 0 : 1;
1462 NYD_LEAVE;
1463 return rv;
1466 FL bool_t
1467 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines){
1468 struct a_lex_input_stack *lip;
1469 size_t i;
1470 int rv;
1471 NYD_ENTER;
1473 lip = smalloc(sizeof(*lip) -
1474 VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1475 (i = strlen(name) +1));
1476 lip->li_outer = a_lex_input;
1477 lip->li_file = NULL;
1478 lip->li_cond = condstack_release();
1479 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1480 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1481 ? a_LEX_SUPER_MACRO : 0);
1482 lip->li_loff = 0;
1483 lip->li_lines = lines;
1484 memcpy(lip->li_name, name, i);
1486 pstate |= PS_ROBOT;
1487 a_lex_input = lip;
1488 rv = a_commands_recursive(lif);
1489 NYD_LEAVE;
1490 return rv;
1493 FL bool_t
1494 n_source_command(enum n_lexinput_flags lif, char const *cmd){
1495 struct a_lex_input_stack *lip;
1496 size_t i, ial;
1497 bool_t rv;
1498 NYD_ENTER;
1500 i = strlen(cmd);
1501 cmd = sbufdup(cmd, i++);
1502 ial = n_ALIGN(i);
1504 lip = smalloc(sizeof(*lip) -
1505 VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1506 ial + 2*sizeof(char*));
1507 lip->li_outer = a_lex_input;
1508 lip->li_file = NULL;
1509 lip->li_cond = condstack_release();
1510 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1511 a_LEX_MACRO_CMD |
1512 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1513 ? a_LEX_SUPER_MACRO : 0);
1514 lip->li_loff = 0;
1515 lip->li_lines = (void*)(lip->li_name + ial);
1516 lip->li_lines[0] = UNCONST(cmd); /* dup'ed above */
1517 lip->li_lines[1] = NULL;
1518 memcpy(lip->li_name, cmd, i);
1520 pstate |= PS_ROBOT;
1521 a_lex_input = lip;
1522 rv = a_commands_recursive(lif);
1523 NYD_LEAVE;
1524 return rv;
1527 FL bool_t
1528 n_source_may_yield_control(void){
1529 return ((options & OPT_INTERACTIVE) &&
1530 (pstate & PS_STARTED) &&
1531 (!(pstate & PS_ROBOT) || (pstate & PS_RECURSED)) && /* Ok for ~: */
1532 (a_lex_input == NULL || a_lex_input->li_outer == NULL));
1535 /* s-it-mode */