MLE, mle-complete: do not start new line for each non-iswalnum(3)
[s-mailx.git] / lex_input.c
blob00005d7ae7e76f4276a9dff8bcf0ba573f34e3d1
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"),
858 word);
859 }else for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
860 if(!strcmp(word, gp->lg_name)){
861 if(line.l > 0){
862 size_t i;
864 i = gp->lg_cmd.l;
865 line.s = salloc(i + line.l +1);
866 memcpy(line.s, gp->lg_cmd.s, i);
867 memcpy(line.s + i, cp, line.l);
868 line.s[i += line.l] = '\0';
869 line.l = i;
870 }else{
871 line.s = gp->lg_cmd.s;
872 line.l = gp->lg_cmd.l;
874 goto jrestart;
878 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
879 bool_t s;
881 if(!(s = condstack_isskip()) || (n_poption & n_PO_D_V))
882 n_err(_("Unknown command%s: `%s'\n"),
883 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
884 if(s)
885 goto jerr0;
886 if(cmd != NULL){
887 c_cmdnotsupp(NULL);
888 cmd = NULL;
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 /* Process the arguments to the command, depending on the type it expects */
900 if((cmd->lc_argtype & ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
901 !(n_poption & n_PO_BATCH_FLAG)){
902 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
903 cmd->lc_name);
904 goto jleave;
906 if(!(cmd->lc_argtype & ARG_M) && (n_psonce & n_PSO_SENDMODE)){
907 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
908 goto jleave;
910 if(cmd->lc_argtype & ARG_R){
911 if(n_pstate & n_PS_COMPOSE_MODE){
912 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
913 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
914 goto jleave;
916 /* TODO Nothing should prevent ARG_R in conjunction with
917 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
918 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING)){
919 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
920 cmd->lc_name);
921 goto jleave;
924 if((cmd->lc_argtype & ARG_S) && !(n_psonce & n_PSO_STARTED)){
925 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
926 goto jleave;
928 if(!(cmd->lc_argtype & ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
929 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
930 cmd->lc_name);
931 goto jleave;
934 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
935 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
936 goto jleave;
938 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
939 n_err(_("May not execute `%s' -- message file is read only\n"),
940 cmd->lc_name);
941 goto jleave;
944 if(cmd->lc_argtype & ARG_O)
945 n_OBSOLETE2(_("this command will be removed"), cmd->lc_name);
947 if((flags & a_WYSH) && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST){
948 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
949 flags &= ~a_WYSH;
951 if((flags & a_VPUT) && !(cmd->lc_argtype & ARG_V)){
952 n_err(_("`vput' prefix doesn't affect `%s'\n"), cmd->lc_name);
953 flags &= ~a_VPUT;
956 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
957 * TODO doesn't use any of those list commands which strip this mask,
958 * TODO and for now we misuse bits for checking relation to history;
959 * TODO argument state should be property of a per-command carrier instead */
960 n_pstate &= ~n_PS_ARGLIST_MASK;
961 switch(cmd->lc_argtype & ARG_ARGMASK){
962 case ARG_MSGLIST:
963 /* Message list defaulting to nearest forward legal message */
964 if(n_msgvec == NULL)
965 goto je96;
966 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
967 break;
968 if(c == 0){
969 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
970 n_msgvec[1] = 0;
972 if(n_msgvec[0] == 0){
973 if(!(n_pstate & n_PS_HOOK_MASK))
974 fprintf(n_stdout, _("No applicable messages\n"));
975 break;
977 rv = (*cmd->lc_func)(n_msgvec);
978 break;
980 case ARG_NDMLIST:
981 /* Message list with no defaults, but no error if none exist */
982 if(n_msgvec == NULL){
983 je96:
984 n_err(_("Invalid use of message list\n"));
985 break;
987 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
988 break;
989 rv = (*cmd->lc_func)(n_msgvec);
990 break;
992 case ARG_STRLIST:
993 /* Just the straight string, with leading blanks removed */
994 while(blankspacechar(*cp))
995 ++cp;
996 rv = (*cmd->lc_func)(cp);
997 break;
999 case ARG_WYSHLIST:
1000 c = 1;
1001 if(0){
1002 /* FALLTHRU */
1003 case ARG_WYRALIST:
1004 c = (flags & a_WYSH) ? 1 : 0;
1005 if(0){
1006 case ARG_RAWLIST:
1007 c = 0;
1010 if((c = getrawlist((c != 0), arglist, n_NELEM(arglist), cp, line.l)) < 0){
1011 n_err(_("Invalid argument list\n"));
1012 break;
1014 c -= ((flags & a_VPUT) != 0); /* XXX c=int */
1016 if(c < cmd->lc_minargs){
1017 n_err(_("`%s' requires at least %u arg(s)\n"),
1018 cmd->lc_name, (ui32_t)cmd->lc_minargs + ((flags & a_VPUT) != 0));
1019 break;
1021 #undef lc_minargs
1022 if(c > cmd->lc_maxargs){
1023 n_err(_("`%s' takes no more than %u arg(s)\n"),
1024 cmd->lc_name, (ui32_t)cmd->lc_maxargs + ((flags & a_VPUT) != 0));
1025 break;
1027 #undef lc_maxargs
1029 if(flags & a_VPUT){
1030 char const *emsg;
1032 if(!n_shexp_is_valid_varname(arglist[0]))
1033 emsg = N_("not a valid variable name");
1034 else if(!n_var_is_user_writable(arglist[0]))
1035 emsg = N_("either not a user writable, or a boolean variable");
1036 else
1037 emsg = NULL;
1038 if(emsg != NULL){
1039 n_err(_("`%s': %s: %s\n"),
1040 cmd->lc_name, V_(emsg), n_shexp_quote_cp(arglist[0], FAL0));
1041 break;
1044 ++c;
1045 n_pstate |= n_PS_ARGMOD_VPUT;
1047 rv = (*cmd->lc_func)(arglist);
1048 break;
1050 default:
1051 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
1052 cmd->lc_argtype & ARG_ARGMASK); )
1053 goto jerr0;
1056 if(!(cmd->lc_argtype & ARG_H))
1057 evp->le_add_history = (((cmd->lc_argtype & ARG_G) ||
1058 (n_pstate & n_PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
1060 jleave:
1061 n_PS_ROOT_BLOCK(ok_vset(__qm, (rv == 0 ? n_0 : n_1))); /* TODO num=1/real */
1063 if(flags & a_IGNERR){
1064 rv = 0;
1065 n_exit_status = n_EXIT_OK;
1068 /* Exit the current source file on error TODO what a mess! */
1069 if(rv == 0)
1070 n_pstate &= ~n_PS_EVAL_ERROR;
1071 else{
1072 n_pstate |= n_PS_EVAL_ERROR;
1073 if(rv < 0 || (n_pstate & n_PS_ROBOT)){ /* FIXME */
1074 rv = 1;
1075 goto jret;
1077 goto jret0;
1080 if(cmd == NULL)
1081 goto jret0;
1082 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint)) /* TODO rid of that! */
1083 if(visible(dot))
1084 n_source_inject_input(n_INPUT_INJECT_COMMIT, "\\type",
1085 sizeof("\\type") -1);
1087 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
1088 !(cmd->lc_argtype & ARG_T))
1089 n_pstate |= n_PS_SAW_COMMAND;
1090 jleave0:
1091 n_pstate &= ~n_PS_EVAL_ERROR;
1092 jret0:
1093 rv = 0;
1094 jret:
1095 NYD_LEAVE;
1096 return rv;
1097 jerr0:
1098 n_PS_ROOT_BLOCK(ok_vset(__qm, n_0)); /* TODO num=1/real */
1099 goto jleave0;
1102 static struct a_lex_cmd const *
1103 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
1104 struct a_lex_cmd const *cp;
1105 NYD2_ENTER;
1107 for(cp = a_lex_cmd_tab;
1108 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
1109 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
1110 goto jleave;
1111 cp = NULL;
1112 jleave:
1113 NYD2_LEAVE;
1114 return cp;
1117 static void
1118 a_lex_hangup(int s){
1119 NYD_X; /* Signal handler */
1120 n_UNUSED(s);
1121 /* nothing to do? */
1122 exit(n_EXIT_ERR);
1125 static void
1126 a_lex_onintr(int s){ /* TODO block signals while acting */
1127 NYD_X; /* Signal handler */
1128 n_UNUSED(s);
1130 safe_signal(SIGINT, a_lex_onintr);
1132 termios_state_reset();
1133 close_all_files(); /* FIXME .. of current level ONLU! */
1134 if(image >= 0){
1135 close(image);
1136 image = -1;
1139 a_lex_unstack(TRUM1);
1141 if(interrupts != 1)
1142 n_err_sighdl(_("Interrupt\n"));
1143 safe_signal(SIGPIPE, a_lex_oldpipe);
1144 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
1147 static void
1148 a_lex_unstack(bool_t eval_error){
1149 struct a_lex_input *lip;
1150 NYD_ENTER;
1152 /* Free input injections of this level first */
1153 /* C99 */{
1154 struct a_lex_input_inject **liipp, *liip;
1156 if((lip = a_lex_input) == NULL)
1157 liipp = &a_lex_input_inject;
1158 else
1159 liipp = &lip->li_inject;
1161 while((liip = *liipp) != NULL){
1162 *liipp = liip->lii_next;
1163 free(liip);
1166 if(lip == NULL || !(lip->li_flags & a_LEX_SLICE))
1167 n_memory_reset();
1170 if(lip == NULL){
1171 /* If called from a_lex_onintr(), be silent FIXME */
1172 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1173 if(eval_error == TRUM1 || !(n_psonce & n_PSO_STARTED))
1174 goto jleave;
1175 goto jerr;
1178 if(lip->li_flags & a_LEX_SLICE){ /* TODO Temporary hack */
1179 n_stdin = lip->li_slice_stdin;
1180 n_stdout = lip->li_slice_stdout;
1181 n_psonce = lip->li_slice_psonce;
1182 goto jthe_slice_hack;
1185 if(lip->li_flags & a_LEX_MACRO){
1186 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
1187 char **lp;
1189 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
1190 free(*lp);
1191 ++lip->li_loff;
1193 /* Part of lip's memory chunk, then */
1194 if(!(lip->li_flags & a_LEX_MACRO_CMD))
1195 free(lip->li_lines);
1197 }else{
1198 if(lip->li_flags & a_LEX_PIPE)
1199 /* XXX command manager should -TERM then -KILL instead of hoping
1200 * XXX for exit of provider due to EPIPE / SIGPIPE */
1201 Pclose(lip->li_file, TRU1);
1202 else
1203 Fclose(lip->li_file);
1206 if(!condstack_take(lip->li_cond)){
1207 n_err(_("Unmatched `if' at end of %s %s\n"),
1208 ((lip->li_flags & a_LEX_MACRO
1209 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1210 : _("`source'd file"))),
1211 lip->li_name);
1212 eval_error = TRU1;
1215 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1217 jthe_slice_hack:
1218 if(lip->li_on_finalize != NULL)
1219 (*lip->li_on_finalize)(lip->li_finalize_arg);
1221 if((a_lex_input = lip->li_outer) == NULL){
1222 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1223 }else{
1224 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1225 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1226 n_pstate &= ~n_PS_SOURCING;
1227 assert(n_pstate & n_PS_ROBOT);
1230 if(eval_error)
1231 goto jerr;
1232 jleave:
1233 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1234 free(lip);
1235 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1236 a_lex_unstack(TRUM1);
1237 NYD_LEAVE;
1238 return;
1240 jerr:
1241 if(lip != NULL){
1242 /* POSIX says
1243 * Any errors in the start-up file shall either cause mailx to
1244 * terminate with a diagnostic message and a non-zero status or to
1245 * continue after writing a diagnostic message, ignoring the
1246 * remainder of the lines in the start-up file
1247 * But print the diagnostic only for the outermost resource unless the
1248 * user is debugging or in verbose mode */
1249 if((n_poption & n_PO_D_V) ||
1250 (!(n_psonce & n_PSO_STARTED) &&
1251 !(lip->li_flags & (a_LEX_SLICE | a_LEX_MACRO)) &&
1252 lip->li_outer == NULL))
1253 n_alert(_("Stopped %s %s due to errors%s"),
1254 (n_psonce & n_PSO_STARTED
1255 ? (lip->li_flags & a_LEX_SLICE ? _("sliced in program")
1256 : (lip->li_flags & a_LEX_MACRO
1257 ? (lip->li_flags & a_LEX_MACRO_CMD
1258 ? _("evaluating command") : _("evaluating macro"))
1259 : (lip->li_flags & a_LEX_PIPE
1260 ? _("executing `source'd pipe")
1261 : _("loading `source'd file")))
1263 : (lip->li_flags & a_LEX_MACRO
1264 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1265 ? _("evaluating command line") : _("evaluating macro"))
1266 : _("loading initialization resource"))),
1267 lip->li_name,
1268 (n_poption & n_PO_DEBUG
1269 ? n_empty : _(" (enable *debug* for trace)")));
1272 if(!(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED))){
1273 if(n_poption & n_PO_D_V)
1274 n_alert(_("Non-interactive, bailing out due to errors "
1275 "in startup load phase"));
1276 exit(n_EXIT_ERR);
1278 goto jleave;
1281 static bool_t
1282 a_lex_source_file(char const *file, bool_t silent_open_error){
1283 struct a_lex_input *lip;
1284 size_t nlen;
1285 char *nbuf;
1286 bool_t ispipe;
1287 FILE *fip;
1288 NYD_ENTER;
1290 fip = NULL;
1292 /* Being a command argument file is space-trimmed *//* TODO v15 with
1293 * TODO WYRALIST this is no longer necessary true, and for that we
1294 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1295 #if 0
1296 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
1297 file[--nlen] == '|')))
1298 #else
1299 ispipe = FAL0;
1300 if(!silent_open_error)
1301 for(nlen = strlen(file); nlen > 0;){
1302 char c;
1304 c = file[--nlen];
1305 if(!blankchar(c)){
1306 if(c == '|'){
1307 nbuf = savestrbuf(file, nlen);
1308 ispipe = TRU1;
1310 break;
1313 #endif
1315 if(ispipe){
1316 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1317 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL)
1318 goto jeopencheck;
1319 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1320 goto jeopencheck;
1321 else if((fip = Fopen(nbuf, "r")) == NULL){
1322 jeopencheck:
1323 if(!silent_open_error || (n_poption & n_PO_D_V))
1324 n_perr(nbuf, 0);
1325 if(silent_open_error)
1326 fip = (FILE*)-1;
1327 goto jleave;
1330 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
1331 (nlen = strlen(nbuf) +1));
1332 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1333 lip->li_outer = a_lex_input;
1334 lip->li_file = fip;
1335 lip->li_cond = condstack_release();
1336 n_memory_autorec_push(&lip->li_autorecmem[0]);
1337 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1338 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1339 ? a_LEX_SUPER_MACRO : 0);
1340 memcpy(lip->li_name, nbuf, nlen);
1342 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1343 a_lex_input = lip;
1344 if(!a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC))
1345 fip = NULL;
1346 jleave:
1347 NYD_LEAVE;
1348 return (fip != NULL);
1351 static bool_t
1352 a_lex_load(struct a_lex_input *lip){
1353 bool_t rv;
1354 NYD2_ENTER;
1356 assert(!(n_psonce & n_PSO_STARTED));
1357 assert(a_lex_input == NULL);
1359 /* POSIX:
1360 * Any errors in the start-up file shall either cause mailx to terminate
1361 * with a diagnostic message and a non-zero status or to continue after
1362 * writing a diagnostic message, ignoring the remainder of the lines in
1363 * the start-up file. */
1364 lip->li_cond = condstack_release();
1365 n_memory_autorec_push(&lip->li_autorecmem[0]);
1367 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1368 n_pstate |= n_PS_ROBOT |
1369 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1371 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1372 if(n_poption & n_PO_D_V)
1373 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1374 a_lex_input = lip;
1375 if(!(rv = n_commands())){
1376 if(!(n_psonce & n_PSO_INTERACTIVE)){
1377 if(n_poption & n_PO_D_V)
1378 n_alert(_("Non-interactive program mode, forced exit"));
1379 exit(n_EXIT_ERR);
1380 }else if(n_poption & n_PO_BATCH_FLAG){
1381 char const *beoe;
1383 if((beoe = ok_vlook(batch_exit_on_error)) != NULL && *beoe == '1')
1384 n_pstate |= n_PS_EXIT;
1387 /* n_PS_EXIT handled by callers */
1388 NYD2_LEAVE;
1389 return rv;
1392 static void
1393 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1394 NYD_X; /* Signal handler */
1395 n_UNUSED(sig);
1396 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1399 static bool_t
1400 a_commands_recursive(enum n_lexinput_flags lif){
1401 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1402 sighandler_type soldhdl;
1403 sigset_t sintset, soldset;
1404 struct a_lex_eval_ctx ev;
1405 bool_t rv, ever;
1406 NYD2_ENTER;
1408 memset(&ev, 0, sizeof ev);
1410 sigfillset(&sintset);
1411 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1412 hadint = FAL0;
1413 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1414 safe_signal(SIGINT, &a_lex__cmdrecint);
1415 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1416 hadint = TRU1;
1417 goto jjump;
1420 sigprocmask(SIG_SETMASK, &soldset, NULL);
1422 n_COLOUR( n_colour_env_push(); )
1423 rv = TRU1;
1424 for(ever = FAL0;; ever = TRU1){
1425 char const *beoe;
1426 int n;
1428 if(ever)
1429 n_memory_reset();
1431 /* Read a line of commands and handle end of file specially */
1432 ev.le_line.l = ev.le_line_size;
1433 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l, NULL);
1434 ev.le_line_size = (ui32_t)ev.le_line.l;
1435 ev.le_line.l = (ui32_t)n;
1437 if(n < 0)
1438 break;
1440 n = a_lex_evaluate(&ev);
1441 beoe = (n_poption & n_PO_BATCH_FLAG)
1442 ? ok_vlook(batch_exit_on_error) : NULL;
1444 if(n){
1445 if(beoe != NULL && *beoe == '1'){
1446 if(n_exit_status == n_EXIT_OK)
1447 n_exit_status = n_EXIT_ERR;
1449 rv = FAL0;
1450 break;
1452 if(beoe != NULL){
1453 if(n_exit_status != n_EXIT_OK)
1454 break;
1457 jjump: /* TODO */
1458 a_lex_unstack(!rv);
1459 n_COLOUR( n_colour_env_pop(FAL0); )
1461 if(ev.le_line.s != NULL)
1462 free(ev.le_line.s);
1464 if(soldhdl != SIG_IGN)
1465 safe_signal(SIGINT, soldhdl);
1466 NYD2_LEAVE;
1467 if(hadint){
1468 sigprocmask(SIG_SETMASK, &soldset, NULL);
1469 n_raise(SIGINT);
1471 return rv;
1474 static int
1475 a_lex_c_read(void *v){ /* TODO IFS? how? -r */
1476 char const **argv, *cp, *emv, *cp2;
1477 int rv;
1478 NYD2_ENTER;
1480 rv = 0;
1481 for(argv = v; (cp = *argv++) != NULL;)
1482 if(!n_shexp_is_valid_varname(cp) || !n_var_is_user_writable(cp)){
1483 n_err(_("`read': variable (name) cannot be used: %s\n"),
1484 n_shexp_quote_cp(cp, FAL0));
1485 rv = 1;
1487 if(rv)
1488 goto jleave;
1490 emv = n_0;
1492 cp = n_lex_input_cp(((n_pstate & n_PS_COMPOSE_MODE
1493 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT) |
1494 n_LEXINPUT_FORCE_STDIN | n_LEXINPUT_NL_ESC |
1495 n_LEXINPUT_PROMPT_NONE /* XXX POSIX: PS2: yes! */),
1496 NULL, NULL);
1497 if(cp == NULL)
1498 cp = n_empty;
1500 for(argv = v; *argv != NULL; ++argv){
1501 char c;
1503 while(blankchar(*cp))
1504 ++cp;
1505 if(*cp == '\0')
1506 break;
1508 /* The last variable gets the remaining line less trailing IFS */
1509 if(argv[1] == NULL){
1510 for(cp2 = cp; *cp2 != '\0'; ++cp2)
1512 for(; cp2 > cp; --cp2){
1513 c = cp2[-1];
1514 if(!blankchar(c))
1515 break;
1517 }else
1518 for(cp2 = cp; (c = *++cp2) != '\0';)
1519 if(blankchar(c))
1520 break;
1522 /* C99 xxx This is a CC warning workaround (-Wbad-function-cast) */{
1523 char *vcp;
1525 vcp = savestrbuf(cp, PTR2SIZE(cp2 - cp));
1526 if(!n_var_vset(*argv, (uintptr_t)vcp))
1527 emv = n_1;
1530 cp = cp2;
1533 /* Set the remains to the empty string */
1534 for(; *argv != NULL; ++argv)
1535 if(!n_var_vset(*argv, (uintptr_t)n_empty))
1536 emv = n_1;
1538 n__EM_SET(emv);
1539 rv = 0;
1540 jleave:
1541 NYD2_LEAVE;
1542 return rv;
1545 FL int
1546 c_cmdnotsupp(void *vp){
1547 NYD_ENTER;
1548 n_UNUSED(vp);
1549 n_err(_("The requested feature is not compiled in\n"));
1550 NYD_LEAVE;
1551 return 1;
1554 FL bool_t
1555 n_commands(void){ /* FIXME */
1556 struct a_lex_eval_ctx ev;
1557 int n;
1558 bool_t volatile rv;
1559 NYD_ENTER;
1561 rv = TRU1;
1563 if (!(n_pstate & n_PS_SOURCING)) {
1564 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1565 safe_signal(SIGINT, &a_lex_onintr);
1566 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1567 safe_signal(SIGHUP, &a_lex_hangup);
1569 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1570 safe_signal(SIGPIPE, a_lex_oldpipe);
1572 memset(&ev, 0, sizeof ev);
1574 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1575 for (;;) {
1576 n_COLOUR( n_colour_env_pop(TRU1); )
1578 /* TODO Unless we have our signal manager (or however we do it) child
1579 * TODO processes may have time slots where their execution isn't
1580 * TODO protected by signal handlers (in between start and setup
1581 * TODO completed). close_all_files() is only called from onintr()
1582 * TODO so those may linger possibly forever */
1583 if(!(n_pstate & n_PS_SOURCING))
1584 close_all_files();
1586 interrupts = 0;
1588 n_memory_reset();
1590 if (!(n_pstate & n_PS_SOURCING)) {
1591 char *cp;
1593 /* TODO Note: this buffer may contain a password. We should redefine
1594 * TODO the code flow which has to do that */
1595 if ((cp = termios_state.ts_linebuf) != NULL) {
1596 termios_state.ts_linebuf = NULL;
1597 termios_state.ts_linesize = 0;
1598 free(cp); /* TODO pool give-back */
1600 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1601 if (ev.le_line.l > LINESIZE * 3) {
1602 free(ev.le_line.s); /* TODO pool! but what? */
1603 ev.le_line.s = NULL;
1604 ev.le_line.l = ev.le_line_size = 0;
1608 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1609 char *cp;
1611 if ((cp = ok_vlook(newmail)) != NULL) {
1612 struct stat st;
1614 /* FIXME TEST WITH NOPOLL ETC. !!! */
1615 n = (cp != NULL && strcmp(cp, "nopoll"));
1616 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1617 st.st_size > mailsize) ||
1618 (mb.mb_type == MB_MAILDIR && n != 0)) {
1619 size_t odot = PTR2SIZE(dot - message);
1620 ui32_t odid = (n_pstate & n_PS_DID_PRINT_DOT);
1622 if (setfile(mailname,
1623 FEDIT_NEWMAIL |
1624 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1625 n_exit_status |= n_EXIT_ERR;
1626 rv = FAL0;
1627 break;
1629 dot = message + odot;
1630 n_pstate |= odid;
1634 n_exit_status = n_EXIT_OK;
1637 /* Read a line of commands and handle end of file specially */
1638 ev.le_line.l = ev.le_line_size;
1639 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1640 &ev.le_line.s, &ev.le_line.l, NULL);
1641 ev.le_line_size = (ui32_t)ev.le_line.l;
1642 ev.le_line.l = (ui32_t)n;
1644 if (n < 0) {
1645 /* FIXME did unstack() when n_PS_SOURCING, only break with n_PS_LOADING */
1646 if (!(n_pstate & n_PS_ROBOT) &&
1647 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof)) {
1648 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1649 n_msleep(500, FAL0);
1650 continue;
1652 break;
1655 n_pstate &= ~n_PS_HOOK_MASK;
1656 /* C99 */{
1657 char const *beoe;
1658 int estat;
1660 estat = a_lex_evaluate(&ev);
1661 beoe = (n_poption & n_PO_BATCH_FLAG)
1662 ? ok_vlook(batch_exit_on_error) : NULL;
1664 if(estat){
1665 if(beoe != NULL && *beoe == '1'){
1666 if(n_exit_status == n_EXIT_OK)
1667 n_exit_status = n_EXIT_ERR;
1668 rv = FAL0;
1669 break;
1671 if(!(n_psonce & n_PSO_STARTED)){ /* TODO join n_PS_EVAL_ERROR */
1672 if(a_lex_input == NULL ||
1673 !(a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)){
1674 rv = FAL0;
1675 break;
1677 }else
1678 break;
1681 if(beoe != NULL){
1682 if(n_exit_status != n_EXIT_OK)
1683 break;
1684 /* TODO n_PS_EVAL_ERROR and n_PS_SOURCING! Sigh!! */
1685 if((n_pstate & (n_PS_SOURCING | n_PS_EVAL_ERROR)
1686 ) == n_PS_EVAL_ERROR){
1687 n_exit_status = n_EXIT_ERR;
1688 break;
1693 if(!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE) &&
1694 ev.le_add_history)
1695 n_tty_addhist(ev.le_line.s, (ev.le_add_history != TRU1));
1697 if(n_pstate & n_PS_EXIT)
1698 break;
1701 a_lex_unstack(!rv);
1703 if (ev.le_line.s != NULL)
1704 free(ev.le_line.s);
1705 NYD_LEAVE;
1706 return rv;
1709 FL int
1710 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1711 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1712 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1713 struct n_string xprompt;
1714 FILE *ifile;
1715 bool_t doprompt, dotty;
1716 char const *iftype;
1717 int nold, n;
1718 NYD2_ENTER;
1720 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_FORCE_EOF)){
1721 n = -1;
1722 goto jleave;
1725 /* Special case macro mode: never need to prompt, lines have always been
1726 * unfolded already */
1727 if(!(lif & n_LEXINPUT_FORCE_STDIN) &&
1728 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1729 struct a_lex_input_inject *liip;
1731 if(*linebuf != NULL)
1732 free(*linebuf);
1734 /* Injection in progress? Don't care about the autocommit state here */
1735 if((liip = a_lex_input->li_inject) != NULL){
1736 a_lex_input->li_inject = liip->lii_next;
1738 *linesize = liip->lii_len;
1739 *linebuf = (char*)liip;
1740 memcpy(*linebuf, liip->lii_dat, liip->lii_len +1);
1741 iftype = "INJECTION";
1742 }else{
1743 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1744 *linesize = 0;
1745 n = -1;
1746 goto jleave;
1749 ++a_lex_input->li_loff;
1750 *linesize = strlen(*linebuf);
1751 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1752 *linebuf = sbufdup(*linebuf, *linesize);
1754 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1755 ? "-X OPTION"
1756 : (a_lex_input->li_flags & a_LEX_MACRO_CMD) ? "CMD" : "MACRO";
1758 n = (int)*linesize;
1759 n_pstate |= n_PS_READLINE_NL;
1760 goto jhave_dat;
1763 /* Injection in progress? */
1764 if(!(lif & n_LEXINPUT_FORCE_STDIN)){
1765 struct a_lex_input_inject **liipp, *liip;
1767 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
1768 : &a_lex_input->li_inject;
1770 if((liip = *liipp) != NULL){
1771 *liipp = liip->lii_next;
1773 if(liip->lii_commit){
1774 if(*linebuf != NULL)
1775 free(*linebuf);
1777 /* Simply reuse the buffer */
1778 n = (int)(*linesize = liip->lii_len);
1779 *linebuf = (char*)liip;
1780 memcpy(*linebuf, liip->lii_dat, liip->lii_len +1);
1781 iftype = "INJECTION";
1782 n_pstate |= n_PS_READLINE_NL;
1783 goto jhave_dat;
1784 }else{
1785 string = savestrbuf(liip->lii_dat, liip->lii_len);
1786 free(liip);
1791 n_pstate &= ~n_PS_READLINE_NL;
1792 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1793 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1794 doprompt = ((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1795 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT));
1796 dotty = (doprompt && !ok_blook(line_editor_disable));
1797 if(!doprompt)
1798 lif |= n_LEXINPUT_PROMPT_NONE;
1799 else{
1800 if(!dotty)
1801 n_string_creat_auto(&xprompt);
1802 if(prompt == NULL)
1803 lif |= n_LEXINPUT_PROMPT_EVAL;
1806 /* Ensure stdout is flushed first anyway */
1807 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1808 fflush(n_stdout);
1810 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : n_stdin;
1811 if(ifile == NULL){
1812 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1813 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO));
1814 ifile = n_stdin;
1817 for(nold = n = 0;;){
1818 if(dotty){
1819 assert(ifile == n_stdin);
1820 if(string != NULL && (n = (int)strlen(string)) > 0){
1821 if(*linesize > 0)
1822 *linesize += n +1;
1823 else
1824 *linesize = (size_t)n + LINESIZE +1;
1825 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1826 memcpy(*linebuf, string, (size_t)n +1);
1828 string = NULL;
1829 /* TODO if nold>0, don't redisplay the entire line!
1830 * TODO needs complete redesign ... */
1831 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1832 n_MEMORY_DEBUG_ARGSCALL);
1833 }else{
1834 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1835 n_tty_create_prompt(&xprompt, prompt, lif);
1836 if(xprompt.s_len > 0){
1837 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1838 fflush(n_stdout);
1842 n = (readline_restart)(ifile, linebuf, linesize, n
1843 n_MEMORY_DEBUG_ARGSCALL);
1845 if(n > 0 && nold > 0){
1846 int i = 0;
1847 char const *cp = *linebuf + nold;
1849 while(blankspacechar(*cp) && nold + i < n)
1850 ++cp, ++i;
1851 if(i > 0){
1852 memmove(*linebuf + nold, cp, n - nold - i);
1853 n -= i;
1854 (*linebuf)[n] = '\0';
1859 if(n <= 0)
1860 break;
1862 /* POSIX says:
1863 * An unquoted <backslash> at the end of a command line shall
1864 * be discarded and the next line shall continue the command */
1865 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1866 if(dotty)
1867 n_pstate |= n_PS_READLINE_NL;
1868 break;
1870 /* Definitely outside of quotes, thus the quoting rules are so that an
1871 * uneven number of successive backslashs at EOL is a continuation */
1872 if(n > 1){
1873 size_t i, j;
1875 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1876 if((*linebuf)[i] != '\\')
1877 break;
1878 if(!(j & 1))
1879 break;
1881 (*linebuf)[nold = --n] = '\0';
1882 lif |= n_LEXINPUT_NL_FOLLOW;
1885 if(n < 0)
1886 goto jleave;
1887 (*linebuf)[*linesize = n] = '\0';
1889 jhave_dat:
1890 #if 0
1891 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1892 char *cp, c;
1893 size_t i;
1895 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1896 c = *--cp;
1897 if(!blankspacechar(c))
1898 break;
1900 (*linebuf)[n = (int)i] = '\0';
1903 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1904 char *cp, c;
1905 size_t j, i;
1907 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1908 c = *cp++;
1909 if(!blankspacechar(c))
1910 break;
1912 if(i > 0){
1913 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1914 (*linebuf)[n = (int)j] = '\0';
1917 #endif /* 0 (notyet - must take care for backslash escaped space) */
1919 if(n_poption & n_PO_D_VV)
1920 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1921 jleave:
1922 if (n_pstate & n_PS_PSTATE_PENDMASK)
1923 a_lex_update_pstate();
1925 /* TODO We need to special case a_LEX_SLICE, since that is not managed by us
1926 * TODO but only established from the outside and we need to drop this
1927 * TODO overlay context somehow */
1928 if(n < 0 && a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SLICE))
1929 a_lex_unstack(FAL0);
1930 NYD2_LEAVE;
1931 return n;
1934 FL char *
1935 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1936 char const *string){
1937 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1938 size_t linesize;
1939 char *linebuf, *rv;
1940 int n;
1941 NYD2_ENTER;
1943 linesize = 0;
1944 linebuf = NULL;
1945 rv = NULL;
1947 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1948 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1949 (lif & n_LEXINPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE))
1950 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1952 if(linebuf != NULL)
1953 free(linebuf);
1954 NYD2_LEAVE;
1955 return rv;
1958 FL void
1959 n_load(char const *name){
1960 struct a_lex_input *lip;
1961 size_t i;
1962 FILE *fip;
1963 NYD_ENTER;
1965 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1966 goto jleave;
1968 i = strlen(name) +1;
1969 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) + i);
1970 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1971 lip->li_file = fip;
1972 lip->li_flags = a_LEX_FREE;
1973 memcpy(lip->li_name, name, i);
1975 a_lex_load(lip);
1976 n_pstate &= ~n_PS_EXIT;
1977 jleave:
1978 NYD_LEAVE;
1981 FL void
1982 n_load_Xargs(char const **lines, size_t cnt){
1983 static char const name[] = "-X";
1985 ui8_t buf[sizeof(struct a_lex_input) + sizeof name];
1986 char const *srcp, *xsrcp;
1987 char *cp;
1988 size_t imax, i, len;
1989 struct a_lex_input *lip;
1990 NYD_ENTER;
1992 lip = (void*)buf;
1993 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
1994 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1995 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1996 memcpy(lip->li_name, name, sizeof name);
1998 /* The problem being that we want to support reverse solidus newline
1999 * escaping also within multiline -X, i.e., POSIX says:
2000 * An unquoted <backslash> at the end of a command line shall
2001 * be discarded and the next line shall continue the command
2002 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
2003 * entire lines array and set _MACRO_FREE_DATA */
2004 imax = cnt + 1;
2005 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
2007 /* For each of the input lines.. */
2008 for(i = len = 0, cp = NULL; cnt > 0;){
2009 bool_t keep;
2010 size_t j;
2012 if((j = strlen(srcp = *lines)) == 0){
2013 ++lines, --cnt;
2014 continue;
2017 /* Separate one line from a possible multiline input string */
2018 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
2019 *lines = &xsrcp[1];
2020 j = PTR2SIZE(xsrcp - srcp);
2021 }else
2022 ++lines, --cnt;
2024 /* The (separated) string may itself indicate soft newline escaping */
2025 if((keep = (srcp[j - 1] == '\\'))){
2026 size_t xj, xk;
2028 /* Need an uneven number of reverse solidus */
2029 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
2030 if(srcp[xj] != '\\')
2031 break;
2032 if(xk & 1)
2033 --j;
2034 else
2035 keep = FAL0;
2038 /* Strip any leading WS from follow lines, then */
2039 if(cp != NULL)
2040 while(j > 0 && blankspacechar(*srcp))
2041 ++srcp, --j;
2043 if(j > 0){
2044 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
2045 imax += 4;
2046 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
2047 imax);
2049 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
2050 memcpy(&cp[len], srcp, j);
2051 cp[len += j] = '\0';
2053 if(!keep)
2054 ++i;
2056 if(!keep)
2057 cp = NULL, len = 0;
2059 if(cp != NULL){
2060 assert(i + 1 < imax);
2061 lip->li_lines[i++] = cp;
2063 lip->li_lines[i] = NULL;
2065 a_lex_load(lip);
2066 if(n_pstate & n_PS_EXIT)
2067 exit(n_exit_status);
2068 NYD_LEAVE;
2071 FL int
2072 c_source(void *v){
2073 int rv;
2074 NYD_ENTER;
2076 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
2077 NYD_LEAVE;
2078 return rv;
2081 FL int
2082 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
2083 int rv;
2084 NYD_ENTER;
2086 rv = (a_lex_source_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
2087 NYD_LEAVE;
2088 return rv;
2091 FL bool_t
2092 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
2093 void (*on_finalize)(void*), void *finalize_arg){
2094 struct a_lex_input *lip;
2095 size_t i;
2096 int rv;
2097 NYD_ENTER;
2099 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2100 (i = strlen(name) +1));
2101 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2102 lip->li_outer = a_lex_input;
2103 lip->li_file = NULL;
2104 lip->li_cond = condstack_release();
2105 n_memory_autorec_push(&lip->li_autorecmem[0]);
2106 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
2107 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2108 ? a_LEX_SUPER_MACRO : 0);
2109 lip->li_lines = lines;
2110 lip->li_on_finalize = on_finalize;
2111 lip->li_finalize_arg = finalize_arg;
2112 memcpy(lip->li_name, name, i);
2114 n_pstate |= n_PS_ROBOT;
2115 a_lex_input = lip;
2116 rv = a_commands_recursive(lif);
2117 NYD_LEAVE;
2118 return rv;
2121 FL bool_t
2122 n_source_command(enum n_lexinput_flags lif, char const *cmd){
2123 struct a_lex_input *lip;
2124 size_t i, ial;
2125 bool_t rv;
2126 NYD_ENTER;
2128 i = strlen(cmd) +1;
2129 ial = n_ALIGN(i);
2131 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2132 ial + 2*sizeof(char*));
2133 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2134 lip->li_outer = a_lex_input;
2135 lip->li_cond = condstack_release();
2136 n_memory_autorec_push(&lip->li_autorecmem[0]);
2137 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_CMD |
2138 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2139 ? a_LEX_SUPER_MACRO : 0);
2140 lip->li_lines = (void*)&lip->li_name[ial];
2141 memcpy(lip->li_lines[0] = &lip->li_name[0], cmd, i);
2142 lip->li_lines[1] = NULL;
2144 n_pstate |= n_PS_ROBOT;
2145 a_lex_input = lip;
2146 rv = a_commands_recursive(lif);
2147 NYD_LEAVE;
2148 return rv;
2151 FL void
2152 n_source_slice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
2153 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
2154 struct a_lex_input *lip;
2155 size_t i;
2156 NYD_ENTER;
2158 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input, li_name) +
2159 (i = strlen(cmd) +1));
2160 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input, li_name));
2161 lip->li_outer = a_lex_input;
2162 lip->li_file = new_stdin;
2163 lip->li_flags = a_LEX_FREE | a_LEX_SLICE;
2164 lip->li_on_finalize = on_finalize;
2165 lip->li_finalize_arg = finalize_arg;
2166 lip->li_slice_stdin = n_stdin;
2167 lip->li_slice_stdout = n_stdout;
2168 lip->li_slice_psonce = n_psonce;
2169 memcpy(lip->li_name, cmd, i);
2171 n_stdin = new_stdin;
2172 n_stdout = new_stdout;
2173 n_psonce = new_psonce;
2174 n_pstate |= n_PS_ROBOT;
2175 a_lex_input = lip;
2176 NYD_LEAVE;
2179 FL void
2180 n_source_slice_hack_remove_after_jump(void){
2181 a_lex_unstack(FAL0);
2184 FL bool_t
2185 n_source_may_yield_control(void){ /* TODO this is a terrible hack */
2186 /* TODO This is obviously hacky in that it depends on _input_stack not
2187 * TODO loosing any flags when creating new contexts... Maybe this
2188 * TODO function should instead walk all up the context stack when
2189 * TODO there is one, and verify neither level prevents yielding! */
2190 struct a_lex_input *lip;
2191 bool_t rv;
2192 NYD2_ENTER;
2194 rv = FAL0;
2196 /* Only when interactive and startup completed */
2197 if((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) !=
2198 (n_PSO_INTERACTIVE | n_PSO_STARTED))
2199 goto jleave;
2201 /* Not when running any hook */
2202 if(n_pstate & n_PS_HOOK_MASK)
2203 goto jleave;
2205 /* Traverse up the stack:
2206 * . not when controlled by a child process
2207 * TODO . not when there are pipes involved, we neither handle job control,
2208 * TODO nor process groups, that is, controlling terminal acceptably
2209 * . not when sourcing a file */
2210 for(lip = a_lex_input; lip != NULL; lip = lip->li_outer){
2211 ui32_t f;
2213 if((f = lip->li_flags) & (a_LEX_PIPE | a_LEX_SLICE))
2214 goto jleave;
2215 if(!(f & a_LEX_MACRO))
2216 goto jleave;
2219 rv = TRU1;
2220 jleave:
2221 NYD2_LEAVE;
2222 return rv;
2225 FL void
2226 n_source_inject_input(enum n_input_inject_flags iif, char const *buf,
2227 size_t len){
2228 NYD_ENTER;
2229 if(len == UIZ_MAX)
2230 len = strlen(buf);
2232 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat) -1 > len &&
2233 len > 0){
2234 size_t i;
2235 struct a_lex_input_inject *liip, **liipp;
2237 liip = n_alloc(n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat
2238 ) + 1 + len +1);
2239 liipp = (a_lex_input == NULL) ? &a_lex_input_inject
2240 : &a_lex_input->li_inject;
2241 liip->lii_next = *liipp;
2242 liip->lii_commit = ((iif & n_INPUT_INJECT_COMMIT) != 0);
2243 if(buf[i = 0] != ' ' && !(iif & n_INPUT_INJECT_HISTORY))
2244 liip->lii_dat[i++] = ' '; /* TODO prim. hack to avoid history put! */
2245 memcpy(&liip->lii_dat[i], buf, len);
2246 i += len;
2247 liip->lii_dat[liip->lii_len = i] = '\0';
2248 *liipp = liip;
2250 NYD_LEAVE;
2253 FL void
2254 n_source_force_eof(void){
2255 NYD_ENTER;
2256 assert(a_lex_input != NULL);
2257 a_lex_input->li_flags |= a_LEX_FORCE_EOF;
2258 NYD_LEAVE;
2261 /* s-it-mode */