(BWDIC!) FIX false decision: for `if' etc., add -le,-gt.. operators..
[s-mailx.git] / lex_input.c
blob9a42d0ad439285187e490e2ebedc7c86aa381d7f
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 n_PS_ROBOT requires yet n_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 - 2017 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 accmacvar.c:temporary_compose_mode_hook_call()
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,
74 /* TODO If it is none of those, we are sourcing or loading a file */
76 a_LEX_FORCE_EOF = 1<<8, /* lex_input() shall return EOF next */
78 a_LEX_SUPER_MACRO = 1<<16 /* *Not* inheriting n_PS_SOURCING state */
81 struct a_lex_cmd{
82 char const *lc_name; /* Name of command */
83 int (*lc_func)(void*); /* Implementor of command */
84 enum n_cmd_arg_flags lc_caflags;
85 si16_t lc_msgflag; /* Required flags of msgs */
86 si16_t lc_msgmask; /* Relevant flags of msgs */
87 #ifdef HAVE_DOCSTRINGS
88 char const *lc_doc; /* One line doc for command */
89 #endif
91 /* Yechh, can't initialize unions */
92 #define lc_minargs lc_msgflag /* Minimum argcount for RAWLIST */
93 #define lc_maxargs lc_msgmask /* Max argcount for RAWLIST */
95 struct a_lex_ghost{
96 struct a_lex_ghost *lg_next;
97 struct str lg_cmd; /* Data follows after .lg_name */
98 char lg_name[n_VFIELD_SIZE(0)];
101 struct a_lex_eval_ctx{
102 struct str le_line; /* The terminated data to _evaluate() */
103 ui32_t le_line_size; /* May be used to store line memory size */
104 bool_t le_is_recursive; /* Evaluation in evaluation? (collect ~:) */
105 ui8_t __dummy[3];
106 bool_t le_add_history; /* Add command to history (TRUM1=gabby)? */
109 struct a_lex_input_inject{
110 struct a_lex_input_inject *lii_next;
111 size_t lii_len;
112 bool_t lii_commit;
113 char lii_dat[n_VFIELD_SIZE(7)];
116 struct a_lex_input{
117 struct a_lex_input *li_outer;
118 FILE *li_file; /* File we were in */
119 void *li_cond; /* Saved state of conditional stack */
120 ui32_t li_flags; /* enum a_lex_input_flags */
121 ui32_t li_loff; /* Pseudo (macro): index in .li_lines */
122 char **li_lines; /* Pseudo content, lines unfolded */
123 struct a_lex_input_inject *li_inject; /* To be consumed first */
124 void (*li_on_finalize)(void *);
125 void *li_finalize_arg;
126 char li_autorecmem[n_MEMORY_AUTOREC_TYPE_SIZEOF];
127 sigjmp_buf li_cmdrec_jmp; /* TODO one day... for command_recursive */
128 /* SLICE hacks: saved stdin/stdout, saved pstate */
129 FILE *li_slice_stdin;
130 FILE *li_slice_stdout;
131 ui32_t li_slice_psonce;
132 ui8_t li_slice__dummy[4];
133 char li_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
135 n_CTA(n_MEMORY_AUTOREC_TYPE_SIZEOF % sizeof(void*) == 0,
136 "Inacceptible size of structure buffer");
138 static sighandler_type a_lex_oldpipe;
139 static struct a_lex_ghost *a_lex_ghosts;
140 /* a_lex_cmd_tab[] after fun protos */
142 /* */
143 static struct a_lex_input *a_lex_input;
145 /* For n_source_inject_input(), if a_lex_input==NULL */
146 static struct a_lex_input_inject *a_lex_input_inject;
148 static sigjmp_buf a_lex_srbuf; /* TODO GET RID */
150 /* Isolate the command from the arguments */
151 static char *a_lex_isolate(char const *comm);
153 /* `eval' */
154 static int a_lex_c_eval(void *v);
156 /* Command ghost handling */
157 static int a_lex_c_ghost(void *v);
158 static int a_lex_c_unghost(void *v);
160 /* Create a multiline info string about all known additional infos for lcp */
161 static char const *a_lex_cmdinfo(struct a_lex_cmd const *lcp);
163 /* Print a list of all commands */
164 static int a_lex_c_list(void *v);
166 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
168 /* `help' / `?' command */
169 static int a_lex_c_help(void *v);
171 /* `exit' and `quit' commands */
172 static int a_lex_c_exit(void *v);
173 static int a_lex_c_quit(void *v);
175 /* Print the binaries version number */
176 static int a_lex_c_version(void *v);
178 static int a_lex__version_cmp(void const *s1, void const *s2);
180 /* n_PS_STATE_PENDMASK requires some actions */
181 static void a_lex_update_pstate(void);
183 /* Evaluate a single command.
184 * .le_add_history will be updated upon success.
185 * Command functions return 0 for success, 1 for error, and -1 for abort.
186 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
187 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
189 /* Get first-fit, or NULL */
190 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
192 /* Branch here on hangup signal and simulate "exit" */
193 static void a_lex_hangup(int s);
195 /* The following gets called on receipt of an interrupt. Close all open files
196 * except 0, 1, 2, and the temporary. Also, unstack all source files */
197 static void a_lex_onintr(int s);
199 /* Pop the current input back to the previous level. Update the program state.
200 * If the argument is TRUM1 then we don't alert and error out if the stack
201 * doesn't exist at all */
202 static void a_lex_unstack(bool_t eval_error);
204 /* `source' and `source_if' (if silent_open_error: no pipes allowed, then).
205 * Returns FAL0 if file is somehow not usable (unless silent_open_error) or
206 * upon evaluation error, and TRU1 on success */
207 static bool_t a_lex_source_file(char const *file, bool_t silent_open_error);
209 /* System resource file load()ing or -X command line option array traversal */
210 static bool_t a_lex_load(struct a_lex_input *lip);
212 /* A simplified command loop for recursed state machines */
213 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
215 /* `read' */
216 static int a_lex_c_read(void *v);
218 static bool_t a_lex__read_set(char const *cp, char const *value);
220 /* List of all commands, and list of commands which are specially treated
221 * and deduced in _evaluate(), but we need a list for _c_list() and
222 * print_comm_docstr() */
223 #ifdef HAVE_DOCSTRINGS
224 # define DS(S) , S
225 #else
226 # define DS(S)
227 #endif
228 static struct a_lex_cmd const a_lex_cmd_tab[] = {
229 #include "cmd_tab.h"
231 a_lex_special_cmd_tab[] = {
232 { "#", NULL, n_CMD_ARG_TYPE_STRING, 0, 0
233 DS(N_("Comment command: ignore remaining (continuable) line")) },
234 { "-", NULL, n_CMD_ARG_TYPE_WYSH, 0, 0
235 DS(N_("Print out the preceding message")) }
237 #undef DS
239 static char *
240 a_lex_isolate(char const *comm){
241 NYD2_ENTER;
242 while(*comm != '\0' &&
243 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
244 ++comm;
245 NYD2_LEAVE;
246 return n_UNCONST(comm);
249 static int
250 a_lex_c_eval(void *v){
251 /* TODO HACK! `eval' should be nothing else but a command prefix, evaluate
252 * TODO ARGV with shell rules, but if that is not possible then simply
253 * TODO adjust argv/argc of "the CmdCtx" that we will have "exec" real cmd */
254 struct n_string s_b, *sp;
255 si32_t rv;
256 size_t i, j;
257 char const **argv, *cp;
258 NYD_ENTER;
260 argv = v;
262 for(j = i = 0; (cp = argv[i]) != NULL; ++i)
263 j += strlen(cp);
265 sp = n_string_creat_auto(&s_b);
266 sp = n_string_reserve(sp, j);
268 for(i = 0; (cp = argv[i]) != NULL; ++i){
269 if(i > 0)
270 sp = n_string_push_c(sp, ' ');
271 sp = n_string_push_cp(sp, cp);
274 /* TODO HACK! We should inherit the current n_lexinput_flags via CmdCtx,
275 * TODO for now we don't have such sort of! n_PS_COMPOSE_MODE is a hack
276 * TODO by itself, since ever: misuse the hack for a hack.
277 * TODO Further more, exit handling is very grazy */
278 (void)/*XXX*/n_source_command((n_pstate & n_PS_COMPOSE_MODE
279 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT), n_string_cp(sp));
280 cp = ok_vlook(__qm);
281 if(cp == n_0) /* This is a hack, but since anything is a hack, be hacky */
282 rv = 0;
283 else if(cp == n_1)
284 rv = 1;
285 else if(cp == n_m1)
286 rv = -1;
287 else
288 n_idec_si32_cp(&rv, cp, 10, NULL);
289 NYD_LEAVE;
290 return rv;
293 static int
294 a_lex_c_ghost(void *v){
295 struct a_lex_ghost *lgp, *gp;
296 size_t i, cl, nl;
297 char *cp;
298 char const **argv;
299 NYD_ENTER;
301 argv = v;
303 /* Show the list? */
304 if(*argv == NULL){
305 FILE *fp;
307 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
308 fp = n_stdout;
310 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
311 fprintf(fp, "wysh ghost %s %s\n",
312 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
314 if(fp != n_stdout){
315 page_or_print(fp, i);
316 Fclose(fp);
318 goto jleave;
321 /* Verify the ghost name is a valid one, and not a command modifier */
322 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0' ||
323 !asccasecmp(argv[0], "ignerr") || !asccasecmp(argv[0], "wysh") ||
324 !asccasecmp(argv[0], "vput")){
325 n_err(_("`ghost': can't canonicalize %s\n"),
326 n_shexp_quote_cp(argv[0], FAL0));
327 v = NULL;
328 goto jleave;
331 /* Show command of single ghost? */
332 if(argv[1] == NULL){
333 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
334 if(!strcmp(argv[0], gp->lg_name)){
335 fprintf(n_stdout, "wysh ghost %s %s\n",
336 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
337 goto jleave;
339 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
340 v = NULL;
341 goto jleave;
344 /* Define command for ghost: verify command content */
345 for(cl = 0, i = 1; (cp = n_UNCONST(argv[i])) != NULL; ++i)
346 if(*cp != '\0')
347 cl += strlen(cp) +1; /* SP or NUL */
348 if(cl == 0){
349 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
350 v = NULL;
351 goto jleave;
354 /* If the ghost already exists, recreate */
355 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
356 if(!strcmp(gp->lg_name, argv[0])){
357 if(lgp != NULL)
358 lgp->lg_next = gp->lg_next;
359 else
360 a_lex_ghosts = gp->lg_next;
361 free(gp);
362 break;
365 nl = strlen(argv[0]) +1;
366 gp = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_ghost, lg_name) + nl + cl);
367 gp->lg_next = a_lex_ghosts;
368 a_lex_ghosts = gp;
369 memcpy(gp->lg_name, argv[0], nl);
370 cp = gp->lg_cmd.s = gp->lg_name + nl;
371 gp->lg_cmd.l = --cl;
373 while(*++argv != NULL)
374 if((i = strlen(*argv)) > 0){
375 memcpy(cp, *argv, i);
376 cp += i;
377 *cp++ = ' ';
379 *--cp = '\0';
380 jleave:
381 NYD_LEAVE;
382 return v == NULL;
385 static int
386 a_lex_c_unghost(void *v){
387 struct a_lex_ghost *lgp, *gp;
388 char const **argv, *cp;
389 int rv;
390 NYD_ENTER;
392 rv = 0;
393 argv = v;
395 while((cp = *argv++) != NULL){
396 if(cp[0] == '*' && cp[1] == '\0'){
397 while((gp = a_lex_ghosts) != NULL){
398 a_lex_ghosts = gp->lg_next;
399 free(gp);
401 }else{
402 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
403 lgp = gp, gp = gp->lg_next)
404 if(!strcmp(gp->lg_name, cp)){
405 if(lgp != NULL)
406 lgp->lg_next = gp->lg_next;
407 else
408 a_lex_ghosts = gp->lg_next;
409 free(gp);
410 goto jouter;
412 n_err(_("`unghost': no such alias: %s\n"),
413 n_shexp_quote_cp(cp, FAL0));
414 rv = 1;
415 jouter: ;
418 NYD_LEAVE;
419 return rv;
422 static char const *
423 a_lex_cmdinfo(struct a_lex_cmd const *lcp){
424 struct n_string rvb, *rv;
425 char const *cp;
426 NYD2_ENTER;
428 rv = n_string_creat_auto(&rvb);
429 rv = n_string_reserve(rv, 80);
431 switch(lcp->lc_caflags & n_CMD_ARG_TYPE_MASK){
432 case n_CMD_ARG_TYPE_MSGLIST:
433 cp = N_("message-list");
434 break;
435 case n_CMD_ARG_TYPE_STRING:
436 case n_CMD_ARG_TYPE_RAWDAT:
437 cp = N_("string data");
438 break;
439 case n_CMD_ARG_TYPE_RAWLIST:
440 cp = N_("old-style quoting");
441 break;
442 case n_CMD_ARG_TYPE_NDMLIST:
443 cp = N_("message-list (no default)");
444 break;
445 case n_CMD_ARG_TYPE_WYRA:
446 cp = N_("`wysh' for sh(1)ell-style quoting");
447 break;
448 default:
449 case n_CMD_ARG_TYPE_WYSH:
450 cp = (lcp->lc_minargs == 0 && lcp->lc_maxargs == 0)
451 ? N_("sh(1)ell-style quoting (takes no arguments)")
452 : N_("sh(1)ell-style quoting");
453 break;
455 rv = n_string_push_cp(rv, V_(cp));
457 if(lcp->lc_caflags & n_CMD_ARG_V)
458 rv = n_string_push_cp(rv, _(" | vput modifier"));
459 if(lcp->lc_caflags & n_CMD_ARG_EM)
460 rv = n_string_push_cp(rv, _(" | status in *!*"));
462 if(lcp->lc_caflags & n_CMD_ARG_A)
463 rv = n_string_push_cp(rv, _(" | needs box"));
464 if(lcp->lc_caflags & n_CMD_ARG_I)
465 rv = n_string_push_cp(rv, _(" | ok: batch or interactive"));
466 if(lcp->lc_caflags & n_CMD_ARG_M)
467 rv = n_string_push_cp(rv, _(" | ok: send mode"));
468 if(lcp->lc_caflags & n_CMD_ARG_R)
469 rv = n_string_push_cp(rv, _(" | not ok: compose mode"));
470 if(lcp->lc_caflags & n_CMD_ARG_S)
471 rv = n_string_push_cp(rv, _(" | not ok: during startup"));
472 if(lcp->lc_caflags & n_CMD_ARG_X)
473 rv = n_string_push_cp(rv, _(" | ok: in subprocess"));
475 if(lcp->lc_caflags & n_CMD_ARG_G)
476 rv = n_string_push_cp(rv, _(" | gabby history"));
478 cp = n_string_cp(rv);
479 NYD2_LEAVE;
480 return cp;
483 static int
484 a_lex_c_list(void *v){
485 FILE *fp;
486 struct a_lex_cmd const **cpa, *cp, **cursor;
487 size_t l, i;
488 NYD_ENTER;
490 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
491 cpa = salloc(sizeof(cp) * i);
493 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
494 cpa[i] = &a_lex_cmd_tab[i];
495 /* C99 */{
496 size_t j;
498 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
499 cpa[i] = &a_lex_special_cmd_tab[j];
501 cpa[i] = NULL;
503 /* C99 */{
504 char const *xcp = v;
506 if(*xcp == '\0')
507 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
510 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
511 fp = n_stdout;
513 fprintf(fp, _("Commands are:\n"));
514 l = 1;
515 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
516 if(cp->lc_func == &c_cmdnotsupp)
517 continue;
518 if(n_poption & n_PO_D_V){
519 fprintf(fp, "%s\n", cp->lc_name);
520 ++l;
521 #ifdef HAVE_DOCSTRINGS
522 fprintf(fp, " : %s\n", V_(cp->lc_doc));
523 ++l;
524 #endif
525 fprintf(fp, " : %s\n", a_lex_cmdinfo(cp));
526 ++l;
527 }else{
528 size_t j = strlen(cp->lc_name) + 2;
530 if((i += j) > 72){
531 i = j;
532 fprintf(fp, "\n");
533 ++l;
535 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
539 if(fp != n_stdout){
540 page_or_print(fp, l);
541 Fclose(fp);
543 NYD_LEAVE;
544 return 0;
547 static int
548 a_lex__pcmd_cmp(void const *s1, void const *s2){
549 struct a_lex_cmd const * const *cp1, * const *cp2;
550 int rv;
551 NYD2_ENTER;
553 cp1 = s1;
554 cp2 = s2;
555 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
556 NYD2_LEAVE;
557 return rv;
560 static int
561 a_lex_c_help(void *v){
562 int rv;
563 char *arg;
564 NYD_ENTER;
566 /* Help for a single command? */
567 if((arg = *(char**)v) != NULL){
568 struct a_lex_ghost const *gp;
569 struct a_lex_cmd const *lcp, *lcpmax;
571 /* Ghosts take precedence */
572 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
573 if(!strcmp(arg, gp->lg_name)){
574 fprintf(n_stdout, "%s -> ", arg);
575 arg = gp->lg_cmd.s;
576 break;
579 lcpmax = &(lcp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
580 jredo:
581 for(; lcp < lcpmax; ++lcp){
582 if(is_prefix(arg, lcp->lc_name)){
583 fputs(arg, n_stdout);
584 if(strcmp(arg, lcp->lc_name))
585 fprintf(n_stdout, " (%s)", lcp->lc_name);
586 }else
587 continue;
589 #ifdef HAVE_DOCSTRINGS
590 fprintf(n_stdout, ": %s", V_(lcp->lc_doc));
591 #endif
592 if(n_poption & n_PO_D_V)
593 fprintf(n_stdout, "\n : %s", a_lex_cmdinfo(lcp));
594 putc('\n', n_stdout);
595 rv = 0;
596 goto jleave;
599 if(PTRCMP(lcpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
600 lcpmax = &(lcp =
601 a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
602 goto jredo;
605 if(gp != NULL){
606 fprintf(n_stdout, "%s\n", n_shexp_quote_cp(arg, TRU1));
607 rv = 0;
608 }else{
609 n_err(_("Unknown command: `%s'\n"), arg);
610 rv = 1;
612 }else{
613 /* Very ugly, but take care for compiler supported string lengths :( */
614 fputs(n_progname, n_stdout);
615 fputs(_(
616 " commands -- <msglist> denotes message specifications,\n"
617 "e.g., 1-5, :n or ., separated by spaces:\n"), n_stdout);
618 fputs(_(
619 "\n"
620 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
621 "Type <msglist> like `type' but always show all headers\n"
622 "next goto and type next message\n"
623 "from <msglist> (search and) print header summary for the given list\n"
624 "headers header summary for messages surrounding \"dot\"\n"
625 "delete <msglist> delete messages (can be `undelete'd)\n"),
626 n_stdout);
628 fputs(_(
629 "\n"
630 "save <msglist> folder append messages to folder and mark as saved\n"
631 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
632 "write <msglist> file write message contents to file (prompts for parts)\n"
633 "Reply <msglist> reply to message senders only\n"
634 "reply <msglist> like `Reply', but address all recipients\n"
635 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
636 n_stdout);
638 fputs(_(
639 "\n"
640 "mail <recipients> compose a mail for the given recipients\n"
641 "file folder change to another mailbox\n"
642 "File folder like `file', but open readonly\n"
643 "quit quit and apply changes to the current mailbox\n"
644 "xit or exit like `quit', but discard changes\n"
645 "!shell command shell escape\n"
646 "list [<anything>] all available commands [in search order]\n"),
647 n_stdout);
649 rv = (ferror(n_stdout) != 0);
651 jleave:
652 NYD_LEAVE;
653 return rv;
656 static int
657 a_lex_c_exit(void *v){
658 NYD_ENTER;
659 n_UNUSED(v);
661 if(n_psonce & n_PSO_STARTED){
662 /* In recursed state, return error to just pop the input level */
663 if(!(n_pstate & n_PS_SOURCING)){
664 #ifdef n_HAVE_TCAP
665 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
666 n_termcap_destroy();
667 #endif
668 exit(n_EXIT_OK);
671 n_pstate |= n_PS_EXIT;
672 NYD_LEAVE;
673 return 0;
676 static int
677 a_lex_c_quit(void *v){
678 NYD_ENTER;
679 n_UNUSED(v);
681 /* If we are n_PS_SOURCING, then return 1 so _evaluate() can handle it.
682 * Otherwise return -1 to abort command loop */
683 n_pstate |= n_PS_EXIT;
684 NYD_LEAVE;
685 return 0;
688 static int
689 a_lex_c_version(void *v){
690 int longest, rv;
691 char *iop;
692 char const *cp, **arr;
693 size_t i, i2;
694 NYD_ENTER;
695 n_UNUSED(v);
697 fprintf(n_stdout, _("%s version %s\nFeatures included (+) or not (-)\n"),
698 n_uagent, ok_vlook(version));
700 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
701 i = strlen(cp = &ok_vlook(features)[1]) +1;
702 iop = salloc(i);
703 memcpy(iop, cp, i);
705 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
706 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
707 arr[i] = cp;
708 i2 = strlen(cp);
709 longest = n_MAX(longest, (int)i2);
711 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
713 for(++longest, i2 = 0; i-- > 0;){
714 cp = *(arr++);
715 fprintf(n_stdout, "%-*s ", longest, cp);
716 i2 += longest;
717 if(UICMP(z, ++i2 + longest, >=, n_scrnwidth) || i == 0){
718 i2 = 0;
719 putc('\n', n_stdout);
723 if((rv = ferror(n_stdout) != 0))
724 clearerr(n_stdout);
725 NYD_LEAVE;
726 return rv;
729 static int
730 a_lex__version_cmp(void const *s1, void const *s2){
731 char const * const *cp1, * const *cp2;
732 int rv;
733 NYD2_ENTER;
735 cp1 = s1;
736 cp2 = s2;
737 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
738 NYD2_LEAVE;
739 return rv;
742 static void
743 a_lex_update_pstate(void){
744 bool_t act;
745 NYD_ENTER;
747 act = ((n_pstate & n_PS_SIGWINCH_PEND) != 0);
748 n_pstate &= ~n_PS_PSTATE_PENDMASK;
750 if(act){
751 char buf[32];
753 snprintf(buf, sizeof buf, "%d", n_scrnwidth);
754 ok_vset(COLUMNS, buf);
755 snprintf(buf, sizeof buf, "%d", n_scrnheight);
756 ok_vset(LINES, buf);
758 NYD_LEAVE;
761 static int
762 a_lex_evaluate(struct a_lex_eval_ctx *evp){
763 /* xxx old style(9), but also old code */
764 struct str line;
765 char _wordbuf[2], *arglist_base[MAXARGC], **arglist, *cp, *word;
766 struct a_lex_ghost *gp;
767 struct a_lex_cmd const *cmd;
768 int rv, c;
769 enum {
770 a_NONE = 0,
771 a_GHOST_MASK = (1<<3) - 1, /* Ghost recursion counter bits */
772 a_NOPREFIX = 1<<4, /* Modifier prefix not allowed right now */
773 a_NOGHOST = 1<<5, /* No ghost expansion modifier */
774 /* New command modifier prefixes must be reflected in a_lex_c_ghost()! */
775 a_IGNERR = 1<<6, /* ignerr modifier prefix */
776 a_WYSH = 1<<7, /* XXX v15+ drop wysh modifier prefix */
777 a_VPUT = 1<<8 /* vput modifier prefix */
778 } flags;
779 NYD_ENTER;
781 flags = a_NONE;
782 rv = 1;
783 cmd = NULL;
784 gp = NULL;
785 arglist = arglist_base;
786 line = evp->le_line; /* XXX don't change original (buffer pointer) */
787 assert(line.s[line.l] == '\0');
788 evp->le_add_history = FAL0;
790 /* Command ghosts that refer to shell commands or macro expansion restart */
791 jrestart:
793 /* Strip the white space away from end and beginning of command */
794 if(line.l > 0){
795 size_t i = line.l;
797 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
798 --i;
799 line.l = i;
801 for(cp = line.s; spacechar(*cp); ++cp)
803 line.l -= PTR2SIZE(cp - line.s);
805 /* Ignore null commands (comments) */
806 if(*cp == '#')
807 goto jerr0;
809 /* Handle ! differently to get the correct lexical conventions */
810 arglist[0] = cp;
811 if(*cp == '!')
812 ++cp;
813 /* Isolate the actual command; since it may not necessarily be
814 * separated from the arguments (as in `p1') we need to duplicate it to
815 * be able to create a NUL terminated version.
816 * We must be aware of several special one letter commands here */
817 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
818 (*cp == '|' || *cp == '~' || *cp == '?'))
819 ++cp;
820 c = (int)PTR2SIZE(cp - arglist[0]);
821 line.l -= c;
822 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
823 memcpy(word, arglist[0], c);
824 word[c] = '\0';
826 /* No-expansion modifier? */
827 if(!(flags & a_NOPREFIX) && *word == '\\'){
828 ++word;
829 --c;
830 flags |= a_NOGHOST;
833 /* It may be a modifier prefix */
834 if(c == sizeof("ignerr") -1 && !asccasecmp(word, "ignerr")){
835 flags |= a_NOPREFIX | a_IGNERR;
836 line.s = cp;
837 goto jrestart;
838 }else if(c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
839 flags |= a_NOPREFIX | a_WYSH;
840 line.s = cp;
841 goto jrestart;
842 }else if(c == sizeof("vput") -1 && !asccasecmp(word, "vput")){
843 flags |= a_NOPREFIX | a_VPUT;
844 line.s = cp;
845 goto jrestart;
848 /* Look up the command; if not found, bitch.
849 * Normally, a blank command would map to the first command in the
850 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
851 * confusion; act just the same for ghosts */
852 if(*word == '\0'){
853 if((n_pstate & n_PS_ROBOT) || gp != NULL)
854 goto jerr0;
855 cmd = &a_lex_cmd_tab[0];
856 goto jexec;
859 if(!(flags & a_NOGHOST) && (flags & a_GHOST_MASK) != a_GHOST_MASK){
860 ui8_t expcnt;
862 expcnt = (flags & a_GHOST_MASK);
863 ++expcnt;
864 flags = (flags & ~(a_GHOST_MASK | a_NOPREFIX)) | expcnt;
866 /* Avoid self-recursion; yes, the user could use \ no-expansion, but.. */
867 if(gp != NULL && !strcmp(word, gp->lg_name)){
868 if(n_poption & n_PO_D_V)
869 n_err(_("Actively avoiding self-recursion of `ghost': %s\n"), word);
870 }else for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)/* TODO BSRCH */
871 if(!strcmp(word, gp->lg_name)){
872 if(line.l > 0){
873 size_t i;
875 i = gp->lg_cmd.l;
876 line.s = salloc(i + line.l +1);
877 memcpy(line.s, gp->lg_cmd.s, i);
878 memcpy(line.s + i, cp, line.l);
879 line.s[i += line.l] = '\0';
880 line.l = i;
881 }else{
882 line.s = gp->lg_cmd.s;
883 line.l = gp->lg_cmd.l;
885 goto jrestart;
889 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
890 bool_t s;
892 if(!(s = condstack_isskip()) || (n_poption & n_PO_D_V))
893 n_err(_("Unknown command%s: `%s'\n"),
894 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
895 if(s)
896 goto jerr0;
897 if(cmd != NULL){
898 c_cmdnotsupp(NULL);
899 cmd = NULL;
901 n_pstate_var__em = n_m1;
902 goto jleave;
905 /* See if we should execute the command -- if a conditional we always
906 * execute it, otherwise, check the state of cond */
907 jexec:
908 if(!(cmd->lc_caflags & n_CMD_ARG_F) && condstack_isskip())
909 goto jerr0;
911 n_pstate_var__em = n_1;
913 /* Process the arguments to the command, depending on the type it expects */
914 if((cmd->lc_caflags & n_CMD_ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
915 !(n_poption & n_PO_BATCH_FLAG)){
916 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
917 cmd->lc_name);
918 goto jleave;
920 if(!(cmd->lc_caflags & n_CMD_ARG_M) && (n_psonce & n_PSO_SENDMODE)){
921 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
922 goto jleave;
924 if(cmd->lc_caflags & n_CMD_ARG_R){
925 if(n_pstate & n_PS_COMPOSE_MODE){
926 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
927 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
928 goto jleave;
930 /* TODO Nothing should prevent n_CMD_ARG_R in conjunction with
931 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
932 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING)){
933 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
934 cmd->lc_name);
935 goto jleave;
938 if((cmd->lc_caflags & n_CMD_ARG_S) && !(n_psonce & n_PSO_STARTED)){
939 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
940 goto jleave;
942 if(!(cmd->lc_caflags & n_CMD_ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
943 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
944 cmd->lc_name);
945 goto jleave;
948 if((cmd->lc_caflags & n_CMD_ARG_A) && mb.mb_type == MB_VOID){
949 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
950 goto jleave;
952 if((cmd->lc_caflags & n_CMD_ARG_W) && !(mb.mb_perm & MB_DELE)){
953 n_err(_("May not execute `%s' -- message file is read only\n"),
954 cmd->lc_name);
955 goto jleave;
958 if(cmd->lc_caflags & n_CMD_ARG_O)
959 n_OBSOLETE2(_("this command will be removed"), cmd->lc_name);
961 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
962 * TODO doesn't use any of those list commands which strip this mask,
963 * TODO and for now we misuse bits for checking relation to history;
964 * TODO argument state should be property of a per-command carrier instead */
965 n_pstate &= ~n_PS_ARGLIST_MASK;
967 if((flags & a_WYSH) &&
968 (cmd->lc_caflags & n_CMD_ARG_TYPE_MASK) != n_CMD_ARG_TYPE_WYRA){
969 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
970 flags &= ~a_WYSH;
973 if(flags & a_VPUT){
974 if(cmd->lc_caflags & n_CMD_ARG_V){
975 char const *xcp;
977 xcp = cp;
978 arglist[0] = n_shexp_parse_token_cp((n_SHEXP_PARSE_TRIMSPACE |
979 n_SHEXP_PARSE_LOG), &xcp);
980 line.l -= PTR2SIZE(xcp - cp);
981 cp = n_UNCONST(xcp);
982 if(cp == NULL)
983 xcp = N_("could not parse input token");
984 else if(!n_shexp_is_valid_varname(arglist[0]))
985 xcp = N_("not a valid variable name");
986 else if(!n_var_is_user_writable(arglist[0]))
987 xcp = N_("either not a user writable, or a boolean variable");
988 else
989 xcp = NULL;
990 if(xcp != NULL){
991 n_err("`%s': vput: %s: %s\n",
992 cmd->lc_name, V_(xcp), n_shexp_quote_cp(arglist[0], FAL0));
993 goto jleave;
995 ++arglist;
996 n_pstate |= n_PS_ARGMOD_VPUT; /* TODO YET useless since stripped later
997 * TODO on in getrawlist() etc., i.e., the argument vector producers,
998 * TODO therefore yet needs to be set again based on flags&a_VPUT! */
999 }else{
1000 n_err(_("`vput' prefix doesn't affect `%s'\n"), cmd->lc_name);
1001 flags &= ~a_VPUT;
1005 switch(cmd->lc_caflags & n_CMD_ARG_TYPE_MASK){
1006 case n_CMD_ARG_TYPE_MSGLIST:
1007 /* Message list defaulting to nearest forward legal message */
1008 if(n_msgvec == NULL)
1009 goto je96;
1010 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
1011 break;
1012 if(c == 0){
1013 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
1014 n_msgvec[1] = 0;
1016 if(n_msgvec[0] == 0){
1017 if(!(n_pstate & n_PS_HOOK_MASK))
1018 fprintf(n_stdout, _("No applicable messages\n"));
1019 break;
1021 rv = (*cmd->lc_func)(n_msgvec);
1022 break;
1024 case n_CMD_ARG_TYPE_NDMLIST:
1025 /* Message list with no defaults, but no error if none exist */
1026 if(n_msgvec == NULL){
1027 je96:
1028 n_err(_("Invalid use of message list\n"));
1029 break;
1031 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
1032 break;
1033 rv = (*cmd->lc_func)(n_msgvec);
1034 break;
1036 case n_CMD_ARG_TYPE_STRING:
1037 /* Just the straight string, old style, with leading blanks removed */
1038 while(blankspacechar(*cp))
1039 ++cp;
1040 rv = (*cmd->lc_func)(cp);
1041 break;
1042 case n_CMD_ARG_TYPE_RAWDAT:
1043 /* Just the straight string, leading blanks removed, placed in argv[] */
1044 while(blankspacechar(*cp))
1045 ++cp;
1046 *arglist++ = cp;
1047 *arglist = NULL;
1048 rv = (*cmd->lc_func)(arglist_base);
1049 break;
1051 case n_CMD_ARG_TYPE_WYSH:
1052 c = 1;
1053 if(0){
1054 /* FALLTHRU */
1055 case n_CMD_ARG_TYPE_WYRA:
1056 c = (flags & a_WYSH) ? 1 : 0;
1057 if(0){
1058 case n_CMD_ARG_TYPE_RAWLIST:
1059 c = 0;
1062 if((c = getrawlist((c != 0), arglist,
1063 n_NELEM(arglist_base) - PTR2SIZE(arglist - arglist_base),
1064 cp, line.l)) < 0){
1065 n_err(_("Invalid argument list\n"));
1066 break;
1069 if(c < cmd->lc_minargs){
1070 n_err(_("`%s' requires at least %u arg(s)\n"),
1071 cmd->lc_name, (ui32_t)cmd->lc_minargs);
1072 break;
1074 #undef lc_minargs
1075 if(c > cmd->lc_maxargs){
1076 n_err(_("`%s' takes no more than %u arg(s)\n"),
1077 cmd->lc_name, (ui32_t)cmd->lc_maxargs);
1078 break;
1080 #undef lc_maxargs
1082 if(flags & a_VPUT)
1083 n_pstate |= n_PS_ARGMOD_VPUT;
1084 rv = (*cmd->lc_func)(arglist_base);
1085 break;
1087 default:
1088 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
1089 cmd->lc_caflags & n_CMD_ARG_TYPE_MASK); )
1090 goto jerr0;
1093 if(!(cmd->lc_caflags & n_CMD_ARG_H))
1094 evp->le_add_history = (((cmd->lc_caflags & n_CMD_ARG_G) ||
1095 (n_pstate & n_PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
1097 if(!(cmd->lc_caflags & n_CMD_ARG_EM) && rv == 0)
1098 n_pstate_var__em = n_0;
1099 jleave:
1100 n_PS_ROOT_BLOCK(
1101 ok_vset(__qm, (rv == 0 ? n_0 : n_1));
1102 ok_vset(__em, n_pstate_var__em)
1105 if(flags & a_IGNERR){
1106 rv = 0;
1107 n_exit_status = n_EXIT_OK;
1110 /* Exit the current source file on error TODO what a mess! */
1111 if(rv == 0)
1112 n_pstate &= ~n_PS_EVAL_ERROR;
1113 else{
1114 n_pstate |= n_PS_EVAL_ERROR;
1115 if(rv < 0 || (n_pstate & n_PS_ROBOT)){ /* FIXME */
1116 rv = 1;
1117 goto jret;
1119 goto jret0;
1122 if(cmd == NULL)
1123 goto jret0;
1124 if((cmd->lc_caflags & n_CMD_ARG_P) && ok_blook(autoprint))
1125 if(visible(dot))
1126 n_source_inject_input(n_INPUT_INJECT_COMMIT, "\\type",
1127 sizeof("\\type") -1);
1129 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
1130 !(cmd->lc_caflags & n_CMD_ARG_T))
1131 n_pstate |= n_PS_SAW_COMMAND;
1132 jleave0:
1133 n_pstate &= ~n_PS_EVAL_ERROR;
1134 jret0:
1135 rv = 0;
1136 jret:
1137 NYD_LEAVE;
1138 return rv;
1139 jerr0:
1140 n_PS_ROOT_BLOCK(
1141 ok_vset(__qm, n_0);
1142 ok_vset(__em, n_0)
1144 goto jleave0;
1147 static struct a_lex_cmd const *
1148 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
1149 struct a_lex_cmd const *cp;
1150 NYD2_ENTER;
1152 for(cp = a_lex_cmd_tab;
1153 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
1154 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
1155 goto jleave;
1156 cp = NULL;
1157 jleave:
1158 NYD2_LEAVE;
1159 return cp;
1162 static void
1163 a_lex_hangup(int s){
1164 NYD_X; /* Signal handler */
1165 n_UNUSED(s);
1166 /* nothing to do? */
1167 exit(n_EXIT_ERR);
1170 static void
1171 a_lex_onintr(int s){ /* TODO block signals while acting */
1172 NYD_X; /* Signal handler */
1173 n_UNUSED(s);
1175 safe_signal(SIGINT, a_lex_onintr);
1177 termios_state_reset();
1178 close_all_files(); /* FIXME .. of current level ONLU! */
1180 a_lex_unstack(TRUM1);
1182 if(interrupts != 1)
1183 n_err_sighdl(_("Interrupt\n"));
1184 safe_signal(SIGPIPE, a_lex_oldpipe);
1185 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
1188 static void
1189 a_lex_unstack(bool_t eval_error){
1190 struct a_lex_input *lip;
1191 NYD_ENTER;
1193 /* Free input injections of this level first */
1194 /* C99 */{
1195 struct a_lex_input_inject **liipp, *liip;
1197 if((lip = a_lex_input) == NULL)
1198 liipp = &a_lex_input_inject;
1199 else
1200 liipp = &lip->li_inject;
1202 while((liip = *liipp) != NULL){
1203 *liipp = liip->lii_next;
1204 free(liip);
1207 if(lip == NULL || !(lip->li_flags & a_LEX_SLICE))
1208 n_memory_reset();
1211 if(lip == NULL){
1212 /* If called from a_lex_onintr(), be silent FIXME */
1213 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1214 if(eval_error == TRUM1 || !(n_psonce & n_PSO_STARTED))
1215 goto jleave;
1216 goto jerr;
1219 if(lip->li_flags & a_LEX_SLICE){ /* TODO Temporary hack */
1220 n_stdin = lip->li_slice_stdin;
1221 n_stdout = lip->li_slice_stdout;
1222 n_psonce = lip->li_slice_psonce;
1223 goto jthe_slice_hack;
1226 if(lip->li_flags & a_LEX_MACRO){
1227 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
1228 char **lp;
1230 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
1231 free(*lp);
1232 ++lip->li_loff;
1234 /* Part of lip's memory chunk, then */
1235 if(!(lip->li_flags & a_LEX_MACRO_CMD))
1236 free(lip->li_lines);
1238 }else{
1239 if(lip->li_flags & a_LEX_PIPE)
1240 /* XXX command manager should -TERM then -KILL instead of hoping
1241 * XXX for exit of provider due to EPIPE / SIGPIPE */
1242 Pclose(lip->li_file, TRU1);
1243 else
1244 Fclose(lip->li_file);
1247 if(!condstack_take(lip->li_cond)){
1248 n_err(_("Unmatched `if' at end of %s %s\n"),
1249 ((lip->li_flags & a_LEX_MACRO
1250 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1251 : _("`source'd file"))),
1252 lip->li_name);
1253 eval_error = TRU1;
1256 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1258 jthe_slice_hack:
1259 if(lip->li_on_finalize != NULL)
1260 (*lip->li_on_finalize)(lip->li_finalize_arg);
1262 if((a_lex_input = lip->li_outer) == NULL){
1263 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1264 }else{
1265 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1266 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1267 n_pstate &= ~n_PS_SOURCING;
1268 assert(n_pstate & n_PS_ROBOT);
1271 if(eval_error)
1272 goto jerr;
1273 jleave:
1274 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1275 free(lip);
1276 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1277 a_lex_unstack(TRUM1);
1278 NYD_LEAVE;
1279 return;
1281 jerr:
1282 if(lip != NULL){
1283 /* POSIX says
1284 * Any errors in the start-up file shall either cause mailx to
1285 * terminate with a diagnostic message and a non-zero status or to
1286 * continue after writing a diagnostic message, ignoring the
1287 * remainder of the lines in the start-up file
1288 * But print the diagnostic only for the outermost resource unless the
1289 * user is debugging or in verbose mode */
1290 if((n_poption & n_PO_D_V) ||
1291 (!(n_psonce & n_PSO_STARTED) &&
1292 !(lip->li_flags & (a_LEX_SLICE | a_LEX_MACRO)) &&
1293 lip->li_outer == NULL))
1294 n_alert(_("Stopped %s %s due to errors%s"),
1295 (n_psonce & n_PSO_STARTED
1296 ? (lip->li_flags & a_LEX_SLICE ? _("sliced in program")
1297 : (lip->li_flags & a_LEX_MACRO
1298 ? (lip->li_flags & a_LEX_MACRO_CMD
1299 ? _("evaluating command") : _("evaluating macro"))
1300 : (lip->li_flags & a_LEX_PIPE
1301 ? _("executing `source'd pipe")
1302 : _("loading `source'd file")))
1304 : (lip->li_flags & a_LEX_MACRO
1305 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1306 ? _("evaluating command line") : _("evaluating macro"))
1307 : _("loading initialization resource"))),
1308 lip->li_name,
1309 (n_poption & n_PO_DEBUG
1310 ? n_empty : _(" (enable *debug* for trace)")));
1313 if(!(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED))){
1314 if(n_poption & n_PO_D_V)
1315 n_alert(_("Non-interactive, bailing out due to errors "
1316 "in startup load phase"));
1317 exit(n_EXIT_ERR);
1319 goto jleave;
1322 static bool_t
1323 a_lex_source_file(char const *file, bool_t silent_open_error){
1324 struct a_lex_input *lip;
1325 size_t nlen;
1326 char *nbuf;
1327 bool_t ispipe;
1328 FILE *fip;
1329 NYD_ENTER;
1331 fip = NULL;
1333 /* Being a command argument file is space-trimmed *//* TODO v15 with
1334 * TODO WYRALIST this is no longer necessary true, and for that we
1335 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1336 #if 0
1337 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
1338 file[--nlen] == '|')))
1339 #else
1340 ispipe = FAL0;
1341 if(!silent_open_error)
1342 for(nlen = strlen(file); nlen > 0;){
1343 char c;
1345 c = file[--nlen];
1346 if(!blankchar(c)){
1347 if(c == '|'){
1348 nbuf = savestrbuf(file, nlen);
1349 ispipe = TRU1;
1351 break;
1354 #endif
1356 if(ispipe){
1357 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1358 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL)
1359 goto jeopencheck;
1360 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1361 goto jeopencheck;
1362 else if((fip = Fopen(nbuf, "r")) == NULL){
1363 jeopencheck:
1364 if(!silent_open_error || (n_poption & n_PO_D_V))
1365 n_perr(nbuf, 0);
1366 if(silent_open_error)
1367 fip = (FILE*)-1;
1368 goto jleave;
1371 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
1372 (nlen = strlen(nbuf) +1));
1373 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1374 lip->li_outer = a_lex_input;
1375 lip->li_file = fip;
1376 lip->li_cond = condstack_release();
1377 n_memory_autorec_push(&lip->li_autorecmem[0]);
1378 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1379 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1380 ? a_LEX_SUPER_MACRO : 0);
1381 memcpy(lip->li_name, nbuf, nlen);
1383 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1384 a_lex_input = lip;
1385 if(!a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC))
1386 fip = NULL;
1387 jleave:
1388 NYD_LEAVE;
1389 return (fip != NULL);
1392 static bool_t
1393 a_lex_load(struct a_lex_input *lip){
1394 bool_t rv;
1395 NYD2_ENTER;
1397 assert(!(n_psonce & n_PSO_STARTED));
1398 assert(a_lex_input == NULL);
1400 /* POSIX:
1401 * Any errors in the start-up file shall either cause mailx to terminate
1402 * with a diagnostic message and a non-zero status or to continue after
1403 * writing a diagnostic message, ignoring the remainder of the lines in
1404 * the start-up file. */
1405 lip->li_cond = condstack_release();
1406 n_memory_autorec_push(&lip->li_autorecmem[0]);
1408 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1409 n_pstate |= n_PS_ROBOT |
1410 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1412 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1413 if(n_poption & n_PO_D_V)
1414 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1415 a_lex_input = lip;
1416 if(!(rv = n_commands())){
1417 if(!(n_psonce & n_PSO_INTERACTIVE)){
1418 if(n_poption & n_PO_D_V)
1419 n_alert(_("Non-interactive program mode, forced exit"));
1420 exit(n_EXIT_ERR);
1421 }else if(n_poption & n_PO_BATCH_FLAG){
1422 char const *beoe;
1424 if((beoe = ok_vlook(batch_exit_on_error)) != NULL && *beoe == '1')
1425 n_pstate |= n_PS_EXIT;
1428 /* n_PS_EXIT handled by callers */
1429 NYD2_LEAVE;
1430 return rv;
1433 static void
1434 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1435 NYD_X; /* Signal handler */
1436 n_UNUSED(sig);
1437 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1440 static bool_t
1441 a_commands_recursive(enum n_lexinput_flags lif){
1442 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1443 sighandler_type soldhdl;
1444 sigset_t sintset, soldset;
1445 struct a_lex_eval_ctx ev;
1446 bool_t rv, ever;
1447 NYD2_ENTER;
1449 memset(&ev, 0, sizeof ev);
1451 sigfillset(&sintset);
1452 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1453 hadint = FAL0;
1454 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1455 safe_signal(SIGINT, &a_lex__cmdrecint);
1456 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1457 hadint = TRU1;
1458 goto jjump;
1461 sigprocmask(SIG_SETMASK, &soldset, NULL);
1463 n_COLOUR( n_colour_env_push(); )
1464 rv = TRU1;
1465 for(ever = FAL0;; ever = TRU1){
1466 char const *beoe;
1467 int n;
1469 if(ever)
1470 n_memory_reset();
1472 /* Read a line of commands and handle end of file specially */
1473 ev.le_line.l = ev.le_line_size;
1474 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l, NULL);
1475 ev.le_line_size = (ui32_t)ev.le_line.l;
1476 ev.le_line.l = (ui32_t)n;
1478 if(n < 0)
1479 break;
1481 n = a_lex_evaluate(&ev);
1482 beoe = (n_poption & n_PO_BATCH_FLAG)
1483 ? ok_vlook(batch_exit_on_error) : NULL;
1485 if(n){
1486 if(beoe != NULL && *beoe == '1'){
1487 if(n_exit_status == n_EXIT_OK)
1488 n_exit_status = n_EXIT_ERR;
1490 rv = FAL0;
1491 break;
1493 if(beoe != NULL){
1494 if(n_exit_status != n_EXIT_OK)
1495 break;
1498 jjump: /* TODO */
1499 a_lex_unstack(!rv);
1500 n_COLOUR( n_colour_env_pop(FAL0); )
1502 if(ev.le_line.s != NULL)
1503 free(ev.le_line.s);
1505 if(soldhdl != SIG_IGN)
1506 safe_signal(SIGINT, soldhdl);
1507 NYD2_LEAVE;
1508 if(hadint){
1509 sigprocmask(SIG_SETMASK, &soldset, NULL);
1510 n_raise(SIGINT);
1512 return rv;
1515 static int
1516 a_lex_c_read(void *v){ /* TODO IFS? how? -r */
1517 struct n_sigman sm;
1518 char const **argv, *cp, *cp2;
1519 char *linebuf;
1520 size_t linesize;
1521 int rv;
1522 NYD2_ENTER;
1524 rv = 0;
1525 linesize = 0;
1526 linebuf = NULL;
1527 argv = v;
1529 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL){
1530 case 0:
1531 break;
1532 default:
1533 rv = 1;
1534 goto jleave;
1536 rv = n_lex_input(((n_pstate & n_PS_COMPOSE_MODE
1537 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT) |
1538 n_LEXINPUT_FORCE_STDIN | n_LEXINPUT_NL_ESC |
1539 n_LEXINPUT_PROMPT_NONE /* XXX POSIX: PS2: yes! */),
1540 NULL, &linebuf, &linesize, NULL);
1541 if(rv < 0)
1542 goto jleave;
1544 if(rv > 0){
1545 cp = linebuf;
1547 for(rv = 0; *argv != NULL; ++argv){
1548 char c;
1550 while(blankspacechar(*cp))
1551 ++cp;
1552 if(*cp == '\0')
1553 break;
1555 /* The last variable gets the remaining line less trailing IFS */
1556 if(argv[1] == NULL){
1557 for(cp2 = cp; *cp2 != '\0'; ++cp2)
1559 for(; cp2 > cp; --cp2){
1560 c = cp2[-1];
1561 if(!blankspacechar(c))
1562 break;
1564 }else
1565 for(cp2 = cp; (c = *++cp2) != '\0';)
1566 if(blankspacechar(c))
1567 break;
1569 /* C99 xxx This is a CC warning workaround (-Wbad-function-cast) */{
1570 char *vcp;
1572 vcp = savestrbuf(cp, PTR2SIZE(cp2 - cp));
1573 if(!a_lex__read_set(*argv, vcp)){
1574 rv = 1;
1575 break;
1579 cp = cp2;
1583 /* Set the remains to the empty string */
1584 for(; *argv != NULL; ++argv)
1585 if(!a_lex__read_set(*argv, n_empty)){
1586 rv = 1;
1587 break;
1590 if(rv == 0)
1591 n_pstate_var__em = n_0;
1593 n_sigman_cleanup_ping(&sm);
1594 jleave:
1595 if(linebuf != NULL)
1596 free(linebuf);
1597 NYD2_LEAVE;
1598 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
1599 return rv;
1602 static bool_t
1603 a_lex__read_set(char const *cp, char const *value){
1604 bool_t rv;
1605 NYD2_ENTER;
1607 if(!n_shexp_is_valid_varname(cp))
1608 value = N_("not a valid variable name");
1609 else if(!n_var_is_user_writable(cp))
1610 value = N_("variable is read-only");
1611 else if(!n_var_vset(cp, (uintptr_t)value))
1612 value = N_("failed to update variable value");
1613 else{
1614 rv = TRU1;
1615 goto jleave;
1617 n_err("`read': %s: %s\n", V_(value), n_shexp_quote_cp(cp, FAL0));
1618 rv = FAL0;
1619 jleave:
1620 NYD2_LEAVE;
1621 return rv;
1624 FL int
1625 c_cmdnotsupp(void *vp){
1626 NYD_ENTER;
1627 n_UNUSED(vp);
1628 n_err(_("The requested feature is not compiled in\n"));
1629 NYD_LEAVE;
1630 return 1;
1633 FL bool_t
1634 n_commands(void){ /* FIXME */
1635 struct a_lex_eval_ctx ev;
1636 int n, eofcnt;
1637 bool_t volatile rv;
1638 NYD_ENTER;
1640 rv = TRU1;
1642 if (!(n_pstate & n_PS_SOURCING)) {
1643 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1644 safe_signal(SIGINT, &a_lex_onintr);
1645 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1646 safe_signal(SIGHUP, &a_lex_hangup);
1648 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1649 safe_signal(SIGPIPE, a_lex_oldpipe);
1651 memset(&ev, 0, sizeof ev);
1653 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1654 for (eofcnt = 0;;) {
1655 n_COLOUR( n_colour_env_pop(TRU1); )
1657 /* TODO Unless we have our signal manager (or however we do it) child
1658 * TODO processes may have time slots where their execution isn't
1659 * TODO protected by signal handlers (in between start and setup
1660 * TODO completed). close_all_files() is only called from onintr()
1661 * TODO so those may linger possibly forever */
1662 if(!(n_pstate & n_PS_SOURCING))
1663 close_all_files();
1665 interrupts = 0;
1667 n_memory_reset();
1669 if (!(n_pstate & n_PS_SOURCING)) {
1670 char *cp;
1672 /* TODO Note: this buffer may contain a password. We should redefine
1673 * TODO the code flow which has to do that */
1674 if ((cp = termios_state.ts_linebuf) != NULL) {
1675 termios_state.ts_linebuf = NULL;
1676 termios_state.ts_linesize = 0;
1677 free(cp); /* TODO pool give-back */
1679 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1680 if (ev.le_line.l > LINESIZE * 3) {
1681 free(ev.le_line.s); /* TODO pool! but what? */
1682 ev.le_line.s = NULL;
1683 ev.le_line.l = ev.le_line_size = 0;
1687 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1688 char *cp;
1690 if ((cp = ok_vlook(newmail)) != NULL) {
1691 struct stat st;
1693 /* FIXME TEST WITH NOPOLL ETC. !!! */
1694 n = (cp != NULL && strcmp(cp, "nopoll"));
1695 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1696 st.st_size > mailsize) ||
1697 (mb.mb_type == MB_MAILDIR && n != 0)) {
1698 size_t odot = PTR2SIZE(dot - message);
1699 ui32_t odid = (n_pstate & n_PS_DID_PRINT_DOT);
1701 if (setfile(mailname,
1702 FEDIT_NEWMAIL |
1703 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1704 n_exit_status |= n_EXIT_ERR;
1705 rv = FAL0;
1706 break;
1708 dot = message + odot;
1709 n_pstate |= odid;
1713 n_exit_status = n_EXIT_OK;
1716 /* Read a line of commands and handle end of file specially */
1717 ev.le_line.l = ev.le_line_size;
1718 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1719 &ev.le_line.s, &ev.le_line.l, NULL);
1720 ev.le_line_size = (ui32_t)ev.le_line.l;
1721 ev.le_line.l = (ui32_t)n;
1723 if (n < 0) {
1724 /* FIXME did unstack() when n_PS_SOURCING, only break with n_PS_LOADING */
1725 if (!(n_pstate & n_PS_ROBOT) &&
1726 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof) &&
1727 ++eofcnt < 4) {
1728 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1729 n_lex_input_clearerr();
1730 continue;
1732 break;
1735 n_pstate &= ~n_PS_HOOK_MASK;
1736 /* C99 */{
1737 char const *beoe;
1738 int estat;
1740 estat = a_lex_evaluate(&ev);
1741 beoe = (n_poption & n_PO_BATCH_FLAG)
1742 ? ok_vlook(batch_exit_on_error) : NULL;
1744 if(estat){
1745 if(beoe != NULL && *beoe == '1'){
1746 if(n_exit_status == n_EXIT_OK)
1747 n_exit_status = n_EXIT_ERR;
1748 rv = FAL0;
1749 break;
1751 if(!(n_psonce & n_PSO_STARTED)){ /* TODO join n_PS_EVAL_ERROR */
1752 if(a_lex_input == NULL ||
1753 !(a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)){
1754 rv = FAL0;
1755 break;
1757 }else
1758 break;
1761 if(beoe != NULL){
1762 if(n_exit_status != n_EXIT_OK)
1763 break;
1764 /* TODO n_PS_EVAL_ERROR and n_PS_SOURCING! Sigh!! */
1765 if((n_pstate & (n_PS_SOURCING | n_PS_EVAL_ERROR)
1766 ) == n_PS_EVAL_ERROR){
1767 n_exit_status = n_EXIT_ERR;
1768 break;
1773 if(!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE) &&
1774 ev.le_add_history)
1775 n_tty_addhist(ev.le_line.s, (ev.le_add_history != TRU1));
1777 if(n_pstate & n_PS_EXIT)
1778 break;
1781 a_lex_unstack(!rv);
1783 if (ev.le_line.s != NULL)
1784 free(ev.le_line.s);
1785 NYD_LEAVE;
1786 return rv;
1789 FL void
1790 n_lex_input_clearerr(void){
1791 FILE *fp;
1792 NYD2_ENTER;
1794 fp = NULL;
1796 if(a_lex_input == NULL)
1797 fp = n_stdin;
1798 else if(!(a_lex_input->li_flags & (a_LEX_FORCE_EOF |
1799 a_LEX_PIPE | a_LEX_MACRO | a_LEX_SLICE)))
1800 fp = a_lex_input->li_file;
1802 if(fp != NULL)
1803 clearerr(fp);
1804 NYD2_LEAVE;
1807 FL int
1808 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1809 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1810 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1811 struct n_string xprompt;
1812 FILE *ifile;
1813 bool_t doprompt, dotty;
1814 char const *iftype;
1815 int nold, n;
1816 NYD2_ENTER;
1818 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_FORCE_EOF)){
1819 n = -1;
1820 goto jleave;
1823 /* Special case macro mode: never need to prompt, lines have always been
1824 * unfolded already */
1825 if(!(lif & n_LEXINPUT_FORCE_STDIN) &&
1826 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1827 struct a_lex_input_inject *liip;
1829 if(*linebuf != NULL)
1830 free(*linebuf);
1832 /* Injection in progress? Don't care about the autocommit state here */
1833 if((liip = a_lex_input->li_inject) != NULL){
1834 a_lex_input->li_inject = liip->lii_next;
1836 *linesize = liip->lii_len;
1837 *linebuf = (char*)liip;
1838 memmove(*linebuf, liip->lii_dat, liip->lii_len +1);
1839 iftype = "INJECTION";
1840 }else{
1841 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1842 *linesize = 0;
1843 n = -1;
1844 goto jleave;
1847 ++a_lex_input->li_loff;
1848 *linesize = strlen(*linebuf);
1849 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1850 *linebuf = sbufdup(*linebuf, *linesize);
1852 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1853 ? "-X OPTION"
1854 : (a_lex_input->li_flags & a_LEX_MACRO_CMD) ? "CMD" : "MACRO";
1856 n = (int)*linesize;
1857 n_pstate |= n_PS_READLINE_NL;
1858 goto jhave_dat;
1861 /* Injection in progress? */
1862 if(!(lif & n_LEXINPUT_FORCE_STDIN)){
1863 struct a_lex_input_inject **liipp, *liip;
1865 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
1866 : &a_lex_input->li_inject;
1868 if((liip = *liipp) != NULL){
1869 *liipp = liip->lii_next;
1871 if(liip->lii_commit){
1872 if(*linebuf != NULL)
1873 free(*linebuf);
1875 /* Simply reuse the buffer */
1876 n = (int)(*linesize = liip->lii_len);
1877 *linebuf = (char*)liip;
1878 memmove(*linebuf, liip->lii_dat, liip->lii_len +1);
1879 iftype = "INJECTION";
1880 n_pstate |= n_PS_READLINE_NL;
1881 goto jhave_dat;
1882 }else{
1883 string = savestrbuf(liip->lii_dat, liip->lii_len);
1884 free(liip);
1889 n_pstate &= ~n_PS_READLINE_NL;
1890 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1891 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1892 doprompt = ((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1893 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT));
1894 dotty = (doprompt && !ok_blook(line_editor_disable));
1895 if(!doprompt)
1896 lif |= n_LEXINPUT_PROMPT_NONE;
1897 else{
1898 if(!dotty)
1899 n_string_creat_auto(&xprompt);
1900 if(prompt == NULL)
1901 lif |= n_LEXINPUT_PROMPT_EVAL;
1904 /* Ensure stdout is flushed first anyway */
1905 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1906 fflush(n_stdout);
1908 ifile = ((lif & n_LEXINPUT_FORCE_STDIN) || a_lex_input == NULL) ? n_stdin
1909 : a_lex_input->li_file;
1910 if(ifile == NULL){
1911 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1912 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO));
1913 ifile = n_stdin;
1916 for(nold = n = 0;;){
1917 if(dotty){
1918 assert(ifile == n_stdin);
1919 if(string != NULL && (n = (int)strlen(string)) > 0){
1920 if(*linesize > 0)
1921 *linesize += n +1;
1922 else
1923 *linesize = (size_t)n + LINESIZE +1;
1924 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1925 memcpy(*linebuf, string, (size_t)n +1);
1927 string = NULL;
1928 /* TODO if nold>0, don't redisplay the entire line!
1929 * TODO needs complete redesign ... */
1930 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1931 n_MEMORY_DEBUG_ARGSCALL);
1932 }else{
1933 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1934 n_tty_create_prompt(&xprompt, prompt, lif);
1935 if(xprompt.s_len > 0){
1936 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1937 fflush(n_stdout);
1941 n = (readline_restart)(ifile, linebuf, linesize, n
1942 n_MEMORY_DEBUG_ARGSCALL);
1944 if(n > 0 && nold > 0){
1945 int i = 0;
1946 char const *cp = *linebuf + nold;
1948 while(blankspacechar(*cp) && nold + i < n)
1949 ++cp, ++i;
1950 if(i > 0){
1951 memmove(*linebuf + nold, cp, n - nold - i);
1952 n -= i;
1953 (*linebuf)[n] = '\0';
1958 if(n <= 0)
1959 break;
1961 /* POSIX says:
1962 * An unquoted <backslash> at the end of a command line shall
1963 * be discarded and the next line shall continue the command */
1964 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1965 if(dotty)
1966 n_pstate |= n_PS_READLINE_NL;
1967 break;
1969 /* Definitely outside of quotes, thus the quoting rules are so that an
1970 * uneven number of successive reverse solidus at EOL is a continuation */
1971 if(n > 1){
1972 size_t i, j;
1974 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1975 if((*linebuf)[i] != '\\')
1976 break;
1977 if(!(j & 1))
1978 break;
1980 (*linebuf)[nold = --n] = '\0';
1981 lif |= n_LEXINPUT_NL_FOLLOW;
1984 if(n < 0)
1985 goto jleave;
1986 (*linebuf)[*linesize = n] = '\0';
1988 jhave_dat:
1989 #if 0
1990 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1991 char *cp, c;
1992 size_t i;
1994 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1995 c = *--cp;
1996 if(!blankspacechar(c))
1997 break;
1999 (*linebuf)[n = (int)i] = '\0';
2002 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
2003 char *cp, c;
2004 size_t j, i;
2006 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
2007 c = *cp++;
2008 if(!blankspacechar(c))
2009 break;
2011 if(i > 0){
2012 memmove(&(*linebuf)[0], &(*linebuf)[i], j -= i);
2013 (*linebuf)[n = (int)j] = '\0';
2016 #endif /* 0 (notyet - must take care for reverse solidus escaped space) */
2018 if(n_poption & n_PO_D_VV)
2019 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
2020 jleave:
2021 if (n_pstate & n_PS_PSTATE_PENDMASK)
2022 a_lex_update_pstate();
2024 /* TODO We need to special case a_LEX_SLICE, since that is not managed by us
2025 * TODO but only established from the outside and we need to drop this
2026 * TODO overlay context somehow */
2027 if(n < 0 && a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SLICE))
2028 a_lex_unstack(FAL0);
2029 NYD2_LEAVE;
2030 return n;
2033 FL char *
2034 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
2035 char const *string){
2036 struct n_sigman sm;
2037 size_t linesize;
2038 char *linebuf, *rv;
2039 int n;
2040 NYD2_ENTER;
2042 linesize = 0;
2043 linebuf = NULL;
2044 rv = NULL;
2046 n_SIGMAN_ENTER_SWITCH(&sm, n_SIGMAN_ALL) {
2047 case 0:
2048 break;
2049 default:
2050 goto jleave;
2053 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
2054 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
2055 (lif & n_LEXINPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE))
2056 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
2058 n_sigman_cleanup_ping(&sm);
2059 jleave:
2060 if(linebuf != NULL)
2061 free(linebuf);
2062 NYD2_LEAVE;
2063 n_sigman_leave(&sm, n_SIGMAN_VIPSIGS_NTTYOUT);
2064 return rv;
2067 FL void
2068 n_load(char const *name){
2069 struct a_lex_input *lip;
2070 size_t i;
2071 FILE *fip;
2072 NYD_ENTER;
2074 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
2075 goto jleave;
2077 i = strlen(name) +1;
2078 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) + i);
2079 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2080 lip->li_file = fip;
2081 lip->li_flags = a_LEX_FREE;
2082 memcpy(lip->li_name, name, i);
2084 a_lex_load(lip);
2085 n_pstate &= ~n_PS_EXIT;
2086 jleave:
2087 NYD_LEAVE;
2090 FL void
2091 n_load_Xargs(char const **lines, size_t cnt){
2092 static char const name[] = "-X";
2094 ui8_t buf[sizeof(struct a_lex_input) + sizeof name];
2095 char const *srcp, *xsrcp;
2096 char *cp;
2097 size_t imax, i, len;
2098 struct a_lex_input *lip;
2099 NYD_ENTER;
2101 lip = (void*)buf;
2102 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2103 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
2104 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
2105 memcpy(lip->li_name, name, sizeof name);
2107 /* The problem being that we want to support reverse solidus newline
2108 * escaping also within multiline -X, i.e., POSIX says:
2109 * An unquoted <backslash> at the end of a command line shall
2110 * be discarded and the next line shall continue the command
2111 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
2112 * entire lines array and set _MACRO_FREE_DATA */
2113 imax = cnt + 1;
2114 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
2116 /* For each of the input lines.. */
2117 for(i = len = 0, cp = NULL; cnt > 0;){
2118 bool_t keep;
2119 size_t j;
2121 if((j = strlen(srcp = *lines)) == 0){
2122 ++lines, --cnt;
2123 continue;
2126 /* Separate one line from a possible multiline input string */
2127 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
2128 *lines = &xsrcp[1];
2129 j = PTR2SIZE(xsrcp - srcp);
2130 }else
2131 ++lines, --cnt;
2133 /* The (separated) string may itself indicate soft newline escaping */
2134 if((keep = (srcp[j - 1] == '\\'))){
2135 size_t xj, xk;
2137 /* Need an uneven number of reverse solidus */
2138 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
2139 if(srcp[xj] != '\\')
2140 break;
2141 if(xk & 1)
2142 --j;
2143 else
2144 keep = FAL0;
2147 /* Strip any leading WS from follow lines, then */
2148 if(cp != NULL)
2149 while(j > 0 && blankspacechar(*srcp))
2150 ++srcp, --j;
2152 if(j > 0){
2153 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
2154 imax += 4;
2155 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
2156 imax);
2158 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
2159 memcpy(&cp[len], srcp, j);
2160 cp[len += j] = '\0';
2162 if(!keep)
2163 ++i;
2165 if(!keep)
2166 cp = NULL, len = 0;
2168 if(cp != NULL){
2169 assert(i + 1 < imax);
2170 lip->li_lines[i++] = cp;
2172 lip->li_lines[i] = NULL;
2174 a_lex_load(lip);
2175 if(n_pstate & n_PS_EXIT)
2176 exit(n_exit_status);
2177 NYD_LEAVE;
2180 FL int
2181 c_source(void *v){
2182 int rv;
2183 NYD_ENTER;
2185 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
2186 NYD_LEAVE;
2187 return rv;
2190 FL int
2191 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
2192 int rv;
2193 NYD_ENTER;
2195 rv = (a_lex_source_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
2196 NYD_LEAVE;
2197 return rv;
2200 FL bool_t
2201 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
2202 void (*on_finalize)(void*), void *finalize_arg){
2203 struct a_lex_input *lip;
2204 size_t i;
2205 int rv;
2206 NYD_ENTER;
2208 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2209 (i = strlen(name) +1));
2210 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2211 lip->li_outer = a_lex_input;
2212 lip->li_file = NULL;
2213 lip->li_cond = condstack_release();
2214 n_memory_autorec_push(&lip->li_autorecmem[0]);
2215 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
2216 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2217 ? a_LEX_SUPER_MACRO : 0);
2218 lip->li_lines = lines;
2219 lip->li_on_finalize = on_finalize;
2220 lip->li_finalize_arg = finalize_arg;
2221 memcpy(lip->li_name, name, i);
2223 n_pstate |= n_PS_ROBOT;
2224 a_lex_input = lip;
2225 rv = a_commands_recursive(lif);
2226 NYD_LEAVE;
2227 return rv;
2230 FL bool_t
2231 n_source_command(enum n_lexinput_flags lif, char const *cmd){
2232 struct a_lex_input *lip;
2233 size_t i, ial;
2234 bool_t rv;
2235 NYD_ENTER;
2237 i = strlen(cmd) +1;
2238 ial = n_ALIGN(i);
2240 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2241 ial + 2*sizeof(char*));
2242 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2243 lip->li_outer = a_lex_input;
2244 lip->li_cond = condstack_release();
2245 n_memory_autorec_push(&lip->li_autorecmem[0]);
2246 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_CMD |
2247 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2248 ? a_LEX_SUPER_MACRO : 0);
2249 lip->li_lines = (void*)&lip->li_name[ial];
2250 memcpy(lip->li_lines[0] = &lip->li_name[0], cmd, i);
2251 lip->li_lines[1] = NULL;
2253 n_pstate |= n_PS_ROBOT;
2254 a_lex_input = lip;
2255 rv = a_commands_recursive(lif);
2256 NYD_LEAVE;
2257 return rv;
2260 FL void
2261 n_source_slice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
2262 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
2263 struct a_lex_input *lip;
2264 size_t i;
2265 NYD_ENTER;
2267 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2268 (i = strlen(cmd) +1));
2269 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2270 lip->li_outer = a_lex_input;
2271 lip->li_file = new_stdin;
2272 lip->li_flags = a_LEX_FREE | a_LEX_SLICE;
2273 lip->li_on_finalize = on_finalize;
2274 lip->li_finalize_arg = finalize_arg;
2275 lip->li_slice_stdin = n_stdin;
2276 lip->li_slice_stdout = n_stdout;
2277 lip->li_slice_psonce = n_psonce;
2278 memcpy(lip->li_name, cmd, i);
2280 n_stdin = new_stdin;
2281 n_stdout = new_stdout;
2282 n_psonce = new_psonce;
2283 n_pstate |= n_PS_ROBOT;
2284 a_lex_input = lip;
2285 NYD_LEAVE;
2288 FL void
2289 n_source_slice_hack_remove_after_jump(void){
2290 a_lex_unstack(FAL0);
2293 FL bool_t
2294 n_source_may_yield_control(void){ /* TODO this is a terrible hack */
2295 /* TODO This is obviously hacky in that it depends on _input_stack not
2296 * TODO loosing any flags when creating new contexts... Maybe this
2297 * TODO function should instead walk all up the context stack when
2298 * TODO there is one, and verify neither level prevents yielding! */
2299 struct a_lex_input *lip;
2300 bool_t rv;
2301 NYD2_ENTER;
2303 rv = FAL0;
2305 /* Only when interactive and startup completed */
2306 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) !=
2307 (n_PSO_INTERACTIVE | n_PSO_STARTED))
2308 goto jleave;
2310 /* Not when running any hook */
2311 if(n_pstate & n_PS_HOOK_MASK)
2312 goto jleave;
2314 /* Traverse up the stack:
2315 * . not when controlled by a child process
2316 * TODO . not when there are pipes involved, we neither handle job control,
2317 * TODO nor process groups, that is, controlling terminal acceptably
2318 * . not when sourcing a file */
2319 for(lip = a_lex_input; lip != NULL; lip = lip->li_outer){
2320 ui32_t f;
2322 if((f = lip->li_flags) & (a_LEX_PIPE | a_LEX_SLICE))
2323 goto jleave;
2324 if(!(f & a_LEX_MACRO))
2325 goto jleave;
2328 rv = TRU1;
2329 jleave:
2330 NYD2_LEAVE;
2331 return rv;
2334 FL void
2335 n_source_inject_input(enum n_input_inject_flags iif, char const *buf,
2336 size_t len){
2337 NYD_ENTER;
2338 if(len == UIZ_MAX)
2339 len = strlen(buf);
2341 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat) -1 > len &&
2342 len > 0){
2343 size_t i;
2344 struct a_lex_input_inject *liip, **liipp;
2346 liip = n_alloc(n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat
2347 ) + 1 + len +1);
2348 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
2349 : &a_lex_input->li_inject;
2350 liip->lii_next = *liipp;
2351 liip->lii_commit = ((iif & n_INPUT_INJECT_COMMIT) != 0);
2352 if(buf[i = 0] != ' ' && !(iif & n_INPUT_INJECT_HISTORY))
2353 liip->lii_dat[i++] = ' '; /* TODO prim. hack to avoid history put! */
2354 memcpy(&liip->lii_dat[i], buf, len);
2355 i += len;
2356 liip->lii_dat[liip->lii_len = i] = '\0';
2357 *liipp = liip;
2359 NYD_LEAVE;
2362 FL void
2363 n_source_force_eof(void){
2364 NYD_ENTER;
2365 assert(a_lex_input != NULL);
2366 a_lex_input->li_flags |= a_LEX_FORCE_EOF;
2367 NYD_LEAVE;
2370 /* s-it-mode */