Extend shell argument parsing and quoting compatibility..
[s-mailx.git] / lex_input.c
blob6e943fd4481138e3bcff3dc43e93066e50248a4e
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 /* */
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_NOLIST, 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_NOLIST: cp = N_("no arguments"); break;
434 case ARG_NDMLIST: cp = N_("message-list (no default)"); break;
435 case ARG_WYSHLIST: cp = N_("sh(1)ell-style quoting"); break;
436 default: cp = N_("`wysh' for sh(1)ell-style quoting"); break;
438 rv = n_string_push_cp(rv, V_(cp));
440 if(lcp->lc_argtype & ARG_V)
441 rv = n_string_push_cp(rv, _(" | `vput' modifier"));
442 if(lcp->lc_argtype & ARG_EM)
443 rv = n_string_push_cp(rv, _(" | status in *!*"));
445 if(lcp->lc_argtype & ARG_A)
446 rv = n_string_push_cp(rv, _(" | needs box"));
447 if(lcp->lc_argtype & ARG_I)
448 rv = n_string_push_cp(rv, _(" | only interactive"));
449 if(lcp->lc_argtype & ARG_M)
450 rv = n_string_push_cp(rv, _(" | send mode"));
451 if(lcp->lc_argtype & ARG_R)
452 rv = n_string_push_cp(rv, _(" | no compose mode"));
453 if(lcp->lc_argtype & ARG_S)
454 rv = n_string_push_cp(rv, _(" | after startup"));
455 if(lcp->lc_argtype & ARG_X)
456 rv = n_string_push_cp(rv, _(" | subprocess"));
458 cp = n_string_cp(rv);
459 NYD2_LEAVE;
460 return cp;
463 static int
464 a_lex_c_list(void *v){
465 FILE *fp;
466 struct a_lex_cmd const **cpa, *cp, **cursor;
467 size_t l, i;
468 NYD_ENTER;
470 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
471 cpa = salloc(sizeof(cp) * i);
473 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
474 cpa[i] = &a_lex_cmd_tab[i];
475 /* C99 */{
476 size_t j;
478 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
479 cpa[i] = &a_lex_special_cmd_tab[j];
481 cpa[i] = NULL;
483 /* C99 */{
484 char const *xcp = v;
486 if(*xcp == '\0')
487 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
490 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
491 fp = n_stdout;
493 fprintf(fp, _("Commands are:\n"));
494 l = 1;
495 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
496 if(cp->lc_func == &c_cmdnotsupp)
497 continue;
498 if(n_poption & n_PO_D_V){
499 fprintf(fp, "%s\n", cp->lc_name);
500 ++l;
501 #ifdef HAVE_DOCSTRINGS
502 fprintf(fp, " : %s\n", V_(cp->lc_doc));
503 ++l;
504 #endif
505 fprintf(fp, " : %s\n", a_lex_cmdinfo(cp));
506 ++l;
507 }else{
508 size_t j = strlen(cp->lc_name) + 2;
510 if((i += j) > 72){
511 i = j;
512 fprintf(fp, "\n");
513 ++l;
515 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
519 if(fp != n_stdout){
520 page_or_print(fp, l);
521 Fclose(fp);
523 NYD_LEAVE;
524 return 0;
527 static int
528 a_lex__pcmd_cmp(void const *s1, void const *s2){
529 struct a_lex_cmd const * const *cp1, * const *cp2;
530 int rv;
531 NYD2_ENTER;
533 cp1 = s1;
534 cp2 = s2;
535 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
536 NYD2_LEAVE;
537 return rv;
540 static int
541 a_lex_c_help(void *v){
542 int rv;
543 char *arg;
544 NYD_ENTER;
546 /* Help for a single command? */
547 if((arg = *(char**)v) != NULL){
548 struct a_lex_ghost const *gp;
549 struct a_lex_cmd const *lcp, *lcpmax;
551 /* Ghosts take precedence */
552 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
553 if(!strcmp(arg, gp->lg_name)){
554 fprintf(n_stdout, "%s -> ", arg);
555 arg = gp->lg_cmd.s;
556 break;
559 lcpmax = &(lcp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
560 jredo:
561 for(; lcp < lcpmax; ++lcp){
562 if(is_prefix(arg, lcp->lc_name)){
563 fputs(arg, n_stdout);
564 if(strcmp(arg, lcp->lc_name))
565 fprintf(n_stdout, " (%s)", lcp->lc_name);
566 }else
567 continue;
569 #ifdef HAVE_DOCSTRINGS
570 fprintf(n_stdout, ": %s", V_(lcp->lc_doc));
571 #endif
572 if(n_poption & n_PO_D_V)
573 fprintf(n_stdout, "\n : %s", a_lex_cmdinfo(lcp));
574 putc('\n', n_stdout);
575 rv = 0;
576 goto jleave;
579 if(PTRCMP(lcpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
580 lcpmax = &(lcp =
581 a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
582 goto jredo;
585 if(gp != NULL){
586 fprintf(n_stdout, "%s\n", n_shexp_quote_cp(arg, TRU1));
587 rv = 0;
588 }else{
589 n_err(_("Unknown command: `%s'\n"), arg);
590 rv = 1;
592 }else{
593 /* Very ugly, but take care for compiler supported string lengths :( */
594 fputs(n_progname, n_stdout);
595 fputs(_(
596 " commands -- <msglist> denotes message specifications,\n"
597 "e.g., 1-5, :n or ., separated by spaces:\n"), n_stdout);
598 fputs(_(
599 "\n"
600 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
601 "Type <msglist> like `type' but always show all headers\n"
602 "next goto and type next message\n"
603 "from <msglist> (search and) print header summary for the given list\n"
604 "headers header summary for messages surrounding \"dot\"\n"
605 "delete <msglist> delete messages (can be `undelete'd)\n"),
606 n_stdout);
608 fputs(_(
609 "\n"
610 "save <msglist> folder append messages to folder and mark as saved\n"
611 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
612 "write <msglist> file write message contents to file (prompts for parts)\n"
613 "Reply <msglist> reply to message senders only\n"
614 "reply <msglist> like `Reply', but address all recipients\n"
615 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
616 n_stdout);
618 fputs(_(
619 "\n"
620 "mail <recipients> compose a mail for the given recipients\n"
621 "file folder change to another mailbox\n"
622 "File folder like `file', but open readonly\n"
623 "quit quit and apply changes to the current mailbox\n"
624 "xit or exit like `quit', but discard changes\n"
625 "!shell command shell escape\n"
626 "list [<anything>] all available commands [in search order]\n"),
627 n_stdout);
629 rv = (ferror(n_stdout) != 0);
631 jleave:
632 NYD_LEAVE;
633 return rv;
636 static int
637 a_lex_c_exit(void *v){
638 NYD_ENTER;
639 n_UNUSED(v);
641 if(n_psonce & n_PSO_STARTED){
642 /* In recursed state, return error to just pop the input level */
643 if(!(n_pstate & n_PS_SOURCING)){
644 #ifdef n_HAVE_TCAP
645 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
646 n_termcap_destroy();
647 #endif
648 exit(n_EXIT_OK);
651 n_pstate |= n_PS_EXIT;
652 NYD_LEAVE;
653 return 0;
656 static int
657 a_lex_c_quit(void *v){
658 NYD_ENTER;
659 n_UNUSED(v);
661 /* If we are n_PS_SOURCING, then return 1 so _evaluate() can handle it.
662 * Otherwise return -1 to abort command loop */
663 n_pstate |= n_PS_EXIT;
664 NYD_LEAVE;
665 return 0;
668 static int
669 a_lex_c_version(void *v){
670 int longest, rv;
671 char *iop;
672 char const *cp, **arr;
673 size_t i, i2;
674 NYD_ENTER;
675 n_UNUSED(v);
677 fprintf(n_stdout, _("%s version %s\nFeatures included (+) or not (-)\n"),
678 n_uagent, ok_vlook(version));
680 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
681 i = strlen(cp = &ok_vlook(features)[1]) +1;
682 iop = salloc(i);
683 memcpy(iop, cp, i);
685 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
686 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
687 arr[i] = cp;
688 i2 = strlen(cp);
689 longest = n_MAX(longest, (int)i2);
691 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
693 for(++longest, i2 = 0; i-- > 0;){
694 cp = *(arr++);
695 fprintf(n_stdout, "%-*s ", longest, cp);
696 i2 += longest;
697 if(UICMP(z, ++i2 + longest, >=, n_scrnwidth) || i == 0){
698 i2 = 0;
699 putc('\n', n_stdout);
703 if((rv = ferror(n_stdout) != 0))
704 clearerr(n_stdout);
705 NYD_LEAVE;
706 return rv;
709 static int
710 a_lex__version_cmp(void const *s1, void const *s2){
711 char const * const *cp1, * const *cp2;
712 int rv;
713 NYD2_ENTER;
715 cp1 = s1;
716 cp2 = s2;
717 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
718 NYD2_LEAVE;
719 return rv;
722 static void
723 a_lex_update_pstate(void){
724 NYD_ENTER;
726 if(n_pstate & n_PS_SIGWINCH_PEND){
727 char buf[32];
729 snprintf(buf, sizeof buf, "%d", n_scrnwidth);
730 ok_vset(COLUMNS, buf);
731 snprintf(buf, sizeof buf, "%d", n_scrnheight);
732 ok_vset(LINES, buf);
735 n_pstate &= ~n_PS_PSTATE_PENDMASK;
736 NYD_LEAVE;
739 static int
740 a_lex_evaluate(struct a_lex_eval_ctx *evp){
741 /* xxx old style(9), but also old code */
742 struct str line;
743 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
744 struct a_lex_ghost *gp;
745 struct a_lex_cmd const *cmd;
746 int rv, c;
747 enum {
748 a_NONE = 0,
749 a_GHOST_MASK = (1<<3) - 1, /* Ghost recursion counter bits */
750 a_NOPREFIX = 1<<4, /* Modifier prefix not allowed right now */
751 a_NOGHOST = 1<<5, /* No ghost expansion modifier */
752 /* New command modifier prefixes must be reflected in a_lex_c_ghost()! */
753 a_IGNERR = 1<<6, /* ignerr modifier prefix */
754 a_WYSH = 1<<7, /* XXX v15+ drop wysh modifier prefix */
755 a_VPUT = 1<<8 /* vput modifier prefix */
756 } flags;
757 NYD_ENTER;
759 flags = a_NONE;
760 rv = 1;
761 cmd = NULL;
762 gp = NULL;
763 line = evp->le_line; /* XXX don't change original (buffer pointer) */
764 assert(line.s[line.l] == '\0');
765 evp->le_add_history = FAL0;
767 /* Command ghosts that refer to shell commands or macro expansion restart */
768 jrestart:
770 /* Strip the white space away from end and beginning of command */
771 if(line.l > 0){
772 size_t i = line.l;
774 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
775 --i;
776 line.l = i;
778 for(cp = line.s; spacechar(*cp); ++cp)
780 line.l -= PTR2SIZE(cp - line.s);
782 /* Ignore null commands (comments) */
783 if(*cp == '#')
784 goto jerr0;
786 /* Handle ! differently to get the correct lexical conventions */
787 arglist[0] = cp;
788 if(*cp == '!')
789 ++cp;
790 /* Isolate the actual command; since it may not necessarily be
791 * separated from the arguments (as in `p1') we need to duplicate it to
792 * be able to create a NUL terminated version.
793 * We must be aware of several special one letter commands here */
794 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
795 (*cp == '|' || *cp == '~' || *cp == '?'))
796 ++cp;
797 c = (int)PTR2SIZE(cp - arglist[0]);
798 line.l -= c;
799 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
800 memcpy(word, arglist[0], c);
801 word[c] = '\0';
803 /* No-expansion modifier? */
804 if(!(flags & a_NOPREFIX) && *word == '\\'){
805 ++word;
806 --c;
807 flags |= a_NOGHOST;
810 /* It may be a modifier prefix */
811 if(c == sizeof("ignerr") -1 && !asccasecmp(word, "ignerr")){
812 flags |= a_NOPREFIX | a_IGNERR;
813 line.s = cp;
814 goto jrestart;
815 }else if(c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
816 flags |= a_NOPREFIX | a_WYSH;
817 line.s = cp;
818 goto jrestart;
819 }else if(c == sizeof("vput") -1 && !asccasecmp(word, "vput")){
820 flags |= a_NOPREFIX | a_VPUT;
821 line.s = cp;
822 goto jrestart;
825 /* Look up the command; if not found, bitch.
826 * Normally, a blank command would map to the first command in the
827 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
828 * confusion; act just the same for ghosts */
829 if(*word == '\0'){
830 if((n_pstate & n_PS_ROBOT) || gp != NULL)
831 goto jerr0;
832 cmd = a_lex_cmd_tab + 0;
833 goto jexec;
836 if(!(flags & a_NOGHOST) && (flags & a_GHOST_MASK) != a_GHOST_MASK){
837 /* TODO relink list head, so it's sorted on usage over time?
838 * TODO in fact, there should be one hashmap over all commands and ghosts
839 * TODO so that the lookup could be made much more efficient than it is
840 * TODO now (two adjacent list searches! */
841 ui8_t expcnt;
843 expcnt = (flags & a_GHOST_MASK);
844 ++expcnt;
845 flags = (flags & ~(a_GHOST_MASK | a_NOPREFIX)) | expcnt;
847 /* Avoid self-recursion; yes, the user could use \ no-expansion, but.. */
848 if(gp != NULL && !strcmp(word, gp->lg_name)){
849 if(n_poption & n_PO_D_V)
850 n_err(_("Actively avoiding self-recursion of `ghost': %s\n"),
851 word);
852 }else for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
853 if(!strcmp(word, gp->lg_name)){
854 if(line.l > 0){
855 size_t i;
857 i = gp->lg_cmd.l;
858 line.s = salloc(i + line.l +1);
859 memcpy(line.s, gp->lg_cmd.s, i);
860 memcpy(line.s + i, cp, line.l);
861 line.s[i += line.l] = '\0';
862 line.l = i;
863 }else{
864 line.s = gp->lg_cmd.s;
865 line.l = gp->lg_cmd.l;
867 goto jrestart;
871 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
872 bool_t s;
874 if(!(s = condstack_isskip()) || (n_poption & n_PO_D_V))
875 n_err(_("Unknown command%s: `%s'\n"),
876 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
877 if(s)
878 goto jerr0;
879 if(cmd != NULL){
880 c_cmdnotsupp(NULL);
881 cmd = NULL;
883 goto jleave;
886 /* See if we should execute the command -- if a conditional we always
887 * execute it, otherwise, check the state of cond */
888 jexec:
889 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
890 goto jerr0;
892 /* Process the arguments to the command, depending on the type it expects */
893 if((cmd->lc_argtype & ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
894 !(n_poption & n_PO_BATCH_FLAG)){
895 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
896 cmd->lc_name);
897 goto jleave;
899 if(!(cmd->lc_argtype & ARG_M) && (n_psonce & n_PSO_SENDMODE)){
900 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
901 goto jleave;
903 if(cmd->lc_argtype & ARG_R){
904 if(n_pstate & n_PS_COMPOSE_MODE){
905 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
906 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
907 goto jleave;
909 /* TODO Nothing should prevent ARG_R in conjunction with
910 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
911 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING)){
912 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
913 cmd->lc_name);
914 goto jleave;
917 if((cmd->lc_argtype & ARG_S) && !(n_psonce & n_PSO_STARTED)){
918 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
919 goto jleave;
921 if(!(cmd->lc_argtype & ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
922 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
923 cmd->lc_name);
924 goto jleave;
927 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
928 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
929 goto jleave;
931 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
932 n_err(_("May not execute `%s' -- message file is read only\n"),
933 cmd->lc_name);
934 goto jleave;
937 if(cmd->lc_argtype & ARG_O)
938 n_OBSOLETE2(_("this command will be removed"), cmd->lc_name);
940 if((flags & a_WYSH) && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST){
941 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
942 flags &= ~a_WYSH;
944 if((flags & a_VPUT) && !(cmd->lc_argtype & ARG_V)){
945 n_err(_("`vput' prefix doesn't affect `%s'\n"), cmd->lc_name);
946 flags &= ~a_VPUT;
949 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
950 * TODO doesn't use any of those list commands which strip this mask,
951 * TODO and for now we misuse bits for checking relation to history;
952 * TODO argument state should be property of a per-command carrier instead */
953 n_pstate &= ~n_PS_ARGLIST_MASK;
954 switch(cmd->lc_argtype & ARG_ARGMASK){
955 case ARG_MSGLIST:
956 /* Message list defaulting to nearest forward legal message */
957 if(n_msgvec == NULL)
958 goto je96;
959 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
960 break;
961 if(c == 0){
962 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
963 n_msgvec[1] = 0;
965 if(n_msgvec[0] == 0){
966 if(!(n_pstate & n_PS_HOOK_MASK))
967 fprintf(n_stdout, _("No applicable messages\n"));
968 break;
970 rv = (*cmd->lc_func)(n_msgvec);
971 break;
973 case ARG_NDMLIST:
974 /* Message list with no defaults, but no error if none exist */
975 if(n_msgvec == NULL){
976 je96:
977 n_err(_("Invalid use of message list\n"));
978 break;
980 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
981 break;
982 rv = (*cmd->lc_func)(n_msgvec);
983 break;
985 case ARG_STRLIST:
986 /* Just the straight string, with leading blanks removed */
987 while(whitechar(*cp))
988 ++cp;
989 rv = (*cmd->lc_func)(cp);
990 break;
992 case ARG_WYSHLIST:
993 c = 1;
994 if(0){
995 /* FALLTHRU */
996 case ARG_WYRALIST:
997 c = (flags & a_WYSH) ? 1 : 0;
998 if(0){
999 case ARG_RAWLIST:
1000 c = 0;
1003 if((c = getrawlist((c != 0), arglist, n_NELEM(arglist), cp, line.l)) < 0){
1004 n_err(_("Invalid argument list\n"));
1005 break;
1007 c -= ((flags & a_VPUT) != 0); /* XXX c=int */
1009 if(c < cmd->lc_minargs){
1010 n_err(_("`%s' requires at least %u arg(s)\n"),
1011 cmd->lc_name, (ui32_t)cmd->lc_minargs + ((flags & a_VPUT) != 0));
1012 break;
1014 #undef lc_minargs
1015 if(c > cmd->lc_maxargs){
1016 n_err(_("`%s' takes no more than %u arg(s)\n"),
1017 cmd->lc_name, (ui32_t)cmd->lc_maxargs + ((flags & a_VPUT) != 0));
1018 break;
1020 #undef lc_maxargs
1022 if(flags & a_VPUT){
1023 char const *emsg;
1025 if(!n_shexp_is_valid_varname(arglist[0]))
1026 emsg = N_("not a valid variable name");
1027 else if(!n_var_is_user_writable(arglist[0]))
1028 emsg = N_("either not a user writable, or a boolean variable");
1029 else
1030 emsg = NULL;
1031 if(emsg != NULL){
1032 n_err(_("`%s': %s: %s\n"),
1033 cmd->lc_name, V_(emsg), n_shexp_quote_cp(arglist[0], FAL0));
1034 break;
1037 ++c;
1038 n_pstate |= n_PS_ARGMOD_VPUT;
1040 rv = (*cmd->lc_func)(arglist);
1041 break;
1043 case ARG_NOLIST:
1044 /* Just the constant zero, for exiting, eg. */
1045 rv = (*cmd->lc_func)(0);
1046 break;
1048 default:
1049 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
1050 cmd->lc_argtype & ARG_ARGMASK); )
1051 goto jerr0;
1054 if(!(cmd->lc_argtype & ARG_H))
1055 evp->le_add_history = (((cmd->lc_argtype & ARG_G) ||
1056 (n_pstate & n_PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
1058 jleave:
1059 n_PS_ROOT_BLOCK(ok_vset(__qm, (rv == 0 ? n_0 : n_1))); /* TODO num=1/real */
1061 if(flags & a_IGNERR){
1062 rv = 0;
1063 n_exit_status = n_EXIT_OK;
1066 /* Exit the current source file on error TODO what a mess! */
1067 if(rv == 0)
1068 n_pstate &= ~n_PS_EVAL_ERROR;
1069 else{
1070 n_pstate |= n_PS_EVAL_ERROR;
1071 if(rv < 0 || (n_pstate & n_PS_ROBOT)){ /* FIXME */
1072 rv = 1;
1073 goto jret;
1075 goto jret0;
1078 if(cmd == NULL)
1079 goto jret0;
1080 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint)) /* TODO rid of that! */
1081 if(visible(dot))
1082 n_source_inject_input("\\type", sizeof("\\type") -1, TRU1);
1084 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
1085 !(cmd->lc_argtype & ARG_T))
1086 n_pstate |= n_PS_SAW_COMMAND;
1087 jleave0:
1088 n_pstate &= ~n_PS_EVAL_ERROR;
1089 jret0:
1090 rv = 0;
1091 jret:
1092 NYD_LEAVE;
1093 return rv;
1094 jerr0:
1095 n_PS_ROOT_BLOCK(ok_vset(__qm, n_0)); /* TODO num=1/real */
1096 goto jleave0;
1099 static struct a_lex_cmd const *
1100 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
1101 struct a_lex_cmd const *cp;
1102 NYD2_ENTER;
1104 for(cp = a_lex_cmd_tab;
1105 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
1106 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
1107 goto jleave;
1108 cp = NULL;
1109 jleave:
1110 NYD2_LEAVE;
1111 return cp;
1114 static void
1115 a_lex_hangup(int s){
1116 NYD_X; /* Signal handler */
1117 n_UNUSED(s);
1118 /* nothing to do? */
1119 exit(n_EXIT_ERR);
1122 static void
1123 a_lex_onintr(int s){ /* TODO block signals while acting */
1124 NYD_X; /* Signal handler */
1125 n_UNUSED(s);
1127 safe_signal(SIGINT, a_lex_onintr);
1129 termios_state_reset();
1130 close_all_files(); /* FIXME .. of current level ONLU! */
1131 if(image >= 0){
1132 close(image);
1133 image = -1;
1136 a_lex_unstack(TRUM1);
1138 if(interrupts != 1)
1139 n_err_sighdl(_("Interrupt\n"));
1140 safe_signal(SIGPIPE, a_lex_oldpipe);
1141 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
1144 static void
1145 a_lex_unstack(bool_t eval_error){
1146 struct a_lex_input *lip;
1147 NYD_ENTER;
1149 /* Free input injections of this level first */
1150 /* C99 */{
1151 struct a_lex_input_inject **liipp, *liip;
1153 if((lip = a_lex_input) == NULL)
1154 liipp = &a_lex_input_inject;
1155 else
1156 liipp = &lip->li_inject;
1158 while((liip = *liipp) != NULL){
1159 *liipp = liip->lii_next;
1160 free(liip);
1163 if(lip == NULL || !(lip->li_flags & a_LEX_SLICE))
1164 n_memory_reset();
1167 if(lip == NULL){
1168 /* If called from a_lex_onintr(), be silent FIXME */
1169 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1170 if(eval_error == TRUM1 || !(n_psonce & n_PSO_STARTED))
1171 goto jleave;
1172 goto jerr;
1175 if(lip->li_flags & a_LEX_SLICE){ /* TODO Temporary hack */
1176 n_stdin = lip->li_slice_stdin;
1177 n_stdout = lip->li_slice_stdout;
1178 n_psonce = lip->li_slice_psonce;
1179 goto jthe_slice_hack;
1182 if(lip->li_flags & a_LEX_MACRO){
1183 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
1184 char **lp;
1186 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
1187 free(*lp);
1188 ++lip->li_loff;
1190 /* Part of lip's memory chunk, then */
1191 if(!(lip->li_flags & a_LEX_MACRO_CMD))
1192 free(lip->li_lines);
1194 }else{
1195 if(lip->li_flags & a_LEX_PIPE)
1196 /* XXX command manager should -TERM then -KILL instead of hoping
1197 * XXX for exit of provider due to EPIPE / SIGPIPE */
1198 Pclose(lip->li_file, TRU1);
1199 else
1200 Fclose(lip->li_file);
1203 if(!condstack_take(lip->li_cond)){
1204 n_err(_("Unmatched `if' at end of %s %s\n"),
1205 ((lip->li_flags & a_LEX_MACRO
1206 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1207 : _("`source'd file"))),
1208 lip->li_name);
1209 eval_error = TRU1;
1212 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1214 jthe_slice_hack:
1215 if(lip->li_on_finalize != NULL)
1216 (*lip->li_on_finalize)(lip->li_finalize_arg);
1218 if((a_lex_input = lip->li_outer) == NULL){
1219 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1220 }else{
1221 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1222 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1223 n_pstate &= ~n_PS_SOURCING;
1224 assert(n_pstate & n_PS_ROBOT);
1227 if(eval_error)
1228 goto jerr;
1229 jleave:
1230 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1231 free(lip);
1232 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1233 a_lex_unstack(TRUM1);
1234 NYD_LEAVE;
1235 return;
1237 jerr:
1238 if(lip != NULL){
1239 /* POSIX says
1240 * Any errors in the start-up file shall either cause mailx to
1241 * terminate with a diagnostic message and a non-zero status or to
1242 * continue after writing a diagnostic message, ignoring the
1243 * remainder of the lines in the start-up file
1244 * But print the diagnostic only for the outermost resource unless the
1245 * user is debugging or in verbose mode */
1246 if((n_poption & n_PO_D_V) ||
1247 (!(n_psonce & n_PSO_STARTED) &&
1248 !(lip->li_flags & (a_LEX_SLICE | a_LEX_MACRO)) &&
1249 lip->li_outer == NULL))
1250 n_alert(_("Stopped %s %s due to errors%s"),
1251 (n_psonce & n_PSO_STARTED
1252 ? (lip->li_flags & a_LEX_SLICE ? _("sliced in program")
1253 : (lip->li_flags & a_LEX_MACRO
1254 ? (lip->li_flags & a_LEX_MACRO_CMD
1255 ? _("evaluating command") : _("evaluating macro"))
1256 : (lip->li_flags & a_LEX_PIPE
1257 ? _("executing `source'd pipe")
1258 : _("loading `source'd file")))
1260 : (lip->li_flags & a_LEX_MACRO
1261 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1262 ? _("evaluating command line") : _("evaluating macro"))
1263 : _("loading initialization resource"))),
1264 lip->li_name,
1265 (n_poption & n_PO_DEBUG
1266 ? n_empty : _(" (enable *debug* for trace)")));
1269 if(!(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED))){
1270 if(n_poption & n_PO_D_V)
1271 n_alert(_("Non-interactive, bailing out due to errors "
1272 "in startup load phase"));
1273 exit(n_EXIT_ERR);
1275 goto jleave;
1278 static bool_t
1279 a_lex_source_file(char const *file, bool_t silent_open_error){
1280 struct a_lex_input *lip;
1281 size_t nlen;
1282 char *nbuf;
1283 bool_t ispipe;
1284 FILE *fip;
1285 NYD_ENTER;
1287 fip = NULL;
1289 /* Being a command argument file is space-trimmed *//* TODO v15 with
1290 * TODO WYRALIST this is no longer necessary true, and for that we
1291 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1292 #if 0
1293 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
1294 file[--nlen] == '|')))
1295 #else
1296 ispipe = FAL0;
1297 if(!silent_open_error)
1298 for(nlen = strlen(file); nlen > 0;){
1299 char c;
1301 c = file[--nlen];
1302 if(!blankchar(c)){
1303 if(c == '|'){
1304 nbuf = savestrbuf(file, nlen);
1305 ispipe = TRU1;
1307 break;
1310 #endif
1312 if(ispipe){
1313 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1314 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL)
1315 goto jeopencheck;
1316 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1317 goto jeopencheck;
1318 else if((fip = Fopen(nbuf, "r")) == NULL){
1319 jeopencheck:
1320 if(!silent_open_error || (n_poption & n_PO_D_V))
1321 n_perr(nbuf, 0);
1322 if(silent_open_error)
1323 fip = (FILE*)-1;
1324 goto jleave;
1327 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
1328 (nlen = strlen(nbuf) +1));
1329 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1330 lip->li_outer = a_lex_input;
1331 lip->li_file = fip;
1332 lip->li_cond = condstack_release();
1333 n_memory_autorec_push(&lip->li_autorecmem[0]);
1334 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1335 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1336 ? a_LEX_SUPER_MACRO : 0);
1337 memcpy(lip->li_name, nbuf, nlen);
1339 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1340 a_lex_input = lip;
1341 if(!a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC))
1342 fip = NULL;
1343 jleave:
1344 NYD_LEAVE;
1345 return (fip != NULL);
1348 static bool_t
1349 a_lex_load(struct a_lex_input *lip){
1350 bool_t rv;
1351 NYD2_ENTER;
1353 assert(!(n_psonce & n_PSO_STARTED));
1354 assert(a_lex_input == NULL);
1356 /* POSIX:
1357 * Any errors in the start-up file shall either cause mailx to terminate
1358 * with a diagnostic message and a non-zero status or to continue after
1359 * writing a diagnostic message, ignoring the remainder of the lines in
1360 * the start-up file. */
1361 lip->li_cond = condstack_release();
1362 n_memory_autorec_push(&lip->li_autorecmem[0]);
1364 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1365 n_pstate |= n_PS_ROBOT |
1366 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1368 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1369 if(n_poption & n_PO_D_V)
1370 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1371 a_lex_input = lip;
1372 if(!(rv = n_commands())){
1373 if(!(n_psonce & n_PSO_INTERACTIVE)){
1374 if(n_poption & n_PO_D_V)
1375 n_alert(_("Non-interactive program mode, forced exit"));
1376 exit(n_EXIT_ERR);
1377 }else if(n_poption & n_PO_BATCH_FLAG){
1378 char const *beoe;
1380 if((beoe = ok_vlook(batch_exit_on_error)) != NULL && *beoe == '1')
1381 n_pstate |= n_PS_EXIT;
1384 /* n_PS_EXIT handled by callers */
1385 NYD2_LEAVE;
1386 return rv;
1389 static void
1390 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1391 NYD_X; /* Signal handler */
1392 n_UNUSED(sig);
1393 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1396 static bool_t
1397 a_commands_recursive(enum n_lexinput_flags lif){
1398 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1399 sighandler_type soldhdl;
1400 sigset_t sintset, soldset;
1401 struct a_lex_eval_ctx ev;
1402 bool_t rv, ever;
1403 NYD2_ENTER;
1405 memset(&ev, 0, sizeof ev);
1407 sigfillset(&sintset);
1408 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1409 hadint = FAL0;
1410 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1411 safe_signal(SIGINT, &a_lex__cmdrecint);
1412 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1413 hadint = TRU1;
1414 goto jjump;
1417 sigprocmask(SIG_SETMASK, &soldset, NULL);
1419 n_COLOUR( n_colour_env_push(); )
1420 rv = TRU1;
1421 for(ever = FAL0;; ever = TRU1){
1422 char const *beoe;
1423 int n;
1425 if(ever)
1426 n_memory_reset();
1428 /* Read a line of commands and handle end of file specially */
1429 ev.le_line.l = ev.le_line_size;
1430 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l, NULL);
1431 ev.le_line_size = (ui32_t)ev.le_line.l;
1432 ev.le_line.l = (ui32_t)n;
1434 if(n < 0)
1435 break;
1437 n = a_lex_evaluate(&ev);
1438 beoe = (n_poption & n_PO_BATCH_FLAG)
1439 ? ok_vlook(batch_exit_on_error) : NULL;
1441 if(n){
1442 if(beoe != NULL && *beoe == '1'){
1443 if(n_exit_status == n_EXIT_OK)
1444 n_exit_status = n_EXIT_ERR;
1446 rv = FAL0;
1447 break;
1449 if(beoe != NULL){
1450 if(n_exit_status != n_EXIT_OK)
1451 break;
1454 jjump: /* TODO */
1455 a_lex_unstack(!rv);
1456 n_COLOUR( n_colour_env_pop(FAL0); )
1458 if(ev.le_line.s != NULL)
1459 free(ev.le_line.s);
1461 if(soldhdl != SIG_IGN)
1462 safe_signal(SIGINT, soldhdl);
1463 NYD2_LEAVE;
1464 if(hadint){
1465 sigprocmask(SIG_SETMASK, &soldset, NULL);
1466 n_raise(SIGINT);
1468 return rv;
1471 static int
1472 a_lex_c_read(void *v){ /* TODO IFS? how? -r */
1473 char const **argv, *cp, *emv, *cp2;
1474 int rv;
1475 NYD2_ENTER;
1477 rv = 0;
1478 for(argv = v; (cp = *argv++) != NULL;)
1479 if(!n_shexp_is_valid_varname(cp) || !n_var_is_user_writable(cp)){
1480 n_err(_("`read': variable (name) cannot be used: %s\n"),
1481 n_shexp_quote_cp(cp, FAL0));
1482 rv = 1;
1484 if(rv)
1485 goto jleave;
1487 emv = n_0;
1489 cp = n_lex_input_cp(((n_pstate & n_PS_COMPOSE_MODE
1490 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT) |
1491 n_LEXINPUT_FORCE_STDIN | n_LEXINPUT_NL_ESC |
1492 n_LEXINPUT_PROMPT_NONE /* XXX POSIX: PS2: yes! */),
1493 NULL, NULL);
1494 if(cp == NULL)
1495 cp = n_empty;
1497 for(argv = v; *argv != NULL; ++argv){
1498 char c;
1500 while(blankchar(*cp))
1501 ++cp;
1502 if(*cp == '\0')
1503 break;
1505 /* The last variable gets the remaining line less trailing IFS */
1506 if(argv[1] == NULL){
1507 for(cp2 = cp; *cp2 != '\0'; ++cp2)
1509 for(; cp2 > cp; --cp2){
1510 c = cp2[-1];
1511 if(!blankchar(c))
1512 break;
1514 }else
1515 for(cp2 = cp; (c = *++cp2) != '\0';)
1516 if(blankchar(c))
1517 break;
1519 /* C99 xxx This is a CC warning workaround (-Wbad-function-cast) */{
1520 char *vcp;
1522 vcp = savestrbuf(cp, PTR2SIZE(cp2 - cp));
1523 if(!n_var_vset(*argv, (uintptr_t)vcp))
1524 emv = n_1;
1527 cp = cp2;
1530 /* Set the remains to the empty string */
1531 for(; *argv != NULL; ++argv)
1532 if(!n_var_vset(*argv, (uintptr_t)n_empty))
1533 emv = n_1;
1535 n__EM_SET(emv);
1536 rv = 0;
1537 jleave:
1538 NYD2_LEAVE;
1539 return rv;
1542 FL int
1543 c_cmdnotsupp(void *vp){
1544 NYD_ENTER;
1545 n_UNUSED(vp);
1546 n_err(_("The requested feature is not compiled in\n"));
1547 NYD_LEAVE;
1548 return 1;
1551 FL bool_t
1552 n_commands(void){ /* FIXME */
1553 struct a_lex_eval_ctx ev;
1554 int n;
1555 bool_t volatile rv;
1556 NYD_ENTER;
1558 rv = TRU1;
1560 if (!(n_pstate & n_PS_SOURCING)) {
1561 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1562 safe_signal(SIGINT, &a_lex_onintr);
1563 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1564 safe_signal(SIGHUP, &a_lex_hangup);
1566 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1567 safe_signal(SIGPIPE, a_lex_oldpipe);
1569 memset(&ev, 0, sizeof ev);
1571 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1572 for (;;) {
1573 n_COLOUR( n_colour_env_pop(TRU1); )
1575 /* TODO Unless we have our signal manager (or however we do it) child
1576 * TODO processes may have time slots where their execution isn't
1577 * TODO protected by signal handlers (in between start and setup
1578 * TODO completed). close_all_files() is only called from onintr()
1579 * TODO so those may linger possibly forever */
1580 if(!(n_pstate & n_PS_SOURCING))
1581 close_all_files();
1583 interrupts = 0;
1585 n_memory_reset();
1587 if (!(n_pstate & n_PS_SOURCING)) {
1588 char *cp;
1590 /* TODO Note: this buffer may contain a password. We should redefine
1591 * TODO the code flow which has to do that */
1592 if ((cp = termios_state.ts_linebuf) != NULL) {
1593 termios_state.ts_linebuf = NULL;
1594 termios_state.ts_linesize = 0;
1595 free(cp); /* TODO pool give-back */
1597 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1598 if (ev.le_line.l > LINESIZE * 3) {
1599 free(ev.le_line.s); /* TODO pool! but what? */
1600 ev.le_line.s = NULL;
1601 ev.le_line.l = ev.le_line_size = 0;
1605 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1606 char *cp;
1608 if ((cp = ok_vlook(newmail)) != NULL) {
1609 struct stat st;
1611 /* FIXME TEST WITH NOPOLL ETC. !!! */
1612 n = (cp != NULL && strcmp(cp, "nopoll"));
1613 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1614 st.st_size > mailsize) ||
1615 (mb.mb_type == MB_MAILDIR && n != 0)) {
1616 size_t odot = PTR2SIZE(dot - message);
1617 ui32_t odid = (n_pstate & n_PS_DID_PRINT_DOT);
1619 if (setfile(mailname,
1620 FEDIT_NEWMAIL |
1621 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1622 n_exit_status |= n_EXIT_ERR;
1623 rv = FAL0;
1624 break;
1626 dot = message + odot;
1627 n_pstate |= odid;
1631 n_exit_status = n_EXIT_OK;
1634 /* Read a line of commands and handle end of file specially */
1635 ev.le_line.l = ev.le_line_size;
1636 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1637 &ev.le_line.s, &ev.le_line.l, NULL);
1638 ev.le_line_size = (ui32_t)ev.le_line.l;
1639 ev.le_line.l = (ui32_t)n;
1641 if (n < 0) {
1642 /* FIXME did unstack() when n_PS_SOURCING, only break with n_PS_LOADING */
1643 if (!(n_pstate & n_PS_ROBOT) &&
1644 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof)) {
1645 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1646 n_msleep(500, FAL0);
1647 continue;
1649 break;
1652 n_pstate &= ~n_PS_HOOK_MASK;
1653 /* C99 */{
1654 char const *beoe;
1655 int estat;
1657 estat = a_lex_evaluate(&ev);
1658 beoe = (n_poption & n_PO_BATCH_FLAG)
1659 ? ok_vlook(batch_exit_on_error) : NULL;
1661 if(estat){
1662 if(beoe != NULL && *beoe == '1'){
1663 if(n_exit_status == n_EXIT_OK)
1664 n_exit_status = n_EXIT_ERR;
1665 rv = FAL0;
1666 break;
1668 if(!(n_psonce & n_PSO_STARTED)){ /* TODO join n_PS_EVAL_ERROR */
1669 if(a_lex_input == NULL ||
1670 !(a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)){
1671 rv = FAL0;
1672 break;
1674 }else
1675 break;
1678 if(beoe != NULL){
1679 if(n_exit_status != n_EXIT_OK)
1680 break;
1681 /* TODO n_PS_EVAL_ERROR and n_PS_SOURCING! Sigh!! */
1682 if((n_pstate & (n_PS_SOURCING | n_PS_EVAL_ERROR)
1683 ) == n_PS_EVAL_ERROR){
1684 n_exit_status = n_EXIT_ERR;
1685 break;
1690 if(!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE))
1691 n_tty_addhist(ev.le_line.s, (ev.le_add_history != TRU1));
1693 if(n_pstate & n_PS_EXIT)
1694 break;
1697 a_lex_unstack(!rv);
1699 if (ev.le_line.s != NULL)
1700 free(ev.le_line.s);
1701 NYD_LEAVE;
1702 return rv;
1705 FL int
1706 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1707 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1708 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1709 struct n_string xprompt;
1710 FILE *ifile;
1711 bool_t doprompt, dotty;
1712 char const *iftype;
1713 int nold, n;
1714 NYD2_ENTER;
1716 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_FORCE_EOF)){
1717 n = -1;
1718 goto jleave;
1721 /* Special case macro mode: never need to prompt, lines have always been
1722 * unfolded already */
1723 if(!(lif & n_LEXINPUT_FORCE_STDIN) &&
1724 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1725 struct a_lex_input_inject *liip;
1727 if(*linebuf != NULL)
1728 free(*linebuf);
1730 /* Injection in progress? Don't care about the autocommit state here */
1731 if((liip = a_lex_input->li_inject) != NULL){
1732 a_lex_input->li_inject = liip->lii_next;
1734 *linesize = liip->lii_len;
1735 *linebuf = (char*)liip;
1736 memcpy(*linebuf, liip->lii_dat, liip->lii_len +1);
1737 iftype = "INJECTION";
1738 }else{
1739 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1740 *linesize = 0;
1741 n = -1;
1742 goto jleave;
1745 ++a_lex_input->li_loff;
1746 *linesize = strlen(*linebuf);
1747 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1748 *linebuf = sbufdup(*linebuf, *linesize);
1750 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1751 ? "-X OPTION"
1752 : (a_lex_input->li_flags & a_LEX_MACRO_CMD) ? "CMD" : "MACRO";
1754 n = (int)*linesize;
1755 n_pstate |= n_PS_READLINE_NL;
1756 goto jhave_dat;
1759 /* Injection in progress? */
1760 if(!(lif & n_LEXINPUT_FORCE_STDIN)){
1761 struct a_lex_input_inject **liipp, *liip;
1763 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
1764 : &a_lex_input->li_inject;
1766 if((liip = *liipp) != NULL){
1767 *liipp = liip->lii_next;
1769 if(liip->lii_commit){
1770 if(*linebuf != NULL)
1771 free(*linebuf);
1773 /* Simply reuse the buffer */
1774 n = (int)(*linesize = liip->lii_len);
1775 *linebuf = (char*)liip;
1776 memcpy(*linebuf, liip->lii_dat, liip->lii_len +1);
1777 iftype = "INJECTION";
1778 n_pstate |= n_PS_READLINE_NL;
1779 goto jhave_dat;
1780 }else{
1781 string = savestrbuf(liip->lii_dat, liip->lii_len);
1782 free(liip);
1787 n_pstate &= ~n_PS_READLINE_NL;
1788 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1789 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1790 doprompt = ((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1791 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT));
1792 dotty = (doprompt && !ok_blook(line_editor_disable));
1793 if(!doprompt)
1794 lif |= n_LEXINPUT_PROMPT_NONE;
1795 else{
1796 if(!dotty)
1797 n_string_creat_auto(&xprompt);
1798 if(prompt == NULL)
1799 lif |= n_LEXINPUT_PROMPT_EVAL;
1802 /* Ensure stdout is flushed first anyway */
1803 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1804 fflush(n_stdout);
1806 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : n_stdin;
1807 if(ifile == NULL){
1808 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1809 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO));
1810 ifile = n_stdin;
1813 for(nold = n = 0;;){
1814 if(dotty){
1815 assert(ifile == n_stdin);
1816 if(string != NULL && (n = (int)strlen(string)) > 0){
1817 if(*linesize > 0)
1818 *linesize += n +1;
1819 else
1820 *linesize = (size_t)n + LINESIZE +1;
1821 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1822 memcpy(*linebuf, string, (size_t)n +1);
1824 string = NULL;
1825 /* TODO if nold>0, don't redisplay the entire line!
1826 * TODO needs complete redesign ... */
1827 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1828 n_MEMORY_DEBUG_ARGSCALL);
1829 }else{
1830 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1831 n_tty_create_prompt(&xprompt, prompt, lif);
1832 if(xprompt.s_len > 0){
1833 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1834 fflush(n_stdout);
1838 n = (readline_restart)(ifile, linebuf, linesize, n
1839 n_MEMORY_DEBUG_ARGSCALL);
1841 if(n > 0 && nold > 0){
1842 int i = 0;
1843 char const *cp = *linebuf + nold;
1845 while(blankspacechar(*cp) && nold + i < n)
1846 ++cp, ++i;
1847 if(i > 0){
1848 memmove(*linebuf + nold, cp, n - nold - i);
1849 n -= i;
1850 (*linebuf)[n] = '\0';
1855 if(n <= 0)
1856 break;
1858 /* POSIX says:
1859 * An unquoted <backslash> at the end of a command line shall
1860 * be discarded and the next line shall continue the command */
1861 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1862 if(dotty)
1863 n_pstate |= n_PS_READLINE_NL;
1864 break;
1866 /* Definitely outside of quotes, thus the quoting rules are so that an
1867 * uneven number of successive backslashs at EOL is a continuation */
1868 if(n > 1){
1869 size_t i, j;
1871 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1872 if((*linebuf)[i] != '\\')
1873 break;
1874 if(!(j & 1))
1875 break;
1877 (*linebuf)[nold = --n] = '\0';
1878 lif |= n_LEXINPUT_NL_FOLLOW;
1881 if(n < 0)
1882 goto jleave;
1883 (*linebuf)[*linesize = n] = '\0';
1885 jhave_dat:
1886 #if 0
1887 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1888 char *cp, c;
1889 size_t i;
1891 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1892 c = *--cp;
1893 if(!blankspacechar(c))
1894 break;
1896 (*linebuf)[n = (int)i] = '\0';
1899 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1900 char *cp, c;
1901 size_t j, i;
1903 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1904 c = *cp++;
1905 if(!blankspacechar(c))
1906 break;
1908 if(i > 0){
1909 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1910 (*linebuf)[n = (int)j] = '\0';
1913 #endif /* 0 (notyet - must take care for backslash escaped space) */
1915 if(n_poption & n_PO_D_VV)
1916 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1917 jleave:
1918 if (n_pstate & n_PS_PSTATE_PENDMASK)
1919 a_lex_update_pstate();
1921 /* TODO We need to special case a_LEX_SLICE, since that is not managed by us
1922 * TODO but only established from the outside and we need to drop this
1923 * TODO overlay context somehow */
1924 if(n < 0 && a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SLICE))
1925 a_lex_unstack(FAL0);
1926 NYD2_LEAVE;
1927 return n;
1930 FL char *
1931 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1932 char const *string){
1933 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1934 size_t linesize;
1935 char *linebuf, *rv;
1936 int n;
1937 NYD2_ENTER;
1939 linesize = 0;
1940 linebuf = NULL;
1941 rv = NULL;
1943 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1944 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1945 (lif & n_LEXINPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE))
1946 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1948 if(linebuf != NULL)
1949 free(linebuf);
1950 NYD2_LEAVE;
1951 return rv;
1954 FL void
1955 n_load(char const *name){
1956 struct a_lex_input *lip;
1957 size_t i;
1958 FILE *fip;
1959 NYD_ENTER;
1961 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1962 goto jleave;
1964 i = strlen(name) +1;
1965 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) + i);
1966 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1967 lip->li_file = fip;
1968 lip->li_flags = a_LEX_FREE;
1969 memcpy(lip->li_name, name, i);
1971 a_lex_load(lip);
1972 n_pstate &= ~n_PS_EXIT;
1973 jleave:
1974 NYD_LEAVE;
1977 FL void
1978 n_load_Xargs(char const **lines, size_t cnt){
1979 static char const name[] = "-X";
1981 ui8_t buf[sizeof(struct a_lex_input) + sizeof name];
1982 char const *srcp, *xsrcp;
1983 char *cp;
1984 size_t imax, i, len;
1985 struct a_lex_input *lip;
1986 NYD_ENTER;
1988 lip = (void*)buf;
1989 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1990 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1991 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1992 memcpy(lip->li_name, name, sizeof name);
1994 /* The problem being that we want to support reverse solidus newline
1995 * escaping also within multiline -X, i.e., POSIX says:
1996 * An unquoted <backslash> at the end of a command line shall
1997 * be discarded and the next line shall continue the command
1998 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
1999 * entire lines array and set _MACRO_FREE_DATA */
2000 imax = cnt + 1;
2001 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
2003 /* For each of the input lines.. */
2004 for(i = len = 0, cp = NULL; cnt > 0;){
2005 bool_t keep;
2006 size_t j;
2008 if((j = strlen(srcp = *lines)) == 0){
2009 ++lines, --cnt;
2010 continue;
2013 /* Separate one line from a possible multiline input string */
2014 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
2015 *lines = &xsrcp[1];
2016 j = PTR2SIZE(xsrcp - srcp);
2017 }else
2018 ++lines, --cnt;
2020 /* The (separated) string may itself indicate soft newline escaping */
2021 if((keep = (srcp[j - 1] == '\\'))){
2022 size_t xj, xk;
2024 /* Need an uneven number of reverse solidus */
2025 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
2026 if(srcp[xj] != '\\')
2027 break;
2028 if(xk & 1)
2029 --j;
2030 else
2031 keep = FAL0;
2034 /* Strip any leading WS from follow lines, then */
2035 if(cp != NULL)
2036 while(j > 0 && blankspacechar(*srcp))
2037 ++srcp, --j;
2039 if(j > 0){
2040 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
2041 imax += 4;
2042 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
2043 imax);
2045 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
2046 memcpy(&cp[len], srcp, j);
2047 cp[len += j] = '\0';
2049 if(!keep)
2050 ++i;
2052 if(!keep)
2053 cp = NULL, len = 0;
2055 if(cp != NULL){
2056 assert(i + 1 < imax);
2057 lip->li_lines[i++] = cp;
2059 lip->li_lines[i] = NULL;
2061 a_lex_load(lip);
2062 if(n_pstate & n_PS_EXIT)
2063 exit(n_exit_status);
2064 NYD_LEAVE;
2067 FL int
2068 c_source(void *v){
2069 int rv;
2070 NYD_ENTER;
2072 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
2073 NYD_LEAVE;
2074 return rv;
2077 FL int
2078 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
2079 int rv;
2080 NYD_ENTER;
2082 rv = (a_lex_source_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
2083 NYD_LEAVE;
2084 return rv;
2087 FL bool_t
2088 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
2089 void (*on_finalize)(void*), void *finalize_arg){
2090 struct a_lex_input *lip;
2091 size_t i;
2092 int rv;
2093 NYD_ENTER;
2095 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2096 (i = strlen(name) +1));
2097 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2098 lip->li_outer = a_lex_input;
2099 lip->li_file = NULL;
2100 lip->li_cond = condstack_release();
2101 n_memory_autorec_push(&lip->li_autorecmem[0]);
2102 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
2103 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2104 ? a_LEX_SUPER_MACRO : 0);
2105 lip->li_lines = lines;
2106 lip->li_on_finalize = on_finalize;
2107 lip->li_finalize_arg = finalize_arg;
2108 memcpy(lip->li_name, name, i);
2110 n_pstate |= n_PS_ROBOT;
2111 a_lex_input = lip;
2112 rv = a_commands_recursive(lif);
2113 NYD_LEAVE;
2114 return rv;
2117 FL bool_t
2118 n_source_command(enum n_lexinput_flags lif, char const *cmd){
2119 struct a_lex_input *lip;
2120 size_t i, ial;
2121 bool_t rv;
2122 NYD_ENTER;
2124 i = strlen(cmd) +1;
2125 ial = n_ALIGN(i);
2127 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2128 ial + 2*sizeof(char*));
2129 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2130 lip->li_outer = a_lex_input;
2131 lip->li_cond = condstack_release();
2132 n_memory_autorec_push(&lip->li_autorecmem[0]);
2133 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_CMD |
2134 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2135 ? a_LEX_SUPER_MACRO : 0);
2136 lip->li_lines = (void*)&lip->li_name[ial];
2137 memcpy(lip->li_lines[0] = &lip->li_name[0], cmd, i);
2138 lip->li_lines[1] = NULL;
2140 n_pstate |= n_PS_ROBOT;
2141 a_lex_input = lip;
2142 rv = a_commands_recursive(lif);
2143 NYD_LEAVE;
2144 return rv;
2147 FL void
2148 n_source_slice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
2149 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
2150 struct a_lex_input *lip;
2151 size_t i;
2152 NYD_ENTER;
2154 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2155 (i = strlen(cmd) +1));
2156 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2157 lip->li_outer = a_lex_input;
2158 lip->li_file = new_stdin;
2159 lip->li_flags = a_LEX_FREE | a_LEX_SLICE;
2160 lip->li_on_finalize = on_finalize;
2161 lip->li_finalize_arg = finalize_arg;
2162 lip->li_slice_stdin = n_stdin;
2163 lip->li_slice_stdout = n_stdout;
2164 lip->li_slice_psonce = n_psonce;
2165 memcpy(lip->li_name, cmd, i);
2167 n_stdin = new_stdin;
2168 n_stdout = new_stdout;
2169 n_psonce = new_psonce;
2170 n_pstate |= n_PS_ROBOT;
2171 a_lex_input = lip;
2172 NYD_LEAVE;
2175 FL void
2176 n_source_slice_hack_remove_after_jump(void){
2177 a_lex_unstack(FAL0);
2180 FL bool_t
2181 n_source_may_yield_control(void){ /* TODO this is a terrible hack */
2182 /* TODO This is obviously hacky in that it depends on _input_stack not
2183 * TODO loosing any flags when creating new contexts... Maybe this
2184 * TODO function should instead walk all up the context stack when
2185 * TODO there is one, and verify neither level prevents yielding! */
2186 struct a_lex_input *lip;
2187 bool_t rv;
2188 NYD2_ENTER;
2190 rv = FAL0;
2192 /* Only when interactive and startup completed */
2193 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) !=
2194 (n_PSO_INTERACTIVE | n_PSO_STARTED))
2195 goto jleave;
2197 /* Not when running any hook */
2198 if(n_pstate & n_PS_HOOK_MASK)
2199 goto jleave;
2201 /* Traverse up the stack:
2202 * . not when controlled by a child process
2203 * TODO . not when there are pipes involved, we neither handle job control,
2204 * TODO nor process groups, that is, controlling terminal acceptably
2205 * . not when sourcing a file */
2206 for(lip = a_lex_input; lip != NULL; lip = lip->li_outer){
2207 ui32_t f;
2209 if((f = lip->li_flags) & (a_LEX_PIPE | a_LEX_SLICE))
2210 goto jleave;
2211 if(!(f & a_LEX_MACRO))
2212 goto jleave;
2215 rv = TRU1;
2216 jleave:
2217 NYD2_LEAVE;
2218 return rv;
2221 FL void
2222 n_source_inject_input(char const *buf, size_t len, bool_t commit){
2223 NYD_ENTER;
2224 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat) -1 > len){
2225 struct a_lex_input_inject *liip, **liipp;
2227 liip = n_alloc(n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat
2228 ) + len +1);
2229 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
2230 : &a_lex_input->li_inject;
2231 liip->lii_next = *liipp;
2232 liip->lii_len = len;
2233 liip->lii_commit = commit;
2234 memcpy(liip->lii_dat, buf, len);
2235 liip->lii_dat[len] = '\0';
2236 *liipp = liip;
2238 NYD_LEAVE;
2241 FL void
2242 n_source_force_eof(void){
2243 NYD_ENTER;
2244 assert(a_lex_input != NULL);
2245 a_lex_input->li_flags |= a_LEX_FORCE_EOF;
2246 NYD_LEAVE;
2249 /* s-it-mode */