Some: stop adding $TMPDIR to ENV, automatic now with new var-handling
[s-mailx.git] / lex_input.c
blobc176e38e54851c87e4804e7fbd216acd237c83e8
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 void (*li_macro_on_finalize)(void *);
93 void *li_macro_finalize_arg;
94 char li_autorecmem[n_MEMORY_AUTOREC_TYPE_SIZEOF];
95 sigjmp_buf li_cmdrec_jmp; /* TODO one day... for command_recursive */
96 char li_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
98 n_CTA(n_MEMORY_AUTOREC_TYPE_SIZEOF % sizeof(void*) == 0,
99 "Inacceptible size of structure buffer");
101 static sighandler_type a_lex_oldpipe;
102 static struct a_lex_ghost *a_lex_ghosts;
103 /* a_lex_cmd_tab[] after fun protos */
105 /* */
106 static struct a_lex_input_stack *a_lex_input;
108 static sigjmp_buf a_lex_srbuf; /* TODO GET RID */
110 /* Isolate the command from the arguments */
111 static char *a_lex_isolate(char const *comm);
113 /* Command ghost handling */
114 static int a_lex_c_ghost(void *v);
115 static int a_lex_c_unghost(void *v);
117 /* Print a list of all commands */
118 static int a_lex_c_list(void *v);
120 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
122 /* `help' / `?' command */
123 static int a_lex_c_help(void *v);
125 /* `quit' command */
126 static int a_lex_c_quit(void *v);
128 /* Print the binaries version number */
129 static int a_lex_c_version(void *v);
131 static int a_lex__version_cmp(void const *s1, void const *s2);
133 /* PS_STATE_PENDMASK requires some actions */
134 static void a_lex_update_pstate(void);
136 /* Evaluate a single command.
137 * .le_add_history and .le_new_content will be updated upon success.
138 * Command functions return 0 for success, 1 for error, and -1 for abort.
139 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
140 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
142 /* Get first-fit, or NULL */
143 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
145 /* Branch here on hangup signal and simulate "exit" */
146 static void a_lex_hangup(int s);
148 /* The following gets called on receipt of an interrupt. Close all open files
149 * except 0, 1, 2, and the temporary. Also, unstack all source files */
150 static void a_lex_onintr(int s);
152 /* Pop the current input back to the previous level. Update the program state.
153 * If the argument is TRUM1 then we don't alert and error out if the stack
154 * doesn't exist at all */
155 static void a_lex_unstack(bool_t eval_error);
157 /* `source' and `source_if' (if silent_error: no pipes allowed, then) */
158 static bool_t a_lex_source_file(char const *file, bool_t silent_error);
160 /* System resource file load()ing or -X command line option array traversal */
161 static bool_t a_lex_load(struct a_lex_input_stack *lip);
163 /* A simplified command loop for recursed state machines */
164 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
166 /* List of all commands, and list of commands which are specially treated
167 * and deduced in _evaluate(), but we need a list for _c_list() and
168 * print_comm_docstr() */
169 #ifdef HAVE_DOCSTRINGS
170 # define DS(S) , S
171 #else
172 # define DS(S)
173 #endif
174 static struct a_lex_cmd const a_lex_cmd_tab[] = {
175 #include "cmd_tab.h"
177 a_lex_special_cmd_tab[] = {
178 { "#", NULL, 0, 0, 0
179 DS(N_("Comment command: ignore remaining (continuable) line")) },
180 { "-", NULL, 0, 0, 0
181 DS(N_("Print out the preceding message")) }
183 #undef DS
185 static char *
186 a_lex_isolate(char const *comm){
187 NYD2_ENTER;
188 while(*comm != '\0' &&
189 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
190 ++comm;
191 NYD2_LEAVE;
192 return n_UNCONST(comm);
195 static int
196 a_lex_c_ghost(void *v){
197 struct a_lex_ghost *lgp, *gp;
198 size_t i, cl, nl;
199 char *cp;
200 char const **argv;
201 NYD_ENTER;
203 argv = v;
205 /* Show the list? */
206 if(*argv == NULL){
207 FILE *fp;
209 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
210 fp = stdout;
212 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
213 fprintf(fp, "wysh ghost %s %s\n",
214 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
216 if(fp != stdout){
217 page_or_print(fp, i);
218 Fclose(fp);
220 goto jleave;
223 /* Verify the ghost name is a valid one */
224 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0'){
225 n_err(_("`ghost': can't canonicalize %s\n"),
226 n_shexp_quote_cp(argv[0], FAL0));
227 v = NULL;
228 goto jleave;
231 /* Show command of single ghost? */
232 if(argv[1] == NULL){
233 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
234 if(!strcmp(argv[0], gp->lg_name)){
235 printf("wysh ghost %s %s\n",
236 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
237 goto jleave;
239 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
240 v = NULL;
241 goto jleave;
244 /* Define command for ghost: verify command content */
245 for(cl = 0, i = 1; (cp = n_UNCONST(argv[i])) != NULL; ++i)
246 if(*cp != '\0')
247 cl += strlen(cp) +1; /* SP or NUL */
248 if(cl == 0){
249 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
250 v = NULL;
251 goto jleave;
254 /* If the ghost already exists, recreate */
255 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
256 if(!strcmp(gp->lg_name, argv[0])){
257 if(lgp != NULL)
258 lgp->lg_next = gp->lg_next;
259 else
260 a_lex_ghosts = gp->lg_next;
261 free(gp);
262 break;
265 nl = strlen(argv[0]) +1;
266 gp = smalloc(sizeof(*gp) - n_VFIELD_SIZEOF(struct a_lex_ghost, lg_name) +
267 nl + cl);
268 gp->lg_next = a_lex_ghosts;
269 a_lex_ghosts = gp;
270 memcpy(gp->lg_name, argv[0], nl);
271 cp = gp->lg_cmd.s = gp->lg_name + nl;
272 gp->lg_cmd.l = --cl;
274 while(*++argv != NULL)
275 if((i = strlen(*argv)) > 0){
276 memcpy(cp, *argv, i);
277 cp += i;
278 *cp++ = ' ';
280 *--cp = '\0';
281 jleave:
282 NYD_LEAVE;
283 return v == NULL;
286 static int
287 a_lex_c_unghost(void *v){
288 struct a_lex_ghost *lgp, *gp;
289 char const **argv, *cp;
290 int rv;
291 NYD_ENTER;
293 rv = 0;
294 argv = v;
296 while((cp = *argv++) != NULL){
297 if(cp[0] == '*' && cp[1] == '\0'){
298 while((gp = a_lex_ghosts) != NULL){
299 a_lex_ghosts = gp->lg_next;
300 free(gp);
302 }else{
303 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
304 lgp = gp, gp = gp->lg_next)
305 if(!strcmp(gp->lg_name, cp)){
306 if(lgp != NULL)
307 lgp->lg_next = gp->lg_next;
308 else
309 a_lex_ghosts = gp->lg_next;
310 free(gp);
311 goto jouter;
313 n_err(_("`unghost': no such alias: %s\n"),
314 n_shexp_quote_cp(cp, FAL0));
315 rv = 1;
316 jouter: ;
319 NYD_LEAVE;
320 return rv;
323 static int
324 a_lex_c_list(void *v){
325 FILE *fp;
326 struct a_lex_cmd const **cpa, *cp, **cursor;
327 size_t l, i;
328 NYD_ENTER;
330 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
331 cpa = salloc(sizeof(cp) * i);
333 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
334 cpa[i] = &a_lex_cmd_tab[i];
335 /* C99 */{
336 size_t j;
338 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
339 cpa[i] = &a_lex_special_cmd_tab[j];
341 cpa[i] = NULL;
343 /* C99 */{
344 char const *xcp = v;
346 if(*xcp == '\0')
347 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
350 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
351 fp = stdout;
353 fprintf(fp, _("Commands are:\n"));
354 l = 1;
355 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
356 if(cp->lc_func == &c_cmdnotsupp)
357 continue;
358 if(options & OPT_D_V){
359 char const *argt;
361 switch(cp->lc_argtype & ARG_ARGMASK){
362 case ARG_MSGLIST: argt = N_("message-list"); break;
363 case ARG_STRLIST: argt = N_("a \"string\""); break;
364 case ARG_RAWLIST: argt = N_("old-style quoting"); break;
365 case ARG_NOLIST: argt = N_("no arguments"); break;
366 case ARG_NDMLIST: argt = N_("message-list (without a default)"); break;
367 case ARG_WYSHLIST: argt = N_("sh(1)ell-style quoting"); break;
368 default: argt = N_("`wysh' for sh(1)ell-style quoting"); break;
370 #ifdef HAVE_DOCSTRINGS
371 fprintf(fp, _("`%s'. Argument type: %s.\n\t%s\n"),
372 cp->lc_name, V_(argt), V_(cp->lc_doc));
373 l += 2;
374 #else
375 fprintf(fp, "`%s' (%s)\n", cp->lc_name, argt);
376 ++l;
377 #endif
378 }else{
379 size_t j = strlen(cp->lc_name) + 2;
381 if((i += j) > 72){
382 i = j;
383 fprintf(fp, "\n");
384 ++l;
386 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
390 if(fp != stdout){
391 page_or_print(fp, l);
392 Fclose(fp);
394 NYD_LEAVE;
395 return 0;
398 static int
399 a_lex__pcmd_cmp(void const *s1, void const *s2){
400 struct a_lex_cmd const * const *cp1, * const *cp2;
401 int rv;
402 NYD2_ENTER;
404 cp1 = s1;
405 cp2 = s2;
406 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
407 NYD2_LEAVE;
408 return rv;
411 static int
412 a_lex_c_help(void *v){
413 int rv;
414 char *arg;
415 NYD_ENTER;
417 /* Help for a single command? */
418 if((arg = *(char**)v) != NULL){
419 struct a_lex_ghost const *gp;
420 struct a_lex_cmd const *cp, *cpmax;
422 /* Ghosts take precedence */
423 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
424 if(!strcmp(arg, gp->lg_name)){
425 printf("%s -> ", arg);
426 arg = gp->lg_cmd.s;
427 break;
430 cpmax = &(cp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
431 jredo:
432 for(; PTRCMP(cp, <, cpmax); ++cp){
433 #ifdef HAVE_DOCSTRINGS
434 # define a_DS V_(cp->lc_doc)
435 #else
436 # define a_DS n_empty
437 #endif
438 if(!strcmp(arg, cp->lc_name))
439 printf("%s: %s", arg, a_DS);
440 else if(is_prefix(arg, cp->lc_name))
441 printf("%s (%s): %s", arg, cp->lc_name, a_DS);
442 else
443 continue;
445 if(options & OPT_D_V){
446 char const *atp;
448 switch(cp->lc_argtype & ARG_ARGMASK){
449 case ARG_MSGLIST: atp = N_("message-list"); break;
450 case ARG_STRLIST: atp = N_("a \"string\""); break;
451 case ARG_RAWLIST: atp = N_("old-style quoting"); break;
452 case ARG_NOLIST: atp = N_("no arguments"); break;
453 case ARG_NDMLIST: atp = N_("message-list (no default)"); break;
454 case ARG_WYSHLIST: atp = N_("sh(1)ell-style quoting"); break;
455 default: atp = N_("`wysh' for sh(1)ell-style quoting"); break;
457 #ifdef HAVE_DOCSTRINGS
458 printf(_("\n\tArgument type: %s"), V_(atp));
459 #else
460 printf(_("argument type: %s"), V_(atp));
461 #endif
462 #undef a_DS
464 putchar('\n');
465 rv = 0;
466 goto jleave;
469 if(PTRCMP(cpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
470 cpmax = &(cp = a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
471 goto jredo;
474 if(gp != NULL){
475 printf("%s\n", n_shexp_quote_cp(arg, TRU1));
476 rv = 0;
477 }else{
478 n_err(_("Unknown command: `%s'\n"), arg);
479 rv = 1;
481 }else{
482 /* Very ugly, but take care for compiler supported string lengths :( */
483 fputs(progname, stdout);
484 fputs(_(
485 " commands -- <msglist> denotes message specifications,\n"
486 "e.g., 1-5, :n or ., separated by spaces:\n"), stdout);
487 fputs(_(
488 "\n"
489 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
490 "Type <msglist> like `type' but always show all headers\n"
491 "next goto and type next message\n"
492 "from <msglist> (search and) print header summary for the given list\n"
493 "headers header summary for messages surrounding \"dot\"\n"
494 "delete <msglist> delete messages (can be `undelete'd)\n"),
495 stdout);
497 fputs(_(
498 "\n"
499 "save <msglist> folder append messages to folder and mark as saved\n"
500 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
501 "write <msglist> file write message contents to file (prompts for parts)\n"
502 "Reply <msglist> reply to message senders only\n"
503 "reply <msglist> like `Reply', but address all recipients\n"
504 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
505 stdout);
507 fputs(_(
508 "\n"
509 "mail <recipients> compose a mail for the given recipients\n"
510 "file folder change to another mailbox\n"
511 "File folder like `file', but open readonly\n"
512 "quit quit and apply changes to the current mailbox\n"
513 "xit or exit like `quit', but discard changes\n"
514 "!shell command shell escape\n"
515 "list [<anything>] all available commands [in search order]\n"),
516 stdout);
518 rv = (ferror(stdout) != 0);
520 jleave:
521 NYD_LEAVE;
522 return rv;
525 static int
526 a_lex_c_quit(void *v){
527 NYD_ENTER;
528 n_UNUSED(v);
530 /* If we are PS_SOURCING, then return 1 so _evaluate() can handle it.
531 * Otherwise return -1 to abort command loop */
532 pstate |= PS_EXIT;
533 NYD_LEAVE;
534 return 0;
537 static int
538 a_lex_c_version(void *v){
539 int longest, rv;
540 char *iop;
541 char const *cp, **arr;
542 size_t i, i2;
543 NYD_ENTER;
544 n_UNUSED(v);
546 printf(_("%s version %s\nFeatures included (+) or not (-)\n"),
547 uagent, ok_vlook(version));
549 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
550 i = strlen(cp = &ok_vlook(features)[1]) +1;
551 iop = salloc(i);
552 memcpy(iop, cp, i);
554 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
555 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
556 arr[i] = cp;
557 i2 = strlen(cp);
558 longest = n_MAX(longest, (int)i2);
560 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
562 for(++longest, i2 = 0; i-- > 0;){
563 cp = *(arr++);
564 printf("%-*s ", longest, cp);
565 i2 += longest;
566 if(UICMP(z, ++i2 + longest, >=, scrnwidth) || i == 0){
567 i2 = 0;
568 putchar('\n');
572 if((rv = ferror(stdout) != 0))
573 clearerr(stdout);
574 NYD_LEAVE;
575 return rv;
578 static int
579 a_lex__version_cmp(void const *s1, void const *s2){
580 char const * const *cp1, * const *cp2;
581 int rv;
582 NYD2_ENTER;
584 cp1 = s1;
585 cp2 = s2;
586 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
587 NYD2_LEAVE;
588 return rv;
591 static void
592 a_lex_update_pstate(void){
593 NYD_ENTER;
595 if(pstate & PS_SIGWINCH_PEND){
596 char buf[32];
598 snprintf(buf, sizeof buf, "%d", scrnwidth);
599 ok_vset(COLUMNS, buf);
600 snprintf(buf, sizeof buf, "%d", scrnheight);
601 ok_vset(LINES, buf);
604 pstate &= ~PS_PSTATE_PENDMASK;
605 NYD_LEAVE;
608 static int
609 a_lex_evaluate(struct a_lex_eval_ctx *evp){
610 /* xxx old style(9), but also old code */
611 struct str line;
612 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
613 struct a_lex_ghost *gp;
614 struct a_lex_cmd const *cmd;
615 int c, e;
616 bool_t wysh;
617 NYD_ENTER;
619 wysh = FAL0;
620 e = 1;
621 cmd = NULL;
622 gp = NULL;
623 line = evp->le_line; /* XXX don't change original (buffer pointer) */
624 assert(line.s[line.l] == '\0');
625 evp->le_add_history = FAL0;
626 evp->le_new_content = NULL;
628 /* Command ghosts that refer to shell commands or macro expansion restart */
629 jrestart:
631 /* Strip the white space away from end and beginning of command */
632 if(line.l > 0){
633 size_t i = line.l;
635 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
636 --i;
637 line.l = i;
639 for(cp = line.s; spacechar(*cp); ++cp)
641 line.l -= PTR2SIZE(cp - line.s);
643 /* Ignore null commands (comments) */
644 if(*cp == '#')
645 goto jleave0;
647 /* Handle ! differently to get the correct lexical conventions */
648 arglist[0] = cp;
649 if(*cp == '!')
650 ++cp;
651 /* Isolate the actual command; since it may not necessarily be
652 * separated from the arguments (as in `p1') we need to duplicate it to
653 * be able to create a NUL terminated version.
654 * We must be aware of several special one letter commands here */
655 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
656 (*cp == '|' || *cp == '~' || *cp == '?'))
657 ++cp;
658 c = (int)PTR2SIZE(cp - arglist[0]);
659 line.l -= c;
660 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
661 memcpy(word, arglist[0], c);
662 word[c] = '\0';
664 /* Look up the command; if not found, bitch.
665 * Normally, a blank command would map to the first command in the
666 * table; while PS_SOURCING, however, we ignore blank lines to eliminate
667 * confusion; act just the same for ghosts */
668 if(*word == '\0'){
669 if((pstate & PS_ROBOT) || gp != NULL)
670 goto jleave0;
671 cmd = a_lex_cmd_tab + 0;
672 goto jexec;
675 /* XXX It may be the argument parse adjuster */
676 if(!wysh && c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
677 wysh = TRU1;
678 line.s = cp;
679 goto jrestart;
682 /* If this is the first evaluation, check command ghosts */
683 if(gp == NULL){
684 /* TODO relink list head, so it's sorted on usage over time?
685 * TODO in fact, there should be one hashmap over all commands and ghosts
686 * TODO so that the lookup could be made much more efficient than it is
687 * TODO now (two adjacent list searches! */
688 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
689 if(!strcmp(word, gp->lg_name)){
690 if(line.l > 0){
691 size_t i;
693 i = gp->lg_cmd.l;
694 line.s = salloc(i + line.l +1);
695 memcpy(line.s, gp->lg_cmd.s, i);
696 memcpy(line.s + i, cp, line.l);
697 line.s[i += line.l] = '\0';
698 line.l = i;
699 }else{
700 line.s = gp->lg_cmd.s;
701 line.l = gp->lg_cmd.l;
703 goto jrestart;
707 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
708 bool_t s;
710 if(!(s = condstack_isskip()) || (options & OPT_D_V))
711 n_err(_("Unknown command%s: `%s'\n"),
712 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
713 if(s)
714 goto jleave0;
715 if(cmd != NULL){
716 c_cmdnotsupp(NULL);
717 cmd = NULL;
719 goto jleave;
722 /* See if we should execute the command -- if a conditional we always
723 * execute it, otherwise, check the state of cond */
724 jexec:
725 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
726 goto jleave0;
728 /* Process the arguments to the command, depending on the type it expects */
729 if(!(cmd->lc_argtype & ARG_M) && (options & OPT_SENDMODE)){
730 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
731 goto jleave;
733 if((cmd->lc_argtype & ARG_S) && !(pstate & PS_STARTED)){
734 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
735 goto jleave;
737 if((cmd->lc_argtype & ARG_I) &&
738 !(options & (OPT_INTERACTIVE | OPT_BATCH_FLAG))){
739 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
740 cmd->lc_name);
741 goto jleave;
743 if(cmd->lc_argtype & ARG_R){
744 if(pstate & PS_RECURSED){
745 /* TODO PS_RECURSED: should allow `reply' in compose mode: ~:reply! */
746 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
747 goto jleave;
749 /* TODO Nothing should prevent ARG_R in conjunction with
750 * TODO PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
751 if(pstate & (PS_ROBOT | PS_SOURCING)){
752 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
753 cmd->lc_name);
754 goto jleave;
758 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
759 n_err(_("May not execute `%s' -- message file is read only\n"),
760 cmd->lc_name);
761 goto jleave;
763 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
764 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
765 goto jleave;
768 if(cmd->lc_argtype & ARG_O)
769 OBSOLETE2(_("this command will be removed"), cmd->lc_name);
770 if(cmd->lc_argtype & ARG_V)
771 temporary_arg_v_store = NULL;
773 if(wysh && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST)
774 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
775 /* TODO v15: strip PS_ARGLIST_MASK off, just in case the actual command
776 * TODO doesn't use any of those list commands which strip this mask,
777 * TODO and for now we misuse bits for checking relation to history;
778 * TODO argument state should be property of a per-command carrier instead */
779 pstate &= ~PS_ARGLIST_MASK;
780 switch(cmd->lc_argtype & ARG_ARGMASK){
781 case ARG_MSGLIST:
782 /* Message list defaulting to nearest forward legal message */
783 if(n_msgvec == NULL)
784 goto je96;
785 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
786 break;
787 if(c == 0){
788 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
789 n_msgvec[1] = 0;
791 if(n_msgvec[0] == 0){
792 if(!(pstate & PS_HOOK_MASK))
793 printf(_("No applicable messages\n"));
794 break;
796 e = (*cmd->lc_func)(n_msgvec);
797 break;
799 case ARG_NDMLIST:
800 /* Message list with no defaults, but no error if none exist */
801 if(n_msgvec == NULL){
802 je96:
803 n_err(_("Invalid use of message list\n"));
804 break;
806 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
807 break;
808 e = (*cmd->lc_func)(n_msgvec);
809 break;
811 case ARG_STRLIST:
812 /* Just the straight string, with leading blanks removed */
813 while(whitechar(*cp))
814 ++cp;
815 e = (*cmd->lc_func)(cp);
816 break;
818 case ARG_WYSHLIST:
819 c = 1;
820 if(0){
821 /* FALLTHRU */
822 case ARG_WYRALIST:
823 c = wysh ? 1 : 0;
824 if(0){
825 case ARG_RAWLIST:
826 c = 0;
830 if((c = getrawlist((c != 0), arglist, n_NELEM(arglist), cp, line.l)) < 0){
831 n_err(_("Invalid argument list\n"));
832 break;
834 if(c < cmd->lc_minargs){
835 n_err(_("`%s' requires at least %d arg(s)\n"),
836 cmd->lc_name, cmd->lc_minargs);
837 break;
839 #undef lc_minargs
840 if(c > cmd->lc_maxargs){
841 n_err(_("`%s' takes no more than %d arg(s)\n"),
842 cmd->lc_name, cmd->lc_maxargs);
843 break;
845 #undef lc_maxargs
846 e = (*cmd->lc_func)(arglist);
847 break;
849 case ARG_NOLIST:
850 /* Just the constant zero, for exiting, eg. */
851 e = (*cmd->lc_func)(0);
852 break;
854 default:
855 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
856 cmd->lc_argtype & ARG_ARGMASK); )
857 goto jleave0;
860 if(e == 0 && (cmd->lc_argtype & ARG_V) &&
861 (cp = temporary_arg_v_store) != NULL){
862 temporary_arg_v_store = NULL;
863 evp->le_new_content = cp;
864 goto jleave0;
866 if(!(cmd->lc_argtype & ARG_H))
867 evp->le_add_history = (((cmd->lc_argtype & ARG_G) ||
868 (pstate & PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
870 jleave:
871 /* C99 */{
872 bool_t reset = !(pstate & PS_ROOT);
874 pstate |= PS_ROOT;
875 ok_vset(_exit_status, (e == 0 ? "0" : "1")); /* TODO num=1 +real value! */
876 if(reset)
877 pstate &= ~PS_ROOT;
880 /* Exit the current source file on error TODO what a mess! */
881 if(e == 0)
882 pstate &= ~PS_EVAL_ERROR;
883 else{
884 pstate |= PS_EVAL_ERROR;
885 if(e < 0 || (pstate & PS_ROBOT)){ /* FIXME */
886 e = 1;
887 goto jret;
889 goto jret0;
892 if(cmd == NULL)
893 goto jret0;
894 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint))
895 if(visible(dot)){
896 line.s = savestr("type");
897 line.l = sizeof("type") -1;
898 gp = (struct a_lex_ghost*)-1; /* Avoid `ghost' interpretation */
899 goto jrestart;
902 if(!(pstate & (PS_SOURCING | PS_HOOK_MASK)) && !(cmd->lc_argtype & ARG_T))
903 pstate |= PS_SAW_COMMAND;
904 jleave0:
905 pstate &= ~PS_EVAL_ERROR;
906 jret0:
907 e = 0;
908 jret:
910 fprintf(stderr, "a_lex_evaluate returns %d for <%s>\n",e,line.s);
912 NYD_LEAVE;
913 return e;
916 static struct a_lex_cmd const *
917 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
918 struct a_lex_cmd const *cp;
919 NYD2_ENTER;
921 for(cp = a_lex_cmd_tab;
922 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
923 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
924 goto jleave;
925 cp = NULL;
926 jleave:
927 NYD2_LEAVE;
928 return cp;
931 static void
932 a_lex_hangup(int s){
933 NYD_X; /* Signal handler */
934 n_UNUSED(s);
935 /* nothing to do? */
936 exit(EXIT_ERR);
939 static void
940 a_lex_onintr(int s){ /* TODO block signals while acting */
941 NYD_X; /* Signal handler */
942 n_UNUSED(s);
944 safe_signal(SIGINT, a_lex_onintr);
946 termios_state_reset();
947 close_all_files(); /* FIXME .. of current level ONLU! */
948 if(image >= 0){
949 close(image);
950 image = -1;
953 a_lex_unstack(TRUM1);
955 if(interrupts != 1)
956 n_err_sighdl(_("Interrupt\n"));
957 safe_signal(SIGPIPE, a_lex_oldpipe);
958 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
961 static void
962 a_lex_unstack(bool_t eval_error){
963 struct a_lex_input_stack *lip;
964 NYD_ENTER;
966 if((lip = a_lex_input) == NULL){
967 n_memory_reset();
969 /* If called from a_lex_onintr(), be silent FIXME */
970 pstate &= ~(PS_SOURCING | PS_ROBOT);
971 if(eval_error == TRUM1 || !(pstate & PS_STARTED))
972 goto jleave;
973 goto jerr;
976 if(lip->li_flags & a_LEX_MACRO){
977 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
978 char **lp;
980 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
981 free(*lp);
982 ++lip->li_loff;
984 /* Part of lip's memory chunk, then */
985 if(!(lip->li_flags & a_LEX_MACRO_CMD))
986 free(lip->li_lines);
988 }else{
989 if(lip->li_flags & a_LEX_PIPE)
990 /* XXX command manager should -TERM then -KILL instead of hoping
991 * XXX for exit of provider due to EPIPE / SIGPIPE */
992 Pclose(lip->li_file, TRU1);
993 else
994 Fclose(lip->li_file);
997 if(!condstack_take(lip->li_cond)){
998 n_err(_("Unmatched `if' at end of %s %s\n"),
999 ((lip->li_flags & a_LEX_MACRO
1000 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1001 : _("`source'd file"))),
1002 lip->li_name);
1003 eval_error = TRU1;
1006 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1008 /* XXX We need some kind of "is real macro" instead of that */
1009 if((lip->li_flags & (a_LEX_MACRO | a_LEX_MACRO_X_OPTION | a_LEX_MACRO_CMD))
1010 == a_LEX_MACRO && lip->li_macro_on_finalize != NULL)
1011 (*lip->li_macro_on_finalize)(lip->li_macro_finalize_arg);
1013 if((a_lex_input = lip->li_outer) == NULL){
1014 pstate &= ~(PS_SOURCING | PS_ROBOT);
1015 }else{
1016 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1017 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1018 pstate &= ~PS_SOURCING;
1019 assert(pstate & PS_ROBOT);
1022 if(eval_error)
1023 goto jerr;
1024 jleave:
1025 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1026 free(lip);
1027 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1028 a_lex_unstack(TRUM1);
1029 NYD_LEAVE;
1030 return;
1032 jerr:
1033 if(lip != NULL){
1034 if(options & OPT_D_V)
1035 n_alert(_("Stopped %s %s due to errors%s"),
1036 (pstate & PS_STARTED
1037 ? (lip->li_flags & a_LEX_MACRO
1038 ? (lip->li_flags & a_LEX_MACRO_CMD
1039 ? _("evaluating command") : _("evaluating macro"))
1040 : (lip->li_flags & a_LEX_PIPE
1041 ? _("executing `source'd pipe")
1042 : _("loading `source'd file")))
1043 : (lip->li_flags & a_LEX_MACRO
1044 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1045 ? _("evaluating command line") : _("evaluating macro"))
1046 : _("loading initialization resource"))),
1047 lip->li_name,
1048 (options & OPT_DEBUG ? n_empty : _(" (enable *debug* for trace)")));
1051 if(!(options & OPT_INTERACTIVE) && !(pstate & PS_STARTED)){
1052 if(options & OPT_D_V)
1053 n_alert(_("Non-interactive, bailing out due to errors "
1054 "in startup load phase"));
1055 exit(EXIT_ERR);
1057 goto jleave;
1060 static bool_t
1061 a_lex_source_file(char const *file, bool_t silent_error){
1062 struct a_lex_input_stack *lip;
1063 size_t nlen;
1064 char *nbuf;
1065 bool_t ispipe;
1066 FILE *fip;
1067 NYD_ENTER;
1069 fip = NULL;
1071 /* Being a command argument file is space-trimmed *//* TODO v15 with
1072 * TODO WYRALIST this is no longer necessary true, and for that we
1073 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1074 #if 0
1075 ((ispipe = (!silent_error && (nlen = strlen(file)) > 0 &&
1076 file[--nlen] == '|')))
1077 #else
1078 ispipe = FAL0;
1079 if(!silent_error)
1080 for(nlen = strlen(file); nlen > 0;){
1081 char c;
1083 c = file[--nlen];
1084 if(!blankchar(c)){
1085 if(c == '|'){
1086 nbuf = savestrbuf(file, nlen);
1087 ispipe = TRU1;
1088 break;
1092 #endif
1094 if(ispipe){
1095 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1096 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL){
1097 if(!silent_error || (options & OPT_D_V))
1098 n_perr(nbuf, 0);
1099 goto jleave;
1101 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1102 goto jleave;
1103 else if((fip = Fopen(nbuf, "r")) == NULL){
1104 if(!silent_error || (options & OPT_D_V))
1105 n_perr(nbuf, 0);
1106 goto jleave;
1109 lip = smalloc(sizeof(*lip) -
1110 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1111 (nlen = strlen(nbuf) +1));
1112 lip->li_outer = a_lex_input;
1113 lip->li_file = fip;
1114 lip->li_cond = condstack_release();
1115 n_memory_autorec_push(&lip->li_autorecmem[0]);
1116 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1117 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1118 ? a_LEX_SUPER_MACRO : 0);
1119 memcpy(lip->li_name, nbuf, nlen);
1121 pstate |= PS_SOURCING | PS_ROBOT;
1122 a_lex_input = lip;
1123 a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC);
1124 /* FIXME return TRUM1 if file can't be opened, FAL0 on eval error */
1125 jleave:
1126 NYD_LEAVE;
1127 return silent_error ? TRU1 : (fip != NULL);
1130 static bool_t
1131 a_lex_load(struct a_lex_input_stack *lip){
1132 bool_t rv;
1133 NYD2_ENTER;
1135 assert(!(pstate & PS_STARTED));
1136 assert(a_lex_input == NULL);
1138 /* POSIX:
1139 * Any errors in the start-up file shall either cause mailx to terminate
1140 * with a diagnostic message and a non-zero status or to continue after
1141 * writing a diagnostic message, ignoring the remainder of the lines in
1142 * the start-up file. */
1143 lip->li_cond = condstack_release();
1144 n_memory_autorec_push(&lip->li_autorecmem[0]);
1146 /* FIXME won't work for now (PS_ROBOT needs PS_SOURCING anyway)
1147 pstate |= PS_ROBOT |
1148 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : PS_SOURCING);
1150 pstate |= PS_ROBOT | PS_SOURCING;
1151 if(options & OPT_D_V)
1152 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1153 a_lex_input = lip;
1154 if(!(rv = n_commands())){
1155 if(!(options & OPT_INTERACTIVE)){
1156 if(options & OPT_D_V)
1157 n_alert(_("Non-interactive program mode, forced exit"));
1158 exit(EXIT_ERR);
1161 /* PS_EXIT handled by callers */
1162 NYD2_LEAVE;
1163 return rv;
1166 static void
1167 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1168 NYD_X; /* Signal handler */
1169 n_UNUSED(sig);
1170 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1173 static bool_t
1174 a_commands_recursive(enum n_lexinput_flags lif){
1175 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1176 sighandler_type soldhdl;
1177 sigset_t sintset, soldset;
1178 struct a_lex_eval_ctx ev;
1179 bool_t rv;
1180 NYD2_ENTER;
1182 memset(&ev, 0, sizeof ev);
1184 sigfillset(&sintset);
1185 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1186 hadint = FAL0;
1187 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1188 safe_signal(SIGINT, &a_lex__cmdrecint);
1189 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1190 hadint = TRU1;
1191 goto jjump;
1194 sigprocmask(SIG_SETMASK, &soldset, NULL);
1196 n_COLOUR( n_colour_env_push(); )
1197 rv = TRU1;
1198 for(;;){
1199 int n;
1201 /* Read a line of commands and handle end of file specially */
1202 ev.le_line.l = ev.le_line_size;
1203 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l,
1204 ev.le_new_content);
1205 ev.le_line_size = (ui32_t)ev.le_line.l;
1206 ev.le_line.l = (ui32_t)n;
1208 if(n < 0)
1209 break;
1211 if(a_lex_evaluate(&ev)){
1212 rv = FAL0;
1213 break;
1215 n_memory_reset();
1217 if((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)){
1218 if(exit_status != EXIT_OK)
1219 break;
1222 jjump: /* TODO */
1223 a_lex_unstack(!rv);
1224 n_COLOUR( n_colour_env_pop(FAL0); )
1226 if(ev.le_line.s != NULL)
1227 free(ev.le_line.s);
1229 if(soldhdl != SIG_IGN)
1230 safe_signal(SIGINT, soldhdl);
1231 NYD2_LEAVE;
1232 if(hadint){
1233 sigprocmask(SIG_SETMASK, &soldset, NULL);
1234 n_raise(SIGINT);
1236 return rv;
1239 FL bool_t
1240 n_commands(void){ /* FIXME */
1241 struct a_lex_eval_ctx ev;
1242 int n;
1243 bool_t volatile rv;
1244 NYD_ENTER;
1246 rv = TRU1;
1248 if (!(pstate & PS_SOURCING)) {
1249 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1250 safe_signal(SIGINT, &a_lex_onintr);
1251 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1252 safe_signal(SIGHUP, &a_lex_hangup);
1254 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1255 safe_signal(SIGPIPE, a_lex_oldpipe);
1257 memset(&ev, 0, sizeof ev);
1259 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1260 for (;;) {
1261 char *temporary_orig_line; /* XXX eval_ctx.le_line not yet constant */
1263 n_COLOUR( n_colour_env_pop(TRU1); )
1265 /* TODO Unless we have our signal manager (or however we do it) child
1266 * TODO processes may have time slots where their execution isn't
1267 * TODO protected by signal handlers (in between start and setup
1268 * TODO completed). close_all_files() is only called from onintr()
1269 * TODO so those may linger possibly forever */
1270 if(!(pstate & PS_SOURCING))
1271 close_all_files();
1273 interrupts = 0;
1275 temporary_localopts_free(); /* XXX intermediate hack */
1277 n_memory_reset();
1279 if (!(pstate & PS_SOURCING)) {
1280 char *cp;
1282 /* TODO Note: this buffer may contain a password. We should redefine
1283 * TODO the code flow which has to do that */
1284 if ((cp = termios_state.ts_linebuf) != NULL) {
1285 termios_state.ts_linebuf = NULL;
1286 termios_state.ts_linesize = 0;
1287 free(cp); /* TODO pool give-back */
1289 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1290 if (ev.le_line.l > LINESIZE * 3) {
1291 free(ev.le_line.s); /* TODO pool! but what? */
1292 ev.le_line.s = NULL;
1293 ev.le_line.l = ev.le_line_size = 0;
1297 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1298 char *cp;
1300 cp = ok_vlook(newmail);
1301 if ((options & OPT_TTYIN) && cp != NULL) {
1302 struct stat st;
1304 /* FIXME TEST WITH NOPOLL ETC. !!! */
1305 n = (cp != NULL && strcmp(cp, "nopoll"));
1306 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1307 st.st_size > mailsize) ||
1308 (mb.mb_type == MB_MAILDIR && n != 0)) {
1309 size_t odot = PTR2SIZE(dot - message);
1310 ui32_t odid = (pstate & PS_DID_PRINT_DOT);
1312 if (setfile(mailname,
1313 FEDIT_NEWMAIL |
1314 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1315 exit_status |= EXIT_ERR;
1316 rv = FAL0;
1317 break;
1319 dot = message + odot;
1320 pstate |= odid;
1324 exit_status = EXIT_OK;
1327 /* Read a line of commands and handle end of file specially */
1328 jreadline:
1329 ev.le_line.l = ev.le_line_size;
1330 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1331 &ev.le_line.s, &ev.le_line.l, ev.le_new_content);
1332 ev.le_line_size = (ui32_t)ev.le_line.l;
1333 ev.le_line.l = (ui32_t)n;
1335 if (n < 0) {
1336 /* FIXME did unstack() when PS_SOURCING, only break with PS_LOADING*/
1337 if (!(pstate & PS_ROBOT) &&
1338 (options & OPT_INTERACTIVE) && ok_blook(ignoreeof)) {
1339 printf(_("*ignoreeof* set, use `quit' to quit.\n"));
1340 n_msleep(500, FAL0);
1341 continue;
1343 break;
1346 temporary_orig_line = ((pstate & PS_SOURCING) ||
1347 !(options & OPT_INTERACTIVE)) ? NULL
1348 : savestrbuf(ev.le_line.s, ev.le_line.l);
1349 pstate &= ~PS_HOOK_MASK;
1350 if (a_lex_evaluate(&ev)) {
1351 if (!(pstate & PS_STARTED)) /* TODO mess; join PS_EVAL_ERROR.. */
1352 rv = FAL0;
1353 break;
1356 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
1357 if (exit_status != EXIT_OK)
1358 break;
1359 if ((pstate & (PS_SOURCING | PS_EVAL_ERROR)) == PS_EVAL_ERROR) {
1360 exit_status = EXIT_ERR;
1361 break;
1364 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1365 if (ev.le_new_content != NULL)
1366 goto jreadline;
1367 /* *Can* happen since _evaluate() n_unstack()s on error! XXX no more */
1368 if (temporary_orig_line != NULL)
1369 n_tty_addhist(temporary_orig_line, (ev.le_add_history != TRU1));
1372 if(pstate & PS_EXIT)
1373 break;
1376 a_lex_unstack(!rv);
1378 if (ev.le_line.s != NULL)
1379 free(ev.le_line.s);
1380 NYD_LEAVE;
1381 return rv;
1384 FL int
1385 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1386 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1387 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1388 struct n_string xprompt;
1389 FILE *ifile;
1390 bool_t doprompt, dotty;
1391 char const *iftype;
1392 int n, nold;
1393 NYD2_ENTER;
1395 /* Special case macro mode: never need to prompt, lines have always been
1396 * unfolded already */
1397 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1398 if(*linebuf != NULL)
1399 free(*linebuf);
1401 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1402 *linesize = 0;
1403 n = -1;
1404 goto jleave;
1407 ++a_lex_input->li_loff;
1408 *linesize = strlen(*linebuf);
1409 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1410 *linebuf = sbufdup(*linebuf, *linesize);
1412 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1413 ? "-X OPTION" : "MACRO";
1414 n = (int)*linesize;
1415 pstate |= PS_READLINE_NL;
1416 goto jhave_dat;
1418 pstate &= ~PS_READLINE_NL;
1420 iftype = (!(pstate & PS_STARTED) ? "LOAD"
1421 : (pstate & PS_SOURCING) ? "SOURCE" : "READ");
1422 doprompt = ((pstate & (PS_STARTED | PS_ROBOT)) == PS_STARTED &&
1423 (options & OPT_INTERACTIVE));
1424 dotty = (doprompt && !ok_blook(line_editor_disable));
1425 if(!doprompt)
1426 lif |= n_LEXINPUT_PROMPT_NONE;
1427 else{
1428 if(!dotty)
1429 n_string_creat_auto(&xprompt);
1430 if(prompt == NULL)
1431 lif |= n_LEXINPUT_PROMPT_EVAL;
1434 /* Ensure stdout is flushed first anyway */
1435 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1436 fflush(stdout);
1438 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : stdin;
1439 assert(ifile != NULL);
1441 for(nold = n = 0;;){
1442 if(dotty){
1443 assert(ifile == stdin);
1444 if(string != NULL && (n = (int)strlen(string)) > 0){
1445 if(*linesize > 0)
1446 *linesize += n +1;
1447 else
1448 *linesize = (size_t)n + LINESIZE +1;
1449 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1450 memcpy(*linebuf, string, (size_t)n +1);
1452 string = NULL;
1453 /* TODO if nold>0, don't redisplay the entire line!
1454 * TODO needs complete redesign ... */
1455 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1456 n_MEMORY_DEBUG_ARGSCALL);
1457 }else{
1458 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1459 n_tty_create_prompt(&xprompt, prompt, lif);
1460 if(xprompt.s_len > 0){
1461 fwrite(xprompt.s_dat, 1, xprompt.s_len, stdout);
1462 fflush(stdout);
1466 n = (readline_restart)(ifile, linebuf, linesize, n
1467 n_MEMORY_DEBUG_ARGSCALL);
1469 if(n > 0 && nold > 0){
1470 int i = 0;
1471 char const *cp = *linebuf + nold;
1473 while(blankspacechar(*cp) && nold + i < n)
1474 ++cp, ++i;
1475 if(i > 0){
1476 memmove(*linebuf + nold, cp, n - nold - i);
1477 n -= i;
1478 (*linebuf)[n] = '\0';
1483 if(n <= 0)
1484 break;
1486 /* POSIX says:
1487 * An unquoted <backslash> at the end of a command line shall
1488 * be discarded and the next line shall continue the command */
1489 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1490 if(dotty)
1491 pstate |= PS_READLINE_NL;
1492 break;
1494 /* Definitely outside of quotes, thus the quoting rules are so that an
1495 * uneven number of successive backslashs at EOL is a continuation */
1496 if(n > 1){
1497 size_t i, j;
1499 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1500 if((*linebuf)[i] != '\\')
1501 break;
1502 if(!(j & 1))
1503 break;
1505 (*linebuf)[nold = --n] = '\0';
1506 lif |= n_LEXINPUT_NL_FOLLOW;
1509 if(n < 0)
1510 goto jleave;
1511 (*linebuf)[*linesize = n] = '\0';
1513 jhave_dat:
1514 #if 0
1515 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1516 char *cp, c;
1517 size_t i;
1519 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1520 c = *--cp;
1521 if(!blankspacechar(c))
1522 break;
1524 (*linebuf)[n = (int)i] = '\0';
1527 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1528 char *cp, c;
1529 size_t j, i;
1531 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1532 c = *cp++;
1533 if(!blankspacechar(c))
1534 break;
1536 if(i > 0){
1537 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1538 (*linebuf)[n = (int)j] = '\0';
1541 #endif /* 0 (notyet - must take care for backslash escaped space) */
1543 if(options & OPT_D_VV)
1544 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1545 jleave:
1546 if (pstate & PS_PSTATE_PENDMASK)
1547 a_lex_update_pstate();
1548 NYD2_LEAVE;
1549 return n;
1552 FL char *
1553 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1554 char const *string){
1555 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1556 size_t linesize;
1557 char *linebuf, *rv;
1558 int n;
1559 NYD2_ENTER;
1561 linesize = 0;
1562 linebuf = NULL;
1563 rv = NULL;
1565 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1566 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1567 (lif & n_LEXINPUT_HIST_ADD) && (options & OPT_INTERACTIVE))
1568 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1570 if(linebuf != NULL)
1571 free(linebuf);
1572 NYD2_LEAVE;
1573 return rv;
1576 FL void
1577 n_load(char const *name){
1578 struct a_lex_input_stack *lip;
1579 size_t i;
1580 FILE *fip;
1581 NYD_ENTER;
1583 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1584 goto jleave;
1586 i = strlen(name) +1;
1587 lip = scalloc(1, sizeof(*lip) -
1588 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) + i);
1589 lip->li_file = fip;
1590 lip->li_flags = a_LEX_FREE;
1591 memcpy(lip->li_name, name, i);
1593 a_lex_load(lip);
1594 pstate &= ~PS_EXIT;
1595 jleave:
1596 NYD_LEAVE;
1599 FL void
1600 n_load_Xargs(char const **lines, size_t cnt){
1601 static char const name[] = "-X";
1603 ui8_t buf[sizeof(struct a_lex_input_stack) + sizeof name];
1604 char const *srcp, *xsrcp;
1605 char *cp;
1606 size_t imax, i, len;
1607 struct a_lex_input_stack *lip;
1608 NYD_ENTER;
1610 memset(buf, 0, sizeof buf);
1611 lip = (void*)buf;
1612 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1613 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1614 memcpy(lip->li_name, name, sizeof name);
1616 /* The problem being that we want to support reverse solidus newline
1617 * escaping also within multiline -X, i.e., POSIX says:
1618 * An unquoted <backslash> at the end of a command line shall
1619 * be discarded and the next line shall continue the command
1620 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
1621 * entire lines array and set _MACRO_FREE_DATA */
1622 imax = cnt + 1;
1623 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
1625 /* For each of the input lines.. */
1626 for(i = len = 0, cp = NULL; cnt > 0;){
1627 bool_t keep;
1628 size_t j;
1630 if((j = strlen(srcp = *lines)) == 0){
1631 ++lines, --cnt;
1632 continue;
1635 /* Separate one line from a possible multiline input string */
1636 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1637 *lines = &xsrcp[1];
1638 j = PTR2SIZE(xsrcp - srcp);
1639 }else
1640 ++lines, --cnt;
1642 /* The (separated) string may itself indicate soft newline escaping */
1643 if((keep = (srcp[j - 1] == '\\'))){
1644 size_t xj, xk;
1646 /* Need an uneven number of reverse solidus */
1647 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1648 if(srcp[xj] != '\\')
1649 break;
1650 if(xk & 1)
1651 --j;
1652 else
1653 keep = FAL0;
1656 /* Strip any leading WS from follow lines, then */
1657 if(cp != NULL)
1658 while(j > 0 && blankspacechar(*srcp))
1659 ++srcp, --j;
1661 if(j > 0){
1662 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1663 imax += 4;
1664 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
1665 imax);
1667 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
1668 memcpy(&cp[len], srcp, j);
1669 cp[len += j] = '\0';
1671 if(!keep)
1672 ++i;
1674 if(!keep)
1675 cp = NULL, len = 0;
1677 if(cp != NULL){
1678 assert(i + 1 < imax);
1679 lip->li_lines[i++] = cp;
1681 lip->li_lines[i] = NULL;
1683 a_lex_load(lip);
1684 if(pstate & PS_EXIT)
1685 exit(EXIT_OK);
1686 NYD_LEAVE;
1689 FL int
1690 c_source(void *v){
1691 int rv;
1692 NYD_ENTER;
1694 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1695 NYD_LEAVE;
1696 return rv;
1699 FL int
1700 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1701 int rv;
1702 NYD_ENTER;
1704 rv = (a_lex_source_file(*(char**)v, TRU1) != FAL0) ? 0 : 1;
1705 NYD_LEAVE;
1706 return rv;
1709 FL bool_t
1710 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
1711 void (*on_finalize)(void*), void *finalize_arg){
1712 struct a_lex_input_stack *lip;
1713 size_t i;
1714 int rv;
1715 NYD_ENTER;
1717 lip = smalloc(sizeof(*lip) -
1718 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1719 (i = strlen(name) +1));
1720 lip->li_outer = a_lex_input;
1721 lip->li_file = NULL;
1722 lip->li_cond = condstack_release();
1723 n_memory_autorec_push(&lip->li_autorecmem[0]);
1724 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1725 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1726 ? a_LEX_SUPER_MACRO : 0);
1727 lip->li_loff = 0;
1728 lip->li_lines = lines;
1729 lip->li_macro_on_finalize = on_finalize;
1730 lip->li_macro_finalize_arg = finalize_arg;
1731 memcpy(lip->li_name, name, i);
1733 pstate |= PS_ROBOT;
1734 a_lex_input = lip;
1735 rv = a_commands_recursive(lif);
1736 NYD_LEAVE;
1737 return rv;
1740 FL bool_t
1741 n_source_command(enum n_lexinput_flags lif, char const *cmd){
1742 struct a_lex_input_stack *lip;
1743 size_t i, ial;
1744 bool_t rv;
1745 NYD_ENTER;
1747 i = strlen(cmd);
1748 cmd = sbufdup(cmd, i++); /* XXX Unfortunately need to dup cmd :( */
1749 ial = n_ALIGN(i);
1751 lip = smalloc(sizeof(*lip) -
1752 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1753 ial + 2*sizeof(char*));
1754 lip->li_outer = a_lex_input;
1755 lip->li_file = NULL;
1756 lip->li_cond = condstack_release();
1757 n_memory_autorec_push(&lip->li_autorecmem[0]);
1758 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1759 a_LEX_MACRO_CMD |
1760 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1761 ? a_LEX_SUPER_MACRO : 0);
1762 lip->li_loff = 0;
1763 lip->li_lines = (void*)(lip->li_name + ial);
1764 lip->li_lines[0] = n_UNCONST(cmd); /* dup'ed above */
1765 lip->li_lines[1] = NULL;
1766 memcpy(lip->li_name, cmd, i);
1768 pstate |= PS_ROBOT;
1769 a_lex_input = lip;
1770 rv = a_commands_recursive(lif);
1771 NYD_LEAVE;
1772 return rv;
1775 FL bool_t
1776 n_source_may_yield_control(void){
1777 return ((options & OPT_INTERACTIVE) &&
1778 (pstate & PS_STARTED) &&
1779 (!(pstate & PS_ROBOT) || (pstate & PS_RECURSED)) && /* Ok for ~: */
1780 (a_lex_input == NULL || a_lex_input->li_outer == NULL));
1783 /* s-it-mode */