Implement `vput' modifier: store result in variable..
[s-mailx.git] / lex_input.c
blob8f931b447590621f6fab37534953c6e37a600d3b
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,
75 a_LEX_FORCE_EOF = 1<<8, /* lex_input() shall return EOF next */
77 a_LEX_SUPER_MACRO = 1<<16 /* *Not* inheriting n_PS_SOURCING state */
80 struct a_lex_cmd{
81 char const *lc_name; /* Name of command */
82 int (*lc_func)(void*); /* Implementor of command */
83 enum argtype lc_argtype; /* Arglist type (see below) */
84 si16_t lc_msgflag; /* Required flags of msgs */
85 si16_t lc_msgmask; /* Relevant flags of msgs */
86 #ifdef HAVE_DOCSTRINGS
87 char const *lc_doc; /* One line doc for command */
88 #endif
90 /* Yechh, can't initialize unions */
91 #define lc_minargs lc_msgflag /* Minimum argcount for RAWLIST */
92 #define lc_maxargs lc_msgmask /* Max argcount for RAWLIST */
94 struct a_lex_ghost{
95 struct a_lex_ghost *lg_next;
96 struct str lg_cmd; /* Data follows after .lg_name */
97 char lg_name[n_VFIELD_SIZE(0)];
100 struct a_lex_eval_ctx{
101 struct str le_line; /* The terminated data to _evaluate() */
102 ui32_t le_line_size; /* May be used to store line memory size */
103 bool_t le_is_recursive; /* Evaluation in evaluation? (collect ~:) */
104 ui8_t __dummy[3];
105 bool_t le_add_history; /* Add command to history (TRUM1=gabby)? */
108 struct a_lex_input_stack{
109 struct a_lex_input_stack *li_outer;
110 FILE *li_file; /* File we were in */
111 void *li_cond; /* Saved state of conditional stack */
112 ui32_t li_flags; /* enum a_lex_input_flags */
113 ui32_t li_loff; /* Pseudo (macro): index in .li_lines */
114 char **li_lines; /* Pseudo content, lines unfolded */
115 void (*li_on_finalize)(void *);
116 void *li_finalize_arg;
117 char li_autorecmem[n_MEMORY_AUTOREC_TYPE_SIZEOF];
118 sigjmp_buf li_cmdrec_jmp; /* TODO one day... for command_recursive */
119 /* SLICE hacks: saved stdin/stdout, saved pstate */
120 FILE *li_slice_stdin;
121 FILE *li_slice_stdout;
122 ui32_t li_slice_psonce;
123 ui8_t li_slice__dummy[4];
124 char li_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
126 n_CTA(n_MEMORY_AUTOREC_TYPE_SIZEOF % sizeof(void*) == 0,
127 "Inacceptible size of structure buffer");
129 struct a_lex_input_inject{
130 struct a_lex_input_inject *lii_next;
131 size_t lii_len;
132 bool_t lii_commit;
133 char lii_dat[n_VFIELD_SIZE(7)];
136 static sighandler_type a_lex_oldpipe;
137 static struct a_lex_ghost *a_lex_ghosts;
138 /* a_lex_cmd_tab[] after fun protos */
140 /* */
141 static struct a_lex_input_stack *a_lex_input;
143 /* For n_source_inject_input() */
144 static struct a_lex_input_inject *a_lex_input_inject;
146 static sigjmp_buf a_lex_srbuf; /* TODO GET RID */
148 /* Isolate the command from the arguments */
149 static char *a_lex_isolate(char const *comm);
151 /* Command ghost handling */
152 static int a_lex_c_ghost(void *v);
153 static int a_lex_c_unghost(void *v);
155 /* */
156 static char const *a_lex_cmdinfo(struct a_lex_cmd const *lcp);
158 /* Print a list of all commands */
159 static int a_lex_c_list(void *v);
161 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
163 /* `help' / `?' command */
164 static int a_lex_c_help(void *v);
166 /* `exit' and `quit' commands */
167 static int a_lex_c_exit(void *v);
168 static int a_lex_c_quit(void *v);
170 /* Print the binaries version number */
171 static int a_lex_c_version(void *v);
173 static int a_lex__version_cmp(void const *s1, void const *s2);
175 /* n_PS_STATE_PENDMASK requires some actions */
176 static void a_lex_update_pstate(void);
178 /* Evaluate a single command.
179 * .le_add_history will be updated upon success.
180 * Command functions return 0 for success, 1 for error, and -1 for abort.
181 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
182 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
184 /* Get first-fit, or NULL */
185 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
187 /* Branch here on hangup signal and simulate "exit" */
188 static void a_lex_hangup(int s);
190 /* The following gets called on receipt of an interrupt. Close all open files
191 * except 0, 1, 2, and the temporary. Also, unstack all source files */
192 static void a_lex_onintr(int s);
194 /* Pop the current input back to the previous level. Update the program state.
195 * If the argument is TRUM1 then we don't alert and error out if the stack
196 * doesn't exist at all */
197 static void a_lex_unstack(bool_t eval_error);
199 /* `source' and `source_if' (if silent_open_error: no pipes allowed, then).
200 * Returns FAL0 if file is somehow not usable (unless silent_open_error) or
201 * upon evaluation error, and TRU1 on success */
202 static bool_t a_lex_source_file(char const *file, bool_t silent_open_error);
204 /* System resource file load()ing or -X command line option array traversal */
205 static bool_t a_lex_load(struct a_lex_input_stack *lip);
207 /* A simplified command loop for recursed state machines */
208 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
210 /* List of all commands, and list of commands which are specially treated
211 * and deduced in _evaluate(), but we need a list for _c_list() and
212 * print_comm_docstr() */
213 #ifdef HAVE_DOCSTRINGS
214 # define DS(S) , S
215 #else
216 # define DS(S)
217 #endif
218 static struct a_lex_cmd const a_lex_cmd_tab[] = {
219 #include "cmd_tab.h"
221 a_lex_special_cmd_tab[] = {
222 { "#", NULL, 0, 0, 0
223 DS(N_("Comment command: ignore remaining (continuable) line")) },
224 { "-", NULL, 0, 0, 0
225 DS(N_("Print out the preceding message")) }
227 #undef DS
229 static char *
230 a_lex_isolate(char const *comm){
231 NYD2_ENTER;
232 while(*comm != '\0' &&
233 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
234 ++comm;
235 NYD2_LEAVE;
236 return n_UNCONST(comm);
239 static int
240 a_lex_c_ghost(void *v){
241 struct a_lex_ghost *lgp, *gp;
242 size_t i, cl, nl;
243 char *cp;
244 char const **argv;
245 NYD_ENTER;
247 argv = v;
249 /* Show the list? */
250 if(*argv == NULL){
251 FILE *fp;
253 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
254 fp = n_stdout;
256 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
257 fprintf(fp, "wysh ghost %s %s\n",
258 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
260 if(fp != n_stdout){
261 page_or_print(fp, i);
262 Fclose(fp);
264 goto jleave;
267 /* Verify the ghost name is a valid one */
268 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0'){
269 n_err(_("`ghost': can't canonicalize %s\n"),
270 n_shexp_quote_cp(argv[0], FAL0));
271 v = NULL;
272 goto jleave;
275 /* Show command of single ghost? */
276 if(argv[1] == NULL){
277 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
278 if(!strcmp(argv[0], gp->lg_name)){
279 fprintf(n_stdout, "wysh ghost %s %s\n",
280 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
281 goto jleave;
283 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
284 v = NULL;
285 goto jleave;
288 /* Define command for ghost: verify command content */
289 for(cl = 0, i = 1; (cp = n_UNCONST(argv[i])) != NULL; ++i)
290 if(*cp != '\0')
291 cl += strlen(cp) +1; /* SP or NUL */
292 if(cl == 0){
293 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
294 v = NULL;
295 goto jleave;
298 /* If the ghost already exists, recreate */
299 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
300 if(!strcmp(gp->lg_name, argv[0])){
301 if(lgp != NULL)
302 lgp->lg_next = gp->lg_next;
303 else
304 a_lex_ghosts = gp->lg_next;
305 free(gp);
306 break;
309 nl = strlen(argv[0]) +1;
310 gp = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_ghost, lg_name) + nl + cl);
311 gp->lg_next = a_lex_ghosts;
312 a_lex_ghosts = gp;
313 memcpy(gp->lg_name, argv[0], nl);
314 cp = gp->lg_cmd.s = gp->lg_name + nl;
315 gp->lg_cmd.l = --cl;
317 while(*++argv != NULL)
318 if((i = strlen(*argv)) > 0){
319 memcpy(cp, *argv, i);
320 cp += i;
321 *cp++ = ' ';
323 *--cp = '\0';
324 jleave:
325 NYD_LEAVE;
326 return v == NULL;
329 static int
330 a_lex_c_unghost(void *v){
331 struct a_lex_ghost *lgp, *gp;
332 char const **argv, *cp;
333 int rv;
334 NYD_ENTER;
336 rv = 0;
337 argv = v;
339 while((cp = *argv++) != NULL){
340 if(cp[0] == '*' && cp[1] == '\0'){
341 while((gp = a_lex_ghosts) != NULL){
342 a_lex_ghosts = gp->lg_next;
343 free(gp);
345 }else{
346 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
347 lgp = gp, gp = gp->lg_next)
348 if(!strcmp(gp->lg_name, cp)){
349 if(lgp != NULL)
350 lgp->lg_next = gp->lg_next;
351 else
352 a_lex_ghosts = gp->lg_next;
353 free(gp);
354 goto jouter;
356 n_err(_("`unghost': no such alias: %s\n"),
357 n_shexp_quote_cp(cp, FAL0));
358 rv = 1;
359 jouter: ;
362 NYD_LEAVE;
363 return rv;
366 static char const *
367 a_lex_cmdinfo(struct a_lex_cmd const *lcp){
368 struct n_string rvb, *rv;
369 char const *cp;
370 NYD2_ENTER;
372 rv = n_string_creat_auto(&rvb);
373 rv = n_string_reserve(rv, 80);
375 switch(lcp->lc_argtype & ARG_ARGMASK){
376 case ARG_MSGLIST: cp = N_("message-list"); break;
377 case ARG_STRLIST: cp = N_("string data"); break;
378 case ARG_RAWLIST: cp = N_("old-style quoting"); break;
379 case ARG_NOLIST: cp = N_("no arguments"); break;
380 case ARG_NDMLIST: cp = N_("message-list (no default)"); break;
381 case ARG_WYSHLIST: cp = N_("sh(1)ell-style quoting"); break;
382 default: cp = N_("`wysh' for sh(1)ell-style quoting"); break;
384 rv = n_string_push_cp(rv, V_(cp));
386 if(lcp->lc_argtype & ARG_V)
387 rv = n_string_push_cp(rv, _(" | `vput' modifier"));
388 if(lcp->lc_argtype & ARG_0)
389 rv = n_string_push_cp(rv, _(" | status in *0*"));
391 if(lcp->lc_argtype & ARG_A)
392 rv = n_string_push_cp(rv, _(" | needs box"));
393 if(lcp->lc_argtype & ARG_I)
394 rv = n_string_push_cp(rv, _(" | only interactive"));
395 if(lcp->lc_argtype & ARG_M)
396 rv = n_string_push_cp(rv, _(" | send mode"));
397 if(lcp->lc_argtype & ARG_R)
398 rv = n_string_push_cp(rv, _(" | no compose mode"));
399 if(lcp->lc_argtype & ARG_S)
400 rv = n_string_push_cp(rv, _(" | after startup"));
401 if(lcp->lc_argtype & ARG_X)
402 rv = n_string_push_cp(rv, _(" | subprocess"));
404 cp = n_string_cp(rv);
405 NYD2_LEAVE;
406 return cp;
409 static int
410 a_lex_c_list(void *v){
411 FILE *fp;
412 struct a_lex_cmd const **cpa, *cp, **cursor;
413 size_t l, i;
414 NYD_ENTER;
416 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
417 cpa = salloc(sizeof(cp) * i);
419 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
420 cpa[i] = &a_lex_cmd_tab[i];
421 /* C99 */{
422 size_t j;
424 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
425 cpa[i] = &a_lex_special_cmd_tab[j];
427 cpa[i] = NULL;
429 /* C99 */{
430 char const *xcp = v;
432 if(*xcp == '\0')
433 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
436 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
437 fp = n_stdout;
439 fprintf(fp, _("Commands are:\n"));
440 l = 1;
441 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
442 if(cp->lc_func == &c_cmdnotsupp)
443 continue;
444 if(n_poption & n_PO_D_V){
445 fprintf(fp, "%s\n", cp->lc_name);
446 ++l;
447 #ifdef HAVE_DOCSTRINGS
448 fprintf(fp, " : %s\n", V_(cp->lc_doc));
449 ++l;
450 #endif
451 fprintf(fp, " : %s\n", a_lex_cmdinfo(cp));
452 ++l;
453 }else{
454 size_t j = strlen(cp->lc_name) + 2;
456 if((i += j) > 72){
457 i = j;
458 fprintf(fp, "\n");
459 ++l;
461 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
465 if(fp != n_stdout){
466 page_or_print(fp, l);
467 Fclose(fp);
469 NYD_LEAVE;
470 return 0;
473 static int
474 a_lex__pcmd_cmp(void const *s1, void const *s2){
475 struct a_lex_cmd const * const *cp1, * const *cp2;
476 int rv;
477 NYD2_ENTER;
479 cp1 = s1;
480 cp2 = s2;
481 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
482 NYD2_LEAVE;
483 return rv;
486 static int
487 a_lex_c_help(void *v){
488 int rv;
489 char *arg;
490 NYD_ENTER;
492 /* Help for a single command? */
493 if((arg = *(char**)v) != NULL){
494 struct a_lex_ghost const *gp;
495 struct a_lex_cmd const *lcp, *lcpmax;
497 /* Ghosts take precedence */
498 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
499 if(!strcmp(arg, gp->lg_name)){
500 fprintf(n_stdout, "%s -> ", arg);
501 arg = gp->lg_cmd.s;
502 break;
505 lcpmax = &(lcp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
506 jredo:
507 for(; lcp < lcpmax; ++lcp){
508 if(is_prefix(arg, lcp->lc_name)){
509 fputs(arg, n_stdout);
510 if(strcmp(arg, lcp->lc_name))
511 fprintf(n_stdout, " (%s)", lcp->lc_name);
512 }else
513 continue;
515 #ifdef HAVE_DOCSTRINGS
516 fprintf(n_stdout, ": %s", V_(lcp->lc_doc));
517 #endif
518 if(n_poption & n_PO_D_V)
519 fprintf(n_stdout, "\n : %s", a_lex_cmdinfo(lcp));
520 putc('\n', n_stdout);
521 rv = 0;
522 goto jleave;
525 if(PTRCMP(lcpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
526 lcpmax = &(lcp =
527 a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
528 goto jredo;
531 if(gp != NULL){
532 fprintf(n_stdout, "%s\n", n_shexp_quote_cp(arg, TRU1));
533 rv = 0;
534 }else{
535 n_err(_("Unknown command: `%s'\n"), arg);
536 rv = 1;
538 }else{
539 /* Very ugly, but take care for compiler supported string lengths :( */
540 fputs(n_progname, n_stdout);
541 fputs(_(
542 " commands -- <msglist> denotes message specifications,\n"
543 "e.g., 1-5, :n or ., separated by spaces:\n"), n_stdout);
544 fputs(_(
545 "\n"
546 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
547 "Type <msglist> like `type' but always show all headers\n"
548 "next goto and type next message\n"
549 "from <msglist> (search and) print header summary for the given list\n"
550 "headers header summary for messages surrounding \"dot\"\n"
551 "delete <msglist> delete messages (can be `undelete'd)\n"),
552 n_stdout);
554 fputs(_(
555 "\n"
556 "save <msglist> folder append messages to folder and mark as saved\n"
557 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
558 "write <msglist> file write message contents to file (prompts for parts)\n"
559 "Reply <msglist> reply to message senders only\n"
560 "reply <msglist> like `Reply', but address all recipients\n"
561 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
562 n_stdout);
564 fputs(_(
565 "\n"
566 "mail <recipients> compose a mail for the given recipients\n"
567 "file folder change to another mailbox\n"
568 "File folder like `file', but open readonly\n"
569 "quit quit and apply changes to the current mailbox\n"
570 "xit or exit like `quit', but discard changes\n"
571 "!shell command shell escape\n"
572 "list [<anything>] all available commands [in search order]\n"),
573 n_stdout);
575 rv = (ferror(n_stdout) != 0);
577 jleave:
578 NYD_LEAVE;
579 return rv;
582 static int
583 a_lex_c_exit(void *v){
584 NYD_ENTER;
585 n_UNUSED(v);
587 if(n_psonce & n_PSO_STARTED){
588 /* In recursed state, return error to just pop the input level */
589 if(!(n_pstate & n_PS_SOURCING)){
590 #ifdef n_HAVE_TCAP
591 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
592 n_termcap_destroy();
593 #endif
594 exit(n_EXIT_OK);
597 n_pstate |= n_PS_EXIT;
598 NYD_LEAVE;
599 return 0;
602 static int
603 a_lex_c_quit(void *v){
604 NYD_ENTER;
605 n_UNUSED(v);
607 /* If we are n_PS_SOURCING, then return 1 so _evaluate() can handle it.
608 * Otherwise return -1 to abort command loop */
609 n_pstate |= n_PS_EXIT;
610 NYD_LEAVE;
611 return 0;
614 static int
615 a_lex_c_version(void *v){
616 int longest, rv;
617 char *iop;
618 char const *cp, **arr;
619 size_t i, i2;
620 NYD_ENTER;
621 n_UNUSED(v);
623 fprintf(n_stdout, _("%s version %s\nFeatures included (+) or not (-)\n"),
624 n_uagent, ok_vlook(version));
626 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
627 i = strlen(cp = &ok_vlook(features)[1]) +1;
628 iop = salloc(i);
629 memcpy(iop, cp, i);
631 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
632 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
633 arr[i] = cp;
634 i2 = strlen(cp);
635 longest = n_MAX(longest, (int)i2);
637 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
639 for(++longest, i2 = 0; i-- > 0;){
640 cp = *(arr++);
641 fprintf(n_stdout, "%-*s ", longest, cp);
642 i2 += longest;
643 if(UICMP(z, ++i2 + longest, >=, n_scrnwidth) || i == 0){
644 i2 = 0;
645 putc('\n', n_stdout);
649 if((rv = ferror(n_stdout) != 0))
650 clearerr(n_stdout);
651 NYD_LEAVE;
652 return rv;
655 static int
656 a_lex__version_cmp(void const *s1, void const *s2){
657 char const * const *cp1, * const *cp2;
658 int rv;
659 NYD2_ENTER;
661 cp1 = s1;
662 cp2 = s2;
663 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
664 NYD2_LEAVE;
665 return rv;
668 static void
669 a_lex_update_pstate(void){
670 NYD_ENTER;
672 if(n_pstate & n_PS_SIGWINCH_PEND){
673 char buf[32];
675 snprintf(buf, sizeof buf, "%d", n_scrnwidth);
676 ok_vset(COLUMNS, buf);
677 snprintf(buf, sizeof buf, "%d", n_scrnheight);
678 ok_vset(LINES, buf);
681 n_pstate &= ~n_PS_PSTATE_PENDMASK;
682 NYD_LEAVE;
685 static int
686 a_lex_evaluate(struct a_lex_eval_ctx *evp){
687 /* xxx old style(9), but also old code */
688 struct str line;
689 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
690 struct a_lex_ghost *gp;
691 struct a_lex_cmd const *cmd;
692 int rv, c;
693 enum {
694 a_NONE = 0,
695 a_GHOST_MASK = (1<<3) - 1, /* Ghost recursion counter bits */
696 a_NOPREFIX = 1<<4, /* Modifier prefix not allowed right now */
697 a_NOGHOST = 1<<5, /* No ghost expansion modifier */
698 a_IGNERR = 1<<6, /* ignerr modifier prefix */
699 a_WYSH = 1<<7, /* XXX v15+ drop wysh modifier prefix */
700 a_VPUT = 1<<8 /* vput modifier prefix */
701 } flags;
702 NYD_ENTER;
704 flags = a_NONE;
705 rv = 1;
706 cmd = NULL;
707 gp = NULL;
708 line = evp->le_line; /* XXX don't change original (buffer pointer) */
709 assert(line.s[line.l] == '\0');
710 evp->le_add_history = FAL0;
712 /* Command ghosts that refer to shell commands or macro expansion restart */
713 jrestart:
715 /* Strip the white space away from end and beginning of command */
716 if(line.l > 0){
717 size_t i = line.l;
719 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
720 --i;
721 line.l = i;
723 for(cp = line.s; spacechar(*cp); ++cp)
725 line.l -= PTR2SIZE(cp - line.s);
727 /* Ignore null commands (comments) */
728 if(*cp == '#')
729 goto jleave0;
731 /* Handle ! differently to get the correct lexical conventions */
732 arglist[0] = cp;
733 if(*cp == '!')
734 ++cp;
735 /* Isolate the actual command; since it may not necessarily be
736 * separated from the arguments (as in `p1') we need to duplicate it to
737 * be able to create a NUL terminated version.
738 * We must be aware of several special one letter commands here */
739 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
740 (*cp == '|' || *cp == '~' || *cp == '?'))
741 ++cp;
742 c = (int)PTR2SIZE(cp - arglist[0]);
743 line.l -= c;
744 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
745 memcpy(word, arglist[0], c);
746 word[c] = '\0';
748 /* No-expansion modifier? */
749 if(!(flags & a_NOPREFIX) && *word == '\\'){
750 ++word;
751 --c;
752 flags |= a_NOGHOST;
755 /* It may be a modifier prefix */
756 if(c == sizeof("ignerr") -1 && !asccasecmp(word, "ignerr")){
757 flags |= a_NOPREFIX | a_IGNERR;
758 line.s = cp;
759 goto jrestart;
760 }else if(c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
761 flags |= a_NOPREFIX | a_WYSH;
762 line.s = cp;
763 goto jrestart;
764 }else if(c == sizeof("vput") -1 && !asccasecmp(word, "vput")){
765 flags |= a_NOPREFIX | a_VPUT;
766 line.s = cp;
767 goto jrestart;
770 /* Look up the command; if not found, bitch.
771 * Normally, a blank command would map to the first command in the
772 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
773 * confusion; act just the same for ghosts */
774 if(*word == '\0'){
775 if((n_pstate & n_PS_ROBOT) || gp != NULL)
776 goto jleave0;
777 cmd = a_lex_cmd_tab + 0;
778 goto jexec;
781 if(!(flags & a_NOGHOST) && (flags & a_GHOST_MASK) != a_GHOST_MASK){
782 /* TODO relink list head, so it's sorted on usage over time?
783 * TODO in fact, there should be one hashmap over all commands and ghosts
784 * TODO so that the lookup could be made much more efficient than it is
785 * TODO now (two adjacent list searches! */
786 ui8_t expcnt;
788 expcnt = (flags & a_GHOST_MASK);
789 ++expcnt;
790 flags = (flags & ~(a_GHOST_MASK | a_NOPREFIX)) | expcnt;
792 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
793 if(!strcmp(word, gp->lg_name)){
794 if(line.l > 0){
795 size_t i;
797 i = gp->lg_cmd.l;
798 line.s = salloc(i + line.l +1);
799 memcpy(line.s, gp->lg_cmd.s, i);
800 memcpy(line.s + i, cp, line.l);
801 line.s[i += line.l] = '\0';
802 line.l = i;
803 }else{
804 line.s = gp->lg_cmd.s;
805 line.l = gp->lg_cmd.l;
807 goto jrestart;
811 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
812 bool_t s;
814 if(!(s = condstack_isskip()) || (n_poption & n_PO_D_V))
815 n_err(_("Unknown command%s: `%s'\n"),
816 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
817 if(s)
818 goto jleave0;
819 if(cmd != NULL){
820 c_cmdnotsupp(NULL);
821 cmd = NULL;
823 goto jleave;
826 /* See if we should execute the command -- if a conditional we always
827 * execute it, otherwise, check the state of cond */
828 jexec:
829 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
830 goto jleave0;
832 /* Process the arguments to the command, depending on the type it expects */
833 if((cmd->lc_argtype & ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
834 !(n_poption & n_PO_BATCH_FLAG)){
835 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
836 cmd->lc_name);
837 goto jleave;
839 if(!(cmd->lc_argtype & ARG_M) && (n_psonce & n_PSO_SENDMODE)){
840 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
841 goto jleave;
843 if(cmd->lc_argtype & ARG_R){
844 if(n_pstate & n_PS_COMPOSE_MODE){
845 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
846 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
847 goto jleave;
849 /* TODO Nothing should prevent ARG_R in conjunction with
850 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
851 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING)){
852 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
853 cmd->lc_name);
854 goto jleave;
857 if((cmd->lc_argtype & ARG_S) && !(n_psonce & n_PSO_STARTED)){
858 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
859 goto jleave;
861 if(!(cmd->lc_argtype & ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
862 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
863 cmd->lc_name);
864 goto jleave;
867 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
868 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
869 goto jleave;
871 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
872 n_err(_("May not execute `%s' -- message file is read only\n"),
873 cmd->lc_name);
874 goto jleave;
877 if(cmd->lc_argtype & ARG_O)
878 n_OBSOLETE2(_("this command will be removed"), cmd->lc_name);
880 if((flags & a_WYSH) && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST){
881 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
882 flags &= ~a_WYSH;
884 if((flags & a_VPUT) && !(cmd->lc_argtype & ARG_V)){
885 n_err(_("`vput' prefix doesn't affect `%s'\n"), cmd->lc_name);
886 flags &= ~a_VPUT;
889 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
890 * TODO doesn't use any of those list commands which strip this mask,
891 * TODO and for now we misuse bits for checking relation to history;
892 * TODO argument state should be property of a per-command carrier instead */
893 n_pstate &= ~n_PS_ARGLIST_MASK;
894 switch(cmd->lc_argtype & ARG_ARGMASK){
895 case ARG_MSGLIST:
896 /* Message list defaulting to nearest forward legal message */
897 if(n_msgvec == NULL)
898 goto je96;
899 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
900 break;
901 if(c == 0){
902 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
903 n_msgvec[1] = 0;
905 if(n_msgvec[0] == 0){
906 if(!(n_pstate & n_PS_HOOK_MASK))
907 fprintf(n_stdout, _("No applicable messages\n"));
908 break;
910 rv = (*cmd->lc_func)(n_msgvec);
911 break;
913 case ARG_NDMLIST:
914 /* Message list with no defaults, but no error if none exist */
915 if(n_msgvec == NULL){
916 je96:
917 n_err(_("Invalid use of message list\n"));
918 break;
920 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
921 break;
922 rv = (*cmd->lc_func)(n_msgvec);
923 break;
925 case ARG_STRLIST:
926 /* Just the straight string, with leading blanks removed */
927 while(whitechar(*cp))
928 ++cp;
929 rv = (*cmd->lc_func)(cp);
930 break;
932 case ARG_WYSHLIST:
933 c = 1;
934 if(0){
935 /* FALLTHRU */
936 case ARG_WYRALIST:
937 c = (flags & a_WYSH) ? 1 : 0;
938 if(0){
939 case ARG_RAWLIST:
940 c = 0;
943 if((c = getrawlist((c != 0), arglist, n_NELEM(arglist), cp, line.l)) < 0){
944 n_err(_("Invalid argument list\n"));
945 break;
947 c -= ((flags & a_VPUT) != 0); /* XXX c=int */
949 if(c < cmd->lc_minargs){
950 n_err(_("`%s' requires at least %d arg(s)\n"),
951 cmd->lc_name, cmd->lc_minargs);
952 break;
954 #undef lc_minargs
955 if(c > cmd->lc_maxargs){
956 n_err(_("`%s' takes no more than %d arg(s)\n"),
957 cmd->lc_name, cmd->lc_maxargs);
958 break;
960 #undef lc_maxargs
962 if(flags & a_VPUT){
963 char const *emsg;
965 if(!n_shexp_is_valid_varname(arglist[0]))
966 emsg = N_("not a valid variable name");
967 else if(!n_var_is_user_writable(arglist[0]))
968 emsg = N_("not a user writable variable");
969 else
970 emsg = NULL;
971 if(emsg != NULL){
972 n_err(_("`%s': %s: %s\n"),
973 cmd->lc_name, V_(emsg), n_shexp_quote_cp(arglist[0], FAL0));
974 break;
977 ++c;
978 n_pstate |= n_PS_ARGMOD_VPUT;
980 rv = (*cmd->lc_func)(arglist);
981 break;
983 case ARG_NOLIST:
984 /* Just the constant zero, for exiting, eg. */
985 rv = (*cmd->lc_func)(0);
986 break;
988 default:
989 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
990 cmd->lc_argtype & ARG_ARGMASK); )
991 goto jleave0;
994 if(!(cmd->lc_argtype & ARG_H))
995 evp->le_add_history = (((cmd->lc_argtype & ARG_G) ||
996 (n_pstate & n_PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
998 jleave:
999 n_PS_ROOT_BLOCK(ok_vset(__qm, (rv == 0 ? "0" : "1"))); /* TODO num=1/real */
1001 if(flags & a_IGNERR){
1002 rv = 0;
1003 n_exit_status = n_EXIT_OK;
1006 /* Exit the current source file on error TODO what a mess! */
1007 if(rv == 0)
1008 n_pstate &= ~n_PS_EVAL_ERROR;
1009 else{
1010 n_pstate |= n_PS_EVAL_ERROR;
1011 if(rv < 0 || (n_pstate & n_PS_ROBOT)){ /* FIXME */
1012 rv = 1;
1013 goto jret;
1015 goto jret0;
1018 if(cmd == NULL)
1019 goto jret0;
1020 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint)) /* TODO rid of that! */
1021 if(visible(dot))
1022 n_source_inject_input("\\type", sizeof("\\type") -1, TRU1);
1024 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
1025 !(cmd->lc_argtype & ARG_T))
1026 n_pstate |= n_PS_SAW_COMMAND;
1027 jleave0:
1028 n_pstate &= ~n_PS_EVAL_ERROR;
1029 jret0:
1030 rv = 0;
1031 jret:
1032 NYD_LEAVE;
1033 return rv;
1036 static struct a_lex_cmd const *
1037 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
1038 struct a_lex_cmd const *cp;
1039 NYD2_ENTER;
1041 for(cp = a_lex_cmd_tab;
1042 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
1043 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
1044 goto jleave;
1045 cp = NULL;
1046 jleave:
1047 NYD2_LEAVE;
1048 return cp;
1051 static void
1052 a_lex_hangup(int s){
1053 NYD_X; /* Signal handler */
1054 n_UNUSED(s);
1055 /* nothing to do? */
1056 exit(n_EXIT_ERR);
1059 static void
1060 a_lex_onintr(int s){ /* TODO block signals while acting */
1061 NYD_X; /* Signal handler */
1062 n_UNUSED(s);
1064 safe_signal(SIGINT, a_lex_onintr);
1066 termios_state_reset();
1067 close_all_files(); /* FIXME .. of current level ONLU! */
1068 if(image >= 0){
1069 close(image);
1070 image = -1;
1073 a_lex_unstack(TRUM1);
1075 if(interrupts != 1)
1076 n_err_sighdl(_("Interrupt\n"));
1077 safe_signal(SIGPIPE, a_lex_oldpipe);
1078 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
1081 static void
1082 a_lex_unstack(bool_t eval_error){
1083 struct a_lex_input_stack *lip;
1084 NYD_ENTER;
1086 if((lip = a_lex_input) == NULL){
1087 struct a_lex_input_inject *liip;
1089 while((liip = a_lex_input_inject) != NULL){
1090 a_lex_input_inject = liip->lii_next;
1091 free(liip);
1094 n_memory_reset();
1096 /* If called from a_lex_onintr(), be silent FIXME */
1097 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1098 if(eval_error == TRUM1 || !(n_psonce & n_PSO_STARTED))
1099 goto jleave;
1100 goto jerr;
1103 if(lip->li_flags & a_LEX_SLICE){ /* TODO Temporary hack */
1104 n_stdin = lip->li_slice_stdin;
1105 n_stdout = lip->li_slice_stdout;
1106 n_psonce = lip->li_slice_psonce;
1107 goto jthe_slice_hack;
1110 if(lip->li_flags & a_LEX_MACRO){
1111 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
1112 char **lp;
1114 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
1115 free(*lp);
1116 ++lip->li_loff;
1118 /* Part of lip's memory chunk, then */
1119 if(!(lip->li_flags & a_LEX_MACRO_CMD))
1120 free(lip->li_lines);
1122 }else{
1123 if(lip->li_flags & a_LEX_PIPE)
1124 /* XXX command manager should -TERM then -KILL instead of hoping
1125 * XXX for exit of provider due to EPIPE / SIGPIPE */
1126 Pclose(lip->li_file, TRU1);
1127 else
1128 Fclose(lip->li_file);
1131 if(!condstack_take(lip->li_cond)){
1132 n_err(_("Unmatched `if' at end of %s %s\n"),
1133 ((lip->li_flags & a_LEX_MACRO
1134 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1135 : _("`source'd file"))),
1136 lip->li_name);
1137 eval_error = TRU1;
1140 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1142 jthe_slice_hack:
1143 if(lip->li_on_finalize != NULL)
1144 (*lip->li_on_finalize)(lip->li_finalize_arg);
1146 if((a_lex_input = lip->li_outer) == NULL){
1147 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1148 }else{
1149 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1150 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1151 n_pstate &= ~n_PS_SOURCING;
1152 assert(n_pstate & n_PS_ROBOT);
1155 if(eval_error)
1156 goto jerr;
1157 jleave:
1158 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1159 free(lip);
1160 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1161 a_lex_unstack(TRUM1);
1162 NYD_LEAVE;
1163 return;
1165 jerr:
1166 if(lip != NULL){
1167 /* POSIX says
1168 * Any errors in the start-up file shall either cause mailx to
1169 * terminate with a diagnostic message and a non-zero status or to
1170 * continue after writing a diagnostic message, ignoring the
1171 * remainder of the lines in the start-up file
1172 * But print the diagnostic only for the outermost resource unless the
1173 * user is debugging or in verbose mode */
1174 if((n_poption & n_PO_D_V) ||
1175 (!(n_psonce & n_PSO_STARTED) &&
1176 !(lip->li_flags & (a_LEX_SLICE | a_LEX_MACRO)) &&
1177 lip->li_outer == NULL))
1178 n_alert(_("Stopped %s %s due to errors%s"),
1179 (n_psonce & n_PSO_STARTED
1180 ? (lip->li_flags & a_LEX_SLICE ? _("sliced in program")
1181 : (lip->li_flags & a_LEX_MACRO
1182 ? (lip->li_flags & a_LEX_MACRO_CMD
1183 ? _("evaluating command") : _("evaluating macro"))
1184 : (lip->li_flags & a_LEX_PIPE
1185 ? _("executing `source'd pipe")
1186 : _("loading `source'd file")))
1188 : (lip->li_flags & a_LEX_MACRO
1189 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1190 ? _("evaluating command line") : _("evaluating macro"))
1191 : _("loading initialization resource"))),
1192 lip->li_name,
1193 (n_poption & n_PO_DEBUG
1194 ? n_empty : _(" (enable *debug* for trace)")));
1197 if(!(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED))){
1198 if(n_poption & n_PO_D_V)
1199 n_alert(_("Non-interactive, bailing out due to errors "
1200 "in startup load phase"));
1201 exit(n_EXIT_ERR);
1203 goto jleave;
1206 static bool_t
1207 a_lex_source_file(char const *file, bool_t silent_open_error){
1208 struct a_lex_input_stack *lip;
1209 size_t nlen;
1210 char *nbuf;
1211 bool_t ispipe;
1212 FILE *fip;
1213 NYD_ENTER;
1215 fip = NULL;
1217 /* Being a command argument file is space-trimmed *//* TODO v15 with
1218 * TODO WYRALIST this is no longer necessary true, and for that we
1219 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1220 #if 0
1221 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
1222 file[--nlen] == '|')))
1223 #else
1224 ispipe = FAL0;
1225 if(!silent_open_error)
1226 for(nlen = strlen(file); nlen > 0;){
1227 char c;
1229 c = file[--nlen];
1230 if(!blankchar(c)){
1231 if(c == '|'){
1232 nbuf = savestrbuf(file, nlen);
1233 ispipe = TRU1;
1235 break;
1238 #endif
1240 if(ispipe){
1241 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1242 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL)
1243 goto jeopencheck;
1244 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1245 goto jeopencheck;
1246 else if((fip = Fopen(nbuf, "r")) == NULL){
1247 jeopencheck:
1248 if(!silent_open_error || (n_poption & n_PO_D_V))
1249 n_perr(nbuf, 0);
1250 if(silent_open_error)
1251 fip = (FILE*)-1;
1252 goto jleave;
1255 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
1256 (nlen = strlen(nbuf) +1));
1257 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1258 lip->li_outer = a_lex_input;
1259 lip->li_file = fip;
1260 lip->li_cond = condstack_release();
1261 n_memory_autorec_push(&lip->li_autorecmem[0]);
1262 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1263 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1264 ? a_LEX_SUPER_MACRO : 0);
1265 memcpy(lip->li_name, nbuf, nlen);
1267 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1268 a_lex_input = lip;
1269 if(!a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC))
1270 fip = NULL;
1271 jleave:
1272 NYD_LEAVE;
1273 return (fip != NULL);
1276 static bool_t
1277 a_lex_load(struct a_lex_input_stack *lip){
1278 bool_t rv;
1279 NYD2_ENTER;
1281 assert(!(n_psonce & n_PSO_STARTED));
1282 assert(a_lex_input == NULL);
1284 /* POSIX:
1285 * Any errors in the start-up file shall either cause mailx to terminate
1286 * with a diagnostic message and a non-zero status or to continue after
1287 * writing a diagnostic message, ignoring the remainder of the lines in
1288 * the start-up file. */
1289 lip->li_cond = condstack_release();
1290 n_memory_autorec_push(&lip->li_autorecmem[0]);
1292 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1293 n_pstate |= n_PS_ROBOT |
1294 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1296 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1297 if(n_poption & n_PO_D_V)
1298 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1299 a_lex_input = lip;
1300 if(!(rv = n_commands())){
1301 if(!(n_psonce & n_PSO_INTERACTIVE)){
1302 if(n_poption & n_PO_D_V)
1303 n_alert(_("Non-interactive program mode, forced exit"));
1304 exit(n_EXIT_ERR);
1305 }else if(n_poption & n_PO_BATCH_FLAG){
1306 char const *beoe;
1308 if((beoe = ok_vlook(batch_exit_on_error)) != NULL && *beoe == '1')
1309 n_pstate |= n_PS_EXIT;
1312 /* n_PS_EXIT handled by callers */
1313 NYD2_LEAVE;
1314 return rv;
1317 static void
1318 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1319 NYD_X; /* Signal handler */
1320 n_UNUSED(sig);
1321 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1324 static bool_t
1325 a_commands_recursive(enum n_lexinput_flags lif){
1326 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1327 sighandler_type soldhdl;
1328 sigset_t sintset, soldset;
1329 struct a_lex_eval_ctx ev;
1330 bool_t rv, ever;
1331 NYD2_ENTER;
1333 memset(&ev, 0, sizeof ev);
1335 sigfillset(&sintset);
1336 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1337 hadint = FAL0;
1338 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1339 safe_signal(SIGINT, &a_lex__cmdrecint);
1340 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1341 hadint = TRU1;
1342 goto jjump;
1345 sigprocmask(SIG_SETMASK, &soldset, NULL);
1347 n_COLOUR( n_colour_env_push(); )
1348 rv = TRU1;
1349 for(ever = FAL0;; ever = TRU1){
1350 char const *beoe;
1351 int n;
1353 if(ever)
1354 n_memory_reset();
1356 /* Read a line of commands and handle end of file specially */
1357 ev.le_line.l = ev.le_line_size;
1358 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l, NULL);
1359 ev.le_line_size = (ui32_t)ev.le_line.l;
1360 ev.le_line.l = (ui32_t)n;
1362 if(n < 0)
1363 break;
1365 n = a_lex_evaluate(&ev);
1366 beoe = (n_poption & n_PO_BATCH_FLAG)
1367 ? ok_vlook(batch_exit_on_error) : NULL;
1369 if(n){
1370 if(beoe != NULL && *beoe == '1'){
1371 if(n_exit_status == n_EXIT_OK)
1372 n_exit_status = n_EXIT_ERR;
1374 rv = FAL0;
1375 break;
1377 if(beoe != NULL){
1378 if(n_exit_status != n_EXIT_OK)
1379 break;
1382 jjump: /* TODO */
1383 a_lex_unstack(!rv);
1384 n_COLOUR( n_colour_env_pop(FAL0); )
1386 if(ev.le_line.s != NULL)
1387 free(ev.le_line.s);
1389 if(soldhdl != SIG_IGN)
1390 safe_signal(SIGINT, soldhdl);
1391 NYD2_LEAVE;
1392 if(hadint){
1393 sigprocmask(SIG_SETMASK, &soldset, NULL);
1394 n_raise(SIGINT);
1396 return rv;
1399 FL int
1400 c_cmdnotsupp(void *vp){
1401 NYD_ENTER;
1402 n_UNUSED(vp);
1403 n_err(_("The requested feature is not compiled in\n"));
1404 NYD_LEAVE;
1405 return 1;
1408 FL bool_t
1409 n_commands(void){ /* FIXME */
1410 struct a_lex_eval_ctx ev;
1411 int n;
1412 bool_t volatile rv;
1413 NYD_ENTER;
1415 rv = TRU1;
1417 if (!(n_pstate & n_PS_SOURCING)) {
1418 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1419 safe_signal(SIGINT, &a_lex_onintr);
1420 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1421 safe_signal(SIGHUP, &a_lex_hangup);
1423 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1424 safe_signal(SIGPIPE, a_lex_oldpipe);
1426 memset(&ev, 0, sizeof ev);
1428 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1429 for (;;) {
1430 n_COLOUR( n_colour_env_pop(TRU1); )
1432 /* TODO Unless we have our signal manager (or however we do it) child
1433 * TODO processes may have time slots where their execution isn't
1434 * TODO protected by signal handlers (in between start and setup
1435 * TODO completed). close_all_files() is only called from onintr()
1436 * TODO so those may linger possibly forever */
1437 if(!(n_pstate & n_PS_SOURCING))
1438 close_all_files();
1440 interrupts = 0;
1442 n_memory_reset();
1444 if (!(n_pstate & n_PS_SOURCING)) {
1445 char *cp;
1447 /* TODO Note: this buffer may contain a password. We should redefine
1448 * TODO the code flow which has to do that */
1449 if ((cp = termios_state.ts_linebuf) != NULL) {
1450 termios_state.ts_linebuf = NULL;
1451 termios_state.ts_linesize = 0;
1452 free(cp); /* TODO pool give-back */
1454 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1455 if (ev.le_line.l > LINESIZE * 3) {
1456 free(ev.le_line.s); /* TODO pool! but what? */
1457 ev.le_line.s = NULL;
1458 ev.le_line.l = ev.le_line_size = 0;
1462 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1463 char *cp;
1465 if ((cp = ok_vlook(newmail)) != NULL) {
1466 struct stat st;
1468 /* FIXME TEST WITH NOPOLL ETC. !!! */
1469 n = (cp != NULL && strcmp(cp, "nopoll"));
1470 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1471 st.st_size > mailsize) ||
1472 (mb.mb_type == MB_MAILDIR && n != 0)) {
1473 size_t odot = PTR2SIZE(dot - message);
1474 ui32_t odid = (n_pstate & n_PS_DID_PRINT_DOT);
1476 if (setfile(mailname,
1477 FEDIT_NEWMAIL |
1478 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1479 n_exit_status |= n_EXIT_ERR;
1480 rv = FAL0;
1481 break;
1483 dot = message + odot;
1484 n_pstate |= odid;
1488 n_exit_status = n_EXIT_OK;
1491 /* Read a line of commands and handle end of file specially */
1492 ev.le_line.l = ev.le_line_size;
1493 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1494 &ev.le_line.s, &ev.le_line.l, NULL);
1495 ev.le_line_size = (ui32_t)ev.le_line.l;
1496 ev.le_line.l = (ui32_t)n;
1498 if (n < 0) {
1499 /* FIXME did unstack() when n_PS_SOURCING, only break with n_PS_LOADING */
1500 if (!(n_pstate & n_PS_ROBOT) &&
1501 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof)) {
1502 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1503 n_msleep(500, FAL0);
1504 continue;
1506 break;
1509 n_pstate &= ~n_PS_HOOK_MASK;
1510 /* C99 */{
1511 char const *beoe;
1512 int estat;
1514 estat = a_lex_evaluate(&ev);
1515 beoe = (n_poption & n_PO_BATCH_FLAG)
1516 ? ok_vlook(batch_exit_on_error) : NULL;
1518 if(estat){
1519 if(beoe != NULL && *beoe == '1'){
1520 if(n_exit_status == n_EXIT_OK)
1521 n_exit_status = n_EXIT_ERR;
1522 rv = FAL0;
1523 break;
1525 if(!(n_psonce & n_PSO_STARTED)){ /* TODO join n_PS_EVAL_ERROR */
1526 if(a_lex_input == NULL ||
1527 !(a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)){
1528 rv = FAL0;
1529 break;
1531 }else
1532 break;
1535 if(beoe != NULL){
1536 if(n_exit_status != n_EXIT_OK)
1537 break;
1538 /* TODO n_PS_EVAL_ERROR and n_PS_SOURCING! Sigh!! */
1539 if((n_pstate & (n_PS_SOURCING | n_PS_EVAL_ERROR)
1540 ) == n_PS_EVAL_ERROR){
1541 n_exit_status = n_EXIT_ERR;
1542 break;
1547 if(!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE))
1548 n_tty_addhist(ev.le_line.s, (ev.le_add_history != TRU1));
1550 if(n_pstate & n_PS_EXIT)
1551 break;
1554 a_lex_unstack(!rv);
1556 if (ev.le_line.s != NULL)
1557 free(ev.le_line.s);
1558 NYD_LEAVE;
1559 return rv;
1562 FL int
1563 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1564 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1565 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1566 struct n_string xprompt;
1567 FILE *ifile;
1568 bool_t doprompt, dotty;
1569 char const *iftype;
1570 int nold, n;
1571 NYD2_ENTER;
1573 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_FORCE_EOF)){
1574 n = -1;
1575 goto jleave;
1578 /* Special case macro mode: never need to prompt, lines have always been
1579 * unfolded already */
1580 if(!(lif & n_LEXINPUT_FORCE_STDIN) &&
1581 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1582 if(*linebuf != NULL)
1583 free(*linebuf);
1585 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1586 *linesize = 0;
1587 n = -1;
1588 goto jleave;
1591 ++a_lex_input->li_loff;
1592 *linesize = strlen(*linebuf);
1593 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1594 *linebuf = sbufdup(*linebuf, *linesize);
1596 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1597 ? "-X OPTION"
1598 : (a_lex_input->li_flags & a_LEX_MACRO_CMD) ? "CMD" : "MACRO";
1599 n = (int)*linesize;
1600 n_pstate |= n_PS_READLINE_NL;
1601 goto jhave_dat;
1604 /* Injection in progress? */
1605 if(a_lex_input == NULL && a_lex_input_inject != NULL){
1606 struct a_lex_input_inject *liip;
1608 liip = a_lex_input_inject;
1609 a_lex_input_inject = liip->lii_next;
1611 if(liip->lii_commit){
1612 if(*linebuf != NULL)
1613 free(*linebuf);
1615 n = (int)(*linesize = liip->lii_len);
1616 *linebuf = (char*)liip;
1617 memcpy(*linebuf, liip->lii_dat, liip->lii_len +1);
1618 iftype = "INJECTION";
1619 n_pstate |= n_PS_READLINE_NL;
1620 goto jhave_dat;
1621 }else{
1622 string = savestrbuf(liip->lii_dat, liip->lii_len);
1623 free(liip);
1627 n_pstate &= ~n_PS_READLINE_NL;
1628 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1629 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1630 doprompt = ((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1631 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT));
1632 dotty = (doprompt && !ok_blook(line_editor_disable));
1633 if(!doprompt)
1634 lif |= n_LEXINPUT_PROMPT_NONE;
1635 else{
1636 if(!dotty)
1637 n_string_creat_auto(&xprompt);
1638 if(prompt == NULL)
1639 lif |= n_LEXINPUT_PROMPT_EVAL;
1642 /* Ensure stdout is flushed first anyway */
1643 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1644 fflush(n_stdout);
1646 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : n_stdin;
1647 if(ifile == NULL){
1648 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1649 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO));
1650 ifile = n_stdin;
1653 for(nold = n = 0;;){
1654 if(dotty){
1655 assert(ifile == n_stdin);
1656 if(string != NULL && (n = (int)strlen(string)) > 0){
1657 if(*linesize > 0)
1658 *linesize += n +1;
1659 else
1660 *linesize = (size_t)n + LINESIZE +1;
1661 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1662 memcpy(*linebuf, string, (size_t)n +1);
1664 string = NULL;
1665 /* TODO if nold>0, don't redisplay the entire line!
1666 * TODO needs complete redesign ... */
1667 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1668 n_MEMORY_DEBUG_ARGSCALL);
1669 }else{
1670 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1671 n_tty_create_prompt(&xprompt, prompt, lif);
1672 if(xprompt.s_len > 0){
1673 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1674 fflush(n_stdout);
1678 n = (readline_restart)(ifile, linebuf, linesize, n
1679 n_MEMORY_DEBUG_ARGSCALL);
1681 if(n > 0 && nold > 0){
1682 int i = 0;
1683 char const *cp = *linebuf + nold;
1685 while(blankspacechar(*cp) && nold + i < n)
1686 ++cp, ++i;
1687 if(i > 0){
1688 memmove(*linebuf + nold, cp, n - nold - i);
1689 n -= i;
1690 (*linebuf)[n] = '\0';
1695 if(n <= 0)
1696 break;
1698 /* POSIX says:
1699 * An unquoted <backslash> at the end of a command line shall
1700 * be discarded and the next line shall continue the command */
1701 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1702 if(dotty)
1703 n_pstate |= n_PS_READLINE_NL;
1704 break;
1706 /* Definitely outside of quotes, thus the quoting rules are so that an
1707 * uneven number of successive backslashs at EOL is a continuation */
1708 if(n > 1){
1709 size_t i, j;
1711 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1712 if((*linebuf)[i] != '\\')
1713 break;
1714 if(!(j & 1))
1715 break;
1717 (*linebuf)[nold = --n] = '\0';
1718 lif |= n_LEXINPUT_NL_FOLLOW;
1721 if(n < 0)
1722 goto jleave;
1723 (*linebuf)[*linesize = n] = '\0';
1725 jhave_dat:
1726 #if 0
1727 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1728 char *cp, c;
1729 size_t i;
1731 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1732 c = *--cp;
1733 if(!blankspacechar(c))
1734 break;
1736 (*linebuf)[n = (int)i] = '\0';
1739 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1740 char *cp, c;
1741 size_t j, i;
1743 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1744 c = *cp++;
1745 if(!blankspacechar(c))
1746 break;
1748 if(i > 0){
1749 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1750 (*linebuf)[n = (int)j] = '\0';
1753 #endif /* 0 (notyet - must take care for backslash escaped space) */
1755 if(n_poption & n_PO_D_VV)
1756 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1757 jleave:
1758 if (n_pstate & n_PS_PSTATE_PENDMASK)
1759 a_lex_update_pstate();
1761 /* TODO We need to special case a_LEX_SLICE, since that is not managed by us
1762 * TODO but only established from the outside and we need to drop this
1763 * TODO overlay context somehow */
1764 if(n < 0 && a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SLICE))
1765 a_lex_unstack(FAL0);
1766 NYD2_LEAVE;
1767 return n;
1770 FL char *
1771 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1772 char const *string){
1773 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1774 size_t linesize;
1775 char *linebuf, *rv;
1776 int n;
1777 NYD2_ENTER;
1779 linesize = 0;
1780 linebuf = NULL;
1781 rv = NULL;
1783 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1784 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1785 (lif & n_LEXINPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE))
1786 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1788 if(linebuf != NULL)
1789 free(linebuf);
1790 NYD2_LEAVE;
1791 return rv;
1794 FL int
1795 c_read(void *v){ /* TODO IFS? how? -r */
1796 char const **argv, *cp, *var0, *cp2;
1797 int rv;
1798 NYD2_ENTER;
1800 rv = 0;
1801 for(argv = v; (cp = *argv++) != NULL;)
1802 if(!n_shexp_is_valid_varname(cp) || !n_var_is_user_writable(cp)){
1803 n_err(_("`read': variable (name) cannot be used: %s\n"),
1804 n_shexp_quote_cp(cp, FAL0));
1805 rv = 1;
1807 if(rv)
1808 goto jleave;
1810 var0 = n_0;
1812 cp = n_lex_input_cp(((n_pstate & n_PS_COMPOSE_MODE
1813 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT) |
1814 n_LEXINPUT_FORCE_STDIN | n_LEXINPUT_NL_ESC |
1815 n_LEXINPUT_PROMPT_NONE /* XXX POSIX: PS2: yes! */),
1816 NULL, NULL);
1817 if(cp == NULL)
1818 cp = n_empty;
1820 for(argv = v; *argv != NULL; ++argv){
1821 char c;
1823 while(blankchar(*cp))
1824 ++cp;
1825 if(*cp == '\0')
1826 break;
1828 /* The last variable gets the remaining line less trailing IFS */
1829 if(argv[1] == NULL){
1830 for(cp2 = cp; *cp2 != '\0'; ++cp2)
1832 for(; cp2 > cp; --cp2){
1833 c = cp2[-1];
1834 if(!blankchar(c))
1835 break;
1837 }else
1838 for(cp2 = cp; (c = *++cp2) != '\0';)
1839 if(blankchar(c))
1840 break;
1842 /* C99 xxx This is a CC warning workaround (-Wbad-function-cast) */{
1843 char *vcp;
1845 vcp = savestrbuf(cp, PTR2SIZE(cp2 - cp));
1846 if(!n_var_vset(*argv, (uintptr_t)vcp))
1847 var0 = n_1;
1850 cp = cp2;
1853 /* Set the remains to the empty string */
1854 for(; *argv != NULL; ++argv)
1855 if(!n_var_vset(*argv, (uintptr_t)n_empty))
1856 var0 = n_1;
1858 n__RV_SET(var0);
1859 rv = 0;
1860 jleave:
1861 NYD2_LEAVE;
1862 return rv;
1865 FL void
1866 n_load(char const *name){
1867 struct a_lex_input_stack *lip;
1868 size_t i;
1869 FILE *fip;
1870 NYD_ENTER;
1872 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1873 goto jleave;
1875 i = strlen(name) +1;
1876 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) + i);
1877 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1878 lip->li_file = fip;
1879 lip->li_flags = a_LEX_FREE;
1880 memcpy(lip->li_name, name, i);
1882 a_lex_load(lip);
1883 n_pstate &= ~n_PS_EXIT;
1884 jleave:
1885 NYD_LEAVE;
1888 FL void
1889 n_load_Xargs(char const **lines, size_t cnt){
1890 static char const name[] = "-X";
1892 ui8_t buf[sizeof(struct a_lex_input_stack) + sizeof name];
1893 char const *srcp, *xsrcp;
1894 char *cp;
1895 size_t imax, i, len;
1896 struct a_lex_input_stack *lip;
1897 NYD_ENTER;
1899 lip = (void*)buf;
1900 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1901 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1902 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1903 memcpy(lip->li_name, name, sizeof name);
1905 /* The problem being that we want to support reverse solidus newline
1906 * escaping also within multiline -X, i.e., POSIX says:
1907 * An unquoted <backslash> at the end of a command line shall
1908 * be discarded and the next line shall continue the command
1909 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
1910 * entire lines array and set _MACRO_FREE_DATA */
1911 imax = cnt + 1;
1912 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
1914 /* For each of the input lines.. */
1915 for(i = len = 0, cp = NULL; cnt > 0;){
1916 bool_t keep;
1917 size_t j;
1919 if((j = strlen(srcp = *lines)) == 0){
1920 ++lines, --cnt;
1921 continue;
1924 /* Separate one line from a possible multiline input string */
1925 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1926 *lines = &xsrcp[1];
1927 j = PTR2SIZE(xsrcp - srcp);
1928 }else
1929 ++lines, --cnt;
1931 /* The (separated) string may itself indicate soft newline escaping */
1932 if((keep = (srcp[j - 1] == '\\'))){
1933 size_t xj, xk;
1935 /* Need an uneven number of reverse solidus */
1936 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1937 if(srcp[xj] != '\\')
1938 break;
1939 if(xk & 1)
1940 --j;
1941 else
1942 keep = FAL0;
1945 /* Strip any leading WS from follow lines, then */
1946 if(cp != NULL)
1947 while(j > 0 && blankspacechar(*srcp))
1948 ++srcp, --j;
1950 if(j > 0){
1951 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1952 imax += 4;
1953 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
1954 imax);
1956 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
1957 memcpy(&cp[len], srcp, j);
1958 cp[len += j] = '\0';
1960 if(!keep)
1961 ++i;
1963 if(!keep)
1964 cp = NULL, len = 0;
1966 if(cp != NULL){
1967 assert(i + 1 < imax);
1968 lip->li_lines[i++] = cp;
1970 lip->li_lines[i] = NULL;
1972 a_lex_load(lip);
1973 if(n_pstate & n_PS_EXIT)
1974 exit(n_exit_status);
1975 NYD_LEAVE;
1978 FL int
1979 c_source(void *v){
1980 int rv;
1981 NYD_ENTER;
1983 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1984 NYD_LEAVE;
1985 return rv;
1988 FL int
1989 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1990 int rv;
1991 NYD_ENTER;
1993 rv = (a_lex_source_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
1994 NYD_LEAVE;
1995 return rv;
1998 FL bool_t
1999 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
2000 void (*on_finalize)(void*), void *finalize_arg){
2001 struct a_lex_input_stack *lip;
2002 size_t i;
2003 int rv;
2004 NYD_ENTER;
2006 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
2007 (i = strlen(name) +1));
2008 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
2009 lip->li_outer = a_lex_input;
2010 lip->li_file = NULL;
2011 lip->li_cond = condstack_release();
2012 n_memory_autorec_push(&lip->li_autorecmem[0]);
2013 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
2014 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2015 ? a_LEX_SUPER_MACRO : 0);
2016 lip->li_lines = lines;
2017 lip->li_on_finalize = on_finalize;
2018 lip->li_finalize_arg = finalize_arg;
2019 memcpy(lip->li_name, name, i);
2021 n_pstate |= n_PS_ROBOT;
2022 a_lex_input = lip;
2023 rv = a_commands_recursive(lif);
2024 NYD_LEAVE;
2025 return rv;
2028 FL bool_t
2029 n_source_command(enum n_lexinput_flags lif, char const *cmd){
2030 struct a_lex_input_stack *lip;
2031 size_t i, ial;
2032 bool_t rv;
2033 NYD_ENTER;
2035 i = strlen(cmd) +1;
2036 ial = n_ALIGN(i);
2038 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
2039 ial + 2*sizeof(char*));
2040 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
2041 lip->li_outer = a_lex_input;
2042 lip->li_cond = condstack_release();
2043 n_memory_autorec_push(&lip->li_autorecmem[0]);
2044 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_CMD |
2045 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
2046 ? a_LEX_SUPER_MACRO : 0);
2047 lip->li_lines = (void*)&lip->li_name[ial];
2048 memcpy(lip->li_lines[0] = &lip->li_name[0], cmd, i);
2049 lip->li_lines[1] = NULL;
2051 n_pstate |= n_PS_ROBOT;
2052 a_lex_input = lip;
2053 rv = a_commands_recursive(lif);
2054 NYD_LEAVE;
2055 return rv;
2058 FL void
2059 n_source_slice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
2060 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
2061 struct a_lex_input_stack *lip;
2062 size_t i;
2063 NYD_ENTER;
2065 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
2066 (i = strlen(cmd) +1));
2067 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
2068 lip->li_outer = a_lex_input;
2069 lip->li_file = new_stdin;
2070 lip->li_flags = a_LEX_FREE | a_LEX_SLICE;
2071 lip->li_on_finalize = on_finalize;
2072 lip->li_finalize_arg = finalize_arg;
2073 lip->li_slice_stdin = n_stdin;
2074 lip->li_slice_stdout = n_stdout;
2075 lip->li_slice_psonce = n_psonce;
2076 memcpy(lip->li_name, cmd, i);
2078 n_stdin = new_stdin;
2079 n_stdout = new_stdout;
2080 n_psonce = new_psonce;
2081 n_pstate |= n_PS_ROBOT;
2082 a_lex_input = lip;
2083 NYD_LEAVE;
2086 FL void
2087 n_source_slice_hack_remove_after_jump(void){
2088 a_lex_unstack(FAL0);
2091 FL bool_t
2092 n_source_may_yield_control(void){
2093 return (((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
2094 (n_PSO_INTERACTIVE | n_PSO_STARTED)) &&
2095 (!(n_pstate & n_PS_ROBOT) ||
2096 /* But: ok for ~:, yet: unless in a hook.
2097 * TODO This is obviously hacky in that it depends on _input_stack not
2098 * TODO loosing any flags when creating new contexts... Maybe this
2099 * TODO function should instead walk all up the context stack when
2100 * TODO there is one, and verify neither level prevents yielding! */
2101 ((n_pstate & n_PS_COMPOSE_MODE) && (a_lex_input == NULL ||
2102 !(a_lex_input->li_flags & a_LEX_SLICE)))) &&
2103 (a_lex_input == NULL || a_lex_input->li_outer == NULL));
2106 FL void
2107 n_source_inject_input(char const *buf, size_t len, bool_t commit){
2108 NYD_ENTER;
2109 if(UIZ_MAX - n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat) -1 > len){
2110 struct a_lex_input_inject *liip;
2112 liip = n_alloc(n_VSTRUCT_SIZEOF(struct a_lex_input_inject, lii_dat
2113 ) + len +1);
2114 liip->lii_next = a_lex_input_inject;
2115 liip->lii_len = len;
2116 liip->lii_commit = commit;
2117 memcpy(liip->lii_dat, buf, len);
2118 liip->lii_dat[len] = '\0';
2119 a_lex_input_inject = liip;
2121 NYD_LEAVE;
2124 FL void
2125 n_source_force_eof(void){
2126 NYD_ENTER;
2127 assert(a_lex_input != NULL);
2128 a_lex_input->li_flags |= a_LEX_FORCE_EOF;
2129 NYD_LEAVE;
2132 /* s-it-mode */