Add n_shexp_is_valid_varname()
[s-mailx.git] / lex_input.c
blobbcb1f4a7010f98d6d83e7db5863aa5f1ecbae03c
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 /* TODO For simplicity this is yet _MACRO plus specialization overlay
51 * TODO (_X_OPTION, _CMD) -- these should be types on their own! */
52 a_LEX_MACRO_X_OPTION = 1<<4, /* Macro indeed command line -X option */
53 a_LEX_MACRO_CMD = 1<<5, /* Macro indeed single-line: ~:COMMAND */
54 /* TODO a_LEX_SLICE: the right way to support *on-compose-done-shell* would
55 * TODO be a command_loop object that emits an on_read_line event, and
56 * TODO have a special handler for the compose mode; with that, then,
57 * TODO commands_recursive() would not call lex_evaluate() but
58 * TODO CTX->on_read_line, and lex_evaluate() would be the standard impl.,
59 * TODO whereas the COMMAND ESCAPE switch in collect.c would be another one.
60 * TODO With this generic approach accmacvar.c:call_compose_mode_hook()
61 * TODO could be dropped, and n_source_macro() could become extended,
62 * TODO and/or we would add a n_source_anything(), which would allow special
63 * TODO input handlers, special I/O input and output, special `localopts'
64 * TODO etc., to be glued to the new execution context. And all I/O all
65 * TODO over this software should not use stdin/stdout, but CTX->in/out.
66 * TODO The pstate must be a property of the current execution context, too.
67 * TODO This not today. :( For now we invent a special SLICE execution
68 * TODO context overlay that at least allows to temporarily modify the
69 * TODO global pstate, and the global stdin and stdout pointers. HACK!
70 * TODO This slice thing is very special and has to go again. HACK!!
71 * TODO a_lex_input() will drop it once it sees EOF (HACK!), but care for
72 * TODO jumps must be taken by slice creators. HACK!!! But works. ;} */
73 a_LEX_SLICE = 1<<6,
75 a_LEX_SUPER_MACRO = 1<<16 /* *Not* inheriting PS_SOURCING state */
78 struct a_lex_cmd{
79 char const *lc_name; /* Name of command */
80 int (*lc_func)(void*); /* Implementor of command */
81 enum argtype lc_argtype; /* Arglist type (see below) */
82 si16_t lc_msgflag; /* Required flags of msgs */
83 si16_t lc_msgmask; /* Relevant flags of msgs */
84 #ifdef HAVE_DOCSTRINGS
85 char const *lc_doc; /* One line doc for command */
86 #endif
88 /* Yechh, can't initialize unions */
89 #define lc_minargs lc_msgflag /* Minimum argcount for RAWLIST */
90 #define lc_maxargs lc_msgmask /* Max argcount for RAWLIST */
92 struct a_lex_ghost{
93 struct a_lex_ghost *lg_next;
94 struct str lg_cmd; /* Data follows after .lg_name */
95 char lg_name[n_VFIELD_SIZE(0)];
98 struct a_lex_eval_ctx{
99 struct str le_line; /* The terminated data to _evaluate() */
100 ui32_t le_line_size; /* May be used to store line memory size */
101 bool_t le_is_recursive; /* Evaluation in evaluation? (collect ~:) */
102 ui8_t __dummy[3];
103 bool_t le_add_history; /* Add command to history (TRUM1=gabby)? */
104 char const *le_new_content; /* History: reenter line, start with this */
107 struct a_lex_input_stack{
108 struct a_lex_input_stack *li_outer;
109 FILE *li_file; /* File we were in */
110 void *li_cond; /* Saved state of conditional stack */
111 ui32_t li_flags; /* enum a_lex_input_flags */
112 ui32_t li_loff; /* Pseudo (macro): index in .li_lines */
113 char **li_lines; /* Pseudo content, lines unfolded */
114 void (*li_on_finalize)(void *);
115 void *li_finalize_arg;
116 char li_autorecmem[n_MEMORY_AUTOREC_TYPE_SIZEOF];
117 sigjmp_buf li_cmdrec_jmp; /* TODO one day... for command_recursive */
118 /* SLICE hacks: saved stdin/stdout, saved pstate */
119 FILE *li_slice_stdin;
120 FILE *li_slice_stdout;
121 ui32_t li_slice_options;
122 ui8_t li_slice__dummy[4];
123 char li_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
125 n_CTA(n_MEMORY_AUTOREC_TYPE_SIZEOF % sizeof(void*) == 0,
126 "Inacceptible size of structure buffer");
128 static sighandler_type a_lex_oldpipe;
129 static struct a_lex_ghost *a_lex_ghosts;
130 /* a_lex_cmd_tab[] after fun protos */
132 /* */
133 static struct a_lex_input_stack *a_lex_input;
135 static sigjmp_buf a_lex_srbuf; /* TODO GET RID */
137 /* Isolate the command from the arguments */
138 static char *a_lex_isolate(char const *comm);
140 /* Command ghost handling */
141 static int a_lex_c_ghost(void *v);
142 static int a_lex_c_unghost(void *v);
144 /* Print a list of all commands */
145 static int a_lex_c_list(void *v);
147 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
149 /* `help' / `?' command */
150 static int a_lex_c_help(void *v);
152 /* `quit' command */
153 static int a_lex_c_quit(void *v);
155 /* Print the binaries version number */
156 static int a_lex_c_version(void *v);
158 static int a_lex__version_cmp(void const *s1, void const *s2);
160 /* PS_STATE_PENDMASK requires some actions */
161 static void a_lex_update_pstate(void);
163 /* Evaluate a single command.
164 * .le_add_history and .le_new_content will be updated upon success.
165 * Command functions return 0 for success, 1 for error, and -1 for abort.
166 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
167 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
169 /* Get first-fit, or NULL */
170 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
172 /* Branch here on hangup signal and simulate "exit" */
173 static void a_lex_hangup(int s);
175 /* The following gets called on receipt of an interrupt. Close all open files
176 * except 0, 1, 2, and the temporary. Also, unstack all source files */
177 static void a_lex_onintr(int s);
179 /* Pop the current input back to the previous level. Update the program state.
180 * If the argument is TRUM1 then we don't alert and error out if the stack
181 * doesn't exist at all */
182 static void a_lex_unstack(bool_t eval_error);
184 /* `source' and `source_if' (if silent_error: no pipes allowed, then) */
185 static bool_t a_lex_source_file(char const *file, bool_t silent_error);
187 /* System resource file load()ing or -X command line option array traversal */
188 static bool_t a_lex_load(struct a_lex_input_stack *lip);
190 /* A simplified command loop for recursed state machines */
191 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
193 /* List of all commands, and list of commands which are specially treated
194 * and deduced in _evaluate(), but we need a list for _c_list() and
195 * print_comm_docstr() */
196 #ifdef HAVE_DOCSTRINGS
197 # define DS(S) , S
198 #else
199 # define DS(S)
200 #endif
201 static struct a_lex_cmd const a_lex_cmd_tab[] = {
202 #include "cmd_tab.h"
204 a_lex_special_cmd_tab[] = {
205 { "#", NULL, 0, 0, 0
206 DS(N_("Comment command: ignore remaining (continuable) line")) },
207 { "-", NULL, 0, 0, 0
208 DS(N_("Print out the preceding message")) }
210 #undef DS
212 static char *
213 a_lex_isolate(char const *comm){
214 NYD2_ENTER;
215 while(*comm != '\0' &&
216 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
217 ++comm;
218 NYD2_LEAVE;
219 return n_UNCONST(comm);
222 static int
223 a_lex_c_ghost(void *v){
224 struct a_lex_ghost *lgp, *gp;
225 size_t i, cl, nl;
226 char *cp;
227 char const **argv;
228 NYD_ENTER;
230 argv = v;
232 /* Show the list? */
233 if(*argv == NULL){
234 FILE *fp;
236 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
237 fp = stdout;
239 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
240 fprintf(fp, "wysh ghost %s %s\n",
241 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
243 if(fp != stdout){
244 page_or_print(fp, i);
245 Fclose(fp);
247 goto jleave;
250 /* Verify the ghost name is a valid one */
251 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0'){
252 n_err(_("`ghost': can't canonicalize %s\n"),
253 n_shexp_quote_cp(argv[0], FAL0));
254 v = NULL;
255 goto jleave;
258 /* Show command of single ghost? */
259 if(argv[1] == NULL){
260 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
261 if(!strcmp(argv[0], gp->lg_name)){
262 printf("wysh ghost %s %s\n",
263 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
264 goto jleave;
266 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
267 v = NULL;
268 goto jleave;
271 /* Define command for ghost: verify command content */
272 for(cl = 0, i = 1; (cp = n_UNCONST(argv[i])) != NULL; ++i)
273 if(*cp != '\0')
274 cl += strlen(cp) +1; /* SP or NUL */
275 if(cl == 0){
276 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
277 v = NULL;
278 goto jleave;
281 /* If the ghost already exists, recreate */
282 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
283 if(!strcmp(gp->lg_name, argv[0])){
284 if(lgp != NULL)
285 lgp->lg_next = gp->lg_next;
286 else
287 a_lex_ghosts = gp->lg_next;
288 free(gp);
289 break;
292 nl = strlen(argv[0]) +1;
293 gp = smalloc(sizeof(*gp) - n_VFIELD_SIZEOF(struct a_lex_ghost, lg_name) +
294 nl + cl);
295 gp->lg_next = a_lex_ghosts;
296 a_lex_ghosts = gp;
297 memcpy(gp->lg_name, argv[0], nl);
298 cp = gp->lg_cmd.s = gp->lg_name + nl;
299 gp->lg_cmd.l = --cl;
301 while(*++argv != NULL)
302 if((i = strlen(*argv)) > 0){
303 memcpy(cp, *argv, i);
304 cp += i;
305 *cp++ = ' ';
307 *--cp = '\0';
308 jleave:
309 NYD_LEAVE;
310 return v == NULL;
313 static int
314 a_lex_c_unghost(void *v){
315 struct a_lex_ghost *lgp, *gp;
316 char const **argv, *cp;
317 int rv;
318 NYD_ENTER;
320 rv = 0;
321 argv = v;
323 while((cp = *argv++) != NULL){
324 if(cp[0] == '*' && cp[1] == '\0'){
325 while((gp = a_lex_ghosts) != NULL){
326 a_lex_ghosts = gp->lg_next;
327 free(gp);
329 }else{
330 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
331 lgp = gp, gp = gp->lg_next)
332 if(!strcmp(gp->lg_name, cp)){
333 if(lgp != NULL)
334 lgp->lg_next = gp->lg_next;
335 else
336 a_lex_ghosts = gp->lg_next;
337 free(gp);
338 goto jouter;
340 n_err(_("`unghost': no such alias: %s\n"),
341 n_shexp_quote_cp(cp, FAL0));
342 rv = 1;
343 jouter: ;
346 NYD_LEAVE;
347 return rv;
350 static int
351 a_lex_c_list(void *v){
352 FILE *fp;
353 struct a_lex_cmd const **cpa, *cp, **cursor;
354 size_t l, i;
355 NYD_ENTER;
357 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
358 cpa = salloc(sizeof(cp) * i);
360 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
361 cpa[i] = &a_lex_cmd_tab[i];
362 /* C99 */{
363 size_t j;
365 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
366 cpa[i] = &a_lex_special_cmd_tab[j];
368 cpa[i] = NULL;
370 /* C99 */{
371 char const *xcp = v;
373 if(*xcp == '\0')
374 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
377 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
378 fp = stdout;
380 fprintf(fp, _("Commands are:\n"));
381 l = 1;
382 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
383 if(cp->lc_func == &c_cmdnotsupp)
384 continue;
385 if(options & OPT_D_V){
386 char const *argt;
388 switch(cp->lc_argtype & ARG_ARGMASK){
389 case ARG_MSGLIST: argt = N_("message-list"); break;
390 case ARG_STRLIST: argt = N_("a \"string\""); break;
391 case ARG_RAWLIST: argt = N_("old-style quoting"); break;
392 case ARG_NOLIST: argt = N_("no arguments"); break;
393 case ARG_NDMLIST: argt = N_("message-list (without a default)"); break;
394 case ARG_WYSHLIST: argt = N_("sh(1)ell-style quoting"); break;
395 default: argt = N_("`wysh' for sh(1)ell-style quoting"); break;
397 #ifdef HAVE_DOCSTRINGS
398 fprintf(fp, _("`%s'. Argument type: %s.\n\t%s\n"),
399 cp->lc_name, V_(argt), V_(cp->lc_doc));
400 l += 2;
401 #else
402 fprintf(fp, "`%s' (%s)\n", cp->lc_name, argt);
403 ++l;
404 #endif
405 }else{
406 size_t j = strlen(cp->lc_name) + 2;
408 if((i += j) > 72){
409 i = j;
410 fprintf(fp, "\n");
411 ++l;
413 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
417 if(fp != stdout){
418 page_or_print(fp, l);
419 Fclose(fp);
421 NYD_LEAVE;
422 return 0;
425 static int
426 a_lex__pcmd_cmp(void const *s1, void const *s2){
427 struct a_lex_cmd const * const *cp1, * const *cp2;
428 int rv;
429 NYD2_ENTER;
431 cp1 = s1;
432 cp2 = s2;
433 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
434 NYD2_LEAVE;
435 return rv;
438 static int
439 a_lex_c_help(void *v){
440 int rv;
441 char *arg;
442 NYD_ENTER;
444 /* Help for a single command? */
445 if((arg = *(char**)v) != NULL){
446 struct a_lex_ghost const *gp;
447 struct a_lex_cmd const *cp, *cpmax;
449 /* Ghosts take precedence */
450 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
451 if(!strcmp(arg, gp->lg_name)){
452 printf("%s -> ", arg);
453 arg = gp->lg_cmd.s;
454 break;
457 cpmax = &(cp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
458 jredo:
459 for(; PTRCMP(cp, <, cpmax); ++cp){
460 #ifdef HAVE_DOCSTRINGS
461 # define a_DS V_(cp->lc_doc)
462 #else
463 # define a_DS n_empty
464 #endif
465 if(!strcmp(arg, cp->lc_name))
466 printf("%s: %s", arg, a_DS);
467 else if(is_prefix(arg, cp->lc_name))
468 printf("%s (%s): %s", arg, cp->lc_name, a_DS);
469 else
470 continue;
472 if(options & OPT_D_V){
473 char const *atp;
475 switch(cp->lc_argtype & ARG_ARGMASK){
476 case ARG_MSGLIST: atp = N_("message-list"); break;
477 case ARG_STRLIST: atp = N_("a \"string\""); break;
478 case ARG_RAWLIST: atp = N_("old-style quoting"); break;
479 case ARG_NOLIST: atp = N_("no arguments"); break;
480 case ARG_NDMLIST: atp = N_("message-list (no default)"); break;
481 case ARG_WYSHLIST: atp = N_("sh(1)ell-style quoting"); break;
482 default: atp = N_("`wysh' for sh(1)ell-style quoting"); break;
484 #ifdef HAVE_DOCSTRINGS
485 printf(_("\n\tArgument type: %s"), V_(atp));
486 #else
487 printf(_("argument type: %s"), V_(atp));
488 #endif
489 #undef a_DS
491 putchar('\n');
492 rv = 0;
493 goto jleave;
496 if(PTRCMP(cpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
497 cpmax = &(cp = a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
498 goto jredo;
501 if(gp != NULL){
502 printf("%s\n", n_shexp_quote_cp(arg, TRU1));
503 rv = 0;
504 }else{
505 n_err(_("Unknown command: `%s'\n"), arg);
506 rv = 1;
508 }else{
509 /* Very ugly, but take care for compiler supported string lengths :( */
510 fputs(progname, stdout);
511 fputs(_(
512 " commands -- <msglist> denotes message specifications,\n"
513 "e.g., 1-5, :n or ., separated by spaces:\n"), stdout);
514 fputs(_(
515 "\n"
516 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
517 "Type <msglist> like `type' but always show all headers\n"
518 "next goto and type next message\n"
519 "from <msglist> (search and) print header summary for the given list\n"
520 "headers header summary for messages surrounding \"dot\"\n"
521 "delete <msglist> delete messages (can be `undelete'd)\n"),
522 stdout);
524 fputs(_(
525 "\n"
526 "save <msglist> folder append messages to folder and mark as saved\n"
527 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
528 "write <msglist> file write message contents to file (prompts for parts)\n"
529 "Reply <msglist> reply to message senders only\n"
530 "reply <msglist> like `Reply', but address all recipients\n"
531 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
532 stdout);
534 fputs(_(
535 "\n"
536 "mail <recipients> compose a mail for the given recipients\n"
537 "file folder change to another mailbox\n"
538 "File folder like `file', but open readonly\n"
539 "quit quit and apply changes to the current mailbox\n"
540 "xit or exit like `quit', but discard changes\n"
541 "!shell command shell escape\n"
542 "list [<anything>] all available commands [in search order]\n"),
543 stdout);
545 rv = (ferror(stdout) != 0);
547 jleave:
548 NYD_LEAVE;
549 return rv;
552 static int
553 a_lex_c_quit(void *v){
554 NYD_ENTER;
555 n_UNUSED(v);
557 /* If we are PS_SOURCING, then return 1 so _evaluate() can handle it.
558 * Otherwise return -1 to abort command loop */
559 pstate |= PS_EXIT;
560 NYD_LEAVE;
561 return 0;
564 static int
565 a_lex_c_version(void *v){
566 int longest, rv;
567 char *iop;
568 char const *cp, **arr;
569 size_t i, i2;
570 NYD_ENTER;
571 n_UNUSED(v);
573 printf(_("%s version %s\nFeatures included (+) or not (-)\n"),
574 uagent, ok_vlook(version));
576 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
577 i = strlen(cp = &ok_vlook(features)[1]) +1;
578 iop = salloc(i);
579 memcpy(iop, cp, i);
581 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
582 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
583 arr[i] = cp;
584 i2 = strlen(cp);
585 longest = n_MAX(longest, (int)i2);
587 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
589 for(++longest, i2 = 0; i-- > 0;){
590 cp = *(arr++);
591 printf("%-*s ", longest, cp);
592 i2 += longest;
593 if(UICMP(z, ++i2 + longest, >=, scrnwidth) || i == 0){
594 i2 = 0;
595 putchar('\n');
599 if((rv = ferror(stdout) != 0))
600 clearerr(stdout);
601 NYD_LEAVE;
602 return rv;
605 static int
606 a_lex__version_cmp(void const *s1, void const *s2){
607 char const * const *cp1, * const *cp2;
608 int rv;
609 NYD2_ENTER;
611 cp1 = s1;
612 cp2 = s2;
613 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
614 NYD2_LEAVE;
615 return rv;
618 static void
619 a_lex_update_pstate(void){
620 NYD_ENTER;
622 if(pstate & PS_SIGWINCH_PEND){
623 char buf[32];
625 snprintf(buf, sizeof buf, "%d", scrnwidth);
626 ok_vset(COLUMNS, buf);
627 snprintf(buf, sizeof buf, "%d", scrnheight);
628 ok_vset(LINES, buf);
631 pstate &= ~PS_PSTATE_PENDMASK;
632 NYD_LEAVE;
635 static int
636 a_lex_evaluate(struct a_lex_eval_ctx *evp){
637 /* xxx old style(9), but also old code */
638 struct str line;
639 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
640 struct a_lex_ghost *gp;
641 struct a_lex_cmd const *cmd;
642 int c, e;
643 bool_t wysh;
644 NYD_ENTER;
646 wysh = FAL0;
647 e = 1;
648 cmd = NULL;
649 gp = NULL;
650 line = evp->le_line; /* XXX don't change original (buffer pointer) */
651 assert(line.s[line.l] == '\0');
652 evp->le_add_history = FAL0;
653 evp->le_new_content = NULL;
655 /* Command ghosts that refer to shell commands or macro expansion restart */
656 jrestart:
658 /* Strip the white space away from end and beginning of command */
659 if(line.l > 0){
660 size_t i = line.l;
662 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
663 --i;
664 line.l = i;
666 for(cp = line.s; spacechar(*cp); ++cp)
668 line.l -= PTR2SIZE(cp - line.s);
670 /* Ignore null commands (comments) */
671 if(*cp == '#')
672 goto jleave0;
674 /* Handle ! differently to get the correct lexical conventions */
675 arglist[0] = cp;
676 if(*cp == '!')
677 ++cp;
678 /* Isolate the actual command; since it may not necessarily be
679 * separated from the arguments (as in `p1') we need to duplicate it to
680 * be able to create a NUL terminated version.
681 * We must be aware of several special one letter commands here */
682 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
683 (*cp == '|' || *cp == '~' || *cp == '?'))
684 ++cp;
685 c = (int)PTR2SIZE(cp - arglist[0]);
686 line.l -= c;
687 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
688 memcpy(word, arglist[0], c);
689 word[c] = '\0';
691 /* Look up the command; if not found, bitch.
692 * Normally, a blank command would map to the first command in the
693 * table; while PS_SOURCING, however, we ignore blank lines to eliminate
694 * confusion; act just the same for ghosts */
695 if(*word == '\0'){
696 if((pstate & PS_ROBOT) || gp != NULL)
697 goto jleave0;
698 cmd = a_lex_cmd_tab + 0;
699 goto jexec;
702 /* XXX It may be the argument parse adjuster */
703 if(!wysh && c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
704 wysh = TRU1;
705 line.s = cp;
706 goto jrestart;
709 /* If this is the first evaluation, check command ghosts */
710 if(gp == NULL){
711 /* TODO relink list head, so it's sorted on usage over time?
712 * TODO in fact, there should be one hashmap over all commands and ghosts
713 * TODO so that the lookup could be made much more efficient than it is
714 * TODO now (two adjacent list searches! */
715 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
716 if(!strcmp(word, gp->lg_name)){
717 if(line.l > 0){
718 size_t i;
720 i = gp->lg_cmd.l;
721 line.s = salloc(i + line.l +1);
722 memcpy(line.s, gp->lg_cmd.s, i);
723 memcpy(line.s + i, cp, line.l);
724 line.s[i += line.l] = '\0';
725 line.l = i;
726 }else{
727 line.s = gp->lg_cmd.s;
728 line.l = gp->lg_cmd.l;
730 goto jrestart;
734 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
735 bool_t s;
737 if(!(s = condstack_isskip()) || (options & OPT_D_V))
738 n_err(_("Unknown command%s: `%s'\n"),
739 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
740 if(s)
741 goto jleave0;
742 if(cmd != NULL){
743 c_cmdnotsupp(NULL);
744 cmd = NULL;
746 goto jleave;
749 /* See if we should execute the command -- if a conditional we always
750 * execute it, otherwise, check the state of cond */
751 jexec:
752 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
753 goto jleave0;
755 /* Process the arguments to the command, depending on the type it expects */
756 if(!(cmd->lc_argtype & ARG_M) && (options & OPT_SENDMODE)){
757 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
758 goto jleave;
760 if((cmd->lc_argtype & ARG_S) && !(pstate & PS_STARTED)){
761 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
762 goto jleave;
764 if((cmd->lc_argtype & ARG_I) &&
765 !(options & (OPT_INTERACTIVE | OPT_BATCH_FLAG))){
766 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
767 cmd->lc_name);
768 goto jleave;
770 if(cmd->lc_argtype & ARG_R){
771 if(pstate & PS_RECURSED){
772 /* TODO PS_RECURSED: should allow `reply' in compose mode: ~:reply! */
773 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
774 goto jleave;
776 /* TODO Nothing should prevent ARG_R in conjunction with
777 * TODO PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
778 if(pstate & (PS_ROBOT | PS_SOURCING)){
779 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
780 cmd->lc_name);
781 goto jleave;
785 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
786 n_err(_("May not execute `%s' -- message file is read only\n"),
787 cmd->lc_name);
788 goto jleave;
790 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
791 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
792 goto jleave;
795 if(cmd->lc_argtype & ARG_O)
796 OBSOLETE2(_("this command will be removed"), cmd->lc_name);
797 if(cmd->lc_argtype & ARG_V)
798 temporary_arg_v_store = NULL;
800 if(wysh && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST)
801 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
802 /* TODO v15: strip PS_ARGLIST_MASK off, just in case the actual command
803 * TODO doesn't use any of those list commands which strip this mask,
804 * TODO and for now we misuse bits for checking relation to history;
805 * TODO argument state should be property of a per-command carrier instead */
806 pstate &= ~PS_ARGLIST_MASK;
807 switch(cmd->lc_argtype & ARG_ARGMASK){
808 case ARG_MSGLIST:
809 /* Message list defaulting to nearest forward legal message */
810 if(n_msgvec == NULL)
811 goto je96;
812 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
813 break;
814 if(c == 0){
815 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
816 n_msgvec[1] = 0;
818 if(n_msgvec[0] == 0){
819 if(!(pstate & PS_HOOK_MASK))
820 printf(_("No applicable messages\n"));
821 break;
823 e = (*cmd->lc_func)(n_msgvec);
824 break;
826 case ARG_NDMLIST:
827 /* Message list with no defaults, but no error if none exist */
828 if(n_msgvec == NULL){
829 je96:
830 n_err(_("Invalid use of message list\n"));
831 break;
833 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
834 break;
835 e = (*cmd->lc_func)(n_msgvec);
836 break;
838 case ARG_STRLIST:
839 /* Just the straight string, with leading blanks removed */
840 while(whitechar(*cp))
841 ++cp;
842 e = (*cmd->lc_func)(cp);
843 break;
845 case ARG_WYSHLIST:
846 c = 1;
847 if(0){
848 /* FALLTHRU */
849 case ARG_WYRALIST:
850 c = wysh ? 1 : 0;
851 if(0){
852 case ARG_RAWLIST:
853 c = 0;
857 if((c = getrawlist((c != 0), arglist, n_NELEM(arglist), cp, line.l)) < 0){
858 n_err(_("Invalid argument list\n"));
859 break;
861 if(c < cmd->lc_minargs){
862 n_err(_("`%s' requires at least %d arg(s)\n"),
863 cmd->lc_name, cmd->lc_minargs);
864 break;
866 #undef lc_minargs
867 if(c > cmd->lc_maxargs){
868 n_err(_("`%s' takes no more than %d arg(s)\n"),
869 cmd->lc_name, cmd->lc_maxargs);
870 break;
872 #undef lc_maxargs
873 e = (*cmd->lc_func)(arglist);
874 break;
876 case ARG_NOLIST:
877 /* Just the constant zero, for exiting, eg. */
878 e = (*cmd->lc_func)(0);
879 break;
881 default:
882 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
883 cmd->lc_argtype & ARG_ARGMASK); )
884 goto jleave0;
887 if(e == 0 && (cmd->lc_argtype & ARG_V) &&
888 (cp = temporary_arg_v_store) != NULL){
889 temporary_arg_v_store = NULL;
890 evp->le_new_content = cp;
891 goto jleave0;
893 if(!(cmd->lc_argtype & ARG_H))
894 evp->le_add_history = (((cmd->lc_argtype & ARG_G) ||
895 (pstate & PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
897 jleave:
898 /* C99 */{
899 bool_t reset = !(pstate & PS_ROOT);
901 pstate |= PS_ROOT;
902 ok_vset(_exit_status, (e == 0 ? "0" : "1")); /* TODO num=1 +real value! */
903 if(reset)
904 pstate &= ~PS_ROOT;
907 /* Exit the current source file on error TODO what a mess! */
908 if(e == 0)
909 pstate &= ~PS_EVAL_ERROR;
910 else{
911 pstate |= PS_EVAL_ERROR;
912 if(e < 0 || (pstate & PS_ROBOT)){ /* FIXME */
913 e = 1;
914 goto jret;
916 goto jret0;
919 if(cmd == NULL)
920 goto jret0;
921 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint))
922 if(visible(dot)){
923 line.s = savestr("type");
924 line.l = sizeof("type") -1;
925 gp = (struct a_lex_ghost*)-1; /* Avoid `ghost' interpretation */
926 goto jrestart;
929 if(!(pstate & (PS_SOURCING | PS_HOOK_MASK)) && !(cmd->lc_argtype & ARG_T))
930 pstate |= PS_SAW_COMMAND;
931 jleave0:
932 pstate &= ~PS_EVAL_ERROR;
933 jret0:
934 e = 0;
935 jret:
937 fprintf(stderr, "a_lex_evaluate returns %d for <%s>\n",e,line.s);
939 NYD_LEAVE;
940 return e;
943 static struct a_lex_cmd const *
944 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
945 struct a_lex_cmd const *cp;
946 NYD2_ENTER;
948 for(cp = a_lex_cmd_tab;
949 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
950 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
951 goto jleave;
952 cp = NULL;
953 jleave:
954 NYD2_LEAVE;
955 return cp;
958 static void
959 a_lex_hangup(int s){
960 NYD_X; /* Signal handler */
961 n_UNUSED(s);
962 /* nothing to do? */
963 exit(EXIT_ERR);
966 static void
967 a_lex_onintr(int s){ /* TODO block signals while acting */
968 NYD_X; /* Signal handler */
969 n_UNUSED(s);
971 safe_signal(SIGINT, a_lex_onintr);
973 termios_state_reset();
974 close_all_files(); /* FIXME .. of current level ONLU! */
975 if(image >= 0){
976 close(image);
977 image = -1;
980 a_lex_unstack(TRUM1);
982 if(interrupts != 1)
983 n_err_sighdl(_("Interrupt\n"));
984 safe_signal(SIGPIPE, a_lex_oldpipe);
985 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
988 static void
989 a_lex_unstack(bool_t eval_error){
990 struct a_lex_input_stack *lip;
991 NYD_ENTER;
993 if((lip = a_lex_input) == NULL){
994 n_memory_reset();
996 /* If called from a_lex_onintr(), be silent FIXME */
997 pstate &= ~(PS_SOURCING | PS_ROBOT);
998 if(eval_error == TRUM1 || !(pstate & PS_STARTED))
999 goto jleave;
1000 goto jerr;
1003 if(lip->li_flags & a_LEX_SLICE){ /* TODO Temporary hack */
1004 stdin = lip->li_slice_stdin;
1005 stdout = lip->li_slice_stdout;
1006 options = lip->li_slice_options;
1007 goto jthe_slice_hack;
1010 if(lip->li_flags & a_LEX_MACRO){
1011 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
1012 char **lp;
1014 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
1015 free(*lp);
1016 ++lip->li_loff;
1018 /* Part of lip's memory chunk, then */
1019 if(!(lip->li_flags & a_LEX_MACRO_CMD))
1020 free(lip->li_lines);
1022 }else{
1023 if(lip->li_flags & a_LEX_PIPE)
1024 /* XXX command manager should -TERM then -KILL instead of hoping
1025 * XXX for exit of provider due to EPIPE / SIGPIPE */
1026 Pclose(lip->li_file, TRU1);
1027 else
1028 Fclose(lip->li_file);
1031 if(!condstack_take(lip->li_cond)){
1032 n_err(_("Unmatched `if' at end of %s %s\n"),
1033 ((lip->li_flags & a_LEX_MACRO
1034 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1035 : _("`source'd file"))),
1036 lip->li_name);
1037 eval_error = TRU1;
1040 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1042 jthe_slice_hack:
1043 if(lip->li_on_finalize != NULL)
1044 (*lip->li_on_finalize)(lip->li_finalize_arg);
1046 if((a_lex_input = lip->li_outer) == NULL){
1047 pstate &= ~(PS_SOURCING | PS_ROBOT);
1048 }else{
1049 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1050 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1051 pstate &= ~PS_SOURCING;
1052 assert(pstate & PS_ROBOT);
1055 if(eval_error)
1056 goto jerr;
1057 jleave:
1058 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1059 free(lip);
1060 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1061 a_lex_unstack(TRUM1);
1062 NYD_LEAVE;
1063 return;
1065 jerr:
1066 if(lip != NULL){
1067 if(options & OPT_D_V)
1068 n_alert(_("Stopped %s %s due to errors%s"),
1069 (pstate & PS_STARTED
1070 ? (lip->li_flags & a_LEX_SLICE ? _("sliced in program")
1071 : (lip->li_flags & a_LEX_MACRO
1072 ? (lip->li_flags & a_LEX_MACRO_CMD
1073 ? _("evaluating command") : _("evaluating macro"))
1074 : (lip->li_flags & a_LEX_PIPE
1075 ? _("executing `source'd pipe")
1076 : _("loading `source'd file")))
1078 : (lip->li_flags & a_LEX_MACRO
1079 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1080 ? _("evaluating command line") : _("evaluating macro"))
1081 : _("loading initialization resource"))),
1082 lip->li_name,
1083 (options & OPT_DEBUG ? n_empty : _(" (enable *debug* for trace)")));
1086 if(!(options & OPT_INTERACTIVE) && !(pstate & PS_STARTED)){
1087 if(options & OPT_D_V)
1088 n_alert(_("Non-interactive, bailing out due to errors "
1089 "in startup load phase"));
1090 exit(EXIT_ERR);
1092 goto jleave;
1095 static bool_t
1096 a_lex_source_file(char const *file, bool_t silent_error){
1097 struct a_lex_input_stack *lip;
1098 size_t nlen;
1099 char *nbuf;
1100 bool_t ispipe;
1101 FILE *fip;
1102 NYD_ENTER;
1104 fip = NULL;
1106 /* Being a command argument file is space-trimmed *//* TODO v15 with
1107 * TODO WYRALIST this is no longer necessary true, and for that we
1108 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1109 #if 0
1110 ((ispipe = (!silent_error && (nlen = strlen(file)) > 0 &&
1111 file[--nlen] == '|')))
1112 #else
1113 ispipe = FAL0;
1114 if(!silent_error)
1115 for(nlen = strlen(file); nlen > 0;){
1116 char c;
1118 c = file[--nlen];
1119 if(!blankchar(c)){
1120 if(c == '|'){
1121 nbuf = savestrbuf(file, nlen);
1122 ispipe = TRU1;
1123 break;
1127 #endif
1129 if(ispipe){
1130 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1131 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL){
1132 if(!silent_error || (options & OPT_D_V))
1133 n_perr(nbuf, 0);
1134 goto jleave;
1136 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1137 goto jleave;
1138 else if((fip = Fopen(nbuf, "r")) == NULL){
1139 if(!silent_error || (options & OPT_D_V))
1140 n_perr(nbuf, 0);
1141 goto jleave;
1144 lip = smalloc(sizeof(*lip) -
1145 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1146 (nlen = strlen(nbuf) +1));
1147 memset(lip, 0,
1148 sizeof(*lip) - n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name));
1149 lip->li_outer = a_lex_input;
1150 lip->li_file = fip;
1151 lip->li_cond = condstack_release();
1152 n_memory_autorec_push(&lip->li_autorecmem[0]);
1153 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1154 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1155 ? a_LEX_SUPER_MACRO : 0);
1156 memcpy(lip->li_name, nbuf, nlen);
1158 pstate |= PS_SOURCING | PS_ROBOT;
1159 a_lex_input = lip;
1160 a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC);
1161 /* FIXME return TRUM1 if file can't be opened, FAL0 on eval error */
1162 jleave:
1163 NYD_LEAVE;
1164 return silent_error ? TRU1 : (fip != NULL);
1167 static bool_t
1168 a_lex_load(struct a_lex_input_stack *lip){
1169 bool_t rv;
1170 NYD2_ENTER;
1172 assert(!(pstate & PS_STARTED));
1173 assert(a_lex_input == NULL);
1175 /* POSIX:
1176 * Any errors in the start-up file shall either cause mailx to terminate
1177 * with a diagnostic message and a non-zero status or to continue after
1178 * writing a diagnostic message, ignoring the remainder of the lines in
1179 * the start-up file. */
1180 lip->li_cond = condstack_release();
1181 n_memory_autorec_push(&lip->li_autorecmem[0]);
1183 /* FIXME won't work for now (PS_ROBOT needs PS_SOURCING anyway)
1184 pstate |= PS_ROBOT |
1185 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : PS_SOURCING);
1187 pstate |= PS_ROBOT | PS_SOURCING;
1188 if(options & OPT_D_V)
1189 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1190 a_lex_input = lip;
1191 if(!(rv = n_commands())){
1192 if(!(options & OPT_INTERACTIVE)){
1193 if(options & OPT_D_V)
1194 n_alert(_("Non-interactive program mode, forced exit"));
1195 exit(EXIT_ERR);
1198 /* PS_EXIT handled by callers */
1199 NYD2_LEAVE;
1200 return rv;
1203 static void
1204 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1205 NYD_X; /* Signal handler */
1206 n_UNUSED(sig);
1207 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1210 static bool_t
1211 a_commands_recursive(enum n_lexinput_flags lif){
1212 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1213 sighandler_type soldhdl;
1214 sigset_t sintset, soldset;
1215 struct a_lex_eval_ctx ev;
1216 bool_t rv;
1217 NYD2_ENTER;
1219 memset(&ev, 0, sizeof ev);
1221 sigfillset(&sintset);
1222 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1223 hadint = FAL0;
1224 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1225 safe_signal(SIGINT, &a_lex__cmdrecint);
1226 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1227 hadint = TRU1;
1228 goto jjump;
1231 sigprocmask(SIG_SETMASK, &soldset, NULL);
1233 n_COLOUR( n_colour_env_push(); )
1234 rv = TRU1;
1235 for(;;){
1236 int n;
1238 /* Read a line of commands and handle end of file specially */
1239 ev.le_line.l = ev.le_line_size;
1240 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l,
1241 ev.le_new_content);
1242 ev.le_line_size = (ui32_t)ev.le_line.l;
1243 ev.le_line.l = (ui32_t)n;
1245 if(n < 0)
1246 break;
1248 if(a_lex_evaluate(&ev)){
1249 rv = FAL0;
1250 break;
1252 n_memory_reset();
1254 if((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)){
1255 if(exit_status != EXIT_OK)
1256 break;
1259 jjump: /* TODO */
1260 a_lex_unstack(!rv);
1261 n_COLOUR( n_colour_env_pop(FAL0); )
1263 if(ev.le_line.s != NULL)
1264 free(ev.le_line.s);
1266 if(soldhdl != SIG_IGN)
1267 safe_signal(SIGINT, soldhdl);
1268 NYD2_LEAVE;
1269 if(hadint){
1270 sigprocmask(SIG_SETMASK, &soldset, NULL);
1271 n_raise(SIGINT);
1273 return rv;
1276 FL bool_t
1277 n_commands(void){ /* FIXME */
1278 struct a_lex_eval_ctx ev;
1279 int n;
1280 bool_t volatile rv;
1281 NYD_ENTER;
1283 rv = TRU1;
1285 if (!(pstate & PS_SOURCING)) {
1286 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1287 safe_signal(SIGINT, &a_lex_onintr);
1288 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1289 safe_signal(SIGHUP, &a_lex_hangup);
1291 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1292 safe_signal(SIGPIPE, a_lex_oldpipe);
1294 memset(&ev, 0, sizeof ev);
1296 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1297 for (;;) {
1298 char *temporary_orig_line; /* XXX eval_ctx.le_line not yet constant */
1300 n_COLOUR( n_colour_env_pop(TRU1); )
1302 /* TODO Unless we have our signal manager (or however we do it) child
1303 * TODO processes may have time slots where their execution isn't
1304 * TODO protected by signal handlers (in between start and setup
1305 * TODO completed). close_all_files() is only called from onintr()
1306 * TODO so those may linger possibly forever */
1307 if(!(pstate & PS_SOURCING))
1308 close_all_files();
1310 interrupts = 0;
1312 n_memory_reset();
1314 if (!(pstate & PS_SOURCING)) {
1315 char *cp;
1317 /* TODO Note: this buffer may contain a password. We should redefine
1318 * TODO the code flow which has to do that */
1319 if ((cp = termios_state.ts_linebuf) != NULL) {
1320 termios_state.ts_linebuf = NULL;
1321 termios_state.ts_linesize = 0;
1322 free(cp); /* TODO pool give-back */
1324 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1325 if (ev.le_line.l > LINESIZE * 3) {
1326 free(ev.le_line.s); /* TODO pool! but what? */
1327 ev.le_line.s = NULL;
1328 ev.le_line.l = ev.le_line_size = 0;
1332 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1333 char *cp;
1335 cp = ok_vlook(newmail);
1336 if ((options & OPT_TTYIN) && cp != NULL) {
1337 struct stat st;
1339 /* FIXME TEST WITH NOPOLL ETC. !!! */
1340 n = (cp != NULL && strcmp(cp, "nopoll"));
1341 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1342 st.st_size > mailsize) ||
1343 (mb.mb_type == MB_MAILDIR && n != 0)) {
1344 size_t odot = PTR2SIZE(dot - message);
1345 ui32_t odid = (pstate & PS_DID_PRINT_DOT);
1347 if (setfile(mailname,
1348 FEDIT_NEWMAIL |
1349 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1350 exit_status |= EXIT_ERR;
1351 rv = FAL0;
1352 break;
1354 dot = message + odot;
1355 pstate |= odid;
1359 exit_status = EXIT_OK;
1362 /* Read a line of commands and handle end of file specially */
1363 jreadline:
1364 ev.le_line.l = ev.le_line_size;
1365 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1366 &ev.le_line.s, &ev.le_line.l, ev.le_new_content);
1367 ev.le_line_size = (ui32_t)ev.le_line.l;
1368 ev.le_line.l = (ui32_t)n;
1370 if (n < 0) {
1371 /* FIXME did unstack() when PS_SOURCING, only break with PS_LOADING*/
1372 if (!(pstate & PS_ROBOT) &&
1373 (options & OPT_INTERACTIVE) && ok_blook(ignoreeof)) {
1374 printf(_("*ignoreeof* set, use `quit' to quit.\n"));
1375 n_msleep(500, FAL0);
1376 continue;
1378 break;
1381 temporary_orig_line = ((pstate & PS_SOURCING) ||
1382 !(options & OPT_INTERACTIVE)) ? NULL
1383 : savestrbuf(ev.le_line.s, ev.le_line.l);
1384 pstate &= ~PS_HOOK_MASK;
1385 if (a_lex_evaluate(&ev)) {
1386 if (!(pstate & PS_STARTED)) /* TODO mess; join PS_EVAL_ERROR.. */
1387 rv = FAL0;
1388 break;
1391 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
1392 if (exit_status != EXIT_OK)
1393 break;
1394 if ((pstate & (PS_SOURCING | PS_EVAL_ERROR)) == PS_EVAL_ERROR) {
1395 exit_status = EXIT_ERR;
1396 break;
1399 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1400 if (ev.le_new_content != NULL)
1401 goto jreadline;
1402 /* *Can* happen since _evaluate() n_unstack()s on error! XXX no more */
1403 if (temporary_orig_line != NULL)
1404 n_tty_addhist(temporary_orig_line, (ev.le_add_history != TRU1));
1407 if(pstate & PS_EXIT)
1408 break;
1411 a_lex_unstack(!rv);
1413 if (ev.le_line.s != NULL)
1414 free(ev.le_line.s);
1415 NYD_LEAVE;
1416 return rv;
1419 FL int
1420 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1421 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1422 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1423 struct n_string xprompt;
1424 FILE *ifile;
1425 bool_t doprompt, dotty;
1426 char const *iftype;
1427 int n, nold;
1428 NYD2_ENTER;
1430 /* Special case macro mode: never need to prompt, lines have always been
1431 * unfolded already */
1432 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1433 if(*linebuf != NULL)
1434 free(*linebuf);
1436 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1437 *linesize = 0;
1438 n = -1;
1439 goto jleave;
1442 ++a_lex_input->li_loff;
1443 *linesize = strlen(*linebuf);
1444 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1445 *linebuf = sbufdup(*linebuf, *linesize);
1447 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1448 ? "-X OPTION"
1449 : (a_lex_input->li_flags & a_LEX_MACRO_CMD) ? "CMD" : "MACRO";
1450 n = (int)*linesize;
1451 pstate |= PS_READLINE_NL;
1452 goto jhave_dat;
1454 pstate &= ~PS_READLINE_NL;
1456 iftype = (!(pstate & PS_STARTED) ? "LOAD"
1457 : (pstate & PS_SOURCING) ? "SOURCE" : "READ");
1458 doprompt = ((pstate & (PS_STARTED | PS_ROBOT)) == PS_STARTED &&
1459 (options & OPT_INTERACTIVE));
1460 dotty = (doprompt && !ok_blook(line_editor_disable));
1461 if(!doprompt)
1462 lif |= n_LEXINPUT_PROMPT_NONE;
1463 else{
1464 if(!dotty)
1465 n_string_creat_auto(&xprompt);
1466 if(prompt == NULL)
1467 lif |= n_LEXINPUT_PROMPT_EVAL;
1470 /* Ensure stdout is flushed first anyway */
1471 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1472 fflush(stdout);
1474 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : stdin;
1475 assert(ifile != NULL);
1477 for(nold = n = 0;;){
1478 if(dotty){
1479 assert(ifile == stdin);
1480 if(string != NULL && (n = (int)strlen(string)) > 0){
1481 if(*linesize > 0)
1482 *linesize += n +1;
1483 else
1484 *linesize = (size_t)n + LINESIZE +1;
1485 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1486 memcpy(*linebuf, string, (size_t)n +1);
1488 string = NULL;
1489 /* TODO if nold>0, don't redisplay the entire line!
1490 * TODO needs complete redesign ... */
1491 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1492 n_MEMORY_DEBUG_ARGSCALL);
1493 }else{
1494 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1495 n_tty_create_prompt(&xprompt, prompt, lif);
1496 if(xprompt.s_len > 0){
1497 fwrite(xprompt.s_dat, 1, xprompt.s_len, stdout);
1498 fflush(stdout);
1502 n = (readline_restart)(ifile, linebuf, linesize, n
1503 n_MEMORY_DEBUG_ARGSCALL);
1505 if(n > 0 && nold > 0){
1506 int i = 0;
1507 char const *cp = *linebuf + nold;
1509 while(blankspacechar(*cp) && nold + i < n)
1510 ++cp, ++i;
1511 if(i > 0){
1512 memmove(*linebuf + nold, cp, n - nold - i);
1513 n -= i;
1514 (*linebuf)[n] = '\0';
1519 if(n <= 0)
1520 break;
1522 /* POSIX says:
1523 * An unquoted <backslash> at the end of a command line shall
1524 * be discarded and the next line shall continue the command */
1525 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1526 if(dotty)
1527 pstate |= PS_READLINE_NL;
1528 break;
1530 /* Definitely outside of quotes, thus the quoting rules are so that an
1531 * uneven number of successive backslashs at EOL is a continuation */
1532 if(n > 1){
1533 size_t i, j;
1535 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1536 if((*linebuf)[i] != '\\')
1537 break;
1538 if(!(j & 1))
1539 break;
1541 (*linebuf)[nold = --n] = '\0';
1542 lif |= n_LEXINPUT_NL_FOLLOW;
1545 if(n < 0)
1546 goto jleave;
1547 (*linebuf)[*linesize = n] = '\0';
1549 jhave_dat:
1550 #if 0
1551 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1552 char *cp, c;
1553 size_t i;
1555 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1556 c = *--cp;
1557 if(!blankspacechar(c))
1558 break;
1560 (*linebuf)[n = (int)i] = '\0';
1563 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1564 char *cp, c;
1565 size_t j, i;
1567 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1568 c = *cp++;
1569 if(!blankspacechar(c))
1570 break;
1572 if(i > 0){
1573 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1574 (*linebuf)[n = (int)j] = '\0';
1577 #endif /* 0 (notyet - must take care for backslash escaped space) */
1579 if(options & OPT_D_VV)
1580 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1581 jleave:
1582 if (pstate & PS_PSTATE_PENDMASK)
1583 a_lex_update_pstate();
1585 /* TODO We need to special case a_LEX_SLICE, since that is not managed by us
1586 * TODO but only established from the outside and we need to drop this
1587 * TODO overlay context somehow */
1588 if(n < 0 && a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SLICE))
1589 a_lex_unstack(FAL0);
1590 NYD2_LEAVE;
1591 return n;
1594 FL char *
1595 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1596 char const *string){
1597 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1598 size_t linesize;
1599 char *linebuf, *rv;
1600 int n;
1601 NYD2_ENTER;
1603 linesize = 0;
1604 linebuf = NULL;
1605 rv = NULL;
1607 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1608 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1609 (lif & n_LEXINPUT_HIST_ADD) && (options & OPT_INTERACTIVE))
1610 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1612 if(linebuf != NULL)
1613 free(linebuf);
1614 NYD2_LEAVE;
1615 return rv;
1618 FL void
1619 n_load(char const *name){
1620 struct a_lex_input_stack *lip;
1621 size_t i;
1622 FILE *fip;
1623 NYD_ENTER;
1625 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1626 goto jleave;
1628 i = strlen(name) +1;
1629 lip = smalloc(sizeof(*lip) -
1630 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) + i);
1631 memset(lip, 0,
1632 sizeof(*lip) - n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name));
1633 lip->li_file = fip;
1634 lip->li_flags = a_LEX_FREE;
1635 memcpy(lip->li_name, name, i);
1637 a_lex_load(lip);
1638 pstate &= ~PS_EXIT;
1639 jleave:
1640 NYD_LEAVE;
1643 FL void
1644 n_load_Xargs(char const **lines, size_t cnt){
1645 static char const name[] = "-X";
1647 ui8_t buf[sizeof(struct a_lex_input_stack) + sizeof name];
1648 char const *srcp, *xsrcp;
1649 char *cp;
1650 size_t imax, i, len;
1651 struct a_lex_input_stack *lip;
1652 NYD_ENTER;
1654 lip = (void*)buf;
1655 memset(lip, 0,
1656 sizeof(*lip) - n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name));
1657 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1658 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1659 memcpy(lip->li_name, name, sizeof name);
1661 /* The problem being that we want to support reverse solidus newline
1662 * escaping also within multiline -X, i.e., POSIX says:
1663 * An unquoted <backslash> at the end of a command line shall
1664 * be discarded and the next line shall continue the command
1665 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
1666 * entire lines array and set _MACRO_FREE_DATA */
1667 imax = cnt + 1;
1668 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
1670 /* For each of the input lines.. */
1671 for(i = len = 0, cp = NULL; cnt > 0;){
1672 bool_t keep;
1673 size_t j;
1675 if((j = strlen(srcp = *lines)) == 0){
1676 ++lines, --cnt;
1677 continue;
1680 /* Separate one line from a possible multiline input string */
1681 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1682 *lines = &xsrcp[1];
1683 j = PTR2SIZE(xsrcp - srcp);
1684 }else
1685 ++lines, --cnt;
1687 /* The (separated) string may itself indicate soft newline escaping */
1688 if((keep = (srcp[j - 1] == '\\'))){
1689 size_t xj, xk;
1691 /* Need an uneven number of reverse solidus */
1692 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1693 if(srcp[xj] != '\\')
1694 break;
1695 if(xk & 1)
1696 --j;
1697 else
1698 keep = FAL0;
1701 /* Strip any leading WS from follow lines, then */
1702 if(cp != NULL)
1703 while(j > 0 && blankspacechar(*srcp))
1704 ++srcp, --j;
1706 if(j > 0){
1707 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1708 imax += 4;
1709 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
1710 imax);
1712 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
1713 memcpy(&cp[len], srcp, j);
1714 cp[len += j] = '\0';
1716 if(!keep)
1717 ++i;
1719 if(!keep)
1720 cp = NULL, len = 0;
1722 if(cp != NULL){
1723 assert(i + 1 < imax);
1724 lip->li_lines[i++] = cp;
1726 lip->li_lines[i] = NULL;
1728 a_lex_load(lip);
1729 if(pstate & PS_EXIT)
1730 exit(EXIT_OK);
1731 NYD_LEAVE;
1734 FL int
1735 c_source(void *v){
1736 int rv;
1737 NYD_ENTER;
1739 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1740 NYD_LEAVE;
1741 return rv;
1744 FL int
1745 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1746 int rv;
1747 NYD_ENTER;
1749 rv = (a_lex_source_file(*(char**)v, TRU1) != FAL0) ? 0 : 1;
1750 NYD_LEAVE;
1751 return rv;
1754 FL bool_t
1755 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
1756 void (*on_finalize)(void*), void *finalize_arg){
1757 struct a_lex_input_stack *lip;
1758 size_t i;
1759 int rv;
1760 NYD_ENTER;
1762 lip = smalloc(sizeof(*lip) -
1763 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1764 (i = strlen(name) +1));
1765 memset(lip, 0,
1766 sizeof(*lip) - n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name));
1767 lip->li_outer = a_lex_input;
1768 lip->li_file = NULL;
1769 lip->li_cond = condstack_release();
1770 n_memory_autorec_push(&lip->li_autorecmem[0]);
1771 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1772 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1773 ? a_LEX_SUPER_MACRO : 0);
1774 lip->li_lines = lines;
1775 lip->li_on_finalize = on_finalize;
1776 lip->li_finalize_arg = finalize_arg;
1777 memcpy(lip->li_name, name, i);
1779 pstate |= PS_ROBOT;
1780 a_lex_input = lip;
1781 rv = a_commands_recursive(lif);
1782 NYD_LEAVE;
1783 return rv;
1786 FL bool_t
1787 n_source_command(enum n_lexinput_flags lif, char const *cmd){
1788 struct a_lex_input_stack *lip;
1789 size_t i, ial;
1790 bool_t rv;
1791 NYD_ENTER;
1793 i = strlen(cmd) +1;
1794 ial = n_ALIGN(i);
1796 lip = smalloc(sizeof(*lip) -
1797 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1798 ial + 2*sizeof(char*));
1799 memset(lip, 0,
1800 sizeof(*lip) - n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name));
1801 lip->li_outer = a_lex_input;
1802 lip->li_cond = condstack_release();
1803 n_memory_autorec_push(&lip->li_autorecmem[0]);
1804 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_CMD |
1805 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1806 ? a_LEX_SUPER_MACRO : 0);
1807 lip->li_lines = (void*)&lip->li_name[ial];
1808 memcpy(lip->li_lines[0] = &lip->li_name[0], cmd, i);
1809 lip->li_lines[1] = NULL;
1811 pstate |= PS_ROBOT;
1812 a_lex_input = lip;
1813 rv = a_commands_recursive(lif);
1814 NYD_LEAVE;
1815 return rv;
1818 FL void
1819 n_source_slice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
1820 ui32_t new_options, void (*on_finalize)(void*), void *finalize_arg){
1821 struct a_lex_input_stack *lip;
1822 size_t i;
1823 NYD_ENTER;
1825 lip = smalloc(sizeof(*lip) -
1826 n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1827 (i = strlen(cmd) +1));
1828 memset(lip, 0,
1829 sizeof(*lip) - n_VFIELD_SIZEOF(struct a_lex_input_stack, li_name));
1830 lip->li_outer = a_lex_input;
1831 lip->li_file = new_stdin;
1832 lip->li_flags = a_LEX_FREE | a_LEX_SLICE;
1833 lip->li_on_finalize = on_finalize;
1834 lip->li_finalize_arg = finalize_arg;
1835 lip->li_slice_stdin = stdin;
1836 lip->li_slice_stdout = stdout;
1837 lip->li_slice_options = options;
1838 memcpy(lip->li_name, cmd, i);
1840 stdin = new_stdin;
1841 stdout = new_stdout;
1842 options = new_options;
1843 pstate |= PS_ROBOT;
1844 a_lex_input = lip;
1845 NYD_LEAVE;
1848 FL void
1849 n_source_slice_hack_remove_after_jump(void){
1850 a_lex_unstack(FAL0);
1853 FL bool_t
1854 n_source_may_yield_control(void){
1855 return ((options & OPT_INTERACTIVE) &&
1856 (pstate & PS_STARTED) &&
1857 (!(pstate & PS_ROBOT) ||
1858 /* But: ok for ~:, yet: unless in a hook.
1859 * TODO This is obviously hacky in that it depends on _input_stack not
1860 * TODO loosing any flags when creating new contexts... Maybe this
1861 * TODO function should instead walk all up the context stack when
1862 * TODO there is one, and verify neither level prevents yielding! */
1863 ((pstate & PS_RECURSED) && (a_lex_input == NULL ||
1864 !(a_lex_input->li_flags & a_LEX_SLICE)))) &&
1865 (a_lex_input == NULL || a_lex_input->li_outer == NULL));
1868 /* s-it-mode */