Several: use standardized names for some characters and terms
[s-mailx.git] / lex_input.c
blob26f8d5807637b8d4f7957aa17f8aa7a4f9e86b40
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 argtype lc_argtype; /* Arglist type (see below) */
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 /* List of all commands, and list of commands which are specially treated
219 * and deduced in _evaluate(), but we need a list for _c_list() and
220 * print_comm_docstr() */
221 #ifdef HAVE_DOCSTRINGS
222 # define DS(S) , S
223 #else
224 # define DS(S)
225 #endif
226 static struct a_lex_cmd const a_lex_cmd_tab[] = {
227 #include "cmd_tab.h"
229 a_lex_special_cmd_tab[] = {
230 { "#", NULL, ARG_STRLIST, 0, 0
231 DS(N_("Comment command: ignore remaining (continuable) line")) },
232 { "-", NULL, ARG_WYSHLIST, 0, 0
233 DS(N_("Print out the preceding message")) }
235 #undef DS
237 static char *
238 a_lex_isolate(char const *comm){
239 NYD2_ENTER;
240 while(*comm != '\0' &&
241 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
242 ++comm;
243 NYD2_LEAVE;
244 return n_UNCONST(comm);
247 static int
248 a_lex_c_eval(void *v){
249 /* TODO HACK! `eval' should be nothing else but a command prefix, evaluate
250 * TODO ARGV with shell rules, but if that is not possible then simply
251 * TODO adjust argv/argc of "the CmdCtx" that we will have "exec" real cmd */
252 struct n_string s_b, *sp;
253 si32_t rv;
254 size_t i, j;
255 char const **argv, *cp;
256 NYD_ENTER;
258 argv = v;
260 for(j = i = 0; (cp = argv[i]) != NULL; ++i)
261 j += strlen(cp);
263 sp = n_string_creat_auto(&s_b);
264 sp = n_string_reserve(sp, j);
266 for(i = 0; (cp = argv[i]) != NULL; ++i){
267 if(i > 0)
268 sp = n_string_push_c(sp, ' ');
269 sp = n_string_push_cp(sp, cp);
272 /* TODO HACK! We should inherit the current n_lexinput_flags via CmdCtx,
273 * TODO for now we don't have such sort of! n_PS_COMPOSE_MODE is a hack
274 * TODO by itself, since ever: misuse the hack for a hack.
275 * TODO Further more, exit handling is very grazy */
276 (void)/*XXX*/n_source_command((n_pstate & n_PS_COMPOSE_MODE
277 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT), n_string_cp(sp));
278 cp = ok_vlook(__qm);
279 if(cp == n_0) /* This is a hack, but since anything is a hack, be hacky */
280 rv = 0;
281 else if(cp == n_1)
282 rv = 1;
283 else if(cp == n_m1)
284 rv = -1;
285 else
286 n_idec_si32_cp(&rv, cp, 10, NULL);
287 NYD_LEAVE;
288 return rv;
291 static int
292 a_lex_c_ghost(void *v){
293 struct a_lex_ghost *lgp, *gp;
294 size_t i, cl, nl;
295 char *cp;
296 char const **argv;
297 NYD_ENTER;
299 argv = v;
301 /* Show the list? */
302 if(*argv == NULL){
303 FILE *fp;
305 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
306 fp = n_stdout;
308 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
309 fprintf(fp, "wysh ghost %s %s\n",
310 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
312 if(fp != n_stdout){
313 page_or_print(fp, i);
314 Fclose(fp);
316 goto jleave;
319 /* Verify the ghost name is a valid one, and not a command modifier */
320 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0' ||
321 !asccasecmp(argv[0], "ignerr") || !asccasecmp(argv[0], "wysh") ||
322 !asccasecmp(argv[0], "vput")){
323 n_err(_("`ghost': can't canonicalize %s\n"),
324 n_shexp_quote_cp(argv[0], FAL0));
325 v = NULL;
326 goto jleave;
329 /* Show command of single ghost? */
330 if(argv[1] == NULL){
331 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
332 if(!strcmp(argv[0], gp->lg_name)){
333 fprintf(n_stdout, "wysh ghost %s %s\n",
334 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
335 goto jleave;
337 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
338 v = NULL;
339 goto jleave;
342 /* Define command for ghost: verify command content */
343 for(cl = 0, i = 1; (cp = n_UNCONST(argv[i])) != NULL; ++i)
344 if(*cp != '\0')
345 cl += strlen(cp) +1; /* SP or NUL */
346 if(cl == 0){
347 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
348 v = NULL;
349 goto jleave;
352 /* If the ghost already exists, recreate */
353 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
354 if(!strcmp(gp->lg_name, argv[0])){
355 if(lgp != NULL)
356 lgp->lg_next = gp->lg_next;
357 else
358 a_lex_ghosts = gp->lg_next;
359 free(gp);
360 break;
363 nl = strlen(argv[0]) +1;
364 gp = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_ghost, lg_name) + nl + cl);
365 gp->lg_next = a_lex_ghosts;
366 a_lex_ghosts = gp;
367 memcpy(gp->lg_name, argv[0], nl);
368 cp = gp->lg_cmd.s = gp->lg_name + nl;
369 gp->lg_cmd.l = --cl;
371 while(*++argv != NULL)
372 if((i = strlen(*argv)) > 0){
373 memcpy(cp, *argv, i);
374 cp += i;
375 *cp++ = ' ';
377 *--cp = '\0';
378 jleave:
379 NYD_LEAVE;
380 return v == NULL;
383 static int
384 a_lex_c_unghost(void *v){
385 struct a_lex_ghost *lgp, *gp;
386 char const **argv, *cp;
387 int rv;
388 NYD_ENTER;
390 rv = 0;
391 argv = v;
393 while((cp = *argv++) != NULL){
394 if(cp[0] == '*' && cp[1] == '\0'){
395 while((gp = a_lex_ghosts) != NULL){
396 a_lex_ghosts = gp->lg_next;
397 free(gp);
399 }else{
400 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
401 lgp = gp, gp = gp->lg_next)
402 if(!strcmp(gp->lg_name, cp)){
403 if(lgp != NULL)
404 lgp->lg_next = gp->lg_next;
405 else
406 a_lex_ghosts = gp->lg_next;
407 free(gp);
408 goto jouter;
410 n_err(_("`unghost': no such alias: %s\n"),
411 n_shexp_quote_cp(cp, FAL0));
412 rv = 1;
413 jouter: ;
416 NYD_LEAVE;
417 return rv;
420 static char const *
421 a_lex_cmdinfo(struct a_lex_cmd const *lcp){
422 struct n_string rvb, *rv;
423 char const *cp;
424 NYD2_ENTER;
426 rv = n_string_creat_auto(&rvb);
427 rv = n_string_reserve(rv, 80);
429 switch(lcp->lc_argtype & ARG_ARGMASK){
430 case ARG_MSGLIST: cp = N_("message-list"); break;
431 case ARG_STRLIST: cp = N_("string data"); break;
432 case ARG_RAWLIST: cp = N_("old-style quoting"); break;
433 case ARG_NDMLIST: cp = N_("message-list (no default)"); break;
434 case ARG_WYRALIST: cp = N_("`wysh' for sh(1)ell-style quoting"); break;
435 default:
436 case ARG_WYSHLIST:
437 cp = (lcp->lc_minargs == 0 && lcp->lc_maxargs == 0)
438 ? N_("sh(1)ell-style quoting (takes no arguments)")
439 : N_("sh(1)ell-style quoting");
440 break;
442 rv = n_string_push_cp(rv, V_(cp));
444 if(lcp->lc_argtype & ARG_V)
445 rv = n_string_push_cp(rv, _(" | vput modifier"));
446 if(lcp->lc_argtype & ARG_EM)
447 rv = n_string_push_cp(rv, _(" | status in *!*"));
449 if(lcp->lc_argtype & ARG_A)
450 rv = n_string_push_cp(rv, _(" | needs box"));
451 if(lcp->lc_argtype & ARG_I)
452 rv = n_string_push_cp(rv, _(" | ok: batch or interactive"));
453 if(lcp->lc_argtype & ARG_M)
454 rv = n_string_push_cp(rv, _(" | ok: send mode"));
455 if(lcp->lc_argtype & ARG_R)
456 rv = n_string_push_cp(rv, _(" | not ok: compose mode"));
457 if(lcp->lc_argtype & ARG_S)
458 rv = n_string_push_cp(rv, _(" | not ok: during startup"));
459 if(lcp->lc_argtype & ARG_X)
460 rv = n_string_push_cp(rv, _(" | ok: in subprocess"));
462 if(lcp->lc_argtype & ARG_G)
463 rv = n_string_push_cp(rv, _(" | gabby history"));
465 cp = n_string_cp(rv);
466 NYD2_LEAVE;
467 return cp;
470 static int
471 a_lex_c_list(void *v){
472 FILE *fp;
473 struct a_lex_cmd const **cpa, *cp, **cursor;
474 size_t l, i;
475 NYD_ENTER;
477 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
478 cpa = salloc(sizeof(cp) * i);
480 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
481 cpa[i] = &a_lex_cmd_tab[i];
482 /* C99 */{
483 size_t j;
485 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
486 cpa[i] = &a_lex_special_cmd_tab[j];
488 cpa[i] = NULL;
490 /* C99 */{
491 char const *xcp = v;
493 if(*xcp == '\0')
494 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
497 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
498 fp = n_stdout;
500 fprintf(fp, _("Commands are:\n"));
501 l = 1;
502 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
503 if(cp->lc_func == &c_cmdnotsupp)
504 continue;
505 if(n_poption & n_PO_D_V){
506 fprintf(fp, "%s\n", cp->lc_name);
507 ++l;
508 #ifdef HAVE_DOCSTRINGS
509 fprintf(fp, " : %s\n", V_(cp->lc_doc));
510 ++l;
511 #endif
512 fprintf(fp, " : %s\n", a_lex_cmdinfo(cp));
513 ++l;
514 }else{
515 size_t j = strlen(cp->lc_name) + 2;
517 if((i += j) > 72){
518 i = j;
519 fprintf(fp, "\n");
520 ++l;
522 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
526 if(fp != n_stdout){
527 page_or_print(fp, l);
528 Fclose(fp);
530 NYD_LEAVE;
531 return 0;
534 static int
535 a_lex__pcmd_cmp(void const *s1, void const *s2){
536 struct a_lex_cmd const * const *cp1, * const *cp2;
537 int rv;
538 NYD2_ENTER;
540 cp1 = s1;
541 cp2 = s2;
542 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
543 NYD2_LEAVE;
544 return rv;
547 static int
548 a_lex_c_help(void *v){
549 int rv;
550 char *arg;
551 NYD_ENTER;
553 /* Help for a single command? */
554 if((arg = *(char**)v) != NULL){
555 struct a_lex_ghost const *gp;
556 struct a_lex_cmd const *lcp, *lcpmax;
558 /* Ghosts take precedence */
559 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
560 if(!strcmp(arg, gp->lg_name)){
561 fprintf(n_stdout, "%s -> ", arg);
562 arg = gp->lg_cmd.s;
563 break;
566 lcpmax = &(lcp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
567 jredo:
568 for(; lcp < lcpmax; ++lcp){
569 if(is_prefix(arg, lcp->lc_name)){
570 fputs(arg, n_stdout);
571 if(strcmp(arg, lcp->lc_name))
572 fprintf(n_stdout, " (%s)", lcp->lc_name);
573 }else
574 continue;
576 #ifdef HAVE_DOCSTRINGS
577 fprintf(n_stdout, ": %s", V_(lcp->lc_doc));
578 #endif
579 if(n_poption & n_PO_D_V)
580 fprintf(n_stdout, "\n : %s", a_lex_cmdinfo(lcp));
581 putc('\n', n_stdout);
582 rv = 0;
583 goto jleave;
586 if(PTRCMP(lcpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
587 lcpmax = &(lcp =
588 a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
589 goto jredo;
592 if(gp != NULL){
593 fprintf(n_stdout, "%s\n", n_shexp_quote_cp(arg, TRU1));
594 rv = 0;
595 }else{
596 n_err(_("Unknown command: `%s'\n"), arg);
597 rv = 1;
599 }else{
600 /* Very ugly, but take care for compiler supported string lengths :( */
601 fputs(n_progname, n_stdout);
602 fputs(_(
603 " commands -- <msglist> denotes message specifications,\n"
604 "e.g., 1-5, :n or ., separated by spaces:\n"), n_stdout);
605 fputs(_(
606 "\n"
607 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
608 "Type <msglist> like `type' but always show all headers\n"
609 "next goto and type next message\n"
610 "from <msglist> (search and) print header summary for the given list\n"
611 "headers header summary for messages surrounding \"dot\"\n"
612 "delete <msglist> delete messages (can be `undelete'd)\n"),
613 n_stdout);
615 fputs(_(
616 "\n"
617 "save <msglist> folder append messages to folder and mark as saved\n"
618 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
619 "write <msglist> file write message contents to file (prompts for parts)\n"
620 "Reply <msglist> reply to message senders only\n"
621 "reply <msglist> like `Reply', but address all recipients\n"
622 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
623 n_stdout);
625 fputs(_(
626 "\n"
627 "mail <recipients> compose a mail for the given recipients\n"
628 "file folder change to another mailbox\n"
629 "File folder like `file', but open readonly\n"
630 "quit quit and apply changes to the current mailbox\n"
631 "xit or exit like `quit', but discard changes\n"
632 "!shell command shell escape\n"
633 "list [<anything>] all available commands [in search order]\n"),
634 n_stdout);
636 rv = (ferror(n_stdout) != 0);
638 jleave:
639 NYD_LEAVE;
640 return rv;
643 static int
644 a_lex_c_exit(void *v){
645 NYD_ENTER;
646 n_UNUSED(v);
648 if(n_psonce & n_PSO_STARTED){
649 /* In recursed state, return error to just pop the input level */
650 if(!(n_pstate & n_PS_SOURCING)){
651 #ifdef n_HAVE_TCAP
652 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
653 n_termcap_destroy();
654 #endif
655 exit(n_EXIT_OK);
658 n_pstate |= n_PS_EXIT;
659 NYD_LEAVE;
660 return 0;
663 static int
664 a_lex_c_quit(void *v){
665 NYD_ENTER;
666 n_UNUSED(v);
668 /* If we are n_PS_SOURCING, then return 1 so _evaluate() can handle it.
669 * Otherwise return -1 to abort command loop */
670 n_pstate |= n_PS_EXIT;
671 NYD_LEAVE;
672 return 0;
675 static int
676 a_lex_c_version(void *v){
677 int longest, rv;
678 char *iop;
679 char const *cp, **arr;
680 size_t i, i2;
681 NYD_ENTER;
682 n_UNUSED(v);
684 fprintf(n_stdout, _("%s version %s\nFeatures included (+) or not (-)\n"),
685 n_uagent, ok_vlook(version));
687 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
688 i = strlen(cp = &ok_vlook(features)[1]) +1;
689 iop = salloc(i);
690 memcpy(iop, cp, i);
692 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
693 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
694 arr[i] = cp;
695 i2 = strlen(cp);
696 longest = n_MAX(longest, (int)i2);
698 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
700 for(++longest, i2 = 0; i-- > 0;){
701 cp = *(arr++);
702 fprintf(n_stdout, "%-*s ", longest, cp);
703 i2 += longest;
704 if(UICMP(z, ++i2 + longest, >=, n_scrnwidth) || i == 0){
705 i2 = 0;
706 putc('\n', n_stdout);
710 if((rv = ferror(n_stdout) != 0))
711 clearerr(n_stdout);
712 NYD_LEAVE;
713 return rv;
716 static int
717 a_lex__version_cmp(void const *s1, void const *s2){
718 char const * const *cp1, * const *cp2;
719 int rv;
720 NYD2_ENTER;
722 cp1 = s1;
723 cp2 = s2;
724 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
725 NYD2_LEAVE;
726 return rv;
729 static void
730 a_lex_update_pstate(void){
731 NYD_ENTER;
733 if(n_pstate & n_PS_SIGWINCH_PEND){
734 char buf[32];
736 snprintf(buf, sizeof buf, "%d", n_scrnwidth);
737 ok_vset(COLUMNS, buf);
738 snprintf(buf, sizeof buf, "%d", n_scrnheight);
739 ok_vset(LINES, buf);
742 n_pstate &= ~n_PS_PSTATE_PENDMASK;
743 NYD_LEAVE;
746 static int
747 a_lex_evaluate(struct a_lex_eval_ctx *evp){
748 /* xxx old style(9), but also old code */
749 struct str line;
750 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
751 struct a_lex_ghost *gp;
752 struct a_lex_cmd const *cmd;
753 int rv, c;
754 enum {
755 a_NONE = 0,
756 a_GHOST_MASK = (1<<3) - 1, /* Ghost recursion counter bits */
757 a_NOPREFIX = 1<<4, /* Modifier prefix not allowed right now */
758 a_NOGHOST = 1<<5, /* No ghost expansion modifier */
759 /* New command modifier prefixes must be reflected in a_lex_c_ghost()! */
760 a_IGNERR = 1<<6, /* ignerr modifier prefix */
761 a_WYSH = 1<<7, /* XXX v15+ drop wysh modifier prefix */
762 a_VPUT = 1<<8 /* vput modifier prefix */
763 } flags;
764 NYD_ENTER;
766 flags = a_NONE;
767 rv = 1;
768 cmd = NULL;
769 gp = NULL;
770 line = evp->le_line; /* XXX don't change original (buffer pointer) */
771 assert(line.s[line.l] == '\0');
772 evp->le_add_history = FAL0;
774 /* Command ghosts that refer to shell commands or macro expansion restart */
775 jrestart:
777 /* Strip the white space away from end and beginning of command */
778 if(line.l > 0){
779 size_t i = line.l;
781 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
782 --i;
783 line.l = i;
785 for(cp = line.s; spacechar(*cp); ++cp)
787 line.l -= PTR2SIZE(cp - line.s);
789 /* Ignore null commands (comments) */
790 if(*cp == '#')
791 goto jerr0;
793 /* Handle ! differently to get the correct lexical conventions */
794 arglist[0] = cp;
795 if(*cp == '!')
796 ++cp;
797 /* Isolate the actual command; since it may not necessarily be
798 * separated from the arguments (as in `p1') we need to duplicate it to
799 * be able to create a NUL terminated version.
800 * We must be aware of several special one letter commands here */
801 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
802 (*cp == '|' || *cp == '~' || *cp == '?'))
803 ++cp;
804 c = (int)PTR2SIZE(cp - arglist[0]);
805 line.l -= c;
806 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
807 memcpy(word, arglist[0], c);
808 word[c] = '\0';
810 /* No-expansion modifier? */
811 if(!(flags & a_NOPREFIX) && *word == '\\'){
812 ++word;
813 --c;
814 flags |= a_NOGHOST;
817 /* It may be a modifier prefix */
818 if(c == sizeof("ignerr") -1 && !asccasecmp(word, "ignerr")){
819 flags |= a_NOPREFIX | a_IGNERR;
820 line.s = cp;
821 goto jrestart;
822 }else if(c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
823 flags |= a_NOPREFIX | a_WYSH;
824 line.s = cp;
825 goto jrestart;
826 }else if(c == sizeof("vput") -1 && !asccasecmp(word, "vput")){
827 flags |= a_NOPREFIX | a_VPUT;
828 line.s = cp;
829 goto jrestart;
832 /* Look up the command; if not found, bitch.
833 * Normally, a blank command would map to the first command in the
834 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
835 * confusion; act just the same for ghosts */
836 if(*word == '\0'){
837 if((n_pstate & n_PS_ROBOT) || gp != NULL)
838 goto jerr0;
839 cmd = &a_lex_cmd_tab[0];
840 goto jexec;
843 if(!(flags & a_NOGHOST) && (flags & a_GHOST_MASK) != a_GHOST_MASK){
844 /* TODO relink list head, so it's sorted on usage over time?
845 * TODO in fact, there should be one hashmap over all commands and ghosts
846 * TODO so that the lookup could be made much more efficient than it is
847 * TODO now (two adjacent list searches! */
848 ui8_t expcnt;
850 expcnt = (flags & a_GHOST_MASK);
851 ++expcnt;
852 flags = (flags & ~(a_GHOST_MASK | a_NOPREFIX)) | expcnt;
854 /* Avoid self-recursion; yes, the user could use \ no-expansion, but.. */
855 if(gp != NULL && !strcmp(word, gp->lg_name)){
856 if(n_poption & n_PO_D_V)
857 n_err(_("Actively avoiding self-recursion of `ghost': %s\n"), word);
858 }else for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
859 if(!strcmp(word, gp->lg_name)){
860 if(line.l > 0){
861 size_t i;
863 i = gp->lg_cmd.l;
864 line.s = salloc(i + line.l +1);
865 memcpy(line.s, gp->lg_cmd.s, i);
866 memcpy(line.s + i, cp, line.l);
867 line.s[i += line.l] = '\0';
868 line.l = i;
869 }else{
870 line.s = gp->lg_cmd.s;
871 line.l = gp->lg_cmd.l;
873 goto jrestart;
877 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
878 bool_t s;
880 if(!(s = condstack_isskip()) || (n_poption & n_PO_D_V))
881 n_err(_("Unknown command%s: `%s'\n"),
882 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
883 if(s)
884 goto jerr0;
885 if(cmd != NULL){
886 c_cmdnotsupp(NULL);
887 cmd = NULL;
889 n_pstate_var__em = n_m1;
890 goto jleave;
893 /* See if we should execute the command -- if a conditional we always
894 * execute it, otherwise, check the state of cond */
895 jexec:
896 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
897 goto jerr0;
899 n_pstate_var__em = n_1;
901 /* Process the arguments to the command, depending on the type it expects */
902 if((cmd->lc_argtype & ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
903 !(n_poption & n_PO_BATCH_FLAG)){
904 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
905 cmd->lc_name);
906 goto jleave;
908 if(!(cmd->lc_argtype & ARG_M) && (n_psonce & n_PSO_SENDMODE)){
909 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
910 goto jleave;
912 if(cmd->lc_argtype & ARG_R){
913 if(n_pstate & n_PS_COMPOSE_MODE){
914 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
915 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
916 goto jleave;
918 /* TODO Nothing should prevent ARG_R in conjunction with
919 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
920 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING)){
921 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
922 cmd->lc_name);
923 goto jleave;
926 if((cmd->lc_argtype & ARG_S) && !(n_psonce & n_PSO_STARTED)){
927 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
928 goto jleave;
930 if(!(cmd->lc_argtype & ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
931 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
932 cmd->lc_name);
933 goto jleave;
936 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
937 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
938 goto jleave;
940 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
941 n_err(_("May not execute `%s' -- message file is read only\n"),
942 cmd->lc_name);
943 goto jleave;
946 if(cmd->lc_argtype & ARG_O)
947 n_OBSOLETE2(_("this command will be removed"), cmd->lc_name);
949 if((flags & a_WYSH) && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST){
950 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
951 flags &= ~a_WYSH;
953 if((flags & a_VPUT) && !(cmd->lc_argtype & ARG_V)){
954 n_err(_("`vput' prefix doesn't affect `%s'\n"), cmd->lc_name);
955 flags &= ~a_VPUT;
958 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
959 * TODO doesn't use any of those list commands which strip this mask,
960 * TODO and for now we misuse bits for checking relation to history;
961 * TODO argument state should be property of a per-command carrier instead */
962 n_pstate &= ~n_PS_ARGLIST_MASK;
963 switch(cmd->lc_argtype & ARG_ARGMASK){
964 case ARG_MSGLIST:
965 /* Message list defaulting to nearest forward legal message */
966 if(n_msgvec == NULL)
967 goto je96;
968 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
969 break;
970 if(c == 0){
971 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
972 n_msgvec[1] = 0;
974 if(n_msgvec[0] == 0){
975 if(!(n_pstate & n_PS_HOOK_MASK))
976 fprintf(n_stdout, _("No applicable messages\n"));
977 break;
979 rv = (*cmd->lc_func)(n_msgvec);
980 break;
982 case ARG_NDMLIST:
983 /* Message list with no defaults, but no error if none exist */
984 if(n_msgvec == NULL){
985 je96:
986 n_err(_("Invalid use of message list\n"));
987 break;
989 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
990 break;
991 rv = (*cmd->lc_func)(n_msgvec);
992 break;
994 case ARG_STRLIST:
995 /* Just the straight string, with leading blanks removed */
996 while(blankspacechar(*cp))
997 ++cp;
998 rv = (*cmd->lc_func)(cp);
999 break;
1001 case ARG_WYSHLIST:
1002 c = 1;
1003 if(0){
1004 /* FALLTHRU */
1005 case ARG_WYRALIST:
1006 c = (flags & a_WYSH) ? 1 : 0;
1007 if(0){
1008 case ARG_RAWLIST:
1009 c = 0;
1012 if((c = getrawlist((c != 0), arglist, n_NELEM(arglist), cp, line.l)) < 0){
1013 n_err(_("Invalid argument list\n"));
1014 break;
1016 c -= ((flags & a_VPUT) != 0); /* XXX c=int */
1018 if(c < cmd->lc_minargs){
1019 n_err(_("`%s' requires at least %u arg(s)\n"),
1020 cmd->lc_name, (ui32_t)cmd->lc_minargs + ((flags & a_VPUT) != 0));
1021 break;
1023 #undef lc_minargs
1024 if(c > cmd->lc_maxargs){
1025 n_err(_("`%s' takes no more than %u arg(s)\n"),
1026 cmd->lc_name, (ui32_t)cmd->lc_maxargs + ((flags & a_VPUT) != 0));
1027 break;
1029 #undef lc_maxargs
1031 if(flags & a_VPUT){
1032 char const *emsg;
1034 if(!n_shexp_is_valid_varname(arglist[0]))
1035 emsg = N_("not a valid variable name");
1036 else if(!n_var_is_user_writable(arglist[0]))
1037 emsg = N_("either not a user writable, or a boolean variable");
1038 else
1039 emsg = NULL;
1040 if(emsg != NULL){
1041 n_err(_("`%s': %s: %s\n"),
1042 cmd->lc_name, V_(emsg), n_shexp_quote_cp(arglist[0], FAL0));
1043 break;
1046 ++c;
1047 n_pstate |= n_PS_ARGMOD_VPUT;
1049 rv = (*cmd->lc_func)(arglist);
1050 break;
1052 default:
1053 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
1054 cmd->lc_argtype & ARG_ARGMASK); )
1055 goto jerr0;
1058 if(!(cmd->lc_argtype & ARG_H))
1059 evp->le_add_history = (((cmd->lc_argtype & ARG_G) ||
1060 (n_pstate & n_PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
1062 if(!(cmd->lc_argtype & ARG_EM) && rv == 0)
1063 n_pstate_var__em = n_0;
1064 jleave:
1065 n_PS_ROOT_BLOCK(
1066 ok_vset(__qm, (rv == 0 ? n_0 : n_1));
1067 ok_vset(__em, n_pstate_var__em)
1070 if(flags & a_IGNERR){
1071 rv = 0;
1072 n_exit_status = n_EXIT_OK;
1075 /* Exit the current source file on error TODO what a mess! */
1076 if(rv == 0)
1077 n_pstate &= ~n_PS_EVAL_ERROR;
1078 else{
1079 n_pstate |= n_PS_EVAL_ERROR;
1080 if(rv < 0 || (n_pstate & n_PS_ROBOT)){ /* FIXME */
1081 rv = 1;
1082 goto jret;
1084 goto jret0;
1087 if(cmd == NULL)
1088 goto jret0;
1089 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint))
1090 if(visible(dot))
1091 n_source_inject_input(n_INPUT_INJECT_COMMIT, "\\type",
1092 sizeof("\\type") -1);
1094 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
1095 !(cmd->lc_argtype & ARG_T))
1096 n_pstate |= n_PS_SAW_COMMAND;
1097 jleave0:
1098 n_pstate &= ~n_PS_EVAL_ERROR;
1099 jret0:
1100 rv = 0;
1101 jret:
1102 NYD_LEAVE;
1103 return rv;
1104 jerr0:
1105 n_PS_ROOT_BLOCK(
1106 ok_vset(__qm, n_0);
1107 ok_vset(__em, n_0)
1109 goto jleave0;
1112 static struct a_lex_cmd const *
1113 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
1114 struct a_lex_cmd const *cp;
1115 NYD2_ENTER;
1117 for(cp = a_lex_cmd_tab;
1118 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
1119 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
1120 goto jleave;
1121 cp = NULL;
1122 jleave:
1123 NYD2_LEAVE;
1124 return cp;
1127 static void
1128 a_lex_hangup(int s){
1129 NYD_X; /* Signal handler */
1130 n_UNUSED(s);
1131 /* nothing to do? */
1132 exit(n_EXIT_ERR);
1135 static void
1136 a_lex_onintr(int s){ /* TODO block signals while acting */
1137 NYD_X; /* Signal handler */
1138 n_UNUSED(s);
1140 safe_signal(SIGINT, a_lex_onintr);
1142 termios_state_reset();
1143 close_all_files(); /* FIXME .. of current level ONLU! */
1145 a_lex_unstack(TRUM1);
1147 if(interrupts != 1)
1148 n_err_sighdl(_("Interrupt\n"));
1149 safe_signal(SIGPIPE, a_lex_oldpipe);
1150 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
1153 static void
1154 a_lex_unstack(bool_t eval_error){
1155 struct a_lex_input *lip;
1156 NYD_ENTER;
1158 /* Free input injections of this level first */
1159 /* C99 */{
1160 struct a_lex_input_inject **liipp, *liip;
1162 if((lip = a_lex_input) == NULL)
1163 liipp = &a_lex_input_inject;
1164 else
1165 liipp = &lip->li_inject;
1167 while((liip = *liipp) != NULL){
1168 *liipp = liip->lii_next;
1169 free(liip);
1172 if(lip == NULL || !(lip->li_flags & a_LEX_SLICE))
1173 n_memory_reset();
1176 if(lip == NULL){
1177 /* If called from a_lex_onintr(), be silent FIXME */
1178 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1179 if(eval_error == TRUM1 || !(n_psonce & n_PSO_STARTED))
1180 goto jleave;
1181 goto jerr;
1184 if(lip->li_flags & a_LEX_SLICE){ /* TODO Temporary hack */
1185 n_stdin = lip->li_slice_stdin;
1186 n_stdout = lip->li_slice_stdout;
1187 n_psonce = lip->li_slice_psonce;
1188 goto jthe_slice_hack;
1191 if(lip->li_flags & a_LEX_MACRO){
1192 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
1193 char **lp;
1195 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
1196 free(*lp);
1197 ++lip->li_loff;
1199 /* Part of lip's memory chunk, then */
1200 if(!(lip->li_flags & a_LEX_MACRO_CMD))
1201 free(lip->li_lines);
1203 }else{
1204 if(lip->li_flags & a_LEX_PIPE)
1205 /* XXX command manager should -TERM then -KILL instead of hoping
1206 * XXX for exit of provider due to EPIPE / SIGPIPE */
1207 Pclose(lip->li_file, TRU1);
1208 else
1209 Fclose(lip->li_file);
1212 if(!condstack_take(lip->li_cond)){
1213 n_err(_("Unmatched `if' at end of %s %s\n"),
1214 ((lip->li_flags & a_LEX_MACRO
1215 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1216 : _("`source'd file"))),
1217 lip->li_name);
1218 eval_error = TRU1;
1221 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1223 jthe_slice_hack:
1224 if(lip->li_on_finalize != NULL)
1225 (*lip->li_on_finalize)(lip->li_finalize_arg);
1227 if((a_lex_input = lip->li_outer) == NULL){
1228 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1229 }else{
1230 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1231 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1232 n_pstate &= ~n_PS_SOURCING;
1233 assert(n_pstate & n_PS_ROBOT);
1236 if(eval_error)
1237 goto jerr;
1238 jleave:
1239 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1240 free(lip);
1241 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1242 a_lex_unstack(TRUM1);
1243 NYD_LEAVE;
1244 return;
1246 jerr:
1247 if(lip != NULL){
1248 /* POSIX says
1249 * Any errors in the start-up file shall either cause mailx to
1250 * terminate with a diagnostic message and a non-zero status or to
1251 * continue after writing a diagnostic message, ignoring the
1252 * remainder of the lines in the start-up file
1253 * But print the diagnostic only for the outermost resource unless the
1254 * user is debugging or in verbose mode */
1255 if((n_poption & n_PO_D_V) ||
1256 (!(n_psonce & n_PSO_STARTED) &&
1257 !(lip->li_flags & (a_LEX_SLICE | a_LEX_MACRO)) &&
1258 lip->li_outer == NULL))
1259 n_alert(_("Stopped %s %s due to errors%s"),
1260 (n_psonce & n_PSO_STARTED
1261 ? (lip->li_flags & a_LEX_SLICE ? _("sliced in program")
1262 : (lip->li_flags & a_LEX_MACRO
1263 ? (lip->li_flags & a_LEX_MACRO_CMD
1264 ? _("evaluating command") : _("evaluating macro"))
1265 : (lip->li_flags & a_LEX_PIPE
1266 ? _("executing `source'd pipe")
1267 : _("loading `source'd file")))
1269 : (lip->li_flags & a_LEX_MACRO
1270 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1271 ? _("evaluating command line") : _("evaluating macro"))
1272 : _("loading initialization resource"))),
1273 lip->li_name,
1274 (n_poption & n_PO_DEBUG
1275 ? n_empty : _(" (enable *debug* for trace)")));
1278 if(!(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED))){
1279 if(n_poption & n_PO_D_V)
1280 n_alert(_("Non-interactive, bailing out due to errors "
1281 "in startup load phase"));
1282 exit(n_EXIT_ERR);
1284 goto jleave;
1287 static bool_t
1288 a_lex_source_file(char const *file, bool_t silent_open_error){
1289 struct a_lex_input *lip;
1290 size_t nlen;
1291 char *nbuf;
1292 bool_t ispipe;
1293 FILE *fip;
1294 NYD_ENTER;
1296 fip = NULL;
1298 /* Being a command argument file is space-trimmed *//* TODO v15 with
1299 * TODO WYRALIST this is no longer necessary true, and for that we
1300 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1301 #if 0
1302 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
1303 file[--nlen] == '|')))
1304 #else
1305 ispipe = FAL0;
1306 if(!silent_open_error)
1307 for(nlen = strlen(file); nlen > 0;){
1308 char c;
1310 c = file[--nlen];
1311 if(!blankchar(c)){
1312 if(c == '|'){
1313 nbuf = savestrbuf(file, nlen);
1314 ispipe = TRU1;
1316 break;
1319 #endif
1321 if(ispipe){
1322 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1323 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL)
1324 goto jeopencheck;
1325 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1326 goto jeopencheck;
1327 else if((fip = Fopen(nbuf, "r")) == NULL){
1328 jeopencheck:
1329 if(!silent_open_error || (n_poption & n_PO_D_V))
1330 n_perr(nbuf, 0);
1331 if(silent_open_error)
1332 fip = (FILE*)-1;
1333 goto jleave;
1336 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
1337 (nlen = strlen(nbuf) +1));
1338 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1339 lip->li_outer = a_lex_input;
1340 lip->li_file = fip;
1341 lip->li_cond = condstack_release();
1342 n_memory_autorec_push(&lip->li_autorecmem[0]);
1343 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1344 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1345 ? a_LEX_SUPER_MACRO : 0);
1346 memcpy(lip->li_name, nbuf, nlen);
1348 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1349 a_lex_input = lip;
1350 if(!a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC))
1351 fip = NULL;
1352 jleave:
1353 NYD_LEAVE;
1354 return (fip != NULL);
1357 static bool_t
1358 a_lex_load(struct a_lex_input *lip){
1359 bool_t rv;
1360 NYD2_ENTER;
1362 assert(!(n_psonce & n_PSO_STARTED));
1363 assert(a_lex_input == NULL);
1365 /* POSIX:
1366 * Any errors in the start-up file shall either cause mailx to terminate
1367 * with a diagnostic message and a non-zero status or to continue after
1368 * writing a diagnostic message, ignoring the remainder of the lines in
1369 * the start-up file. */
1370 lip->li_cond = condstack_release();
1371 n_memory_autorec_push(&lip->li_autorecmem[0]);
1373 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1374 n_pstate |= n_PS_ROBOT |
1375 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1377 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1378 if(n_poption & n_PO_D_V)
1379 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1380 a_lex_input = lip;
1381 if(!(rv = n_commands())){
1382 if(!(n_psonce & n_PSO_INTERACTIVE)){
1383 if(n_poption & n_PO_D_V)
1384 n_alert(_("Non-interactive program mode, forced exit"));
1385 exit(n_EXIT_ERR);
1386 }else if(n_poption & n_PO_BATCH_FLAG){
1387 char const *beoe;
1389 if((beoe = ok_vlook(batch_exit_on_error)) != NULL && *beoe == '1')
1390 n_pstate |= n_PS_EXIT;
1393 /* n_PS_EXIT handled by callers */
1394 NYD2_LEAVE;
1395 return rv;
1398 static void
1399 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1400 NYD_X; /* Signal handler */
1401 n_UNUSED(sig);
1402 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1405 static bool_t
1406 a_commands_recursive(enum n_lexinput_flags lif){
1407 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1408 sighandler_type soldhdl;
1409 sigset_t sintset, soldset;
1410 struct a_lex_eval_ctx ev;
1411 bool_t rv, ever;
1412 NYD2_ENTER;
1414 memset(&ev, 0, sizeof ev);
1416 sigfillset(&sintset);
1417 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1418 hadint = FAL0;
1419 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1420 safe_signal(SIGINT, &a_lex__cmdrecint);
1421 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1422 hadint = TRU1;
1423 goto jjump;
1426 sigprocmask(SIG_SETMASK, &soldset, NULL);
1428 n_COLOUR( n_colour_env_push(); )
1429 rv = TRU1;
1430 for(ever = FAL0;; ever = TRU1){
1431 char const *beoe;
1432 int n;
1434 if(ever)
1435 n_memory_reset();
1437 /* Read a line of commands and handle end of file specially */
1438 ev.le_line.l = ev.le_line_size;
1439 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l, NULL);
1440 ev.le_line_size = (ui32_t)ev.le_line.l;
1441 ev.le_line.l = (ui32_t)n;
1443 if(n < 0)
1444 break;
1446 n = a_lex_evaluate(&ev);
1447 beoe = (n_poption & n_PO_BATCH_FLAG)
1448 ? ok_vlook(batch_exit_on_error) : NULL;
1450 if(n){
1451 if(beoe != NULL && *beoe == '1'){
1452 if(n_exit_status == n_EXIT_OK)
1453 n_exit_status = n_EXIT_ERR;
1455 rv = FAL0;
1456 break;
1458 if(beoe != NULL){
1459 if(n_exit_status != n_EXIT_OK)
1460 break;
1463 jjump: /* TODO */
1464 a_lex_unstack(!rv);
1465 n_COLOUR( n_colour_env_pop(FAL0); )
1467 if(ev.le_line.s != NULL)
1468 free(ev.le_line.s);
1470 if(soldhdl != SIG_IGN)
1471 safe_signal(SIGINT, soldhdl);
1472 NYD2_LEAVE;
1473 if(hadint){
1474 sigprocmask(SIG_SETMASK, &soldset, NULL);
1475 n_raise(SIGINT);
1477 return rv;
1480 static int
1481 a_lex_c_read(void *v){ /* TODO IFS? how? -r */
1482 char const **argv, *cp, *cp2;
1483 int rv;
1484 NYD2_ENTER;
1486 rv = 0;
1488 for(argv = v; (cp = *argv++) != NULL;)
1489 if(!n_shexp_is_valid_varname(cp) || !n_var_is_user_writable(cp)){
1490 n_err(_("`read': variable (name) cannot be used: %s\n"),
1491 n_shexp_quote_cp(cp, FAL0));
1492 rv = 1;
1494 if(rv)
1495 goto jleave;
1497 cp = n_lex_input_cp(((n_pstate & n_PS_COMPOSE_MODE
1498 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT) |
1499 n_LEXINPUT_FORCE_STDIN | n_LEXINPUT_NL_ESC |
1500 n_LEXINPUT_PROMPT_NONE /* XXX POSIX: PS2: yes! */),
1501 NULL, NULL);
1502 if(cp == NULL){
1503 cp = n_empty;
1504 rv = 1;
1507 for(argv = v; *argv != NULL; ++argv){
1508 char c;
1510 while(blankspacechar(*cp))
1511 ++cp;
1512 if(*cp == '\0')
1513 break;
1515 /* The last variable gets the remaining line less trailing IFS */
1516 if(argv[1] == NULL){
1517 for(cp2 = cp; *cp2 != '\0'; ++cp2)
1519 for(; cp2 > cp; --cp2){
1520 c = cp2[-1];
1521 if(!blankspacechar(c))
1522 break;
1524 }else
1525 for(cp2 = cp; (c = *++cp2) != '\0';)
1526 if(blankspacechar(c))
1527 break;
1529 /* C99 xxx This is a CC warning workaround (-Wbad-function-cast) */{
1530 char *vcp;
1532 vcp = savestrbuf(cp, PTR2SIZE(cp2 - cp));
1533 if(!n_var_vset(*argv, (uintptr_t)vcp))
1534 rv = 1;
1537 cp = cp2;
1540 /* Set the remains to the empty string */
1541 for(; *argv != NULL; ++argv)
1542 if(!n_var_vset(*argv, (uintptr_t)n_empty))
1543 rv = 1;
1545 if(rv == 0)
1546 n_pstate_var__em = n_0;
1547 rv = 0;
1548 jleave:
1549 NYD2_LEAVE;
1550 return rv;
1553 FL int
1554 c_cmdnotsupp(void *vp){
1555 NYD_ENTER;
1556 n_UNUSED(vp);
1557 n_err(_("The requested feature is not compiled in\n"));
1558 NYD_LEAVE;
1559 return 1;
1562 FL bool_t
1563 n_commands(void){ /* FIXME */
1564 struct a_lex_eval_ctx ev;
1565 int n, eofcnt;
1566 bool_t volatile rv;
1567 NYD_ENTER;
1569 rv = TRU1;
1571 if (!(n_pstate & n_PS_SOURCING)) {
1572 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1573 safe_signal(SIGINT, &a_lex_onintr);
1574 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1575 safe_signal(SIGHUP, &a_lex_hangup);
1577 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1578 safe_signal(SIGPIPE, a_lex_oldpipe);
1580 memset(&ev, 0, sizeof ev);
1582 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1583 for (eofcnt = 0;;) {
1584 n_COLOUR( n_colour_env_pop(TRU1); )
1586 /* TODO Unless we have our signal manager (or however we do it) child
1587 * TODO processes may have time slots where their execution isn't
1588 * TODO protected by signal handlers (in between start and setup
1589 * TODO completed). close_all_files() is only called from onintr()
1590 * TODO so those may linger possibly forever */
1591 if(!(n_pstate & n_PS_SOURCING))
1592 close_all_files();
1594 interrupts = 0;
1596 n_memory_reset();
1598 if (!(n_pstate & n_PS_SOURCING)) {
1599 char *cp;
1601 /* TODO Note: this buffer may contain a password. We should redefine
1602 * TODO the code flow which has to do that */
1603 if ((cp = termios_state.ts_linebuf) != NULL) {
1604 termios_state.ts_linebuf = NULL;
1605 termios_state.ts_linesize = 0;
1606 free(cp); /* TODO pool give-back */
1608 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1609 if (ev.le_line.l > LINESIZE * 3) {
1610 free(ev.le_line.s); /* TODO pool! but what? */
1611 ev.le_line.s = NULL;
1612 ev.le_line.l = ev.le_line_size = 0;
1616 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1617 char *cp;
1619 if ((cp = ok_vlook(newmail)) != NULL) {
1620 struct stat st;
1622 /* FIXME TEST WITH NOPOLL ETC. !!! */
1623 n = (cp != NULL && strcmp(cp, "nopoll"));
1624 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1625 st.st_size > mailsize) ||
1626 (mb.mb_type == MB_MAILDIR && n != 0)) {
1627 size_t odot = PTR2SIZE(dot - message);
1628 ui32_t odid = (n_pstate & n_PS_DID_PRINT_DOT);
1630 if (setfile(mailname,
1631 FEDIT_NEWMAIL |
1632 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1633 n_exit_status |= n_EXIT_ERR;
1634 rv = FAL0;
1635 break;
1637 dot = message + odot;
1638 n_pstate |= odid;
1642 n_exit_status = n_EXIT_OK;
1645 /* Read a line of commands and handle end of file specially */
1646 ev.le_line.l = ev.le_line_size;
1647 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1648 &ev.le_line.s, &ev.le_line.l, NULL);
1649 ev.le_line_size = (ui32_t)ev.le_line.l;
1650 ev.le_line.l = (ui32_t)n;
1652 if (n < 0) {
1653 /* FIXME did unstack() when n_PS_SOURCING, only break with n_PS_LOADING */
1654 if (!(n_pstate & n_PS_ROBOT) &&
1655 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof) &&
1656 ++eofcnt < 4) {
1657 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1658 n_lex_input_clearerr();
1659 continue;
1661 break;
1664 n_pstate &= ~n_PS_HOOK_MASK;
1665 /* C99 */{
1666 char const *beoe;
1667 int estat;
1669 estat = a_lex_evaluate(&ev);
1670 beoe = (n_poption & n_PO_BATCH_FLAG)
1671 ? ok_vlook(batch_exit_on_error) : NULL;
1673 if(estat){
1674 if(beoe != NULL && *beoe == '1'){
1675 if(n_exit_status == n_EXIT_OK)
1676 n_exit_status = n_EXIT_ERR;
1677 rv = FAL0;
1678 break;
1680 if(!(n_psonce & n_PSO_STARTED)){ /* TODO join n_PS_EVAL_ERROR */
1681 if(a_lex_input == NULL ||
1682 !(a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)){
1683 rv = FAL0;
1684 break;
1686 }else
1687 break;
1690 if(beoe != NULL){
1691 if(n_exit_status != n_EXIT_OK)
1692 break;
1693 /* TODO n_PS_EVAL_ERROR and n_PS_SOURCING! Sigh!! */
1694 if((n_pstate & (n_PS_SOURCING | n_PS_EVAL_ERROR)
1695 ) == n_PS_EVAL_ERROR){
1696 n_exit_status = n_EXIT_ERR;
1697 break;
1702 if(!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE) &&
1703 ev.le_add_history)
1704 n_tty_addhist(ev.le_line.s, (ev.le_add_history != TRU1));
1706 if(n_pstate & n_PS_EXIT)
1707 break;
1710 a_lex_unstack(!rv);
1712 if (ev.le_line.s != NULL)
1713 free(ev.le_line.s);
1714 NYD_LEAVE;
1715 return rv;
1718 FL void
1719 n_lex_input_clearerr(void){
1720 FILE *fp;
1721 NYD2_ENTER;
1723 fp = NULL;
1725 if(a_lex_input == NULL)
1726 fp = n_stdin;
1727 else if(!(a_lex_input->li_flags & (a_LEX_FORCE_EOF |
1728 a_LEX_PIPE | a_LEX_MACRO | a_LEX_SLICE)))
1729 fp = a_lex_input->li_file;
1731 if(fp != NULL)
1732 clearerr(fp);
1733 NYD2_LEAVE;
1736 FL int
1737 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1738 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1739 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1740 struct n_string xprompt;
1741 FILE *ifile;
1742 bool_t doprompt, dotty;
1743 char const *iftype;
1744 int nold, n;
1745 NYD2_ENTER;
1747 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_FORCE_EOF)){
1748 n = -1;
1749 goto jleave;
1752 /* Special case macro mode: never need to prompt, lines have always been
1753 * unfolded already */
1754 if(!(lif & n_LEXINPUT_FORCE_STDIN) &&
1755 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1756 struct a_lex_input_inject *liip;
1758 if(*linebuf != NULL)
1759 free(*linebuf);
1761 /* Injection in progress? Don't care about the autocommit state here */
1762 if((liip = a_lex_input->li_inject) != NULL){
1763 a_lex_input->li_inject = liip->lii_next;
1765 *linesize = liip->lii_len;
1766 *linebuf = (char*)liip;
1767 memmove(*linebuf, liip->lii_dat, liip->lii_len +1);
1768 iftype = "INJECTION";
1769 }else{
1770 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1771 *linesize = 0;
1772 n = -1;
1773 goto jleave;
1776 ++a_lex_input->li_loff;
1777 *linesize = strlen(*linebuf);
1778 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1779 *linebuf = sbufdup(*linebuf, *linesize);
1781 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1782 ? "-X OPTION"
1783 : (a_lex_input->li_flags & a_LEX_MACRO_CMD) ? "CMD" : "MACRO";
1785 n = (int)*linesize;
1786 n_pstate |= n_PS_READLINE_NL;
1787 goto jhave_dat;
1790 /* Injection in progress? */
1791 if(!(lif & n_LEXINPUT_FORCE_STDIN)){
1792 struct a_lex_input_inject **liipp, *liip;
1794 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
1795 : &a_lex_input->li_inject;
1797 if((liip = *liipp) != NULL){
1798 *liipp = liip->lii_next;
1800 if(liip->lii_commit){
1801 if(*linebuf != NULL)
1802 free(*linebuf);
1804 /* Simply reuse the buffer */
1805 n = (int)(*linesize = liip->lii_len);
1806 *linebuf = (char*)liip;
1807 memmove(*linebuf, liip->lii_dat, liip->lii_len +1);
1808 iftype = "INJECTION";
1809 n_pstate |= n_PS_READLINE_NL;
1810 goto jhave_dat;
1811 }else{
1812 string = savestrbuf(liip->lii_dat, liip->lii_len);
1813 free(liip);
1818 n_pstate &= ~n_PS_READLINE_NL;
1819 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1820 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1821 doprompt = ((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1822 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT));
1823 dotty = (doprompt && !ok_blook(line_editor_disable));
1824 if(!doprompt)
1825 lif |= n_LEXINPUT_PROMPT_NONE;
1826 else{
1827 if(!dotty)
1828 n_string_creat_auto(&xprompt);
1829 if(prompt == NULL)
1830 lif |= n_LEXINPUT_PROMPT_EVAL;
1833 /* Ensure stdout is flushed first anyway */
1834 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1835 fflush(n_stdout);
1837 ifile = ((lif & n_LEXINPUT_FORCE_STDIN) || a_lex_input == NULL) ? n_stdin
1838 : a_lex_input->li_file;
1839 if(ifile == NULL){
1840 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1841 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO));
1842 ifile = n_stdin;
1845 for(nold = n = 0;;){
1846 if(dotty){
1847 assert(ifile == n_stdin);
1848 if(string != NULL && (n = (int)strlen(string)) > 0){
1849 if(*linesize > 0)
1850 *linesize += n +1;
1851 else
1852 *linesize = (size_t)n + LINESIZE +1;
1853 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1854 memcpy(*linebuf, string, (size_t)n +1);
1856 string = NULL;
1857 /* TODO if nold>0, don't redisplay the entire line!
1858 * TODO needs complete redesign ... */
1859 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1860 n_MEMORY_DEBUG_ARGSCALL);
1861 }else{
1862 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1863 n_tty_create_prompt(&xprompt, prompt, lif);
1864 if(xprompt.s_len > 0){
1865 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1866 fflush(n_stdout);
1870 n = (readline_restart)(ifile, linebuf, linesize, n
1871 n_MEMORY_DEBUG_ARGSCALL);
1873 if(n > 0 && nold > 0){
1874 int i = 0;
1875 char const *cp = *linebuf + nold;
1877 while(blankspacechar(*cp) && nold + i < n)
1878 ++cp, ++i;
1879 if(i > 0){
1880 memmove(*linebuf + nold, cp, n - nold - i);
1881 n -= i;
1882 (*linebuf)[n] = '\0';
1887 if(n <= 0)
1888 break;
1890 /* POSIX says:
1891 * An unquoted <backslash> at the end of a command line shall
1892 * be discarded and the next line shall continue the command */
1893 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1894 if(dotty)
1895 n_pstate |= n_PS_READLINE_NL;
1896 break;
1898 /* Definitely outside of quotes, thus the quoting rules are so that an
1899 * uneven number of successive backslashs at EOL is a continuation */
1900 if(n > 1){
1901 size_t i, j;
1903 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1904 if((*linebuf)[i] != '\\')
1905 break;
1906 if(!(j & 1))
1907 break;
1909 (*linebuf)[nold = --n] = '\0';
1910 lif |= n_LEXINPUT_NL_FOLLOW;
1913 if(n < 0)
1914 goto jleave;
1915 (*linebuf)[*linesize = n] = '\0';
1917 jhave_dat:
1918 #if 0
1919 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1920 char *cp, c;
1921 size_t i;
1923 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1924 c = *--cp;
1925 if(!blankspacechar(c))
1926 break;
1928 (*linebuf)[n = (int)i] = '\0';
1931 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1932 char *cp, c;
1933 size_t j, i;
1935 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1936 c = *cp++;
1937 if(!blankspacechar(c))
1938 break;
1940 if(i > 0){
1941 memmove(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1942 (*linebuf)[n = (int)j] = '\0';
1945 #endif /* 0 (notyet - must take care for backslash escaped space) */
1947 if(n_poption & n_PO_D_VV)
1948 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1949 jleave:
1950 if (n_pstate & n_PS_PSTATE_PENDMASK)
1951 a_lex_update_pstate();
1953 /* TODO We need to special case a_LEX_SLICE, since that is not managed by us
1954 * TODO but only established from the outside and we need to drop this
1955 * TODO overlay context somehow */
1956 if(n < 0 && a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SLICE))
1957 a_lex_unstack(FAL0);
1958 NYD2_LEAVE;
1959 return n;
1962 FL char *
1963 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1964 char const *string){
1965 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1966 size_t linesize;
1967 char *linebuf, *rv;
1968 int n;
1969 NYD2_ENTER;
1971 linesize = 0;
1972 linebuf = NULL;
1973 rv = NULL;
1975 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1976 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1977 (lif & n_LEXINPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE))
1978 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1980 if(linebuf != NULL)
1981 free(linebuf);
1982 NYD2_LEAVE;
1983 return rv;
1986 FL void
1987 n_load(char const *name){
1988 struct a_lex_input *lip;
1989 size_t i;
1990 FILE *fip;
1991 NYD_ENTER;
1993 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1994 goto jleave;
1996 i = strlen(name) +1;
1997 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) + i);
1998 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1999 lip->li_file = fip;
2000 lip->li_flags = a_LEX_FREE;
2001 memcpy(lip->li_name, name, i);
2003 a_lex_load(lip);
2004 n_pstate &= ~n_PS_EXIT;
2005 jleave:
2006 NYD_LEAVE;
2009 FL void
2010 n_load_Xargs(char const **lines, size_t cnt){
2011 static char const name[] = "-X";
2013 ui8_t buf[sizeof(struct a_lex_input) + sizeof name];
2014 char const *srcp, *xsrcp;
2015 char *cp;
2016 size_t imax, i, len;
2017 struct a_lex_input *lip;
2018 NYD_ENTER;
2020 lip = (void*)buf;
2021 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2022 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
2023 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
2024 memcpy(lip->li_name, name, sizeof name);
2026 /* The problem being that we want to support reverse solidus newline
2027 * escaping also within multiline -X, i.e., POSIX says:
2028 * An unquoted <backslash> at the end of a command line shall
2029 * be discarded and the next line shall continue the command
2030 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
2031 * entire lines array and set _MACRO_FREE_DATA */
2032 imax = cnt + 1;
2033 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
2035 /* For each of the input lines.. */
2036 for(i = len = 0, cp = NULL; cnt > 0;){
2037 bool_t keep;
2038 size_t j;
2040 if((j = strlen(srcp = *lines)) == 0){
2041 ++lines, --cnt;
2042 continue;
2045 /* Separate one line from a possible multiline input string */
2046 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
2047 *lines = &xsrcp[1];
2048 j = PTR2SIZE(xsrcp - srcp);
2049 }else
2050 ++lines, --cnt;
2052 /* The (separated) string may itself indicate soft newline escaping */
2053 if((keep = (srcp[j - 1] == '\\'))){
2054 size_t xj, xk;
2056 /* Need an uneven number of reverse solidus */
2057 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
2058 if(srcp[xj] != '\\')
2059 break;
2060 if(xk & 1)
2061 --j;
2062 else
2063 keep = FAL0;
2066 /* Strip any leading WS from follow lines, then */
2067 if(cp != NULL)
2068 while(j > 0 && blankspacechar(*srcp))
2069 ++srcp, --j;
2071 if(j > 0){
2072 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
2073 imax += 4;
2074 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
2075 imax);
2077 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
2078 memcpy(&cp[len], srcp, j);
2079 cp[len += j] = '\0';
2081 if(!keep)
2082 ++i;
2084 if(!keep)
2085 cp = NULL, len = 0;
2087 if(cp != NULL){
2088 assert(i + 1 < imax);
2089 lip->li_lines[i++] = cp;
2091 lip->li_lines[i] = NULL;
2093 a_lex_load(lip);
2094 if(n_pstate & n_PS_EXIT)
2095 exit(n_exit_status);
2096 NYD_LEAVE;
2099 FL int
2100 c_source(void *v){
2101 int rv;
2102 NYD_ENTER;
2104 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
2105 NYD_LEAVE;
2106 return rv;
2109 FL int
2110 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
2111 int rv;
2112 NYD_ENTER;
2114 rv = (a_lex_source_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
2115 NYD_LEAVE;
2116 return rv;
2119 FL bool_t
2120 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
2121 void (*on_finalize)(void*), void *finalize_arg){
2122 struct a_lex_input *lip;
2123 size_t i;
2124 int rv;
2125 NYD_ENTER;
2127 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2128 (i = strlen(name) +1));
2129 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2130 lip->li_outer = a_lex_input;
2131 lip->li_file = NULL;
2132 lip->li_cond = condstack_release();
2133 n_memory_autorec_push(&lip->li_autorecmem[0]);
2134 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
2135 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2136 ? a_LEX_SUPER_MACRO : 0);
2137 lip->li_lines = lines;
2138 lip->li_on_finalize = on_finalize;
2139 lip->li_finalize_arg = finalize_arg;
2140 memcpy(lip->li_name, name, i);
2142 n_pstate |= n_PS_ROBOT;
2143 a_lex_input = lip;
2144 rv = a_commands_recursive(lif);
2145 NYD_LEAVE;
2146 return rv;
2149 FL bool_t
2150 n_source_command(enum n_lexinput_flags lif, char const *cmd){
2151 struct a_lex_input *lip;
2152 size_t i, ial;
2153 bool_t rv;
2154 NYD_ENTER;
2156 i = strlen(cmd) +1;
2157 ial = n_ALIGN(i);
2159 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2160 ial + 2*sizeof(char*));
2161 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2162 lip->li_outer = a_lex_input;
2163 lip->li_cond = condstack_release();
2164 n_memory_autorec_push(&lip->li_autorecmem[0]);
2165 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_CMD |
2166 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2167 ? a_LEX_SUPER_MACRO : 0);
2168 lip->li_lines = (void*)&lip->li_name[ial];
2169 memcpy(lip->li_lines[0] = &lip->li_name[0], cmd, i);
2170 lip->li_lines[1] = NULL;
2172 n_pstate |= n_PS_ROBOT;
2173 a_lex_input = lip;
2174 rv = a_commands_recursive(lif);
2175 NYD_LEAVE;
2176 return rv;
2179 FL void
2180 n_source_slice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
2181 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
2182 struct a_lex_input *lip;
2183 size_t i;
2184 NYD_ENTER;
2186 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2187 (i = strlen(cmd) +1));
2188 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2189 lip->li_outer = a_lex_input;
2190 lip->li_file = new_stdin;
2191 lip->li_flags = a_LEX_FREE | a_LEX_SLICE;
2192 lip->li_on_finalize = on_finalize;
2193 lip->li_finalize_arg = finalize_arg;
2194 lip->li_slice_stdin = n_stdin;
2195 lip->li_slice_stdout = n_stdout;
2196 lip->li_slice_psonce = n_psonce;
2197 memcpy(lip->li_name, cmd, i);
2199 n_stdin = new_stdin;
2200 n_stdout = new_stdout;
2201 n_psonce = new_psonce;
2202 n_pstate |= n_PS_ROBOT;
2203 a_lex_input = lip;
2204 NYD_LEAVE;
2207 FL void
2208 n_source_slice_hack_remove_after_jump(void){
2209 a_lex_unstack(FAL0);
2212 FL bool_t
2213 n_source_may_yield_control(void){ /* TODO this is a terrible hack */
2214 /* TODO This is obviously hacky in that it depends on _input_stack not
2215 * TODO loosing any flags when creating new contexts... Maybe this
2216 * TODO function should instead walk all up the context stack when
2217 * TODO there is one, and verify neither level prevents yielding! */
2218 struct a_lex_input *lip;
2219 bool_t rv;
2220 NYD2_ENTER;
2222 rv = FAL0;
2224 /* Only when interactive and startup completed */
2225 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) !=
2226 (n_PSO_INTERACTIVE | n_PSO_STARTED))
2227 goto jleave;
2229 /* Not when running any hook */
2230 if(n_pstate & n_PS_HOOK_MASK)
2231 goto jleave;
2233 /* Traverse up the stack:
2234 * . not when controlled by a child process
2235 * TODO . not when there are pipes involved, we neither handle job control,
2236 * TODO nor process groups, that is, controlling terminal acceptably
2237 * . not when sourcing a file */
2238 for(lip = a_lex_input; lip != NULL; lip = lip->li_outer){
2239 ui32_t f;
2241 if((f = lip->li_flags) & (a_LEX_PIPE | a_LEX_SLICE))
2242 goto jleave;
2243 if(!(f & a_LEX_MACRO))
2244 goto jleave;
2247 rv = TRU1;
2248 jleave:
2249 NYD2_LEAVE;
2250 return rv;
2253 FL void
2254 n_source_inject_input(enum n_input_inject_flags iif, char const *buf,
2255 size_t len){
2256 NYD_ENTER;
2257 if(len == UIZ_MAX)
2258 len = strlen(buf);
2260 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat) -1 > len &&
2261 len > 0){
2262 size_t i;
2263 struct a_lex_input_inject *liip, **liipp;
2265 liip = n_alloc(n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat
2266 ) + 1 + len +1);
2267 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
2268 : &a_lex_input->li_inject;
2269 liip->lii_next = *liipp;
2270 liip->lii_commit = ((iif & n_INPUT_INJECT_COMMIT) != 0);
2271 if(buf[i = 0] != ' ' && !(iif & n_INPUT_INJECT_HISTORY))
2272 liip->lii_dat[i++] = ' '; /* TODO prim. hack to avoid history put! */
2273 memcpy(&liip->lii_dat[i], buf, len);
2274 i += len;
2275 liip->lii_dat[liip->lii_len = i] = '\0';
2276 *liipp = liip;
2278 NYD_LEAVE;
2281 FL void
2282 n_source_force_eof(void){
2283 NYD_ENTER;
2284 assert(a_lex_input != NULL);
2285 a_lex_input->li_flags |= a_LEX_FORCE_EOF;
2286 NYD_LEAVE;
2289 /* s-it-mode */