THANKS: Felipe Gasper
[s-mailx.git] / lex_input.c
blobc5c77fe02988bef3167e8af5821b06a4afc857b7
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 PS_ROBOT requires yet 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 - 2016 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 approach accmacvar.c:call_compose_mode_hook()
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_SUPER_MACRO = 1<<16 /* *Not* inheriting PS_SOURCING state */
78 struct a_lex_cmd{
79 char const *lc_name; /* Name of command */
80 int (*lc_func)(void*); /* Implementor of command */
81 enum argtype lc_argtype; /* Arglist type (see below) */
82 si16_t lc_msgflag; /* Required flags of msgs */
83 si16_t lc_msgmask; /* Relevant flags of msgs */
84 #ifdef HAVE_DOCSTRINGS
85 char const *lc_doc; /* One line doc for command */
86 #endif
88 /* Yechh, can't initialize unions */
89 #define lc_minargs lc_msgflag /* Minimum argcount for RAWLIST */
90 #define lc_maxargs lc_msgmask /* Max argcount for RAWLIST */
92 struct a_lex_ghost{
93 struct a_lex_ghost *lg_next;
94 struct str lg_cmd; /* Data follows after .lg_name */
95 char lg_name[n_VFIELD_SIZE(0)];
98 struct a_lex_eval_ctx{
99 struct str le_line; /* The terminated data to _evaluate() */
100 ui32_t le_line_size; /* May be used to store line memory size */
101 bool_t le_is_recursive; /* Evaluation in evaluation? (collect ~:) */
102 ui8_t __dummy[3];
103 bool_t le_add_history; /* Add command to history (TRUM1=gabby)? */
104 char const *le_new_content; /* History: reenter line, start with this */
107 struct a_lex_input_stack{
108 struct a_lex_input_stack *li_outer;
109 FILE *li_file; /* File we were in */
110 void *li_cond; /* Saved state of conditional stack */
111 ui32_t li_flags; /* enum a_lex_input_flags */
112 ui32_t li_loff; /* Pseudo (macro): index in .li_lines */
113 char **li_lines; /* Pseudo content, lines unfolded */
114 void (*li_on_finalize)(void *);
115 void *li_finalize_arg;
116 char li_autorecmem[n_MEMORY_AUTOREC_TYPE_SIZEOF];
117 sigjmp_buf li_cmdrec_jmp; /* TODO one day... for command_recursive */
118 /* SLICE hacks: saved stdin/stdout, saved pstate */
119 FILE *li_slice_stdin;
120 FILE *li_slice_stdout;
121 ui32_t li_slice_options;
122 ui8_t li_slice__dummy[4];
123 char li_name[n_VFIELD_SIZE(0)]; /* Name of file or macro */
125 n_CTA(n_MEMORY_AUTOREC_TYPE_SIZEOF % sizeof(void*) == 0,
126 "Inacceptible size of structure buffer");
128 static sighandler_type a_lex_oldpipe;
129 static struct a_lex_ghost *a_lex_ghosts;
130 /* a_lex_cmd_tab[] after fun protos */
132 /* */
133 static struct a_lex_input_stack *a_lex_input;
135 static sigjmp_buf a_lex_srbuf; /* TODO GET RID */
137 /* Isolate the command from the arguments */
138 static char *a_lex_isolate(char const *comm);
140 /* Command ghost handling */
141 static int a_lex_c_ghost(void *v);
142 static int a_lex_c_unghost(void *v);
144 /* Print a list of all commands */
145 static int a_lex_c_list(void *v);
147 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
149 /* `help' / `?' command */
150 static int a_lex_c_help(void *v);
152 /* `quit' command */
153 static int a_lex_c_quit(void *v);
155 /* Print the binaries version number */
156 static int a_lex_c_version(void *v);
158 static int a_lex__version_cmp(void const *s1, void const *s2);
160 /* PS_STATE_PENDMASK requires some actions */
161 static void a_lex_update_pstate(void);
163 /* Evaluate a single command.
164 * .le_add_history and .le_new_content will be updated upon success.
165 * Command functions return 0 for success, 1 for error, and -1 for abort.
166 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
167 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
169 /* Get first-fit, or NULL */
170 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
172 /* Branch here on hangup signal and simulate "exit" */
173 static void a_lex_hangup(int s);
175 /* The following gets called on receipt of an interrupt. Close all open files
176 * except 0, 1, 2, and the temporary. Also, unstack all source files */
177 static void a_lex_onintr(int s);
179 /* Pop the current input back to the previous level. Update the program state.
180 * If the argument is TRUM1 then we don't alert and error out if the stack
181 * doesn't exist at all */
182 static void a_lex_unstack(bool_t eval_error);
184 /* `source' and `source_if' (if silent_error: no pipes allowed, then) */
185 static bool_t a_lex_source_file(char const *file, bool_t silent_error);
187 /* System resource file load()ing or -X command line option array traversal */
188 static bool_t a_lex_load(struct a_lex_input_stack *lip);
190 /* A simplified command loop for recursed state machines */
191 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
193 /* List of all commands, and list of commands which are specially treated
194 * and deduced in _evaluate(), but we need a list for _c_list() and
195 * print_comm_docstr() */
196 #ifdef HAVE_DOCSTRINGS
197 # define DS(S) , S
198 #else
199 # define DS(S)
200 #endif
201 static struct a_lex_cmd const a_lex_cmd_tab[] = {
202 #include "cmd_tab.h"
204 a_lex_special_cmd_tab[] = {
205 { "#", NULL, 0, 0, 0
206 DS(N_("Comment command: ignore remaining (continuable) line")) },
207 { "-", NULL, 0, 0, 0
208 DS(N_("Print out the preceding message")) }
210 #undef DS
212 static char *
213 a_lex_isolate(char const *comm){
214 NYD2_ENTER;
215 while(*comm != '\0' &&
216 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
217 ++comm;
218 NYD2_LEAVE;
219 return n_UNCONST(comm);
222 static int
223 a_lex_c_ghost(void *v){
224 struct a_lex_ghost *lgp, *gp;
225 size_t i, cl, nl;
226 char *cp;
227 char const **argv;
228 NYD_ENTER;
230 argv = v;
232 /* Show the list? */
233 if(*argv == NULL){
234 FILE *fp;
236 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
237 fp = stdout;
239 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
240 fprintf(fp, "wysh ghost %s %s\n",
241 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
243 if(fp != stdout){
244 page_or_print(fp, i);
245 Fclose(fp);
247 goto jleave;
250 /* Verify the ghost name is a valid one */
251 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0'){
252 n_err(_("`ghost': can't canonicalize %s\n"),
253 n_shexp_quote_cp(argv[0], FAL0));
254 v = NULL;
255 goto jleave;
258 /* Show command of single ghost? */
259 if(argv[1] == NULL){
260 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
261 if(!strcmp(argv[0], gp->lg_name)){
262 printf("wysh ghost %s %s\n",
263 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
264 goto jleave;
266 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
267 v = NULL;
268 goto jleave;
271 /* Define command for ghost: verify command content */
272 for(cl = 0, i = 1; (cp = n_UNCONST(argv[i])) != NULL; ++i)
273 if(*cp != '\0')
274 cl += strlen(cp) +1; /* SP or NUL */
275 if(cl == 0){
276 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
277 v = NULL;
278 goto jleave;
281 /* If the ghost already exists, recreate */
282 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
283 if(!strcmp(gp->lg_name, argv[0])){
284 if(lgp != NULL)
285 lgp->lg_next = gp->lg_next;
286 else
287 a_lex_ghosts = gp->lg_next;
288 free(gp);
289 break;
292 nl = strlen(argv[0]) +1;
293 gp = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_ghost, lg_name) + nl + cl);
294 gp->lg_next = a_lex_ghosts;
295 a_lex_ghosts = gp;
296 memcpy(gp->lg_name, argv[0], nl);
297 cp = gp->lg_cmd.s = gp->lg_name + nl;
298 gp->lg_cmd.l = --cl;
300 while(*++argv != NULL)
301 if((i = strlen(*argv)) > 0){
302 memcpy(cp, *argv, i);
303 cp += i;
304 *cp++ = ' ';
306 *--cp = '\0';
307 jleave:
308 NYD_LEAVE;
309 return v == NULL;
312 static int
313 a_lex_c_unghost(void *v){
314 struct a_lex_ghost *lgp, *gp;
315 char const **argv, *cp;
316 int rv;
317 NYD_ENTER;
319 rv = 0;
320 argv = v;
322 while((cp = *argv++) != NULL){
323 if(cp[0] == '*' && cp[1] == '\0'){
324 while((gp = a_lex_ghosts) != NULL){
325 a_lex_ghosts = gp->lg_next;
326 free(gp);
328 }else{
329 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
330 lgp = gp, gp = gp->lg_next)
331 if(!strcmp(gp->lg_name, cp)){
332 if(lgp != NULL)
333 lgp->lg_next = gp->lg_next;
334 else
335 a_lex_ghosts = gp->lg_next;
336 free(gp);
337 goto jouter;
339 n_err(_("`unghost': no such alias: %s\n"),
340 n_shexp_quote_cp(cp, FAL0));
341 rv = 1;
342 jouter: ;
345 NYD_LEAVE;
346 return rv;
349 static int
350 a_lex_c_list(void *v){
351 FILE *fp;
352 struct a_lex_cmd const **cpa, *cp, **cursor;
353 size_t l, i;
354 NYD_ENTER;
356 i = n_NELEM(a_lex_cmd_tab) + n_NELEM(a_lex_special_cmd_tab) +1;
357 cpa = salloc(sizeof(cp) * i);
359 for(i = 0; i < n_NELEM(a_lex_cmd_tab); ++i)
360 cpa[i] = &a_lex_cmd_tab[i];
361 /* C99 */{
362 size_t j;
364 for(j = 0; j < n_NELEM(a_lex_special_cmd_tab); ++i, ++j)
365 cpa[i] = &a_lex_special_cmd_tab[j];
367 cpa[i] = NULL;
369 /* C99 */{
370 char const *xcp = v;
372 if(*xcp == '\0')
373 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
376 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
377 fp = stdout;
379 fprintf(fp, _("Commands are:\n"));
380 l = 1;
381 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
382 if(cp->lc_func == &c_cmdnotsupp)
383 continue;
384 if(options & OPT_D_V){
385 char const *argt;
387 switch(cp->lc_argtype & ARG_ARGMASK){
388 case ARG_MSGLIST: argt = N_("message-list"); break;
389 case ARG_STRLIST: argt = N_("a \"string\""); break;
390 case ARG_RAWLIST: argt = N_("old-style quoting"); break;
391 case ARG_NOLIST: argt = N_("no arguments"); break;
392 case ARG_NDMLIST: argt = N_("message-list (without a default)"); break;
393 case ARG_WYSHLIST: argt = N_("sh(1)ell-style quoting"); break;
394 default: argt = N_("`wysh' for sh(1)ell-style quoting"); break;
396 #ifdef HAVE_DOCSTRINGS
397 fprintf(fp, _("`%s'. Argument type: %s.\n\t%s\n"),
398 cp->lc_name, V_(argt), V_(cp->lc_doc));
399 l += 2;
400 #else
401 fprintf(fp, "`%s' (%s)\n", cp->lc_name, argt);
402 ++l;
403 #endif
404 }else{
405 size_t j = strlen(cp->lc_name) + 2;
407 if((i += j) > 72){
408 i = j;
409 fprintf(fp, "\n");
410 ++l;
412 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
416 if(fp != stdout){
417 page_or_print(fp, l);
418 Fclose(fp);
420 NYD_LEAVE;
421 return 0;
424 static int
425 a_lex__pcmd_cmp(void const *s1, void const *s2){
426 struct a_lex_cmd const * const *cp1, * const *cp2;
427 int rv;
428 NYD2_ENTER;
430 cp1 = s1;
431 cp2 = s2;
432 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
433 NYD2_LEAVE;
434 return rv;
437 static int
438 a_lex_c_help(void *v){
439 int rv;
440 char *arg;
441 NYD_ENTER;
443 /* Help for a single command? */
444 if((arg = *(char**)v) != NULL){
445 struct a_lex_ghost const *gp;
446 struct a_lex_cmd const *cp, *cpmax;
448 /* Ghosts take precedence */
449 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
450 if(!strcmp(arg, gp->lg_name)){
451 printf("%s -> ", arg);
452 arg = gp->lg_cmd.s;
453 break;
456 cpmax = &(cp = a_lex_cmd_tab)[n_NELEM(a_lex_cmd_tab)];
457 jredo:
458 for(; PTRCMP(cp, <, cpmax); ++cp){
459 #ifdef HAVE_DOCSTRINGS
460 # define a_DS V_(cp->lc_doc)
461 #else
462 # define a_DS n_empty
463 #endif
464 if(!strcmp(arg, cp->lc_name))
465 printf("%s: %s", arg, a_DS);
466 else if(is_prefix(arg, cp->lc_name))
467 printf("%s (%s): %s", arg, cp->lc_name, a_DS);
468 else
469 continue;
471 if(options & OPT_D_V){
472 char const *atp;
474 switch(cp->lc_argtype & ARG_ARGMASK){
475 case ARG_MSGLIST: atp = N_("message-list"); break;
476 case ARG_STRLIST: atp = N_("a \"string\""); break;
477 case ARG_RAWLIST: atp = N_("old-style quoting"); break;
478 case ARG_NOLIST: atp = N_("no arguments"); break;
479 case ARG_NDMLIST: atp = N_("message-list (no default)"); break;
480 case ARG_WYSHLIST: atp = N_("sh(1)ell-style quoting"); break;
481 default: atp = N_("`wysh' for sh(1)ell-style quoting"); break;
483 #ifdef HAVE_DOCSTRINGS
484 printf(_("\n\tArgument type: %s"), V_(atp));
485 #else
486 printf(_("argument type: %s"), V_(atp));
487 #endif
488 #undef a_DS
490 putchar('\n');
491 rv = 0;
492 goto jleave;
495 if(PTRCMP(cpmax, ==, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)])){
496 cpmax = &(cp = a_lex_special_cmd_tab)[n_NELEM(a_lex_special_cmd_tab)];
497 goto jredo;
500 if(gp != NULL){
501 printf("%s\n", n_shexp_quote_cp(arg, TRU1));
502 rv = 0;
503 }else{
504 n_err(_("Unknown command: `%s'\n"), arg);
505 rv = 1;
507 }else{
508 /* Very ugly, but take care for compiler supported string lengths :( */
509 fputs(progname, stdout);
510 fputs(_(
511 " commands -- <msglist> denotes message specifications,\n"
512 "e.g., 1-5, :n or ., separated by spaces:\n"), stdout);
513 fputs(_(
514 "\n"
515 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
516 "Type <msglist> like `type' but always show all headers\n"
517 "next goto and type next message\n"
518 "from <msglist> (search and) print header summary for the given list\n"
519 "headers header summary for messages surrounding \"dot\"\n"
520 "delete <msglist> delete messages (can be `undelete'd)\n"),
521 stdout);
523 fputs(_(
524 "\n"
525 "save <msglist> folder append messages to folder and mark as saved\n"
526 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
527 "write <msglist> file write message contents to file (prompts for parts)\n"
528 "Reply <msglist> reply to message senders only\n"
529 "reply <msglist> like `Reply', but address all recipients\n"
530 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
531 stdout);
533 fputs(_(
534 "\n"
535 "mail <recipients> compose a mail for the given recipients\n"
536 "file folder change to another mailbox\n"
537 "File folder like `file', but open readonly\n"
538 "quit quit and apply changes to the current mailbox\n"
539 "xit or exit like `quit', but discard changes\n"
540 "!shell command shell escape\n"
541 "list [<anything>] all available commands [in search order]\n"),
542 stdout);
544 rv = (ferror(stdout) != 0);
546 jleave:
547 NYD_LEAVE;
548 return rv;
551 static int
552 a_lex_c_quit(void *v){
553 NYD_ENTER;
554 n_UNUSED(v);
556 /* If we are PS_SOURCING, then return 1 so _evaluate() can handle it.
557 * Otherwise return -1 to abort command loop */
558 pstate |= PS_EXIT;
559 NYD_LEAVE;
560 return 0;
563 static int
564 a_lex_c_version(void *v){
565 int longest, rv;
566 char *iop;
567 char const *cp, **arr;
568 size_t i, i2;
569 NYD_ENTER;
570 n_UNUSED(v);
572 printf(_("%s version %s\nFeatures included (+) or not (-)\n"),
573 uagent, ok_vlook(version));
575 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
576 i = strlen(cp = &ok_vlook(features)[1]) +1;
577 iop = salloc(i);
578 memcpy(iop, cp, i);
580 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
581 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
582 arr[i] = cp;
583 i2 = strlen(cp);
584 longest = n_MAX(longest, (int)i2);
586 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
588 for(++longest, i2 = 0; i-- > 0;){
589 cp = *(arr++);
590 printf("%-*s ", longest, cp);
591 i2 += longest;
592 if(UICMP(z, ++i2 + longest, >=, scrnwidth) || i == 0){
593 i2 = 0;
594 putchar('\n');
598 if((rv = ferror(stdout) != 0))
599 clearerr(stdout);
600 NYD_LEAVE;
601 return rv;
604 static int
605 a_lex__version_cmp(void const *s1, void const *s2){
606 char const * const *cp1, * const *cp2;
607 int rv;
608 NYD2_ENTER;
610 cp1 = s1;
611 cp2 = s2;
612 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
613 NYD2_LEAVE;
614 return rv;
617 static void
618 a_lex_update_pstate(void){
619 NYD_ENTER;
621 if(pstate & PS_SIGWINCH_PEND){
622 char buf[32];
624 snprintf(buf, sizeof buf, "%d", scrnwidth);
625 ok_vset(COLUMNS, buf);
626 snprintf(buf, sizeof buf, "%d", scrnheight);
627 ok_vset(LINES, buf);
630 pstate &= ~PS_PSTATE_PENDMASK;
631 NYD_LEAVE;
634 static int
635 a_lex_evaluate(struct a_lex_eval_ctx *evp){
636 /* xxx old style(9), but also old code */
637 struct str line;
638 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
639 struct a_lex_ghost *gp;
640 struct a_lex_cmd const *cmd;
641 int c, e;
642 bool_t wysh;
643 NYD_ENTER;
645 wysh = FAL0;
646 e = 1;
647 cmd = NULL;
648 gp = NULL;
649 line = evp->le_line; /* XXX don't change original (buffer pointer) */
650 assert(line.s[line.l] == '\0');
651 evp->le_add_history = FAL0;
652 evp->le_new_content = NULL;
654 /* Command ghosts that refer to shell commands or macro expansion restart */
655 jrestart:
657 /* Strip the white space away from end and beginning of command */
658 if(line.l > 0){
659 size_t i = line.l;
661 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
662 --i;
663 line.l = i;
665 for(cp = line.s; spacechar(*cp); ++cp)
667 line.l -= PTR2SIZE(cp - line.s);
669 /* Ignore null commands (comments) */
670 if(*cp == '#')
671 goto jleave0;
673 /* Handle ! differently to get the correct lexical conventions */
674 arglist[0] = cp;
675 if(*cp == '!')
676 ++cp;
677 /* Isolate the actual command; since it may not necessarily be
678 * separated from the arguments (as in `p1') we need to duplicate it to
679 * be able to create a NUL terminated version.
680 * We must be aware of several special one letter commands here */
681 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
682 (*cp == '|' || *cp == '~' || *cp == '?'))
683 ++cp;
684 c = (int)PTR2SIZE(cp - arglist[0]);
685 line.l -= c;
686 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
687 memcpy(word, arglist[0], c);
688 word[c] = '\0';
690 /* Look up the command; if not found, bitch.
691 * Normally, a blank command would map to the first command in the
692 * table; while PS_SOURCING, however, we ignore blank lines to eliminate
693 * confusion; act just the same for ghosts */
694 if(*word == '\0'){
695 if((pstate & PS_ROBOT) || gp != NULL)
696 goto jleave0;
697 cmd = a_lex_cmd_tab + 0;
698 goto jexec;
701 /* XXX It may be the argument parse adjuster */
702 if(!wysh && c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
703 wysh = TRU1;
704 line.s = cp;
705 goto jrestart;
708 /* If this is the first evaluation, check command ghosts */
709 if(gp == NULL){
710 /* TODO relink list head, so it's sorted on usage over time?
711 * TODO in fact, there should be one hashmap over all commands and ghosts
712 * TODO so that the lookup could be made much more efficient than it is
713 * TODO now (two adjacent list searches! */
714 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
715 if(!strcmp(word, gp->lg_name)){
716 if(line.l > 0){
717 size_t i;
719 i = gp->lg_cmd.l;
720 line.s = salloc(i + line.l +1);
721 memcpy(line.s, gp->lg_cmd.s, i);
722 memcpy(line.s + i, cp, line.l);
723 line.s[i += line.l] = '\0';
724 line.l = i;
725 }else{
726 line.s = gp->lg_cmd.s;
727 line.l = gp->lg_cmd.l;
729 goto jrestart;
733 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
734 bool_t s;
736 if(!(s = condstack_isskip()) || (options & OPT_D_V))
737 n_err(_("Unknown command%s: `%s'\n"),
738 (s ? _(" (ignored due to `if' condition)") : n_empty), word);
739 if(s)
740 goto jleave0;
741 if(cmd != NULL){
742 c_cmdnotsupp(NULL);
743 cmd = NULL;
745 goto jleave;
748 /* See if we should execute the command -- if a conditional we always
749 * execute it, otherwise, check the state of cond */
750 jexec:
751 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
752 goto jleave0;
754 /* Process the arguments to the command, depending on the type it expects */
755 if(!(cmd->lc_argtype & ARG_M) && (options & OPT_SENDMODE)){
756 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
757 goto jleave;
759 if((cmd->lc_argtype & ARG_S) && !(pstate & PS_STARTED)){
760 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
761 goto jleave;
763 if((cmd->lc_argtype & ARG_I) &&
764 !(options & (OPT_INTERACTIVE | OPT_BATCH_FLAG))){
765 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
766 cmd->lc_name);
767 goto jleave;
769 if(cmd->lc_argtype & ARG_R){
770 if(pstate & PS_RECURSED){
771 /* TODO PS_RECURSED: should allow `reply' in compose mode: ~:reply! */
772 n_err(_("Cannot invoke `%s' when in compose mode\n"), cmd->lc_name);
773 goto jleave;
775 /* TODO Nothing should prevent ARG_R in conjunction with
776 * TODO PS_ROBOT|_SOURCING; see a.._may_yield_control()! */
777 if(pstate & (PS_ROBOT | PS_SOURCING)){
778 n_err(_("Cannot invoke `%s' from a macro or during file inclusion\n"),
779 cmd->lc_name);
780 goto jleave;
784 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
785 n_err(_("May not execute `%s' -- message file is read only\n"),
786 cmd->lc_name);
787 goto jleave;
789 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
790 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
791 goto jleave;
794 if(cmd->lc_argtype & ARG_O)
795 OBSOLETE2(_("this command will be removed"), cmd->lc_name);
796 if(cmd->lc_argtype & ARG_V)
797 temporary_arg_v_store = NULL;
799 if(wysh && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST)
800 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
801 /* TODO v15: strip PS_ARGLIST_MASK off, just in case the actual command
802 * TODO doesn't use any of those list commands which strip this mask,
803 * TODO and for now we misuse bits for checking relation to history;
804 * TODO argument state should be property of a per-command carrier instead */
805 pstate &= ~PS_ARGLIST_MASK;
806 switch(cmd->lc_argtype & ARG_ARGMASK){
807 case ARG_MSGLIST:
808 /* Message list defaulting to nearest forward legal message */
809 if(n_msgvec == NULL)
810 goto je96;
811 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
812 break;
813 if(c == 0){
814 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
815 n_msgvec[1] = 0;
817 if(n_msgvec[0] == 0){
818 if(!(pstate & PS_HOOK_MASK))
819 printf(_("No applicable messages\n"));
820 break;
822 e = (*cmd->lc_func)(n_msgvec);
823 break;
825 case ARG_NDMLIST:
826 /* Message list with no defaults, but no error if none exist */
827 if(n_msgvec == NULL){
828 je96:
829 n_err(_("Invalid use of message list\n"));
830 break;
832 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
833 break;
834 e = (*cmd->lc_func)(n_msgvec);
835 break;
837 case ARG_STRLIST:
838 /* Just the straight string, with leading blanks removed */
839 while(whitechar(*cp))
840 ++cp;
841 e = (*cmd->lc_func)(cp);
842 break;
844 case ARG_WYSHLIST:
845 c = 1;
846 if(0){
847 /* FALLTHRU */
848 case ARG_WYRALIST:
849 c = wysh ? 1 : 0;
850 if(0){
851 case ARG_RAWLIST:
852 c = 0;
856 if((c = getrawlist((c != 0), arglist, n_NELEM(arglist), cp, line.l)) < 0){
857 n_err(_("Invalid argument list\n"));
858 break;
860 if(c < cmd->lc_minargs){
861 n_err(_("`%s' requires at least %d arg(s)\n"),
862 cmd->lc_name, cmd->lc_minargs);
863 break;
865 #undef lc_minargs
866 if(c > cmd->lc_maxargs){
867 n_err(_("`%s' takes no more than %d arg(s)\n"),
868 cmd->lc_name, cmd->lc_maxargs);
869 break;
871 #undef lc_maxargs
872 e = (*cmd->lc_func)(arglist);
873 break;
875 case ARG_NOLIST:
876 /* Just the constant zero, for exiting, eg. */
877 e = (*cmd->lc_func)(0);
878 break;
880 default:
881 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
882 cmd->lc_argtype & ARG_ARGMASK); )
883 goto jleave0;
886 if(e == 0 && (cmd->lc_argtype & ARG_V) &&
887 (cp = temporary_arg_v_store) != NULL){
888 temporary_arg_v_store = NULL;
889 evp->le_new_content = cp;
890 goto jleave0;
892 if(!(cmd->lc_argtype & ARG_H))
893 evp->le_add_history = (((cmd->lc_argtype & ARG_G) ||
894 (pstate & PS_MSGLIST_GABBY)) ? TRUM1 : TRU1);
896 jleave:
897 /* C99 */{
898 bool_t reset = !(pstate & PS_ROOT);
900 pstate |= PS_ROOT;
901 ok_vset(_exit_status, (e == 0 ? "0" : "1")); /* TODO num=1 +real value! */
902 if(reset)
903 pstate &= ~PS_ROOT;
906 /* Exit the current source file on error TODO what a mess! */
907 if(e == 0)
908 pstate &= ~PS_EVAL_ERROR;
909 else{
910 pstate |= PS_EVAL_ERROR;
911 if(e < 0 || (pstate & PS_ROBOT)){ /* FIXME */
912 e = 1;
913 goto jret;
915 goto jret0;
918 if(cmd == NULL)
919 goto jret0;
920 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint))
921 if(visible(dot)){
922 line.s = savestr("type");
923 line.l = sizeof("type") -1;
924 gp = (struct a_lex_ghost*)-1; /* Avoid `ghost' interpretation */
925 goto jrestart;
928 if(!(pstate & (PS_SOURCING | PS_HOOK_MASK)) && !(cmd->lc_argtype & ARG_T))
929 pstate |= PS_SAW_COMMAND;
930 jleave0:
931 pstate &= ~PS_EVAL_ERROR;
932 jret0:
933 e = 0;
934 jret:
936 fprintf(stderr, "a_lex_evaluate returns %d for <%s>\n",e,line.s);
938 NYD_LEAVE;
939 return e;
942 static struct a_lex_cmd const *
943 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
944 struct a_lex_cmd const *cp;
945 NYD2_ENTER;
947 for(cp = a_lex_cmd_tab;
948 PTRCMP(cp, <, &a_lex_cmd_tab[n_NELEM(a_lex_cmd_tab)]); ++cp)
949 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
950 goto jleave;
951 cp = NULL;
952 jleave:
953 NYD2_LEAVE;
954 return cp;
957 static void
958 a_lex_hangup(int s){
959 NYD_X; /* Signal handler */
960 n_UNUSED(s);
961 /* nothing to do? */
962 exit(EXIT_ERR);
965 static void
966 a_lex_onintr(int s){ /* TODO block signals while acting */
967 NYD_X; /* Signal handler */
968 n_UNUSED(s);
970 safe_signal(SIGINT, a_lex_onintr);
972 termios_state_reset();
973 close_all_files(); /* FIXME .. of current level ONLU! */
974 if(image >= 0){
975 close(image);
976 image = -1;
979 a_lex_unstack(TRUM1);
981 if(interrupts != 1)
982 n_err_sighdl(_("Interrupt\n"));
983 safe_signal(SIGPIPE, a_lex_oldpipe);
984 siglongjmp(a_lex_srbuf, 0); /* FIXME get rid */
987 static void
988 a_lex_unstack(bool_t eval_error){
989 struct a_lex_input_stack *lip;
990 NYD_ENTER;
992 if((lip = a_lex_input) == NULL){
993 n_memory_reset();
995 /* If called from a_lex_onintr(), be silent FIXME */
996 pstate &= ~(PS_SOURCING | PS_ROBOT);
997 if(eval_error == TRUM1 || !(pstate & PS_STARTED))
998 goto jleave;
999 goto jerr;
1002 if(lip->li_flags & a_LEX_SLICE){ /* TODO Temporary hack */
1003 stdin = lip->li_slice_stdin;
1004 stdout = lip->li_slice_stdout;
1005 options = lip->li_slice_options;
1006 goto jthe_slice_hack;
1009 if(lip->li_flags & a_LEX_MACRO){
1010 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
1011 char **lp;
1013 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
1014 free(*lp);
1015 ++lip->li_loff;
1017 /* Part of lip's memory chunk, then */
1018 if(!(lip->li_flags & a_LEX_MACRO_CMD))
1019 free(lip->li_lines);
1021 }else{
1022 if(lip->li_flags & a_LEX_PIPE)
1023 /* XXX command manager should -TERM then -KILL instead of hoping
1024 * XXX for exit of provider due to EPIPE / SIGPIPE */
1025 Pclose(lip->li_file, TRU1);
1026 else
1027 Fclose(lip->li_file);
1030 if(!condstack_take(lip->li_cond)){
1031 n_err(_("Unmatched `if' at end of %s %s\n"),
1032 ((lip->li_flags & a_LEX_MACRO
1033 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
1034 : _("`source'd file"))),
1035 lip->li_name);
1036 eval_error = TRU1;
1039 n_memory_autorec_pop(&lip->li_autorecmem[0]);
1041 jthe_slice_hack:
1042 if(lip->li_on_finalize != NULL)
1043 (*lip->li_on_finalize)(lip->li_finalize_arg);
1045 if((a_lex_input = lip->li_outer) == NULL){
1046 pstate &= ~(PS_SOURCING | PS_ROBOT);
1047 }else{
1048 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
1049 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
1050 pstate &= ~PS_SOURCING;
1051 assert(pstate & PS_ROBOT);
1054 if(eval_error)
1055 goto jerr;
1056 jleave:
1057 if(lip != NULL && (lip->li_flags & a_LEX_FREE))
1058 free(lip);
1059 if(n_UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
1060 a_lex_unstack(TRUM1);
1061 NYD_LEAVE;
1062 return;
1064 jerr:
1065 if(lip != NULL){
1066 if(options & OPT_D_V)
1067 n_alert(_("Stopped %s %s due to errors%s"),
1068 (pstate & PS_STARTED
1069 ? (lip->li_flags & a_LEX_SLICE ? _("sliced in program")
1070 : (lip->li_flags & a_LEX_MACRO
1071 ? (lip->li_flags & a_LEX_MACRO_CMD
1072 ? _("evaluating command") : _("evaluating macro"))
1073 : (lip->li_flags & a_LEX_PIPE
1074 ? _("executing `source'd pipe")
1075 : _("loading `source'd file")))
1077 : (lip->li_flags & a_LEX_MACRO
1078 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1079 ? _("evaluating command line") : _("evaluating macro"))
1080 : _("loading initialization resource"))),
1081 lip->li_name,
1082 (options & OPT_DEBUG ? n_empty : _(" (enable *debug* for trace)")));
1085 if(!(options & OPT_INTERACTIVE) && !(pstate & PS_STARTED)){
1086 if(options & OPT_D_V)
1087 n_alert(_("Non-interactive, bailing out due to errors "
1088 "in startup load phase"));
1089 exit(EXIT_ERR);
1091 goto jleave;
1094 static bool_t
1095 a_lex_source_file(char const *file, bool_t silent_error){
1096 struct a_lex_input_stack *lip;
1097 size_t nlen;
1098 char *nbuf;
1099 bool_t ispipe;
1100 FILE *fip;
1101 NYD_ENTER;
1103 fip = NULL;
1105 /* Being a command argument file is space-trimmed *//* TODO v15 with
1106 * TODO WYRALIST this is no longer necessary true, and for that we
1107 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1108 #if 0
1109 ((ispipe = (!silent_error && (nlen = strlen(file)) > 0 &&
1110 file[--nlen] == '|')))
1111 #else
1112 ispipe = FAL0;
1113 if(!silent_error)
1114 for(nlen = strlen(file); nlen > 0;){
1115 char c;
1117 c = file[--nlen];
1118 if(!blankchar(c)){
1119 if(c == '|'){
1120 nbuf = savestrbuf(file, nlen);
1121 ispipe = TRU1;
1122 break;
1126 #endif
1128 if(ispipe){
1129 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1130 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL){
1131 if(!silent_error || (options & OPT_D_V))
1132 n_perr(nbuf, 0);
1133 goto jleave;
1135 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1136 goto jleave;
1137 else if((fip = Fopen(nbuf, "r")) == NULL){
1138 if(!silent_error || (options & OPT_D_V))
1139 n_perr(nbuf, 0);
1140 goto jleave;
1143 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
1144 (nlen = strlen(nbuf) +1));
1145 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1146 lip->li_outer = a_lex_input;
1147 lip->li_file = fip;
1148 lip->li_cond = condstack_release();
1149 n_memory_autorec_push(&lip->li_autorecmem[0]);
1150 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1151 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1152 ? a_LEX_SUPER_MACRO : 0);
1153 memcpy(lip->li_name, nbuf, nlen);
1155 pstate |= PS_SOURCING | PS_ROBOT;
1156 a_lex_input = lip;
1157 a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC);
1158 /* FIXME return TRUM1 if file can't be opened, FAL0 on eval error */
1159 jleave:
1160 NYD_LEAVE;
1161 return silent_error ? TRU1 : (fip != NULL);
1164 static bool_t
1165 a_lex_load(struct a_lex_input_stack *lip){
1166 bool_t rv;
1167 NYD2_ENTER;
1169 assert(!(pstate & PS_STARTED));
1170 assert(a_lex_input == NULL);
1172 /* POSIX:
1173 * Any errors in the start-up file shall either cause mailx to terminate
1174 * with a diagnostic message and a non-zero status or to continue after
1175 * writing a diagnostic message, ignoring the remainder of the lines in
1176 * the start-up file. */
1177 lip->li_cond = condstack_release();
1178 n_memory_autorec_push(&lip->li_autorecmem[0]);
1180 /* FIXME won't work for now (PS_ROBOT needs PS_SOURCING anyway)
1181 pstate |= PS_ROBOT |
1182 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : PS_SOURCING);
1184 pstate |= PS_ROBOT | PS_SOURCING;
1185 if(options & OPT_D_V)
1186 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1187 a_lex_input = lip;
1188 if(!(rv = n_commands())){
1189 if(!(options & OPT_INTERACTIVE)){
1190 if(options & OPT_D_V)
1191 n_alert(_("Non-interactive program mode, forced exit"));
1192 exit(EXIT_ERR);
1195 /* PS_EXIT handled by callers */
1196 NYD2_LEAVE;
1197 return rv;
1200 static void
1201 a_lex__cmdrecint(int sig){ /* TODO one day, we don't need it no more */
1202 NYD_X; /* Signal handler */
1203 n_UNUSED(sig);
1204 siglongjmp(a_lex_input->li_cmdrec_jmp, 1);
1207 static bool_t
1208 a_commands_recursive(enum n_lexinput_flags lif){
1209 volatile int hadint; /* TODO get rid of shitty signal stuff (see signal.c) */
1210 sighandler_type soldhdl;
1211 sigset_t sintset, soldset;
1212 struct a_lex_eval_ctx ev;
1213 bool_t rv;
1214 NYD2_ENTER;
1216 memset(&ev, 0, sizeof ev);
1218 sigfillset(&sintset);
1219 sigprocmask(SIG_BLOCK, &sintset, &soldset);
1220 hadint = FAL0;
1221 if((soldhdl = safe_signal(SIGINT, SIG_IGN)) != SIG_IGN){
1222 safe_signal(SIGINT, &a_lex__cmdrecint);
1223 if(sigsetjmp(a_lex_input->li_cmdrec_jmp, 1)){
1224 hadint = TRU1;
1225 goto jjump;
1228 sigprocmask(SIG_SETMASK, &soldset, NULL);
1230 n_COLOUR( n_colour_env_push(); )
1231 rv = TRU1;
1232 for(;;){
1233 int n;
1235 /* Read a line of commands and handle end of file specially */
1236 ev.le_line.l = ev.le_line_size;
1237 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l,
1238 ev.le_new_content);
1239 ev.le_line_size = (ui32_t)ev.le_line.l;
1240 ev.le_line.l = (ui32_t)n;
1242 if(n < 0)
1243 break;
1245 if(a_lex_evaluate(&ev)){
1246 rv = FAL0;
1247 break;
1249 n_memory_reset();
1251 if((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)){
1252 if(exit_status != EXIT_OK)
1253 break;
1256 jjump: /* TODO */
1257 a_lex_unstack(!rv);
1258 n_COLOUR( n_colour_env_pop(FAL0); )
1260 if(ev.le_line.s != NULL)
1261 free(ev.le_line.s);
1263 if(soldhdl != SIG_IGN)
1264 safe_signal(SIGINT, soldhdl);
1265 NYD2_LEAVE;
1266 if(hadint){
1267 sigprocmask(SIG_SETMASK, &soldset, NULL);
1268 n_raise(SIGINT);
1270 return rv;
1273 FL bool_t
1274 n_commands(void){ /* FIXME */
1275 struct a_lex_eval_ctx ev;
1276 int n;
1277 bool_t volatile rv;
1278 NYD_ENTER;
1280 rv = TRU1;
1282 if (!(pstate & PS_SOURCING)) {
1283 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1284 safe_signal(SIGINT, &a_lex_onintr);
1285 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1286 safe_signal(SIGHUP, &a_lex_hangup);
1288 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1289 safe_signal(SIGPIPE, a_lex_oldpipe);
1291 memset(&ev, 0, sizeof ev);
1293 (void)sigsetjmp(a_lex_srbuf, 1); /* FIXME get rid */
1294 for (;;) {
1295 char *temporary_orig_line; /* XXX eval_ctx.le_line not yet constant */
1297 n_COLOUR( n_colour_env_pop(TRU1); )
1299 /* TODO Unless we have our signal manager (or however we do it) child
1300 * TODO processes may have time slots where their execution isn't
1301 * TODO protected by signal handlers (in between start and setup
1302 * TODO completed). close_all_files() is only called from onintr()
1303 * TODO so those may linger possibly forever */
1304 if(!(pstate & PS_SOURCING))
1305 close_all_files();
1307 interrupts = 0;
1309 n_memory_reset();
1311 if (!(pstate & PS_SOURCING)) {
1312 char *cp;
1314 /* TODO Note: this buffer may contain a password. We should redefine
1315 * TODO the code flow which has to do that */
1316 if ((cp = termios_state.ts_linebuf) != NULL) {
1317 termios_state.ts_linebuf = NULL;
1318 termios_state.ts_linesize = 0;
1319 free(cp); /* TODO pool give-back */
1321 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1322 if (ev.le_line.l > LINESIZE * 3) {
1323 free(ev.le_line.s); /* TODO pool! but what? */
1324 ev.le_line.s = NULL;
1325 ev.le_line.l = ev.le_line_size = 0;
1329 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1330 char *cp;
1332 cp = ok_vlook(newmail);
1333 if ((options & OPT_TTYIN) && cp != NULL) {
1334 struct stat st;
1336 /* FIXME TEST WITH NOPOLL ETC. !!! */
1337 n = (cp != NULL && strcmp(cp, "nopoll"));
1338 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1339 st.st_size > mailsize) ||
1340 (mb.mb_type == MB_MAILDIR && n != 0)) {
1341 size_t odot = PTR2SIZE(dot - message);
1342 ui32_t odid = (pstate & PS_DID_PRINT_DOT);
1344 if (setfile(mailname,
1345 FEDIT_NEWMAIL |
1346 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1347 exit_status |= EXIT_ERR;
1348 rv = FAL0;
1349 break;
1351 dot = message + odot;
1352 pstate |= odid;
1356 exit_status = EXIT_OK;
1359 /* Read a line of commands and handle end of file specially */
1360 jreadline:
1361 ev.le_line.l = ev.le_line_size;
1362 n = n_lex_input(n_LEXINPUT_CTX_DEFAULT | n_LEXINPUT_NL_ESC, NULL,
1363 &ev.le_line.s, &ev.le_line.l, ev.le_new_content);
1364 ev.le_line_size = (ui32_t)ev.le_line.l;
1365 ev.le_line.l = (ui32_t)n;
1367 if (n < 0) {
1368 /* FIXME did unstack() when PS_SOURCING, only break with PS_LOADING*/
1369 if (!(pstate & PS_ROBOT) &&
1370 (options & OPT_INTERACTIVE) && ok_blook(ignoreeof)) {
1371 printf(_("*ignoreeof* set, use `quit' to quit.\n"));
1372 n_msleep(500, FAL0);
1373 continue;
1375 break;
1378 temporary_orig_line = ((pstate & PS_SOURCING) ||
1379 !(options & OPT_INTERACTIVE)) ? NULL
1380 : savestrbuf(ev.le_line.s, ev.le_line.l);
1381 pstate &= ~PS_HOOK_MASK;
1382 if (a_lex_evaluate(&ev)) {
1383 if (!(pstate & PS_STARTED)) /* TODO mess; join PS_EVAL_ERROR.. */
1384 rv = FAL0;
1385 break;
1388 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
1389 if (exit_status != EXIT_OK)
1390 break;
1391 if ((pstate & (PS_SOURCING | PS_EVAL_ERROR)) == PS_EVAL_ERROR) {
1392 exit_status = EXIT_ERR;
1393 break;
1396 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1397 if (ev.le_new_content != NULL)
1398 goto jreadline;
1399 /* *Can* happen since _evaluate() n_unstack()s on error! XXX no more */
1400 if (temporary_orig_line != NULL)
1401 n_tty_addhist(temporary_orig_line, (ev.le_add_history != TRU1));
1404 if(pstate & PS_EXIT)
1405 break;
1408 a_lex_unstack(!rv);
1410 if (ev.le_line.s != NULL)
1411 free(ev.le_line.s);
1412 NYD_LEAVE;
1413 return rv;
1416 FL int
1417 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1418 size_t *linesize, char const *string n_MEMORY_DEBUG_ARGS){
1419 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1420 struct n_string xprompt;
1421 FILE *ifile;
1422 bool_t doprompt, dotty;
1423 char const *iftype;
1424 int n, nold;
1425 NYD2_ENTER;
1427 /* Special case macro mode: never need to prompt, lines have always been
1428 * unfolded already */
1429 if(!(lif & n_LEXINPUT_FORCE_STDIN) &&
1430 a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1431 if(*linebuf != NULL)
1432 free(*linebuf);
1434 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1435 *linesize = 0;
1436 n = -1;
1437 goto jleave;
1440 ++a_lex_input->li_loff;
1441 *linesize = strlen(*linebuf);
1442 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1443 *linebuf = sbufdup(*linebuf, *linesize);
1445 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1446 ? "-X OPTION"
1447 : (a_lex_input->li_flags & a_LEX_MACRO_CMD) ? "CMD" : "MACRO";
1448 n = (int)*linesize;
1449 pstate |= PS_READLINE_NL;
1450 goto jhave_dat;
1452 pstate &= ~PS_READLINE_NL;
1454 iftype = (!(pstate & PS_STARTED) ? "LOAD"
1455 : (pstate & PS_SOURCING) ? "SOURCE" : "READ");
1456 doprompt = ((pstate & (PS_STARTED | PS_ROBOT)) == PS_STARTED &&
1457 (options & OPT_INTERACTIVE));
1458 dotty = (doprompt && !ok_blook(line_editor_disable));
1459 if(!doprompt)
1460 lif |= n_LEXINPUT_PROMPT_NONE;
1461 else{
1462 if(!dotty)
1463 n_string_creat_auto(&xprompt);
1464 if(prompt == NULL)
1465 lif |= n_LEXINPUT_PROMPT_EVAL;
1468 /* Ensure stdout is flushed first anyway */
1469 if(!dotty && (lif & n_LEXINPUT_PROMPT_NONE))
1470 fflush(stdout);
1472 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : stdin;
1473 assert(ifile != NULL);
1475 for(nold = n = 0;;){
1476 if(dotty){
1477 assert(ifile == stdin);
1478 if(string != NULL && (n = (int)strlen(string)) > 0){
1479 if(*linesize > 0)
1480 *linesize += n +1;
1481 else
1482 *linesize = (size_t)n + LINESIZE +1;
1483 *linebuf = (n_realloc)(*linebuf, *linesize n_MEMORY_DEBUG_ARGSCALL);
1484 memcpy(*linebuf, string, (size_t)n +1);
1486 string = NULL;
1487 /* TODO if nold>0, don't redisplay the entire line!
1488 * TODO needs complete redesign ... */
1489 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1490 n_MEMORY_DEBUG_ARGSCALL);
1491 }else{
1492 if(!(lif & n_LEXINPUT_PROMPT_NONE)){
1493 n_tty_create_prompt(&xprompt, prompt, lif);
1494 if(xprompt.s_len > 0){
1495 fwrite(xprompt.s_dat, 1, xprompt.s_len, stdout);
1496 fflush(stdout);
1500 n = (readline_restart)(ifile, linebuf, linesize, n
1501 n_MEMORY_DEBUG_ARGSCALL);
1503 if(n > 0 && nold > 0){
1504 int i = 0;
1505 char const *cp = *linebuf + nold;
1507 while(blankspacechar(*cp) && nold + i < n)
1508 ++cp, ++i;
1509 if(i > 0){
1510 memmove(*linebuf + nold, cp, n - nold - i);
1511 n -= i;
1512 (*linebuf)[n] = '\0';
1517 if(n <= 0)
1518 break;
1520 /* POSIX says:
1521 * An unquoted <backslash> at the end of a command line shall
1522 * be discarded and the next line shall continue the command */
1523 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1524 if(dotty)
1525 pstate |= PS_READLINE_NL;
1526 break;
1528 /* Definitely outside of quotes, thus the quoting rules are so that an
1529 * uneven number of successive backslashs at EOL is a continuation */
1530 if(n > 1){
1531 size_t i, j;
1533 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1534 if((*linebuf)[i] != '\\')
1535 break;
1536 if(!(j & 1))
1537 break;
1539 (*linebuf)[nold = --n] = '\0';
1540 lif |= n_LEXINPUT_NL_FOLLOW;
1543 if(n < 0)
1544 goto jleave;
1545 (*linebuf)[*linesize = n] = '\0';
1547 jhave_dat:
1548 #if 0
1549 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1550 char *cp, c;
1551 size_t i;
1553 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1554 c = *--cp;
1555 if(!blankspacechar(c))
1556 break;
1558 (*linebuf)[n = (int)i] = '\0';
1561 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1562 char *cp, c;
1563 size_t j, i;
1565 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1566 c = *cp++;
1567 if(!blankspacechar(c))
1568 break;
1570 if(i > 0){
1571 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1572 (*linebuf)[n = (int)j] = '\0';
1575 #endif /* 0 (notyet - must take care for backslash escaped space) */
1577 if(options & OPT_D_VV)
1578 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1579 jleave:
1580 if (pstate & PS_PSTATE_PENDMASK)
1581 a_lex_update_pstate();
1583 /* TODO We need to special case a_LEX_SLICE, since that is not managed by us
1584 * TODO but only established from the outside and we need to drop this
1585 * TODO overlay context somehow */
1586 if(n < 0 && a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SLICE))
1587 a_lex_unstack(FAL0);
1588 NYD2_LEAVE;
1589 return n;
1592 FL char *
1593 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1594 char const *string){
1595 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1596 size_t linesize;
1597 char *linebuf, *rv;
1598 int n;
1599 NYD2_ENTER;
1601 linesize = 0;
1602 linebuf = NULL;
1603 rv = NULL;
1605 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1606 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1607 (lif & n_LEXINPUT_HIST_ADD) && (options & OPT_INTERACTIVE))
1608 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1610 if(linebuf != NULL)
1611 free(linebuf);
1612 NYD2_LEAVE;
1613 return rv;
1616 FL int
1617 c_read(void *v){ /* TODO IFS? how? -r */
1618 char const **argv, *cp, *cp2;
1619 int rv;
1620 NYD2_ENTER;
1622 rv = 0;
1623 for(argv = v; (cp = *argv++) != NULL;)
1624 if(!n_shexp_is_valid_varname(cp)){
1625 n_err(_("`read': not a valid variable name: %s\n"),
1626 n_shexp_quote_cp(cp, FAL0));
1627 rv = 1;
1629 if(rv)
1630 goto jleave;
1632 cp = n_lex_input_cp(((pstate & PS_RECURSED /* TODO this IS compose-mode! */
1633 ? n_LEXINPUT_CTX_COMPOSE : n_LEXINPUT_CTX_DEFAULT) |
1634 n_LEXINPUT_FORCE_STDIN | n_LEXINPUT_NL_ESC |
1635 n_LEXINPUT_PROMPT_NONE /* XXX POSIX: PS2: yes! */),
1636 NULL, NULL);
1637 if(cp == NULL)
1638 cp = n_empty;
1640 for(argv = v; *argv != NULL; ++argv){
1641 char c;
1643 while(blankchar(*cp))
1644 ++cp;
1645 if(*cp == '\0')
1646 break;
1648 /* The last variable gets the remaining line less trailing IFS */
1649 if(argv[1] == NULL){
1650 for(cp2 = cp; *cp2 != '\0'; ++cp2)
1652 for(; cp2 > cp; --cp2){
1653 c = cp2[-1];
1654 if(!blankchar(c))
1655 break;
1657 }else
1658 for(cp2 = cp; (c = *++cp2) != '\0';)
1659 if(blankchar(c))
1660 break;
1662 vok_vset(*argv, savestrbuf(cp, PTR2SIZE(cp2 - cp)));
1663 cp = cp2;
1666 /* Set the remains to the empty string */
1667 for(; *argv != NULL; ++argv)
1668 vok_vset(*argv, "");
1670 rv = 0;
1671 jleave:
1672 NYD2_LEAVE;
1673 return rv;
1676 FL void
1677 n_load(char const *name){
1678 struct a_lex_input_stack *lip;
1679 size_t i;
1680 FILE *fip;
1681 NYD_ENTER;
1683 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1684 goto jleave;
1686 i = strlen(name) +1;
1687 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) + i);
1688 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1689 lip->li_file = fip;
1690 lip->li_flags = a_LEX_FREE;
1691 memcpy(lip->li_name, name, i);
1693 a_lex_load(lip);
1694 pstate &= ~PS_EXIT;
1695 jleave:
1696 NYD_LEAVE;
1699 FL void
1700 n_load_Xargs(char const **lines, size_t cnt){
1701 static char const name[] = "-X";
1703 ui8_t buf[sizeof(struct a_lex_input_stack) + sizeof name];
1704 char const *srcp, *xsrcp;
1705 char *cp;
1706 size_t imax, i, len;
1707 struct a_lex_input_stack *lip;
1708 NYD_ENTER;
1710 lip = (void*)buf;
1711 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1712 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1713 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1714 memcpy(lip->li_name, name, sizeof name);
1716 /* The problem being that we want to support reverse solidus newline
1717 * escaping also within multiline -X, i.e., POSIX says:
1718 * An unquoted <backslash> at the end of a command line shall
1719 * be discarded and the next line shall continue the command
1720 * Therefore instead of "lip->li_lines = n_UNCONST(lines)", duplicate the
1721 * entire lines array and set _MACRO_FREE_DATA */
1722 imax = cnt + 1;
1723 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
1725 /* For each of the input lines.. */
1726 for(i = len = 0, cp = NULL; cnt > 0;){
1727 bool_t keep;
1728 size_t j;
1730 if((j = strlen(srcp = *lines)) == 0){
1731 ++lines, --cnt;
1732 continue;
1735 /* Separate one line from a possible multiline input string */
1736 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1737 *lines = &xsrcp[1];
1738 j = PTR2SIZE(xsrcp - srcp);
1739 }else
1740 ++lines, --cnt;
1742 /* The (separated) string may itself indicate soft newline escaping */
1743 if((keep = (srcp[j - 1] == '\\'))){
1744 size_t xj, xk;
1746 /* Need an uneven number of reverse solidus */
1747 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1748 if(srcp[xj] != '\\')
1749 break;
1750 if(xk & 1)
1751 --j;
1752 else
1753 keep = FAL0;
1756 /* Strip any leading WS from follow lines, then */
1757 if(cp != NULL)
1758 while(j > 0 && blankspacechar(*srcp))
1759 ++srcp, --j;
1761 if(j > 0){
1762 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1763 imax += 4;
1764 lip->li_lines = n_realloc(lip->li_lines, sizeof(*lip->li_lines) *
1765 imax);
1767 lip->li_lines[i] = cp = n_realloc(cp, len + j +1);
1768 memcpy(&cp[len], srcp, j);
1769 cp[len += j] = '\0';
1771 if(!keep)
1772 ++i;
1774 if(!keep)
1775 cp = NULL, len = 0;
1777 if(cp != NULL){
1778 assert(i + 1 < imax);
1779 lip->li_lines[i++] = cp;
1781 lip->li_lines[i] = NULL;
1783 a_lex_load(lip);
1784 if(pstate & PS_EXIT)
1785 exit(EXIT_OK);
1786 NYD_LEAVE;
1789 FL int
1790 c_source(void *v){
1791 int rv;
1792 NYD_ENTER;
1794 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1795 NYD_LEAVE;
1796 return rv;
1799 FL int
1800 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1801 int rv;
1802 NYD_ENTER;
1804 rv = (a_lex_source_file(*(char**)v, TRU1) != FAL0) ? 0 : 1;
1805 NYD_LEAVE;
1806 return rv;
1809 FL bool_t
1810 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines,
1811 void (*on_finalize)(void*), void *finalize_arg){
1812 struct a_lex_input_stack *lip;
1813 size_t i;
1814 int rv;
1815 NYD_ENTER;
1817 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
1818 (i = strlen(name) +1));
1819 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1820 lip->li_outer = a_lex_input;
1821 lip->li_file = NULL;
1822 lip->li_cond = condstack_release();
1823 n_memory_autorec_push(&lip->li_autorecmem[0]);
1824 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1825 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1826 ? a_LEX_SUPER_MACRO : 0);
1827 lip->li_lines = lines;
1828 lip->li_on_finalize = on_finalize;
1829 lip->li_finalize_arg = finalize_arg;
1830 memcpy(lip->li_name, name, i);
1832 pstate |= PS_ROBOT;
1833 a_lex_input = lip;
1834 rv = a_commands_recursive(lif);
1835 NYD_LEAVE;
1836 return rv;
1839 FL bool_t
1840 n_source_command(enum n_lexinput_flags lif, char const *cmd){
1841 struct a_lex_input_stack *lip;
1842 size_t i, ial;
1843 bool_t rv;
1844 NYD_ENTER;
1846 i = strlen(cmd) +1;
1847 ial = n_ALIGN(i);
1849 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
1850 ial + 2*sizeof(char*));
1851 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1852 lip->li_outer = a_lex_input;
1853 lip->li_cond = condstack_release();
1854 n_memory_autorec_push(&lip->li_autorecmem[0]);
1855 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_CMD |
1856 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1857 ? a_LEX_SUPER_MACRO : 0);
1858 lip->li_lines = (void*)&lip->li_name[ial];
1859 memcpy(lip->li_lines[0] = &lip->li_name[0], cmd, i);
1860 lip->li_lines[1] = NULL;
1862 pstate |= PS_ROBOT;
1863 a_lex_input = lip;
1864 rv = a_commands_recursive(lif);
1865 NYD_LEAVE;
1866 return rv;
1869 FL void
1870 n_source_slice_hack(char const *cmd, FILE *new_stdin, FILE *new_stdout,
1871 ui32_t new_options, void (*on_finalize)(void*), void *finalize_arg){
1872 struct a_lex_input_stack *lip;
1873 size_t i;
1874 NYD_ENTER;
1876 lip = smalloc(n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name) +
1877 (i = strlen(cmd) +1));
1878 memset(lip, 0, n_VSTRUCT_SIZEOF(struct a_lex_input_stack, li_name));
1879 lip->li_outer = a_lex_input;
1880 lip->li_file = new_stdin;
1881 lip->li_flags = a_LEX_FREE | a_LEX_SLICE;
1882 lip->li_on_finalize = on_finalize;
1883 lip->li_finalize_arg = finalize_arg;
1884 lip->li_slice_stdin = stdin;
1885 lip->li_slice_stdout = stdout;
1886 lip->li_slice_options = options;
1887 memcpy(lip->li_name, cmd, i);
1889 stdin = new_stdin;
1890 stdout = new_stdout;
1891 options = new_options;
1892 pstate |= PS_ROBOT;
1893 a_lex_input = lip;
1894 NYD_LEAVE;
1897 FL void
1898 n_source_slice_hack_remove_after_jump(void){
1899 a_lex_unstack(FAL0);
1902 FL bool_t
1903 n_source_may_yield_control(void){
1904 return ((options & OPT_INTERACTIVE) &&
1905 (pstate & PS_STARTED) &&
1906 (!(pstate & PS_ROBOT) ||
1907 /* But: ok for ~:, yet: unless in a hook.
1908 * TODO This is obviously hacky in that it depends on _input_stack not
1909 * TODO loosing any flags when creating new contexts... Maybe this
1910 * TODO function should instead walk all up the context stack when
1911 * TODO there is one, and verify neither level prevents yielding! */
1912 ((pstate & PS_RECURSED) && (a_lex_input == NULL ||
1913 !(a_lex_input->li_flags & a_LEX_SLICE)))) &&
1914 (a_lex_input == NULL || a_lex_input->li_outer == NULL));
1917 /* s-it-mode */