Drop requirement of BYTE_ORDER knowledge ++ for OPT_CROSS_BUILD..
[s-mailx.git] / lex_input.c
blob03fb78aae57ec40f0ded75e417fd1430cc1dedf6
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)? */
106 char const *le_new_content; /* History: reenter line, start with this */
109 struct a_lex_input_stack{
110 struct a_lex_input_stack *li_outer;
111 FILE *li_file; /* File we were in */
112 void *li_cond; /* Saved state of conditional stack */
113 ui32_t li_flags; /* enum a_lex_input_flags */
114 ui32_t li_loff; /* Pseudo (macro): index in .li_lines */
115 char **li_lines; /* Pseudo content, lines unfolded */
116 void (*li_on_finalize)(void *);
117 void *li_finalize_arg;
118 char li_autorecmem[n_MEMORY_AUTOREC_TYPE_SIZEOF];
119 sigjmp_buf li_cmdrec_jmp; /* TODO one day... for command_recursive */
120 /* SLICE hacks: saved stdin/stdout, saved pstate */
121 FILE *li_slice_stdin;
122 FILE *li_slice_stdout;
123 ui32_t li_slice_psonce;
124 ui8_t li_slice__dummy[4];
125 char li_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
127 n_CTA(n_MEMORY_AUTOREC_TYPE_SIZEOF % sizeof(void*) == 0,
128 "Inacceptible size of structure buffer");
130 static sighandler_type a_lex_oldpipe;
131 static struct a_lex_ghost *a_lex_ghosts;
132 /* a_lex_cmd_tab[] after fun protos */
134 /* */
135 static struct a_lex_input_stack *a_lex_input;
137 static sigjmp_buf a_lex_srbuf; /* TODO GET RID */
139 /* Isolate the command from the arguments */
140 static char *a_lex_isolate(char const *comm);
142 /* Command ghost handling */
143 static int a_lex_c_ghost(void *v);
144 static int a_lex_c_unghost(void *v);
146 /* */
147 static char const *a_lex_cmdinfo(struct a_lex_cmd const *lcp);
149 /* Print a list of all commands */
150 static int a_lex_c_list(void *v);
152 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
154 /* `help' / `?' command */
155 static int a_lex_c_help(void *v);
157 /* `exit' and `quit' commands */
158 static int a_lex_c_exit(void *v);
159 static int a_lex_c_quit(void *v);
161 /* Print the binaries version number */
162 static int a_lex_c_version(void *v);
164 static int a_lex__version_cmp(void const *s1, void const *s2);
166 /* n_PS_STATE_PENDMASK requires some actions */
167 static void a_lex_update_pstate(void);
169 /* Evaluate a single command.
170 * .le_add_history and .le_new_content will be updated upon success.
171 * Command functions return 0 for success, 1 for error, and -1 for abort.
172 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
173 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
175 /* Get first-fit, or NULL */
176 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
178 /* Branch here on hangup signal and simulate "exit" */
179 static void a_lex_hangup(int s);
181 /* The following gets called on receipt of an interrupt. Close all open files
182 * except 0, 1, 2, and the temporary. Also, unstack all source files */
183 static void a_lex_onintr(int s);
185 /* Pop the current input back to the previous level. Update the program state.
186 * If the argument is TRUM1 then we don't alert and error out if the stack
187 * doesn't exist at all */
188 static void a_lex_unstack(bool_t eval_error);
190 /* `source' and `source_if' (if silent_open_error: no pipes allowed, then).
191 * Returns FAL0 if file is somehow not usable (unless silent_open_error) or
192 * upon evaluation error, and TRU1 on success */
193 static bool_t a_lex_source_file(char const *file, bool_t silent_open_error);
195 /* System resource file load()ing or -X command line option array traversal */
196 static bool_t a_lex_load(struct a_lex_input_stack *lip);
198 /* A simplified command loop for recursed state machines */
199 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
201 /* List of all commands, and list of commands which are specially treated
202 * and deduced in _evaluate(), but we need a list for _c_list() and
203 * print_comm_docstr() */
204 #ifdef HAVE_DOCSTRINGS
205 # define DS(S) , S
206 #else
207 # define DS(S)
208 #endif
209 static struct a_lex_cmd const a_lex_cmd_tab[] = {
210 #include "cmd_tab.h"
212 a_lex_special_cmd_tab[] = {
213 { "#", NULL, 0, 0, 0
214 DS(N_("Comment command: ignore remaining (continuable) line")) },
215 { "-", NULL, 0, 0, 0
216 DS(N_("Print out the preceding message")) }
218 #undef DS
220 static char *
221 a_lex_isolate(char const *comm){
222 NYD2_ENTER;
223 while(*comm != '\0' &&
224 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
225 ++comm;
226 NYD2_LEAVE;
227 return n_UNCONST(comm);
230 static int
231 a_lex_c_ghost(void *v){
232 struct a_lex_ghost *lgp, *gp;
233 size_t i, cl, nl;
234 char *cp;
235 char const **argv;
236 NYD_ENTER;
238 argv = v;
240 /* Show the list? */
241 if(*argv == NULL){
242 FILE *fp;
244 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
245 fp = n_stdout;
247 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
248 fprintf(fp, "wysh ghost %s %s\n",
249 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
251 if(fp != n_stdout){
252 page_or_print(fp, i);
253 Fclose(fp);
255 goto jleave;
258 /* Verify the ghost name is a valid one */
259 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0'){
260 n_err(_("`ghost': can't canonicalize %s\n"),
261 n_shexp_quote_cp(argv[0], FAL0));
262 v = NULL;
263 goto jleave;
266 /* Show command of single ghost? */
267 if(argv[1] == NULL){
268 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
269 if(!strcmp(argv[0], gp->lg_name)){
270 fprintf(n_stdout, "wysh ghost %s %s\n",
271 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
272 goto jleave;
274 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
275 v = NULL;
276 goto jleave;
279 /* Define command for ghost: verify command content */
280 for(cl = 0, i = 1; (cp = n_UNCONST(argv[i])) != NULL; ++i)
281 if(*cp != '\0')
282 cl += strlen(cp) +1; /* SP or NUL */
283 if(cl == 0){
284 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
285 v = NULL;
286 goto jleave;
289 /* If the ghost already exists, recreate */
290 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
291 if(!strcmp(gp->lg_name, argv[0])){
292 if(lgp != NULL)
293 lgp->lg_next = gp->lg_next;
294 else
295 a_lex_ghosts = gp->lg_next;
296 free(gp);
297 break;
300 nl = strlen(argv[0]) +1;
301 gp = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_ghost, lg_name) + nl + cl);
302 gp->lg_next = a_lex_ghosts;
303 a_lex_ghosts = gp;
304 memcpy(gp->lg_name, argv[0], nl);
305 cp = gp->lg_cmd.s = gp->lg_name + nl;
306 gp->lg_cmd.l = --cl;
308 while(*++argv != NULL)
309 if((i = strlen(*argv)) > 0){
310 memcpy(cp, *argv, i);
311 cp += i;
312 *cp++ = ' ';
314 *--cp = '\0';
315 jleave:
316 NYD_LEAVE;
317 return v == NULL;
320 static int
321 a_lex_c_unghost(void *v){
322 struct a_lex_ghost *lgp, *gp;
323 char const **argv, *cp;
324 int rv;
325 NYD_ENTER;
327 rv = 0;
328 argv = v;
330 while((cp = *argv++) != NULL){
331 if(cp[0] == '*' && cp[1] == '\0'){
332 while((gp = a_lex_ghosts) != NULL){
333 a_lex_ghosts = gp->lg_next;
334 free(gp);
336 }else{
337 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
338 lgp = gp, gp = gp->lg_next)
339 if(!strcmp(gp->lg_name, cp)){
340 if(lgp != NULL)
341 lgp->lg_next = gp->lg_next;
342 else
343 a_lex_ghosts = gp->lg_next;
344 free(gp);
345 goto jouter;
347 n_err(_("`unghost': no such alias: %s\n"),
348 n_shexp_quote_cp(cp, FAL0));
349 rv = 1;
350 jouter: ;
353 NYD_LEAVE;
354 return rv;
357 static char const *
358 a_lex_cmdinfo(struct a_lex_cmd const *lcp){
359 struct n_string rvb, *rv;
360 char const *cp;
361 NYD2_ENTER;
363 rv = n_string_creat_auto(&rvb);
364 rv = n_string_reserve(rv, 80);
366 switch(lcp->lc_argtype & ARG_ARGMASK){
367 case ARG_MSGLIST: cp = N_("message-list"); break;
368 case ARG_STRLIST: cp = N_("string data"); break;
369 case ARG_RAWLIST: cp = N_("old-style quoting"); break;
370 case ARG_NOLIST: cp = N_("no arguments"); break;
371 case ARG_NDMLIST: cp = N_("message-list (no default)"); break;
372 case ARG_WYSHLIST: cp = N_("sh(1)ell-style quoting"); break;
373 default: cp = N_("`wysh' for sh(1)ell-style quoting"); break;
375 rv = n_string_push_cp(rv, V_(cp));
377 if(lcp->lc_argtype & (ARG_A | ARG_I | ARG_M | ARG_R | ARG_S | ARG_X))
378 rv = n_string_push_buf(rv, " |", 2);
380 if(lcp->lc_argtype & ARG_A)
381 rv = n_string_push_cp(rv, _(" needs box"));
382 if(lcp->lc_argtype & ARG_I)
383 rv = n_string_push_cp(rv, _(" only interactive"));
384 if(lcp->lc_argtype & ARG_M)
385 rv = n_string_push_cp(rv, _(" send mode"));
386 if(lcp->lc_argtype & ARG_R)
387 rv = n_string_push_cp(rv, _(" no compose mode"));
388 if(lcp->lc_argtype & ARG_S)
389 rv = n_string_push_cp(rv, _(" after startup"));
390 if(lcp->lc_argtype & ARG_X)
391 rv = n_string_push_cp(rv, _(" subprocess"));
393 cp = n_string_cp(rv);
394 NYD2_LEAVE;
395 return cp;
398 static int
399 a_lex_c_list(void *v){
400 FILE *fp;
401 struct a_lex_cmd const **cpa, *cp, **cursor;
402 size_t l, i;
403 NYD_ENTER;
405 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
406 cpa = salloc(sizeof(cp) * i);
408 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
409 cpa[i] = &a_lex_cmd_tab[i];
410 /* C99 */{
411 size_t j;
413 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
414 cpa[i] = &a_lex_special_cmd_tab[j];
416 cpa[i] = NULL;
418 /* C99 */{
419 char const *xcp = v;
421 if(*xcp == '\0')
422 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
425 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
426 fp = n_stdout;
428 fprintf(fp, _("Commands are:\n"));
429 l = 1;
430 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
431 if(cp->lc_func == &c_cmdnotsupp)
432 continue;
433 if(n_poption & n_PO_D_V){
434 fprintf(fp, "%s\n", cp->lc_name);
435 ++l;
436 #ifdef HAVE_DOCSTRINGS
437 fprintf(fp, " : %s\n", V_(cp->lc_doc));
438 ++l;
439 #endif
440 fprintf(fp, " : %s\n", a_lex_cmdinfo(cp));
441 ++l;
442 }else{
443 size_t j = strlen(cp->lc_name) + 2;
445 if((i += j) > 72){
446 i = j;
447 fprintf(fp, "\n");
448 ++l;
450 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
454 if(fp != n_stdout){
455 page_or_print(fp, l);
456 Fclose(fp);
458 NYD_LEAVE;
459 return 0;
462 static int
463 a_lex__pcmd_cmp(void const *s1, void const *s2){
464 struct a_lex_cmd const * const *cp1, * const *cp2;
465 int rv;
466 NYD2_ENTER;
468 cp1 = s1;
469 cp2 = s2;
470 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
471 NYD2_LEAVE;
472 return rv;
475 static int
476 a_lex_c_help(void *v){
477 int rv;
478 char *arg;
479 NYD_ENTER;
481 /* Help for a single command? */
482 if((arg = *(char**)v) != NULL){
483 struct a_lex_ghost const *gp;
484 struct a_lex_cmd const *lcp, *lcpmax;
486 /* Ghosts take precedence */
487 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
488 if(!strcmp(arg, gp->lg_name)){
489 fprintf(n_stdout, "%s -> ", arg);
490 arg = gp->lg_cmd.s;
491 break;
494 lcpmax = &(lcp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
495 jredo:
496 for(; lcp < lcpmax; ++lcp){
497 if(is_prefix(arg, lcp->lc_name)){
498 fputs(arg, n_stdout);
499 if(strcmp(arg, lcp->lc_name))
500 fprintf(n_stdout, " (%s)", lcp->lc_name);
501 }else
502 continue;
504 #ifdef HAVE_DOCSTRINGS
505 fprintf(n_stdout, ": %s", V_(lcp->lc_doc));
506 #endif
507 if(n_poption & n_PO_D_V)
508 fprintf(n_stdout, "\n : %s", a_lex_cmdinfo(lcp));
509 putc('\n', n_stdout);
510 rv = 0;
511 goto jleave;
514 if(PTRCMP(lcpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
515 lcpmax = &(lcp =
516 a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
517 goto jredo;
520 if(gp != NULL){
521 fprintf(n_stdout, "%s\n", n_shexp_quote_cp(arg, TRU1));
522 rv = 0;
523 }else{
524 n_err(_("Unknown command: `%s'\n"), arg);
525 rv = 1;
527 }else{
528 /* Very ugly, but take care for compiler supported string lengths :( */
529 fputs(n_progname, n_stdout);
530 fputs(_(
531 " commands -- <msglist> denotes message specifications,\n"
532 "e.g., 1-5, :n or ., separated by spaces:\n"), n_stdout);
533 fputs(_(
534 "\n"
535 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
536 "Type <msglist> like `type' but always show all headers\n"
537 "next goto and type next message\n"
538 "from <msglist> (search and) print header summary for the given list\n"
539 "headers header summary for messages surrounding \"dot\"\n"
540 "delete <msglist> delete messages (can be `undelete'd)\n"),
541 n_stdout);
543 fputs(_(
544 "\n"
545 "save <msglist> folder append messages to folder and mark as saved\n"
546 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
547 "write <msglist> file write message contents to file (prompts for parts)\n"
548 "Reply <msglist> reply to message senders only\n"
549 "reply <msglist> like `Reply', but address all recipients\n"
550 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
551 n_stdout);
553 fputs(_(
554 "\n"
555 "mail <recipients> compose a mail for the given recipients\n"
556 "file folder change to another mailbox\n"
557 "File folder like `file', but open readonly\n"
558 "quit quit and apply changes to the current mailbox\n"
559 "xit or exit like `quit', but discard changes\n"
560 "!shell command shell escape\n"
561 "list [<anything>] all available commands [in search order]\n"),
562 n_stdout);
564 rv = (ferror(n_stdout) != 0);
566 jleave:
567 NYD_LEAVE;
568 return rv;
571 static int
572 a_lex_c_exit(void *v){
573 NYD_ENTER;
574 n_UNUSED(v);
576 if(n_psonce & n_PSO_STARTED){
577 /* In recursed state, return error to just pop the input level */
578 if(!(n_pstate & n_PS_SOURCING)){
579 #ifdef n_HAVE_TCAP
580 if((n_psonce & n_PSO_INTERACTIVE) && !(n_poption & n_PO_QUICKRUN_MASK))
581 n_termcap_destroy();
582 #endif
583 exit(n_EXIT_OK);
586 n_pstate |= n_PS_EXIT;
587 NYD_LEAVE;
588 return 0;
591 static int
592 a_lex_c_quit(void *v){
593 NYD_ENTER;
594 n_UNUSED(v);
596 /* If we are n_PS_SOURCING, then return 1 so _evaluate() can handle it.
597 * Otherwise return -1 to abort command loop */
598 n_pstate |= n_PS_EXIT;
599 NYD_LEAVE;
600 return 0;
603 static int
604 a_lex_c_version(void *v){
605 int longest, rv;
606 char *iop;
607 char const *cp, **arr;
608 size_t i, i2;
609 NYD_ENTER;
610 n_UNUSED(v);
612 fprintf(n_stdout, _("%s version %s\nFeatures included (+) or not (-)\n"),
613 n_uagent, ok_vlook(version));
615 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
616 i = strlen(cp = &ok_vlook(features)[1]) +1;
617 iop = salloc(i);
618 memcpy(iop, cp, i);
620 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
621 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
622 arr[i] = cp;
623 i2 = strlen(cp);
624 longest = n_MAX(longest, (int)i2);
626 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
628 for(++longest, i2 = 0; i-- > 0;){
629 cp = *(arr++);
630 fprintf(n_stdout, "%-*s ", longest, cp);
631 i2 += longest;
632 if(UICMP(z, ++i2 + longest, >=, n_scrnwidth) || i == 0){
633 i2 = 0;
634 putc('\n', n_stdout);
638 if((rv = ferror(n_stdout) != 0))
639 clearerr(n_stdout);
640 NYD_LEAVE;
641 return rv;
644 static int
645 a_lex__version_cmp(void const *s1, void const *s2){
646 char const * const *cp1, * const *cp2;
647 int rv;
648 NYD2_ENTER;
650 cp1 = s1;
651 cp2 = s2;
652 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
653 NYD2_LEAVE;
654 return rv;
657 static void
658 a_lex_update_pstate(void){
659 NYD_ENTER;
661 if(n_pstate & n_PS_SIGWINCH_PEND){
662 char buf[32];
664 snprintf(buf, sizeof buf, "%d", n_scrnwidth);
665 ok_vset(COLUMNS, buf);
666 snprintf(buf, sizeof buf, "%d", n_scrnheight);
667 ok_vset(LINES, buf);
670 n_pstate &= ~n_PS_PSTATE_PENDMASK;
671 NYD_LEAVE;
674 static int
675 a_lex_evaluate(struct a_lex_eval_ctx *evp){
676 /* xxx old style(9), but also old code */
677 struct str line;
678 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
679 struct a_lex_ghost *gp;
680 struct a_lex_cmd const *cmd;
681 int rv, c;
682 enum {
683 a_NONE = 0,
684 a_GHOST_MASK = (1<<3) - 1, /* Ghost recursion counter bits */
685 a_NOPREFIX = 1<<4, /* Modifier prefix not allowed right now */
686 a_NOGHOST = 1<<5, /* No ghost expansion modifier */
687 a_IGNERR = 1<<6, /* ignerr modifier prefix */
688 a_WYSH = 1<<7 /* XXX v15+ drop wysh modifier prefix */
689 } flags;
690 NYD_ENTER;
692 flags = a_NONE;
693 rv = 1;
694 cmd = NULL;
695 gp = NULL;
696 line = evp->le_line; /* XXX don't change original (buffer pointer) */
697 assert(line.s[line.l] == '\0');
698 evp->le_add_history = FAL0;
699 evp->le_new_content = NULL;
701 /* Command ghosts that refer to shell commands or macro expansion restart */
702 jrestart:
704 /* Strip the white space away from end and beginning of command */
705 if(line.l > 0){
706 size_t i = line.l;
708 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
709 --i;
710 line.l = i;
712 for(cp = line.s; spacechar(*cp); ++cp)
714 line.l -= PTR2SIZE(cp - line.s);
716 /* Ignore null commands (comments) */
717 if(*cp == '#')
718 goto jleave0;
720 /* Handle ! differently to get the correct lexical conventions */
721 arglist[0] = cp;
722 if(*cp == '!')
723 ++cp;
724 /* Isolate the actual command; since it may not necessarily be
725 * separated from the arguments (as in `p1') we need to duplicate it to
726 * be able to create a NUL terminated version.
727 * We must be aware of several special one letter commands here */
728 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
729 (*cp == '|' || *cp == '~' || *cp == '?'))
730 ++cp;
731 c = (int)PTR2SIZE(cp - arglist[0]);
732 line.l -= c;
733 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
734 memcpy(word, arglist[0], c);
735 word[c] = '\0';
737 /* No-expansion modifier? */
738 if(!(flags & a_NOPREFIX) && *word == '\\'){
739 ++word;
740 --c;
741 flags |= a_NOGHOST;
744 /* It may be a modifier prefix */
745 if(c == sizeof("ignerr") -1 && !asccasecmp(word, "ignerr")){
746 flags |= a_NOPREFIX | a_IGNERR;
747 line.s = cp;
748 goto jrestart;
749 }else if(c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
750 flags |= a_NOPREFIX | a_WYSH;
751 line.s = cp;
752 goto jrestart;
755 /* Look up the command; if not found, bitch.
756 * Normally, a blank command would map to the first command in the
757 * table; while n_PS_SOURCING, however, we ignore blank lines to eliminate
758 * confusion; act just the same for ghosts */
759 if(*word == '\0'){
760 if((n_pstate & n_PS_ROBOT) || gp != NULL)
761 goto jleave0;
762 cmd = a_lex_cmd_tab + 0;
763 goto jexec;
766 if(!(flags & a_NOGHOST) && (flags & a_GHOST_MASK) != a_GHOST_MASK){
767 /* TODO relink list head, so it's sorted on usage over time?
768 * TODO in fact, there should be one hashmap over all commands and ghosts
769 * TODO so that the lookup could be made much more efficient than it is
770 * TODO now (two adjacent list searches! */
771 ui8_t expcnt;
773 expcnt = (flags & a_GHOST_MASK);
774 ++expcnt;
775 flags = (flags & ~(a_GHOST_MASK | a_NOPREFIX)) | expcnt;
777 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
778 if(!strcmp(word, gp->lg_name)){
779 if(line.l > 0){
780 size_t i;
782 i = gp->lg_cmd.l;
783 line.s = salloc(i + line.l +1);
784 memcpy(line.s, gp->lg_cmd.s, i);
785 memcpy(line.s + i, cp, line.l);
786 line.s[i += line.l] = '\0';
787 line.l = i;
788 }else{
789 line.s = gp->lg_cmd.s;
790 line.l = gp->lg_cmd.l;
792 goto jrestart;
796 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
797 bool_t s;
799 if(!(s = condstack_isskip()) || (n_poption & n_PO_D_V))
800 n_err(_("Unknown command%s: `%s'\n"),
801 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
802 if(s)
803 goto jleave0;
804 if(cmd != NULL){
805 c_cmdnotsupp(NULL);
806 cmd = NULL;
808 goto jleave;
811 /* See if we should execute the command -- if a conditional we always
812 * execute it, otherwise, check the state of cond */
813 jexec:
814 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
815 goto jleave0;
817 /* Process the arguments to the command, depending on the type it expects */
818 if((cmd->lc_argtype & ARG_I) && !(n_psonce & n_PSO_INTERACTIVE) &&
819 !(n_poption & n_PO_BATCH_FLAG)){
820 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
821 cmd->lc_name);
822 goto jleave;
824 if(!(cmd->lc_argtype & ARG_M) && (n_psonce & n_PSO_SENDMODE)){
825 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
826 goto jleave;
828 if(cmd->lc_argtype & ARG_R){
829 if(n_pstate & n_PS_COMPOSE_MODE){
830 /* TODO n_PS_COMPOSE_MODE: should allow `reply': ~:reply! */
831 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
832 goto jleave;
834 /* TODO Nothing should prevent ARG_R in conjunction with
835 * TODO n_PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
836 if(n_pstate & (n_PS_ROBOT | n_PS_SOURCING)){
837 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
838 cmd->lc_name);
839 goto jleave;
842 if((cmd->lc_argtype & ARG_S) && !(n_psonce & n_PSO_STARTED)){
843 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
844 goto jleave;
846 if(!(cmd->lc_argtype & ARG_X) && (n_pstate & n_PS_COMPOSE_FORKHOOK)){
847 n_err(_("Cannot invoke `%s' from a hook running in a child process\n"),
848 cmd->lc_name);
849 goto jleave;
852 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
853 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
854 goto jleave;
856 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
857 n_err(_("May not execute `%s' -- message file is read only\n"),
858 cmd->lc_name);
859 goto jleave;
862 if(cmd->lc_argtype & ARG_O)
863 n_OBSOLETE2(_("this command will be removed"), cmd->lc_name);
864 if(cmd->lc_argtype & ARG_V)
865 temporary_arg_v_store = NULL;
867 if((flags & a_WYSH) && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST)
868 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
869 /* TODO v15: strip n_PS_ARGLIST_MASK off, just in case the actual command
870 * TODO doesn't use any of those list commands which strip this mask,
871 * TODO and for now we misuse bits for checking relation to history;
872 * TODO argument state should be property of a per-command carrier instead */
873 n_pstate &= ~n_PS_ARGLIST_MASK;
874 switch(cmd->lc_argtype & ARG_ARGMASK){
875 case ARG_MSGLIST:
876 /* Message list defaulting to nearest forward legal message */
877 if(n_msgvec == NULL)
878 goto je96;
879 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
880 break;
881 if(c == 0){
882 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
883 n_msgvec[1] = 0;
885 if(n_msgvec[0] == 0){
886 if(!(n_pstate & n_PS_HOOK_MASK))
887 fprintf(n_stdout, _("No applicable messages\n"));
888 break;
890 rv = (*cmd->lc_func)(n_msgvec);
891 break;
893 case ARG_NDMLIST:
894 /* Message list with no defaults, but no error if none exist */
895 if(n_msgvec == NULL){
896 je96:
897 n_err(_("Invalid use of message list\n"));
898 break;
900 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
901 break;
902 rv = (*cmd->lc_func)(n_msgvec);
903 break;
905 case ARG_STRLIST:
906 /* Just the straight string, with leading blanks removed */
907 while(whitechar(*cp))
908 ++cp;
909 rv = (*cmd->lc_func)(cp);
910 break;
912 case ARG_WYSHLIST:
913 c = 1;
914 if(0){
915 /* FALLTHRU */
916 case ARG_WYRALIST:
917 c = (flags & a_WYSH) ? 1 : 0;
918 if(0){
919 case ARG_RAWLIST:
920 c = 0;
924 if((c = getrawlist((c != 0), arglist, n_NELEM(arglist), cp, line.l)) < 0){
925 n_err(_("Invalid argument list\n"));
926 break;
928 if(c < cmd->lc_minargs){
929 n_err(_("`%s' requires at least %d arg(s)\n"),
930 cmd->lc_name, cmd->lc_minargs);
931 break;
933 #undef lc_minargs
934 if(c > cmd->lc_maxargs){
935 n_err(_("`%s' takes no more than %d arg(s)\n"),
936 cmd->lc_name, cmd->lc_maxargs);
937 break;
939 #undef lc_maxargs
940 rv = (*cmd->lc_func)(arglist);
941 break;
943 case ARG_NOLIST:
944 /* Just the constant zero, for exiting, eg. */
945 rv = (*cmd->lc_func)(0);
946 break;
948 default:
949 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
950 cmd->lc_argtype & ARG_ARGMASK); )
951 goto jleave0;
954 if(rv == 0 && (cmd->lc_argtype & ARG_V) &&
955 (cp = temporary_arg_v_store) != NULL){
956 temporary_arg_v_store = NULL;
957 evp->le_new_content = cp;
958 goto jleave0;
960 if(!(cmd->lc_argtype & ARG_H))
961 evp->le_add_history = (((cmd->lc_argtype & ARG_G) ||
962 (n_pstate & n_PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
964 jleave:
965 n_PS_ROOT_BLOCK(ok_vset(__qm, (rv == 0 ? "0" : "1"))); /* TODO num=1/real */
967 if(flags & a_IGNERR){
968 rv = 0;
969 n_exit_status = n_EXIT_OK;
972 /* Exit the current source file on error TODO what a mess! */
973 if(rv == 0)
974 n_pstate &= ~n_PS_EVAL_ERROR;
975 else{
976 n_pstate |= n_PS_EVAL_ERROR;
977 if(rv < 0 || (n_pstate & n_PS_ROBOT)){ /* FIXME */
978 rv = 1;
979 goto jret;
981 goto jret0;
984 if(cmd == NULL)
985 goto jret0;
986 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint)) /* TODO rid of that! */
987 if(visible(dot)){
988 line.s = savestr("type");
989 line.l = sizeof("type") -1;
990 flags = a_GHOST_MASK; /* Avoid `ghost' lookups.. */
991 goto jrestart;
994 if(!(n_pstate & (n_PS_SOURCING | n_PS_HOOK_MASK)) &&
995 !(cmd->lc_argtype & ARG_T))
996 n_pstate |= n_PS_SAW_COMMAND;
997 jleave0:
998 n_pstate &= ~n_PS_EVAL_ERROR;
999 jret0:
1000 rv = 0;
1001 jret:
1002 NYD_LEAVE;
1003 return rv;
1006 static struct a_lex_cmd const *
1007 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
1008 struct a_lex_cmd const *cp;
1009 NYD2_ENTER;
1011 for(cp = a_lex_cmd_tab;
1012 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
1013 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
1014 goto jleave;
1015 cp = NULL;
1016 jleave:
1017 NYD2_LEAVE;
1018 return cp;
1021 static void
1022 a_lex_hangup(int s){
1023 NYD_X; /* Signal handler */
1024 n_UNUSED(s);
1025 /* nothing to do? */
1026 exit(n_EXIT_ERR);
1029 static void
1030 a_lex_onintr(int s){ /* TODO block signals while acting */
1031 NYD_X; /* Signal handler */
1032 n_UNUSED(s);
1034 safe_signal(SIGINT, a_lex_onintr);
1036 termios_state_reset();
1037 close_all_files(); /* FIXME .. of current level ONLU! */
1038 if(image >= 0){
1039 close(image);
1040 image = -1;
1043 a_lex_unstack(TRUM1);
1045 if(interrupts != 1)
1046 n_err_sighdl(_("Interrupt\n"));
1047 safe_signal(SIGPIPE, a_lex_oldpipe);
1048 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
1051 static void
1052 a_lex_unstack(bool_t eval_error){
1053 struct a_lex_input_stack *lip;
1054 NYD_ENTER;
1056 if((lip = a_lex_input) == NULL){
1057 n_memory_reset();
1059 /* If called from a_lex_onintr(), be silent FIXME */
1060 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1061 if(eval_error == TRUM1 || !(n_psonce & n_PSO_STARTED))
1062 goto jleave;
1063 goto jerr;
1066 if(lip->li_flags & a_LEX_SLICE){ /* TODO Temporary hack */
1067 n_stdin = lip->li_slice_stdin;
1068 n_stdout = lip->li_slice_stdout;
1069 n_psonce = lip->li_slice_psonce;
1070 goto jthe_slice_hack;
1073 if(lip->li_flags & a_LEX_MACRO){
1074 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
1075 char **lp;
1077 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
1078 free(*lp);
1079 ++lip->li_loff;
1081 /* Part of lip's memory chunk, then */
1082 if(!(lip->li_flags & a_LEX_MACRO_CMD))
1083 free(lip->li_lines);
1085 }else{
1086 if(lip->li_flags & a_LEX_PIPE)
1087 /* XXX command manager should -TERM then -KILL instead of hoping
1088 * XXX for exit of provider due to EPIPE / SIGPIPE */
1089 Pclose(lip->li_file, TRU1);
1090 else
1091 Fclose(lip->li_file);
1094 if(!condstack_take(lip->li_cond)){
1095 n_err(_("Unmatched `if' at end of %s %s\n"),
1096 ((lip->li_flags & a_LEX_MACRO
1097 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1098 : _("`source'd file"))),
1099 lip->li_name);
1100 eval_error = TRU1;
1103 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1105 jthe_slice_hack:
1106 if(lip->li_on_finalize != NULL)
1107 (*lip->li_on_finalize)(lip->li_finalize_arg);
1109 if((a_lex_input = lip->li_outer) == NULL){
1110 n_pstate &= ~(n_PS_SOURCING | n_PS_ROBOT);
1111 }else{
1112 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1113 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1114 n_pstate &= ~n_PS_SOURCING;
1115 assert(n_pstate & n_PS_ROBOT);
1118 if(eval_error)
1119 goto jerr;
1120 jleave:
1121 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1122 free(lip);
1123 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1124 a_lex_unstack(TRUM1);
1125 NYD_LEAVE;
1126 return;
1128 jerr:
1129 if(lip != NULL){
1130 /* POSIX says
1131 * Any errors in the start-up file shall either cause mailx to
1132 * terminate with a diagnostic message and a non-zero status or to
1133 * continue after writing a diagnostic message, ignoring the
1134 * remainder of the lines in the start-up file
1135 * But print the diagnostic only for the outermost resource unless the
1136 * user is debugging or in verbose mode */
1137 if((n_poption & n_PO_D_V) ||
1138 (!(n_psonce & n_PSO_STARTED) &&
1139 !(lip->li_flags & (a_LEX_SLICE | a_LEX_MACRO)) &&
1140 lip->li_outer == NULL))
1141 n_alert(_("Stopped %s %s due to errors%s"),
1142 (n_psonce & n_PSO_STARTED
1143 ? (lip->li_flags & a_LEX_SLICE ? _("sliced in program")
1144 : (lip->li_flags & a_LEX_MACRO
1145 ? (lip->li_flags & a_LEX_MACRO_CMD
1146 ? _("evaluating command") : _("evaluating macro"))
1147 : (lip->li_flags & a_LEX_PIPE
1148 ? _("executing `source'd pipe")
1149 : _("loading `source'd file")))
1151 : (lip->li_flags & a_LEX_MACRO
1152 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1153 ? _("evaluating command line") : _("evaluating macro"))
1154 : _("loading initialization resource"))),
1155 lip->li_name,
1156 (n_poption & n_PO_DEBUG
1157 ? n_empty : _(" (enable *debug* for trace)")));
1160 if(!(n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED))){
1161 if(n_poption & n_PO_D_V)
1162 n_alert(_("Non-interactive, bailing out due to errors "
1163 "in startup load phase"));
1164 exit(n_EXIT_ERR);
1166 goto jleave;
1169 static bool_t
1170 a_lex_source_file(char const *file, bool_t silent_open_error){
1171 struct a_lex_input_stack *lip;
1172 size_t nlen;
1173 char *nbuf;
1174 bool_t ispipe;
1175 FILE *fip;
1176 NYD_ENTER;
1178 fip = NULL;
1180 /* Being a command argument file is space-trimmed *//* TODO v15 with
1181 * TODO WYRALIST this is no longer necessary true, and for that we
1182 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1183 #if 0
1184 ((ispipe = (!silent_open_error && (nlen = strlen(file)) > 0 &&
1185 file[--nlen] == '|')))
1186 #else
1187 ispipe = FAL0;
1188 if(!silent_open_error)
1189 for(nlen = strlen(file); nlen > 0;){
1190 char c;
1192 c = file[--nlen];
1193 if(!blankchar(c)){
1194 if(c == '|'){
1195 nbuf = savestrbuf(file, nlen);
1196 ispipe = TRU1;
1198 break;
1201 #endif
1203 if(ispipe){
1204 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1205 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL)
1206 goto jeopencheck;
1207 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1208 goto jeopencheck;
1209 else if((fip = Fopen(nbuf, "r")) == NULL){
1210 jeopencheck:
1211 if(!silent_open_error || (n_poption & n_PO_D_V))
1212 n_perr(nbuf, 0);
1213 if(silent_open_error)
1214 fip = (FILE*)-1;
1215 goto jleave;
1218 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
1219 (nlen = strlen(nbuf) +1));
1220 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1221 lip->li_outer = a_lex_input;
1222 lip->li_file = fip;
1223 lip->li_cond = condstack_release();
1224 n_memory_autorec_push(&lip->li_autorecmem[0]);
1225 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1226 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1227 ? a_LEX_SUPER_MACRO : 0);
1228 memcpy(lip->li_name, nbuf, nlen);
1230 n_pstate |= n_PS_SOURCING | n_PS_ROBOT;
1231 a_lex_input = lip;
1232 if(!a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC))
1233 fip = NULL;
1234 jleave:
1235 NYD_LEAVE;
1236 return (fip != NULL);
1239 static bool_t
1240 a_lex_load(struct a_lex_input_stack *lip){
1241 bool_t rv;
1242 NYD2_ENTER;
1244 assert(!(n_psonce & n_PSO_STARTED));
1245 assert(a_lex_input == NULL);
1247 /* POSIX:
1248 * Any errors in the start-up file shall either cause mailx to terminate
1249 * with a diagnostic message and a non-zero status or to continue after
1250 * writing a diagnostic message, ignoring the remainder of the lines in
1251 * the start-up file. */
1252 lip->li_cond = condstack_release();
1253 n_memory_autorec_push(&lip->li_autorecmem[0]);
1255 /* FIXME won't work for now (n_PS_ROBOT needs n_PS_SOURCING sofar)
1256 n_pstate |= n_PS_ROBOT |
1257 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : n_PS_SOURCING);
1259 n_pstate |= n_PS_ROBOT | n_PS_SOURCING;
1260 if(n_poption & n_PO_D_V)
1261 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1262 a_lex_input = lip;
1263 if(!(rv = n_commands())){
1264 if(!(n_psonce & n_PSO_INTERACTIVE)){
1265 if(n_poption & n_PO_D_V)
1266 n_alert(_("Non-interactive program mode, forced exit"));
1267 exit(n_EXIT_ERR);
1268 }else if(n_poption & n_PO_BATCH_FLAG){
1269 char const *beoe;
1271 if((beoe = ok_vlook(batch_exit_on_error)) != NULL && *beoe == '1')
1272 n_pstate |= n_PS_EXIT;
1275 /* n_PS_EXIT handled by callers */
1276 NYD2_LEAVE;
1277 return rv;
1280 static void
1281 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1282 NYD_X; /* Signal handler */
1283 n_UNUSED(sig);
1284 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1287 static bool_t
1288 a_commands_recursive(enum n_lexinput_flags lif){
1289 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1290 sighandler_type soldhdl;
1291 sigset_t sintset, soldset;
1292 struct a_lex_eval_ctx ev;
1293 bool_t rv, ever;
1294 NYD2_ENTER;
1296 memset(&ev, 0, sizeof ev);
1298 sigfillset(&sintset);
1299 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1300 hadint = FAL0;
1301 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1302 safe_signal(SIGINT, &a_lex__cmdrecint);
1303 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1304 hadint = TRU1;
1305 goto jjump;
1308 sigprocmask(SIG_SETMASK, &soldset, NULL);
1310 n_COLOUR( n_colour_env_push(); )
1311 rv = TRU1;
1312 for(ever = FAL0;; ever = TRU1){
1313 char const *beoe;
1314 int n;
1316 if(ever)
1317 n_memory_reset();
1319 /* Read a line of commands and handle end of file specially */
1320 ev.le_line.l = ev.le_line_size;
1321 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l,
1322 ev.le_new_content);
1323 ev.le_line_size = (ui32_t)ev.le_line.l;
1324 ev.le_line.l = (ui32_t)n;
1326 if(n < 0)
1327 break;
1329 n = a_lex_evaluate(&ev);
1330 beoe = (n_poption & n_PO_BATCH_FLAG)
1331 ? ok_vlook(batch_exit_on_error) : NULL;
1333 if(n){
1334 if(beoe != NULL && *beoe == '1'){
1335 if(n_exit_status == n_EXIT_OK)
1336 n_exit_status = n_EXIT_ERR;
1338 rv = FAL0;
1339 break;
1341 if(beoe != NULL){
1342 if(n_exit_status != n_EXIT_OK)
1343 break;
1346 jjump: /* TODO */
1347 a_lex_unstack(!rv);
1348 n_COLOUR( n_colour_env_pop(FAL0); )
1350 if(ev.le_line.s != NULL)
1351 free(ev.le_line.s);
1353 if(soldhdl != SIG_IGN)
1354 safe_signal(SIGINT, soldhdl);
1355 NYD2_LEAVE;
1356 if(hadint){
1357 sigprocmask(SIG_SETMASK, &soldset, NULL);
1358 n_raise(SIGINT);
1360 return rv;
1363 FL int
1364 c_cmdnotsupp(void *vp){
1365 NYD_ENTER;
1366 n_UNUSED(vp);
1367 n_err(_("The requested feature is not compiled in\n"));
1368 NYD_LEAVE;
1369 return 1;
1372 FL bool_t
1373 n_commands(void){ /* FIXME */
1374 struct a_lex_eval_ctx ev;
1375 int n;
1376 bool_t volatile rv;
1377 NYD_ENTER;
1379 rv = TRU1;
1381 if (!(n_pstate & n_PS_SOURCING)) {
1382 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1383 safe_signal(SIGINT, &a_lex_onintr);
1384 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1385 safe_signal(SIGHUP, &a_lex_hangup);
1387 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1388 safe_signal(SIGPIPE, a_lex_oldpipe);
1390 memset(&ev, 0, sizeof ev);
1392 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1393 for (;;) {
1394 char *temporary_orig_line; /* XXX eval_ctx.le_line not yet constant */
1396 n_COLOUR( n_colour_env_pop(TRU1); )
1398 /* TODO Unless we have our signal manager (or however we do it) child
1399 * TODO processes may have time slots where their execution isn't
1400 * TODO protected by signal handlers (in between start and setup
1401 * TODO completed). close_all_files() is only called from onintr()
1402 * TODO so those may linger possibly forever */
1403 if(!(n_pstate & n_PS_SOURCING))
1404 close_all_files();
1406 interrupts = 0;
1408 n_memory_reset();
1410 if (!(n_pstate & n_PS_SOURCING)) {
1411 char *cp;
1413 /* TODO Note: this buffer may contain a password. We should redefine
1414 * TODO the code flow which has to do that */
1415 if ((cp = termios_state.ts_linebuf) != NULL) {
1416 termios_state.ts_linebuf = NULL;
1417 termios_state.ts_linesize = 0;
1418 free(cp); /* TODO pool give-back */
1420 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1421 if (ev.le_line.l > LINESIZE * 3) {
1422 free(ev.le_line.s); /* TODO pool! but what? */
1423 ev.le_line.s = NULL;
1424 ev.le_line.l = ev.le_line_size = 0;
1428 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1429 char *cp;
1431 if ((cp = ok_vlook(newmail)) != NULL) {
1432 struct stat st;
1434 /* FIXME TEST WITH NOPOLL ETC. !!! */
1435 n = (cp != NULL && strcmp(cp, "nopoll"));
1436 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1437 st.st_size > mailsize) ||
1438 (mb.mb_type == MB_MAILDIR && n != 0)) {
1439 size_t odot = PTR2SIZE(dot - message);
1440 ui32_t odid = (n_pstate & n_PS_DID_PRINT_DOT);
1442 if (setfile(mailname,
1443 FEDIT_NEWMAIL |
1444 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1445 n_exit_status |= n_EXIT_ERR;
1446 rv = FAL0;
1447 break;
1449 dot = message + odot;
1450 n_pstate |= odid;
1454 n_exit_status = n_EXIT_OK;
1457 /* Read a line of commands and handle end of file specially */
1458 jreadline:
1459 ev.le_line.l = ev.le_line_size;
1460 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1461 &ev.le_line.s, &ev.le_line.l, ev.le_new_content);
1462 ev.le_line_size = (ui32_t)ev.le_line.l;
1463 ev.le_line.l = (ui32_t)n;
1465 if (n < 0) {
1466 /* FIXME did unstack() when n_PS_SOURCING, only break with n_PS_LOADING */
1467 if (!(n_pstate & n_PS_ROBOT) &&
1468 (n_psonce & n_PSO_INTERACTIVE) && ok_blook(ignoreeof)) {
1469 fprintf(n_stdout, _("*ignoreeof* set, use `quit' to quit.\n"));
1470 n_msleep(500, FAL0);
1471 continue;
1473 break;
1476 temporary_orig_line = ((n_pstate & n_PS_SOURCING) ||
1477 !(n_psonce & n_PSO_INTERACTIVE))
1478 ? NULL : savestrbuf(ev.le_line.s, ev.le_line.l);
1480 n_pstate &= ~n_PS_HOOK_MASK;
1481 /* C99 */{
1482 char const *beoe;
1483 int estat;
1485 estat = a_lex_evaluate(&ev);
1486 beoe = (n_poption & n_PO_BATCH_FLAG)
1487 ? ok_vlook(batch_exit_on_error) : NULL;
1489 if(estat){
1490 if(beoe != NULL && *beoe == '1'){
1491 if(n_exit_status == n_EXIT_OK)
1492 n_exit_status = n_EXIT_ERR;
1493 rv = FAL0;
1494 break;
1496 if(!(n_psonce & n_PSO_STARTED)){ /* TODO join n_PS_EVAL_ERROR */
1497 if(a_lex_input == NULL ||
1498 !(a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)){
1499 rv = FAL0;
1500 break;
1502 }else
1503 break;
1506 if(beoe != NULL){
1507 if(n_exit_status != n_EXIT_OK)
1508 break;
1509 /* TODO n_PS_EVAL_ERROR and n_PS_SOURCING! Sigh!! */
1510 if((n_pstate & (n_PS_SOURCING | n_PS_EVAL_ERROR)
1511 ) == n_PS_EVAL_ERROR){
1512 n_exit_status = n_EXIT_ERR;
1513 break;
1518 if (!(n_pstate & n_PS_SOURCING) && (n_psonce & n_PSO_INTERACTIVE)) {
1519 if (ev.le_new_content != NULL)
1520 goto jreadline;
1521 /* *Can* happen since _evaluate() n_unstack()s on error! XXX no more */
1522 if (temporary_orig_line != NULL)
1523 n_tty_addhist(temporary_orig_line, (ev.le_add_history != TRU1));
1526 if(n_pstate & n_PS_EXIT)
1527 break;
1530 a_lex_unstack(!rv);
1532 if (ev.le_line.s != NULL)
1533 free(ev.le_line.s);
1534 NYD_LEAVE;
1535 return rv;
1538 FL int
1539 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1540 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1541 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1542 struct n_string xprompt;
1543 FILE *ifile;
1544 bool_t doprompt, dotty;
1545 char const *iftype;
1546 int n, nold;
1547 NYD2_ENTER;
1549 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_FORCE_EOF)){
1550 n = -1;
1551 goto jleave;
1554 /* Special case macro mode: never need to prompt, lines have always been
1555 * unfolded already */
1556 if(!(lif & n_LEXINPUT_FORCE_STDIN) &&
1557 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1558 if(*linebuf != NULL)
1559 free(*linebuf);
1561 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1562 *linesize = 0;
1563 n = -1;
1564 goto jleave;
1567 ++a_lex_input->li_loff;
1568 *linesize = strlen(*linebuf);
1569 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1570 *linebuf = sbufdup(*linebuf, *linesize);
1572 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1573 ? "-X OPTION"
1574 : (a_lex_input->li_flags & a_LEX_MACRO_CMD) ? "CMD" : "MACRO";
1575 n = (int)*linesize;
1576 n_pstate |= n_PS_READLINE_NL;
1577 goto jhave_dat;
1579 n_pstate &= ~n_PS_READLINE_NL;
1581 iftype = (!(n_psonce & n_PSO_STARTED) ? "LOAD"
1582 : (n_pstate & n_PS_SOURCING) ? "SOURCE" : "READ");
1583 doprompt = ((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
1584 (n_PSO_INTERACTIVE | n_PSO_STARTED) && !(n_pstate & n_PS_ROBOT));
1585 dotty = (doprompt && !ok_blook(line_editor_disable));
1586 if(!doprompt)
1587 lif |= n_LEXINPUT_PROMPT_NONE;
1588 else{
1589 if(!dotty)
1590 n_string_creat_auto(&xprompt);
1591 if(prompt == NULL)
1592 lif |= n_LEXINPUT_PROMPT_EVAL;
1595 /* Ensure stdout is flushed first anyway */
1596 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1597 fflush(n_stdout);
1599 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : n_stdin;
1600 if(ifile == NULL){
1601 assert((n_pstate & n_PS_COMPOSE_FORKHOOK) &&
1602 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO));
1603 ifile = n_stdin;
1606 for(nold = n = 0;;){
1607 if(dotty){
1608 assert(ifile == n_stdin);
1609 if(string != NULL && (n = (int)strlen(string)) > 0){
1610 if(*linesize > 0)
1611 *linesize += n +1;
1612 else
1613 *linesize = (size_t)n + LINESIZE +1;
1614 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1615 memcpy(*linebuf, string, (size_t)n +1);
1617 string = NULL;
1618 /* TODO if nold>0, don't redisplay the entire line!
1619 * TODO needs complete redesign ... */
1620 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1621 n_MEMORY_DEBUG_ARGSCALL);
1622 }else{
1623 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1624 n_tty_create_prompt(&xprompt, prompt, lif);
1625 if(xprompt.s_len > 0){
1626 fwrite(xprompt.s_dat, 1, xprompt.s_len, n_stdout);
1627 fflush(n_stdout);
1631 n = (readline_restart)(ifile, linebuf, linesize, n
1632 n_MEMORY_DEBUG_ARGSCALL);
1634 if(n > 0 && nold > 0){
1635 int i = 0;
1636 char const *cp = *linebuf + nold;
1638 while(blankspacechar(*cp) && nold + i < n)
1639 ++cp, ++i;
1640 if(i > 0){
1641 memmove(*linebuf + nold, cp, n - nold - i);
1642 n -= i;
1643 (*linebuf)[n] = '\0';
1648 if(n <= 0)
1649 break;
1651 /* POSIX says:
1652 * An unquoted <backslash> at the end of a command line shall
1653 * be discarded and the next line shall continue the command */
1654 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1655 if(dotty)
1656 n_pstate |= n_PS_READLINE_NL;
1657 break;
1659 /* Definitely outside of quotes, thus the quoting rules are so that an
1660 * uneven number of successive backslashs at EOL is a continuation */
1661 if(n > 1){
1662 size_t i, j;
1664 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1665 if((*linebuf)[i] != '\\')
1666 break;
1667 if(!(j & 1))
1668 break;
1670 (*linebuf)[nold = --n] = '\0';
1671 lif |= n_LEXINPUT_NL_FOLLOW;
1674 if(n < 0)
1675 goto jleave;
1676 (*linebuf)[*linesize = n] = '\0';
1678 jhave_dat:
1679 #if 0
1680 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1681 char *cp, c;
1682 size_t i;
1684 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1685 c = *--cp;
1686 if(!blankspacechar(c))
1687 break;
1689 (*linebuf)[n = (int)i] = '\0';
1692 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1693 char *cp, c;
1694 size_t j, i;
1696 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1697 c = *cp++;
1698 if(!blankspacechar(c))
1699 break;
1701 if(i > 0){
1702 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1703 (*linebuf)[n = (int)j] = '\0';
1706 #endif /* 0 (notyet - must take care for backslash escaped space) */
1708 if(n_poption & n_PO_D_VV)
1709 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1710 jleave:
1711 if (n_pstate & n_PS_PSTATE_PENDMASK)
1712 a_lex_update_pstate();
1714 /* TODO We need to special case a_LEX_SLICE, since that is not managed by us
1715 * TODO but only established from the outside and we need to drop this
1716 * TODO overlay context somehow */
1717 if(n < 0 && a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SLICE))
1718 a_lex_unstack(FAL0);
1719 NYD2_LEAVE;
1720 return n;
1723 FL char *
1724 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1725 char const *string){
1726 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1727 size_t linesize;
1728 char *linebuf, *rv;
1729 int n;
1730 NYD2_ENTER;
1732 linesize = 0;
1733 linebuf = NULL;
1734 rv = NULL;
1736 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1737 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1738 (lif & n_LEXINPUT_HIST_ADD) && (n_psonce & n_PSO_INTERACTIVE))
1739 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1741 if(linebuf != NULL)
1742 free(linebuf);
1743 NYD2_LEAVE;
1744 return rv;
1747 FL int
1748 c_read(void *v){ /* TODO IFS? how? -r */
1749 char const **argv, *cp, *cp2;
1750 int rv;
1751 NYD2_ENTER;
1753 rv = 0;
1754 for(argv = v; (cp = *argv++) != NULL;)
1755 if(!n_shexp_is_valid_varname(cp)){
1756 n_err(_("`read': not a valid variable name: %s\n"),
1757 n_shexp_quote_cp(cp, FAL0));
1758 rv = 1;
1760 if(rv)
1761 goto jleave;
1763 cp = n_lex_input_cp(((n_pstate & n_PS_COMPOSE_MODE
1764 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT) |
1765 n_LEXINPUT_FORCE_STDIN | n_LEXINPUT_NL_ESC |
1766 n_LEXINPUT_PROMPT_NONE /* XXX POSIX: PS2: yes! */),
1767 NULL, NULL);
1768 if(cp == NULL)
1769 cp = n_empty;
1771 for(argv = v; *argv != NULL; ++argv){
1772 char c;
1774 while(blankchar(*cp))
1775 ++cp;
1776 if(*cp == '\0')
1777 break;
1779 /* The last variable gets the remaining line less trailing IFS */
1780 if(argv[1] == NULL){
1781 for(cp2 = cp; *cp2 != '\0'; ++cp2)
1783 for(; cp2 > cp; --cp2){
1784 c = cp2[-1];
1785 if(!blankchar(c))
1786 break;
1788 }else
1789 for(cp2 = cp; (c = *++cp2) != '\0';)
1790 if(blankchar(c))
1791 break;
1793 /* C99 xxx This is a CC warning workaround (-Wbad-function-cast) */{
1794 char *vcp;
1796 vcp = savestrbuf(cp, PTR2SIZE(cp2 - cp));
1797 n_var_vset(*argv, (uintptr_t)vcp);
1800 cp = cp2;
1803 /* Set the remains to the empty string */
1804 for(; *argv != NULL; ++argv)
1805 n_var_vset(*argv, (uintptr_t)n_empty);
1807 rv = 0;
1808 jleave:
1809 NYD2_LEAVE;
1810 return rv;
1813 FL void
1814 n_load(char const *name){
1815 struct a_lex_input_stack *lip;
1816 size_t i;
1817 FILE *fip;
1818 NYD_ENTER;
1820 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1821 goto jleave;
1823 i = strlen(name) +1;
1824 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) + i);
1825 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1826 lip->li_file = fip;
1827 lip->li_flags = a_LEX_FREE;
1828 memcpy(lip->li_name, name, i);
1830 a_lex_load(lip);
1831 n_pstate &= ~n_PS_EXIT;
1832 jleave:
1833 NYD_LEAVE;
1836 FL void
1837 n_load_Xargs(char const **lines, size_t cnt){
1838 static char const name[] = "-X";
1840 ui8_t buf[sizeof(struct a_lex_input_stack) + sizeof name];
1841 char const *srcp, *xsrcp;
1842 char *cp;
1843 size_t imax, i, len;
1844 struct a_lex_input_stack *lip;
1845 NYD_ENTER;
1847 lip = (void*)buf;
1848 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1849 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1850 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1851 memcpy(lip->li_name, name, sizeof name);
1853 /* The problem being that we want to support reverse solidus newline
1854 * escaping also within multiline -X, i.e., POSIX says:
1855 * An unquoted <backslash> at the end of a command line shall
1856 * be discarded and the next line shall continue the command
1857 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
1858 * entire lines array and set _MACRO_FREE_DATA */
1859 imax = cnt + 1;
1860 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
1862 /* For each of the input lines.. */
1863 for(i = len = 0, cp = NULL; cnt > 0;){
1864 bool_t keep;
1865 size_t j;
1867 if((j = strlen(srcp = *lines)) == 0){
1868 ++lines, --cnt;
1869 continue;
1872 /* Separate one line from a possible multiline input string */
1873 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1874 *lines = &xsrcp[1];
1875 j = PTR2SIZE(xsrcp - srcp);
1876 }else
1877 ++lines, --cnt;
1879 /* The (separated) string may itself indicate soft newline escaping */
1880 if((keep = (srcp[j - 1] == '\\'))){
1881 size_t xj, xk;
1883 /* Need an uneven number of reverse solidus */
1884 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1885 if(srcp[xj] != '\\')
1886 break;
1887 if(xk & 1)
1888 --j;
1889 else
1890 keep = FAL0;
1893 /* Strip any leading WS from follow lines, then */
1894 if(cp != NULL)
1895 while(j > 0 && blankspacechar(*srcp))
1896 ++srcp, --j;
1898 if(j > 0){
1899 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1900 imax += 4;
1901 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
1902 imax);
1904 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
1905 memcpy(&cp[len], srcp, j);
1906 cp[len += j] = '\0';
1908 if(!keep)
1909 ++i;
1911 if(!keep)
1912 cp = NULL, len = 0;
1914 if(cp != NULL){
1915 assert(i + 1 < imax);
1916 lip->li_lines[i++] = cp;
1918 lip->li_lines[i] = NULL;
1920 a_lex_load(lip);
1921 if(n_pstate & n_PS_EXIT)
1922 exit(n_exit_status);
1923 NYD_LEAVE;
1926 FL int
1927 c_source(void *v){
1928 int rv;
1929 NYD_ENTER;
1931 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1932 NYD_LEAVE;
1933 return rv;
1936 FL int
1937 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1938 int rv;
1939 NYD_ENTER;
1941 rv = (a_lex_source_file(*(char**)v, TRU1) == TRU1) ? 0 : 1;
1942 NYD_LEAVE;
1943 return rv;
1946 FL bool_t
1947 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
1948 void (*on_finalize)(void*), void *finalize_arg){
1949 struct a_lex_input_stack *lip;
1950 size_t i;
1951 int rv;
1952 NYD_ENTER;
1954 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
1955 (i = strlen(name) +1));
1956 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1957 lip->li_outer = a_lex_input;
1958 lip->li_file = NULL;
1959 lip->li_cond = condstack_release();
1960 n_memory_autorec_push(&lip->li_autorecmem[0]);
1961 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1962 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1963 ? a_LEX_SUPER_MACRO : 0);
1964 lip->li_lines = lines;
1965 lip->li_on_finalize = on_finalize;
1966 lip->li_finalize_arg = finalize_arg;
1967 memcpy(lip->li_name, name, i);
1969 n_pstate |= n_PS_ROBOT;
1970 a_lex_input = lip;
1971 rv = a_commands_recursive(lif);
1972 NYD_LEAVE;
1973 return rv;
1976 FL bool_t
1977 n_source_command(enum n_lexinput_flags lif, char const *cmd){
1978 struct a_lex_input_stack *lip;
1979 size_t i, ial;
1980 bool_t rv;
1981 NYD_ENTER;
1983 i = strlen(cmd) +1;
1984 ial = n_ALIGN(i);
1986 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
1987 ial + 2*sizeof(char*));
1988 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1989 lip->li_outer = a_lex_input;
1990 lip->li_cond = condstack_release();
1991 n_memory_autorec_push(&lip->li_autorecmem[0]);
1992 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_CMD |
1993 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1994 ? a_LEX_SUPER_MACRO : 0);
1995 lip->li_lines = (void*)&lip->li_name[ial];
1996 memcpy(lip->li_lines[0] = &lip->li_name[0], cmd, i);
1997 lip->li_lines[1] = NULL;
1999 n_pstate |= n_PS_ROBOT;
2000 a_lex_input = lip;
2001 rv = a_commands_recursive(lif);
2002 NYD_LEAVE;
2003 return rv;
2006 FL void
2007 n_source_slice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
2008 ui32_t new_psonce, void (*on_finalize)(void*), void *finalize_arg){
2009 struct a_lex_input_stack *lip;
2010 size_t i;
2011 NYD_ENTER;
2013 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
2014 (i = strlen(cmd) +1));
2015 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
2016 lip->li_outer = a_lex_input;
2017 lip->li_file = new_stdin;
2018 lip->li_flags = a_LEX_FREE | a_LEX_SLICE;
2019 lip->li_on_finalize = on_finalize;
2020 lip->li_finalize_arg = finalize_arg;
2021 lip->li_slice_stdin = n_stdin;
2022 lip->li_slice_stdout = n_stdout;
2023 lip->li_slice_psonce = n_psonce;
2024 memcpy(lip->li_name, cmd, i);
2026 n_stdin = new_stdin;
2027 n_stdout = new_stdout;
2028 n_psonce = new_psonce;
2029 n_pstate |= n_PS_ROBOT;
2030 a_lex_input = lip;
2031 NYD_LEAVE;
2034 FL void
2035 n_source_slice_hack_remove_after_jump(void){
2036 a_lex_unstack(FAL0);
2039 FL bool_t
2040 n_source_may_yield_control(void){
2041 return (((n_psonce & (n_PSO_INTERACTIVE | n_PSO_STARTED)) ==
2042 (n_PSO_INTERACTIVE | n_PSO_STARTED)) &&
2043 (!(n_pstate & n_PS_ROBOT) ||
2044 /* But: ok for ~:, yet: unless in a hook.
2045 * TODO This is obviously hacky in that it depends on _input_stack not
2046 * TODO loosing any flags when creating new contexts... Maybe this
2047 * TODO function should instead walk all up the context stack when
2048 * TODO there is one, and verify neither level prevents yielding! */
2049 ((n_pstate & n_PS_COMPOSE_MODE) && (a_lex_input == NULL ||
2050 !(a_lex_input->li_flags & a_LEX_SLICE)))) &&
2051 (a_lex_input == NULL || a_lex_input->li_outer == NULL));
2054 FL void
2055 n_source_force_eof(void){
2056 NYD_ENTER;
2057 assert(a_lex_input != NULL);
2058 a_lex_input->li_flags |= a_LEX_FORCE_EOF;
2059 NYD_LEAVE;
2062 /* s-it-mode */