`write'++: !interactive: urlxenc() attachment paths (Ralph Corderoy)..
[s-mailx.git] / lex_input.c
bloba14c6194b4cf6d2085239170c7e9af99fb88b118
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 a_LEX_MACRO_X_OPTION = 1<<4, /* Macro indeed command line -X option */
51 a_LEX_MACRO_CMD = 1<<5, /* Macro indeed single-line: ~:COMMAND */
53 a_LEX_SUPER_MACRO = 1<<16 /* *Not* inheriting PS_SOURCING state */
56 struct a_lex_cmd{
57 char const *lc_name; /* Name of command */
58 int (*lc_func)(void*); /* Implementor of command */
59 enum argtype lc_argtype; /* Arglist type (see below) */
60 si16_t lc_msgflag; /* Required flags of msgs */
61 si16_t lc_msgmask; /* Relevant flags of msgs */
62 #ifdef HAVE_DOCSTRINGS
63 char const *lc_doc; /* One line doc for command */
64 #endif
66 /* Yechh, can't initialize unions */
67 #define lc_minargs lc_msgflag /* Minimum argcount for RAWLIST */
68 #define lc_maxargs lc_msgmask /* Max argcount for RAWLIST */
70 struct a_lex_ghost{
71 struct a_lex_ghost *lg_next;
72 struct str lg_cmd; /* Data follows after .lg_name */
73 char lg_name[VFIELD_SIZE(0)];
76 struct a_lex_eval_ctx{
77 struct str le_line; /* The terminated data to _evaluate() */
78 ui32_t le_line_size; /* May be used to store line memory size */
79 bool_t le_is_recursive; /* Evaluation in evaluation? (collect ~:) */
80 ui8_t __dummy[3];
81 bool_t le_add_history; /* Enter (final) command in history? */
82 char const *le_new_content; /* History: reenter line, start with this */
85 struct a_lex_input_stack{
86 struct a_lex_input_stack *li_outer;
87 FILE *li_file; /* File we were in */
88 void *li_cond; /* Saved state of conditional stack */
89 ui32_t li_flags; /* enum a_lex_input_flags */
90 ui32_t li_loff; /* Pseudo (macro): index in .li_lines */
91 char **li_lines; /* Pseudo content, lines unfolded */
92 char li_name[VFIELD_SIZE(0)]; /* Name of file or macro */
95 static sighandler_type a_lex_oldpipe;
96 static struct a_lex_ghost *a_lex_ghosts;
97 /* a_lex_cmd_tab[] after fun protos */
99 /* */
100 static struct a_lex_input_stack *a_lex_input;
102 /* Isolate the command from the arguments */
103 static char *a_lex_isolate(char const *comm);
105 /* Command ghost handling */
106 static int a_lex_c_ghost(void *v);
107 static int a_lex_c_unghost(void *v);
109 /* Print a list of all commands */
110 static int a_lex_c_list(void *v);
112 static int a_lex__pcmd_cmp(void const *s1, void const *s2);
114 /* `help' / `?' command */
115 static int a_lex_c_help(void *v);
117 /* `quit' command */
118 static int a_lex_c_quit(void *v);
120 /* Print the binaries version number */
121 static int a_lex_c_version(void *v);
123 static int a_lex__version_cmp(void const *s1, void const *s2);
125 /* PS_STATE_PENDMASK requires some actions */
126 static void a_lex_update_pstate(void);
128 /* Evaluate a single command.
129 * .le_add_history and .le_new_content will be updated upon success.
130 * Command functions return 0 for success, 1 for error, and -1 for abort.
131 * 1 or -1 aborts a load or source, a -1 aborts the interactive command loop */
132 static int a_lex_evaluate(struct a_lex_eval_ctx *evp);
134 /* Get first-fit, or NULL */
135 static struct a_lex_cmd const *a_lex__firstfit(char const *comm);
137 /* Branch here on hangup signal and simulate "exit" */
138 static void a_lex_hangup(int s);
140 /* The following gets called on receipt of an interrupt. Close all open files
141 * except 0, 1, 2, and the temporary. Also, unstack all source files */
142 static void a_lex_onintr(int s);
144 /* Pop the current input back to the previous level. Update the program state.
145 * If the argument is TRUM1 then we don't alert and error out if the stack
146 * doesn't exist at all */
147 static void a_lex_unstack(bool_t eval_error);
149 /* `source' and `source_if' (if silent_error: no pipes allowed, then) */
150 static bool_t a_lex_source_file(char const *file, bool_t silent_error);
152 /* System resource file load()ing or -X command line option array traversal */
153 static bool_t a_lex_load(struct a_lex_input_stack *lip);
155 /* A simplified command loop for recursed state machines */
156 static bool_t a_commands_recursive(enum n_lexinput_flags lif);
158 /* List of all commands, and list of commands which are specially treated
159 * and deduced in _evaluate(), but we need a list for _c_list() and
160 * print_comm_docstr() */
161 #ifdef HAVE_DOCSTRINGS
162 # define DS(S) , S
163 #else
164 # define DS(S)
165 #endif
166 static struct a_lex_cmd const a_lex_cmd_tab[] = {
167 #include "cmd_tab.h"
169 a_lex_special_cmd_tab[] = {
170 { "#", NULL, 0, 0, 0
171 DS(N_("Comment command: ignore remaining (continuable) line")) },
172 { "-", NULL, 0, 0, 0
173 DS(N_("Print out the preceding message")) }
175 #undef DS
177 static char *
178 a_lex_isolate(char const *comm){
179 NYD2_ENTER;
180 while(*comm != '\0' &&
181 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
182 ++comm;
183 NYD2_LEAVE;
184 return UNCONST(comm);
187 static int
188 a_lex_c_ghost(void *v){
189 struct a_lex_ghost *lgp, *gp;
190 size_t i, cl, nl;
191 char *cp;
192 char const **argv;
193 NYD_ENTER;
195 argv = v;
197 /* Show the list? */
198 if(*argv == NULL){
199 FILE *fp;
201 if((fp = Ftmp(NULL, "ghost", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
202 fp = stdout;
204 for(i = 0, gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
205 fprintf(fp, "wysh ghost %s %s\n",
206 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
208 if(fp != stdout){
209 page_or_print(fp, i);
210 Fclose(fp);
212 goto jleave;
215 /* Verify the ghost name is a valid one */
216 if(*argv[0] == '\0' || *a_lex_isolate(argv[0]) != '\0'){
217 n_err(_("`ghost': can't canonicalize %s\n"),
218 n_shexp_quote_cp(argv[0], FAL0));
219 v = NULL;
220 goto jleave;
223 /* Show command of single ghost? */
224 if(argv[1] == NULL){
225 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
226 if(!strcmp(argv[0], gp->lg_name)){
227 printf("wysh ghost %s %s\n",
228 gp->lg_name, n_shexp_quote_cp(gp->lg_cmd.s, TRU1));
229 goto jleave;
231 n_err(_("`ghost': no such alias: %s\n"), argv[0]);
232 v = NULL;
233 goto jleave;
236 /* Define command for ghost: verify command content */
237 for(cl = 0, i = 1; (cp = UNCONST(argv[i])) != NULL; ++i)
238 if(*cp != '\0')
239 cl += strlen(cp) +1; /* SP or NUL */
240 if(cl == 0){
241 n_err(_("`ghost': empty command arguments after %s\n"), argv[0]);
242 v = NULL;
243 goto jleave;
246 /* If the ghost already exists, recreate */
247 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL; lgp = gp, gp = gp->lg_next)
248 if(!strcmp(gp->lg_name, argv[0])){
249 if(lgp != NULL)
250 lgp->lg_next = gp->lg_next;
251 else
252 a_lex_ghosts = gp->lg_next;
253 free(gp);
254 break;
257 nl = strlen(argv[0]) +1;
258 gp = smalloc(sizeof(*gp) - VFIELD_SIZEOF(struct a_lex_ghost, lg_name) +
259 nl + cl);
260 gp->lg_next = a_lex_ghosts;
261 a_lex_ghosts = gp;
262 memcpy(gp->lg_name, argv[0], nl);
263 cp = gp->lg_cmd.s = gp->lg_name + nl;
264 gp->lg_cmd.l = --cl;
266 while(*++argv != NULL)
267 if((i = strlen(*argv)) > 0){
268 memcpy(cp, *argv, i);
269 cp += i;
270 *cp++ = ' ';
272 *--cp = '\0';
273 jleave:
274 NYD_LEAVE;
275 return v == NULL;
278 static int
279 a_lex_c_unghost(void *v){
280 struct a_lex_ghost *lgp, *gp;
281 char const **argv, *cp;
282 int rv;
283 NYD_ENTER;
285 rv = 0;
286 argv = v;
288 while((cp = *argv++) != NULL){
289 if(cp[0] == '*' && cp[1] == '\0'){
290 while((gp = a_lex_ghosts) != NULL){
291 a_lex_ghosts = gp->lg_next;
292 free(gp);
294 }else{
295 for(lgp = NULL, gp = a_lex_ghosts; gp != NULL;
296 lgp = gp, gp = gp->lg_next)
297 if(!strcmp(gp->lg_name, cp)){
298 if(lgp != NULL)
299 lgp->lg_next = gp->lg_next;
300 else
301 a_lex_ghosts = gp->lg_next;
302 free(gp);
303 goto jouter;
305 n_err(_("`unghost': no such alias: %s\n"),
306 n_shexp_quote_cp(cp, FAL0));
307 rv = 1;
308 jouter: ;
311 NYD_LEAVE;
312 return rv;
315 static int
316 a_lex_c_list(void *v){
317 FILE *fp;
318 struct a_lex_cmd const **cpa, *cp, **cursor;
319 size_t l, i;
320 NYD_ENTER;
322 i = NELEM(a_lex_cmd_tab) + NELEM(a_lex_special_cmd_tab) +1;
323 cpa = salloc(sizeof(cp) * i);
325 for(i = 0; i < NELEM(a_lex_cmd_tab); ++i)
326 cpa[i] = &a_lex_cmd_tab[i];
327 /* C99 */{
328 size_t j;
330 for(j = 0; j < NELEM(a_lex_special_cmd_tab); ++i, ++j)
331 cpa[i] = &a_lex_special_cmd_tab[j];
333 cpa[i] = NULL;
335 /* C99 */{
336 char const *xcp = v;
338 if(*xcp == '\0')
339 qsort(cpa, i, sizeof(xcp), &a_lex__pcmd_cmp);
342 if((fp = Ftmp(NULL, "list", OF_RDWR | OF_UNLINK | OF_REGISTER)) == NULL)
343 fp = stdout;
345 fprintf(fp, _("Commands are:\n"));
346 l = 1;
347 for(i = 0, cursor = cpa; (cp = *cursor++) != NULL;){
348 if(cp->lc_func == &c_cmdnotsupp)
349 continue;
350 if(options & OPT_D_V){
351 char const *argt;
353 switch(cp->lc_argtype & ARG_ARGMASK){
354 case ARG_MSGLIST: argt = N_("message-list"); break;
355 case ARG_STRLIST: argt = N_("a \"string\""); break;
356 case ARG_RAWLIST: argt = N_("old-style quoting"); break;
357 case ARG_NOLIST: argt = N_("no arguments"); break;
358 case ARG_NDMLIST: argt = N_("message-list (without a default)"); break;
359 case ARG_WYSHLIST: argt = N_("sh(1)ell-style quoting"); break;
360 default: argt = N_("`wysh' for sh(1)ell-style quoting"); break;
362 #ifdef HAVE_DOCSTRINGS
363 fprintf(fp, _("`%s'. Argument type: %s.\n\t%s\n"),
364 cp->lc_name, V_(argt), V_(cp->lc_doc));
365 l += 2;
366 #else
367 fprintf(fp, "`%s' (%s)\n", cp->lc_name, argt);
368 ++l;
369 #endif
370 }else{
371 size_t j = strlen(cp->lc_name) + 2;
373 if((i += j) > 72){
374 i = j;
375 fprintf(fp, "\n");
376 ++l;
378 fprintf(fp, (*cursor != NULL ? "%s, " : "%s\n"), cp->lc_name);
382 if(fp != stdout){
383 page_or_print(fp, l);
384 Fclose(fp);
386 NYD_LEAVE;
387 return 0;
390 static int
391 a_lex__pcmd_cmp(void const *s1, void const *s2){
392 struct a_lex_cmd const * const *cp1, * const *cp2;
393 int rv;
394 NYD2_ENTER;
396 cp1 = s1;
397 cp2 = s2;
398 rv = strcmp((*cp1)->lc_name, (*cp2)->lc_name);
399 NYD2_LEAVE;
400 return rv;
403 static int
404 a_lex_c_help(void *v){
405 int rv;
406 char *arg;
407 NYD_ENTER;
409 /* Help for a single command? */
410 if((arg = *(char**)v) != NULL){
411 struct a_lex_ghost const *gp;
412 struct a_lex_cmd const *cp, *cpmax;
414 /* Ghosts take precedence */
415 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
416 if(!strcmp(arg, gp->lg_name)){
417 printf("%s -> ", arg);
418 arg = gp->lg_cmd.s;
419 break;
422 cpmax = &(cp = a_lex_cmd_tab)[NELEM(a_lex_cmd_tab)];
423 jredo:
424 for(; PTRCMP(cp, <, cpmax); ++cp){
425 #ifdef HAVE_DOCSTRINGS
426 # define a_DS V_(cp->lc_doc)
427 #else
428 # define a_DS ""
429 #endif
430 if(!strcmp(arg, cp->lc_name))
431 printf("%s: %s", arg, a_DS);
432 else if(is_prefix(arg, cp->lc_name))
433 printf("%s (%s): %s", arg, cp->lc_name, a_DS);
434 else
435 continue;
437 if(options & OPT_D_V){
438 char const *atp;
440 switch(cp->lc_argtype & ARG_ARGMASK){
441 case ARG_MSGLIST: atp = N_("message-list"); break;
442 case ARG_STRLIST: atp = N_("a \"string\""); break;
443 case ARG_RAWLIST: atp = N_("old-style quoting"); break;
444 case ARG_NOLIST: atp = N_("no arguments"); break;
445 case ARG_NDMLIST: atp = N_("message-list (no default)"); break;
446 case ARG_WYSHLIST: atp = N_("sh(1)ell-style quoting"); break;
447 default: atp = N_("`wysh' for sh(1)ell-style quoting"); break;
449 #ifdef HAVE_DOCSTRINGS
450 printf(_("\n\tArgument type: %s"), V_(atp));
451 #else
452 printf(_("argument type: %s"), V_(atp));
453 #endif
454 #undef a_DS
456 putchar('\n');
457 rv = 0;
458 goto jleave;
461 if(PTRCMP(cpmax, ==, &a_lex_cmd_tab[NELEM(a_lex_cmd_tab)])){
462 cpmax = &(cp = a_lex_special_cmd_tab)[NELEM(a_lex_special_cmd_tab)];
463 goto jredo;
466 if(gp != NULL){
467 printf("%s\n", n_shexp_quote_cp(arg, TRU1));
468 rv = 0;
469 }else{
470 n_err(_("Unknown command: `%s'\n"), arg);
471 rv = 1;
473 }else{
474 /* Very ugly, but take care for compiler supported string lengths :( */
475 fputs(progname, stdout);
476 fputs(_(
477 " commands -- <msglist> denotes message specifications,\n"
478 "e.g., 1-5, :n or ., separated by spaces:\n"), stdout);
479 fputs(_(
480 "\n"
481 "type <msglist> type (alias: `print') messages (honour `retain' etc.)\n"
482 "Type <msglist> like `type' but always show all headers\n"
483 "next goto and type next message\n"
484 "from <msglist> (search and) print header summary for the given list\n"
485 "headers header summary for messages surrounding \"dot\"\n"
486 "delete <msglist> delete messages (can be `undelete'd)\n"),
487 stdout);
489 fputs(_(
490 "\n"
491 "save <msglist> folder append messages to folder and mark as saved\n"
492 "copy <msglist> folder like `save', but don't mark them (`move' moves)\n"
493 "write <msglist> file write message contents to file (prompts for parts)\n"
494 "Reply <msglist> reply to message senders only\n"
495 "reply <msglist> like `Reply', but address all recipients\n"
496 "Lreply <msglist> forced mailing-list `reply' (see `mlist')\n"),
497 stdout);
499 fputs(_(
500 "\n"
501 "mail <recipients> compose a mail for the given recipients\n"
502 "file folder change to another mailbox\n"
503 "File folder like `file', but open readonly\n"
504 "quit quit and apply changes to the current mailbox\n"
505 "xit or exit like `quit', but discard changes\n"
506 "!shell command shell escape\n"
507 "list [<anything>] all available commands [in search order]\n"),
508 stdout);
510 rv = (ferror(stdout) != 0);
512 jleave:
513 NYD_LEAVE;
514 return rv;
517 static int
518 a_lex_c_quit(void *v){
519 NYD_ENTER;
520 UNUSED(v);
522 /* If we are PS_SOURCING, then return 1 so _evaluate() can handle it.
523 * Otherwise return -1 to abort command loop */
524 pstate |= PS_EXIT;
525 NYD_LEAVE;
526 return 0;
529 static int
530 a_lex_c_version(void *v){
531 int longest, rv;
532 char *iop;
533 char const *cp, **arr;
534 size_t i, i2;
535 NYD_ENTER;
536 UNUSED(v);
538 printf(_("%s version %s\nFeatures included (+) or not (-)\n"),
539 uagent, ok_vlook(version));
541 /* *features* starts with dummy byte to avoid + -> *folder* expansions */
542 i = strlen(cp = &ok_vlook(features)[1]) +1;
543 iop = salloc(i);
544 memcpy(iop, cp, i);
546 arr = salloc(sizeof(cp) * VAL_FEATURES_CNT);
547 for(longest = 0, i = 0; (cp = n_strsep(&iop, ',', TRU1)) != NULL; ++i){
548 arr[i] = cp;
549 i2 = strlen(cp);
550 longest = MAX(longest, (int)i2);
552 qsort(arr, i, sizeof(cp), &a_lex__version_cmp);
554 for(++longest, i2 = 0; i-- > 0;){
555 cp = *(arr++);
556 printf("%-*s ", longest, cp);
557 i2 += longest;
558 if(UICMP(z, ++i2 + longest, >=, scrnwidth) || i == 0){
559 i2 = 0;
560 putchar('\n');
564 if((rv = ferror(stdout) != 0))
565 clearerr(stdout);
566 NYD_LEAVE;
567 return rv;
570 static int
571 a_lex__version_cmp(void const *s1, void const *s2){
572 char const * const *cp1, * const *cp2;
573 int rv;
574 NYD2_ENTER;
576 cp1 = s1;
577 cp2 = s2;
578 rv = strcmp(&(*cp1)[1], &(*cp2)[1]);
579 NYD2_LEAVE;
580 return rv;
583 static void
584 a_lex_update_pstate(void){
585 NYD_ENTER;
587 if(pstate & PS_SIGWINCH_PEND){
588 char buf[32];
590 snprintf(buf, sizeof buf, "%d", scrnwidth);
591 ok_vset(COLUMNS, buf);
592 snprintf(buf, sizeof buf, "%d", scrnheight);
593 ok_vset(LINES, buf);
596 pstate &= ~PS_PSTATE_PENDMASK;
597 NYD_LEAVE;
600 static int
601 a_lex_evaluate(struct a_lex_eval_ctx *evp){
602 /* xxx old style(9), but also old code */
603 struct str line;
604 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
605 struct a_lex_ghost *gp;
606 struct a_lex_cmd const *cmd;
607 int c, e;
608 bool_t wysh;
609 NYD_ENTER;
611 wysh = FAL0;
612 e = 1;
613 cmd = NULL;
614 gp = NULL;
615 line = evp->le_line; /* XXX don't change original (buffer pointer) */
616 assert(line.s[line.l] == '\0');
617 evp->le_add_history = FAL0;
618 evp->le_new_content = NULL;
620 /* Command ghosts that refer to shell commands or macro expansion restart */
621 jrestart:
623 /* Strip the white space away from end and beginning of command */
624 if(line.l > 0){
625 size_t i = line.l;
627 for(cp = &line.s[i -1]; spacechar(*cp); --cp)
628 --i;
629 line.l = i;
631 for(cp = line.s; spacechar(*cp); ++cp)
633 line.l -= PTR2SIZE(cp - line.s);
635 /* Ignore null commands (comments) */
636 if(*cp == '#')
637 goto jleave0;
639 /* Handle ! differently to get the correct lexical conventions */
640 arglist[0] = cp;
641 if(*cp == '!')
642 ++cp;
643 /* Isolate the actual command; since it may not necessarily be
644 * separated from the arguments (as in `p1') we need to duplicate it to
645 * be able to create a NUL terminated version.
646 * We must be aware of several special one letter commands here */
647 else if((cp = a_lex_isolate(cp)) == arglist[0] &&
648 (*cp == '|' || *cp == '~' || *cp == '?'))
649 ++cp;
650 c = (int)PTR2SIZE(cp - arglist[0]);
651 line.l -= c;
652 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
653 memcpy(word, arglist[0], c);
654 word[c] = '\0';
656 /* Look up the command; if not found, bitch.
657 * Normally, a blank command would map to the first command in the
658 * table; while PS_SOURCING, however, we ignore blank lines to eliminate
659 * confusion; act just the same for ghosts */
660 if(*word == '\0'){
661 if((pstate & PS_ROBOT) || gp != NULL)
662 goto jleave0;
663 cmd = a_lex_cmd_tab + 0;
664 goto jexec;
667 /* XXX It may be the argument parse adjuster */
668 if(!wysh && c == sizeof("wysh") -1 && !asccasecmp(word, "wysh")){
669 wysh = TRU1;
670 line.s = cp;
671 goto jrestart;
674 /* If this is the first evaluation, check command ghosts */
675 if(gp == NULL){
676 /* TODO relink list head, so it's sorted on usage over time?
677 * TODO in fact, there should be one hashmap over all commands and ghosts
678 * TODO so that the lookup could be made much more efficient than it is
679 * TODO now (two adjacent list searches! */
680 for(gp = a_lex_ghosts; gp != NULL; gp = gp->lg_next)
681 if(!strcmp(word, gp->lg_name)){
682 if(line.l > 0){
683 size_t i;
685 i = gp->lg_cmd.l;
686 line.s = salloc(i + line.l +1);
687 memcpy(line.s, gp->lg_cmd.s, i);
688 memcpy(line.s + i, cp, line.l);
689 line.s[i += line.l] = '\0';
690 line.l = i;
691 }else{
692 line.s = gp->lg_cmd.s;
693 line.l = gp->lg_cmd.l;
695 goto jrestart;
699 if((cmd = a_lex__firstfit(word)) == NULL || cmd->lc_func == &c_cmdnotsupp){
700 bool_t s;
702 if(!(s = condstack_isskip()) || (options & OPT_D_V))
703 n_err(_("Unknown command%s: `%s'\n"),
704 (s ? _(" (ignored due to `if' condition)") : ""), word);
705 if(s)
706 goto jleave0;
707 if(cmd != NULL){
708 c_cmdnotsupp(NULL);
709 cmd = NULL;
711 goto jleave;
714 /* See if we should execute the command -- if a conditional we always
715 * execute it, otherwise, check the state of cond */
716 jexec:
717 if(!(cmd->lc_argtype & ARG_F) && condstack_isskip())
718 goto jleave0;
720 /* Process the arguments to the command, depending on the type it expects */
721 if(!(cmd->lc_argtype & ARG_M) && (options & OPT_SENDMODE)){
722 n_err(_("May not execute `%s' while sending\n"), cmd->lc_name);
723 goto jleave;
725 if((cmd->lc_argtype & ARG_S) && !(pstate & PS_STARTED)){
726 n_err(_("May not execute `%s' during startup\n"), cmd->lc_name);
727 goto jleave;
729 if((cmd->lc_argtype & ARG_I) &&
730 !(options & (OPT_INTERACTIVE | OPT_BATCH_FLAG))){
731 n_err(_("May not execute `%s' unless interactive or in batch mode\n"),
732 cmd->lc_name);
733 goto jleave;
735 if((cmd->lc_argtype & ARG_R) && (pstate & PS_RECURSED)){
736 n_err(_("Cannot invoke `%s' when in recursed mode (e.g., composing)\n"),
737 cmd->lc_name);
738 goto jleave;
741 if((cmd->lc_argtype & ARG_W) && !(mb.mb_perm & MB_DELE)){
742 n_err(_("May not execute `%s' -- message file is read only\n"),
743 cmd->lc_name);
744 goto jleave;
746 if((cmd->lc_argtype & ARG_A) && mb.mb_type == MB_VOID){
747 n_err(_("Cannot execute `%s' without active mailbox\n"), cmd->lc_name);
748 goto jleave;
751 if(cmd->lc_argtype & ARG_O)
752 OBSOLETE2(_("this command will be removed"), cmd->lc_name);
753 if(cmd->lc_argtype & ARG_V)
754 temporary_arg_v_store = NULL;
756 if(wysh && (cmd->lc_argtype & ARG_ARGMASK) != ARG_WYRALIST)
757 n_err(_("`wysh' prefix doesn't affect `%s'\n"), cmd->lc_name);
758 /* TODO v15: strip PS_ARGLIST_MASK off, just in case the actual command
759 * TODO doesn't use any of those list commands which strip this mask,
760 * TODO and for now we misuse bits for checking relation to history;
761 * TODO argument state should be property of a per-command carrier instead */
762 pstate &= ~PS_ARGLIST_MASK;
763 switch(cmd->lc_argtype & ARG_ARGMASK){
764 case ARG_MSGLIST:
765 /* Message list defaulting to nearest forward legal message */
766 if(n_msgvec == NULL)
767 goto je96;
768 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
769 break;
770 if(c == 0){
771 if((n_msgvec[0] = first(cmd->lc_msgflag, cmd->lc_msgmask)) != 0)
772 n_msgvec[1] = 0;
774 if(n_msgvec[0] == 0){
775 if(!(pstate & PS_HOOK_MASK))
776 printf(_("No applicable messages\n"));
777 break;
779 e = (*cmd->lc_func)(n_msgvec);
780 break;
782 case ARG_NDMLIST:
783 /* Message list with no defaults, but no error if none exist */
784 if(n_msgvec == NULL){
785 je96:
786 n_err(_("Invalid use of message list\n"));
787 break;
789 if((c = getmsglist(cp, n_msgvec, cmd->lc_msgflag)) < 0)
790 break;
791 e = (*cmd->lc_func)(n_msgvec);
792 break;
794 case ARG_STRLIST:
795 /* Just the straight string, with leading blanks removed */
796 while(whitechar(*cp))
797 ++cp;
798 e = (*cmd->lc_func)(cp);
799 break;
801 case ARG_WYSHLIST:
802 c = 1;
803 if(0){
804 /* FALLTHRU */
805 case ARG_WYRALIST:
806 c = wysh ? 1 : 0;
807 if(0){
808 case ARG_RAWLIST:
809 c = 0;
813 if((c = getrawlist((c != 0), arglist, NELEM(arglist), cp, line.l)) < 0){
814 n_err(_("Invalid argument list\n"));
815 break;
817 if(c < cmd->lc_minargs){
818 n_err(_("`%s' requires at least %d arg(s)\n"),
819 cmd->lc_name, cmd->lc_minargs);
820 break;
822 #undef lc_minargs
823 if(c > cmd->lc_maxargs){
824 n_err(_("`%s' takes no more than %d arg(s)\n"),
825 cmd->lc_name, cmd->lc_maxargs);
826 break;
828 #undef lc_maxargs
829 e = (*cmd->lc_func)(arglist);
830 break;
832 case ARG_NOLIST:
833 /* Just the constant zero, for exiting, eg. */
834 e = (*cmd->lc_func)(0);
835 break;
837 default:
838 DBG( n_panic(_("Implementation error: unknown argument type: %d"),
839 cmd->lc_argtype & ARG_ARGMASK); )
840 goto jleave0;
843 if(e == 0 && (cmd->lc_argtype & ARG_V) &&
844 (cp = temporary_arg_v_store) != NULL){
845 temporary_arg_v_store = NULL;
846 evp->le_new_content = cp;
847 goto jleave0;
849 /* TODO v15 with PS_MSGLIST_GABBY the history entry is at least gabby */
850 if(!(cmd->lc_argtype & ARG_H) && !(pstate & PS_MSGLIST_GABBY))
851 evp->le_add_history = TRU1;
853 jleave:
854 /* Exit the current source file on error TODO what a mess! */
855 if(e == 0)
856 pstate &= ~PS_EVAL_ERROR;
857 else{
858 pstate |= PS_EVAL_ERROR;
859 if(e < 0 || (pstate & PS_ROBOT)){ /* FIXME */
860 e = 1;
861 goto jret;
863 goto jret0;
866 if(cmd == NULL)
867 goto jret0;
868 if((cmd->lc_argtype & ARG_P) && ok_blook(autoprint))
869 if(visible(dot)){
870 line.s = savestr("type");
871 line.l = sizeof("type") -1;
872 gp = (struct a_lex_ghost*)-1; /* Avoid `ghost' interpretation */
873 goto jrestart;
876 if(!(pstate & (PS_SOURCING | PS_HOOK_MASK)) && !(cmd->lc_argtype & ARG_T))
877 pstate |= PS_SAW_COMMAND;
878 jleave0:
879 pstate &= ~PS_EVAL_ERROR;
880 jret0:
881 e = 0;
882 jret:
884 fprintf(stderr, "a_lex_evaluate returns %d for <%s>\n",e,line.s);
886 NYD_LEAVE;
887 return e;
890 static struct a_lex_cmd const *
891 a_lex__firstfit(char const *comm){ /* TODO *hashtable*! linear list search!!! */
892 struct a_lex_cmd const *cp;
893 NYD2_ENTER;
895 for(cp = a_lex_cmd_tab; PTRCMP(cp, <, &a_lex_cmd_tab[NELEM(a_lex_cmd_tab)]);
896 ++cp)
897 if(*comm == *cp->lc_name && is_prefix(comm, cp->lc_name))
898 goto jleave;
899 cp = NULL;
900 jleave:
901 NYD2_LEAVE;
902 return cp;
905 static void
906 a_lex_hangup(int s){
907 NYD_X; /* Signal handler */
908 UNUSED(s);
909 /* nothing to do? */
910 exit(EXIT_ERR);
913 static void
914 a_lex_onintr(int s){
915 NYD_X; /* Signal handler */
916 UNUSED(s);
918 safe_signal(SIGINT, a_lex_onintr);
919 noreset = 0;
920 a_lex_unstack(TRUM1);
922 termios_state_reset();
923 close_all_files(); /* FIXME .. to outer level ONLU! */
925 if(image >= 0){
926 close(image);
927 image = -1;
929 if(interrupts != 1)
930 n_err_sighdl(_("Interrupt\n"));
931 safe_signal(SIGPIPE, a_lex_oldpipe);
932 siglongjmp(srbuf, 0); /* FIXME get rid */
935 static void
936 a_lex_unstack(bool_t eval_error){
937 struct a_lex_input_stack *lip;
938 NYD_ENTER;
940 if((lip = a_lex_input) == NULL){
941 /* If called from a_lex_onintr(), be silent FIXME */
942 pstate &= ~(PS_SOURCING | PS_ROBOT);
943 if(eval_error == TRUM1 || !(pstate & PS_STARTED))
944 goto jleave;
945 goto jerr;
948 if(lip->li_flags & a_LEX_MACRO){
949 if(lip->li_flags & a_LEX_MACRO_FREE_DATA){
950 char **lp;
952 while(*(lp = &lip->li_lines[lip->li_loff]) != NULL){
953 free(*lp);
954 ++lip->li_loff;
956 /* Part of lip's memory chunk, then */
957 if(!(lip->li_flags & a_LEX_MACRO_CMD))
958 free(lip->li_lines);
960 }else{
961 if(lip->li_flags & a_LEX_PIPE)
962 /* XXX command manager should -TERM then -KILL instead of hoping
963 * XXX for exit of provider due to EPIPE / SIGPIPE */
964 Pclose(lip->li_file, TRU1);
965 else
966 Fclose(lip->li_file);
969 if(!condstack_take(lip->li_cond)){
970 n_err(_("Unmatched `if' at end of %s %s\n"),
971 ((lip->li_flags & a_LEX_MACRO
972 ? (lip->li_flags & a_LEX_MACRO_CMD ? _("command") : _("macro"))
973 : _("`source'd file"))),
974 lip->li_name);
975 eval_error = TRU1;
978 if((a_lex_input = lip->li_outer) == NULL){
979 pstate &= ~(PS_SOURCING | PS_ROBOT);
980 }else{
981 if((a_lex_input->li_flags & (a_LEX_MACRO | a_LEX_SUPER_MACRO)) ==
982 (a_LEX_MACRO | a_LEX_SUPER_MACRO))
983 pstate &= ~PS_SOURCING;
984 assert(pstate & PS_ROBOT);
987 if(eval_error)
988 goto jerr;
989 if(lip->li_flags & a_LEX_FREE)
990 free(lip);
991 jleave:
992 if(UNLIKELY(a_lex_input != NULL && eval_error == TRUM1))
993 a_lex_unstack(TRUM1);
994 NYD_LEAVE;
995 return;
997 jerr:
998 if(lip != NULL){
999 if(options & OPT_D_V)
1000 n_alert(_("Stopped %s %s due to errors%s"),
1001 (pstate & PS_STARTED
1002 ? (lip->li_flags & a_LEX_MACRO
1003 ? (lip->li_flags & a_LEX_MACRO_CMD
1004 ? _("evaluating command") : _("evaluating macro"))
1005 : (lip->li_flags & a_LEX_PIPE
1006 ? _("executing `source'd pipe")
1007 : _("loading `source'd file")))
1008 : (lip->li_flags & a_LEX_MACRO
1009 ? (lip->li_flags & a_LEX_MACRO_X_OPTION
1010 ? _("evaluating command line") : _("evaluating macro"))
1011 : _("loading initialization resource"))),
1012 lip->li_name,
1013 (options & OPT_DEBUG ? "" : _(" (enable *debug* for trace)")));
1014 if(lip->li_flags & a_LEX_FREE)
1015 free(lip);
1018 if(!(options & OPT_INTERACTIVE) && !(pstate & PS_STARTED)){
1019 if(options & OPT_D_V)
1020 n_alert(_("Non-interactive, bailing out due to errors "
1021 "in startup load phase"));
1022 exit(EXIT_ERR);
1024 goto jleave;
1027 static bool_t
1028 a_lex_source_file(char const *file, bool_t silent_error){
1029 struct a_lex_input_stack *lip;
1030 size_t nlen;
1031 char *nbuf;
1032 bool_t ispipe;
1033 FILE *fip;
1034 NYD_ENTER;
1036 fip = NULL;
1038 /* Being a command argument file is space-trimmed *//* TODO v15 with
1039 * TODO WYRALIST this is no longer necessary true, and for that we
1040 * TODO don't set _PARSE_TRIMSPACE because we cannot! -> cmd_tab.h!! */
1041 #if 0
1042 ((ispipe = (!silent_error && (nlen = strlen(file)) > 0 &&
1043 file[--nlen] == '|')))
1044 #else
1045 ispipe = FAL0;
1046 if(!silent_error)
1047 for(nlen = strlen(file); nlen > 0;){
1048 char c;
1050 c = file[--nlen];
1051 if(!blankchar(c)){
1052 if(c == '|'){
1053 nbuf = savestrbuf(file, nlen);
1054 ispipe = TRU1;
1055 break;
1059 #endif
1061 if(ispipe){
1062 if((fip = Popen(nbuf /* #if 0 above = savestrbuf(file, nlen)*/, "r",
1063 ok_vlook(SHELL), NULL, COMMAND_FD_NULL)) == NULL){
1064 if(!silent_error || (options & OPT_D_V))
1065 n_perr(nbuf, 0);
1066 goto jleave;
1068 }else if((nbuf = fexpand(file, FEXP_LOCAL)) == NULL)
1069 goto jleave;
1070 else if((fip = Fopen(nbuf, "r")) == NULL){
1071 if(!silent_error || (options & OPT_D_V))
1072 n_perr(nbuf, 0);
1073 goto jleave;
1076 lip = smalloc(sizeof(*lip) -
1077 VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1078 (nlen = strlen(nbuf) +1));
1079 lip->li_outer = a_lex_input;
1080 lip->li_file = fip;
1081 lip->li_cond = condstack_release();
1082 lip->li_flags = (ispipe ? a_LEX_FREE | a_LEX_PIPE : a_LEX_FREE) |
1083 (a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1084 ? a_LEX_SUPER_MACRO : 0);
1085 memcpy(lip->li_name, nbuf, nlen);
1087 pstate |= PS_SOURCING | PS_ROBOT;
1088 a_lex_input = lip;
1089 a_commands_recursive(n_LEXINPUT_NONE | n_LEXINPUT_NL_ESC);
1090 /* FIXME return TRUM1 if file can't be opened, FAL0 on eval error */
1091 jleave:
1092 NYD_LEAVE;
1093 return silent_error ? TRU1 : (fip != NULL);
1096 static bool_t
1097 a_lex_load(struct a_lex_input_stack *lip){
1098 bool_t rv;
1099 NYD2_ENTER;
1101 assert(!(pstate & PS_STARTED));
1102 assert(a_lex_input == NULL);
1104 /* POSIX:
1105 * Any errors in the start-up file shall either cause mailx to terminate
1106 * with a diagnostic message and a non-zero status or to continue after
1107 * writing a diagnostic message, ignoring the remainder of the lines in
1108 * the start-up file. */
1109 lip->li_cond = condstack_release();
1111 /* FIXME won't work for now (PS_ROBOT needs PS_SOURCING anyway)
1112 pstate |= PS_ROBOT |
1113 (lip->li_flags & a_LEX_MACRO_X_OPTION ? 0 : PS_SOURCING);
1115 pstate |= PS_ROBOT | PS_SOURCING;
1116 if(options & OPT_D_V)
1117 n_err(_("Loading %s\n"), n_shexp_quote_cp(lip->li_name, FAL0));
1118 a_lex_input = lip;
1119 if(!(rv = n_commands())){
1120 if(!(options & OPT_INTERACTIVE)){
1121 if(options & OPT_D_V)
1122 n_alert(_("Non-interactive program mode, forced exit"));
1123 exit(EXIT_ERR);
1126 /* PS_EXIT handled by callers */
1127 NYD2_LEAVE;
1128 return rv;
1131 static bool_t
1132 a_commands_recursive(enum n_lexinput_flags lif){
1133 struct a_lex_eval_ctx ev;
1134 bool_t rv;
1135 NYD2_ENTER;
1137 memset(&ev, 0, sizeof ev);
1139 /* FIXME sigkondom */
1140 n_COLOUR( n_colour_env_push(); )
1141 rv = TRU1;
1142 for(;;){
1143 int n;
1145 /* Read a line of commands and handle end of file specially */
1146 ev.le_line.l = ev.le_line_size;
1147 n = n_lex_input(lif, NULL, &ev.le_line.s, &ev.le_line.l,
1148 ev.le_new_content);
1149 ev.le_line_size = (ui32_t)ev.le_line.l;
1150 ev.le_line.l = (ui32_t)n;
1152 if(n < 0)
1153 break;
1155 if(a_lex_evaluate(&ev)){
1156 rv = FAL0;
1157 break;
1160 if((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)){
1161 if(exit_status != EXIT_OK)
1162 break;
1165 a_lex_unstack(!rv);
1166 n_COLOUR( n_colour_env_pop(FAL0); )
1168 if(ev.le_line.s != NULL)
1169 free(ev.le_line.s);
1170 NYD2_LEAVE;
1171 return rv;
1174 FL bool_t
1175 n_commands(void){ /* FIXME */
1176 struct a_lex_eval_ctx ev;
1177 int n;
1178 bool_t volatile rv = TRU1;
1179 NYD_ENTER;
1181 if (!(pstate & PS_SOURCING)) {
1182 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
1183 safe_signal(SIGINT, &a_lex_onintr);
1184 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
1185 safe_signal(SIGHUP, &a_lex_hangup);
1187 a_lex_oldpipe = safe_signal(SIGPIPE, SIG_IGN);
1188 safe_signal(SIGPIPE, a_lex_oldpipe);
1190 memset(&ev, 0, sizeof ev);
1192 (void)sigsetjmp(srbuf, 1); /* FIXME get rid */
1193 for (;;) {
1194 char *temporary_orig_line; /* XXX eval_ctx.le_line not yet constant */
1196 n_COLOUR( n_colour_env_pop(TRU1); )
1198 /* TODO Unless we have our signal manager (or however we do it) child
1199 * TODO processes may have time slots where their execution isn't
1200 * TODO protected by signal handlers (in between start and setup
1201 * TODO completed). close_all_files() is only called from onintr()
1202 * TODO so those may linger possibly forever */
1203 if(!(pstate & PS_SOURCING))
1204 close_all_files();
1206 interrupts = 0;
1208 temporary_localopts_free(); /* XXX intermediate hack */
1209 sreset((pstate & PS_SOURCING) != 0);
1210 if (!(pstate & PS_SOURCING)) {
1211 char *cp;
1213 /* TODO Note: this buffer may contain a password. We should redefine
1214 * TODO the code flow which has to do that */
1215 if ((cp = termios_state.ts_linebuf) != NULL) {
1216 termios_state.ts_linebuf = NULL;
1217 termios_state.ts_linesize = 0;
1218 free(cp); /* TODO pool give-back */
1220 /* TODO Due to expand-on-tab of NCL the buffer may grow */
1221 if (ev.le_line.l > LINESIZE * 3) {
1222 free(ev.le_line.s); /* TODO pool! but what? */
1223 ev.le_line.s = NULL;
1224 ev.le_line.l = ev.le_line_size = 0;
1228 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1229 char *cp;
1231 cp = ok_vlook(newmail);
1232 if ((options & OPT_TTYIN) && cp != NULL) {
1233 struct stat st;
1235 /* FIXME TEST WITH NOPOLL ETC. !!! */
1236 n = (cp != NULL && strcmp(cp, "nopoll"));
1237 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
1238 st.st_size > mailsize) ||
1239 (mb.mb_type == MB_MAILDIR && n != 0)) {
1240 size_t odot = PTR2SIZE(dot - message);
1241 ui32_t odid = (pstate & PS_DID_PRINT_DOT);
1243 if (setfile(mailname,
1244 FEDIT_NEWMAIL |
1245 ((mb.mb_perm & MB_DELE) ? 0 : FEDIT_RDONLY)) < 0) {
1246 exit_status |= EXIT_ERR;
1247 rv = FAL0;
1248 break;
1250 dot = message + odot;
1251 pstate |= odid;
1255 exit_status = EXIT_OK;
1258 /* Read a line of commands and handle end of file specially */
1259 jreadline:
1260 ev.le_line.l = ev.le_line_size;
1261 n = n_lex_input(n_LEXINPUT_CTX_BASE | n_LEXINPUT_NL_ESC, NULL,
1262 &ev.le_line.s, &ev.le_line.l, ev.le_new_content);
1263 ev.le_line_size = (ui32_t)ev.le_line.l;
1264 ev.le_line.l = (ui32_t)n;
1266 if (n < 0) {
1267 /* FIXME did unstack() when PS_SOURCING, only break with PS_LOADING*/
1268 if (!(pstate & PS_ROBOT) &&
1269 (options & OPT_INTERACTIVE) && ok_blook(ignoreeof)) {
1270 printf(_("*ignoreeof* set, use `quit' to quit.\n"));
1271 n_msleep(500, FAL0);
1272 continue;
1274 break;
1277 temporary_orig_line = ((pstate & PS_SOURCING) ||
1278 !(options & OPT_INTERACTIVE)) ? NULL
1279 : savestrbuf(ev.le_line.s, ev.le_line.l);
1280 pstate &= ~PS_HOOK_MASK;
1281 if (a_lex_evaluate(&ev)) {
1282 if (!(pstate & PS_STARTED)) /* TODO mess; join PS_EVAL_ERROR.. */
1283 rv = FAL0;
1284 break;
1287 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
1288 if (exit_status != EXIT_OK)
1289 break;
1290 if ((pstate & (PS_SOURCING | PS_EVAL_ERROR)) == PS_EVAL_ERROR) {
1291 exit_status = EXIT_ERR;
1292 break;
1295 if (!(pstate & PS_SOURCING) && (options & OPT_INTERACTIVE)) {
1296 if (ev.le_new_content != NULL)
1297 goto jreadline;
1298 /* *Can* happen since _evaluate() n_unstack()s on error! XXX no more */
1299 if (temporary_orig_line != NULL)
1300 n_tty_addhist(temporary_orig_line, !ev.le_add_history);
1303 if(pstate & PS_EXIT)
1304 break;
1306 a_lex_unstack(!rv);
1308 if (ev.le_line.s != NULL)
1309 free(ev.le_line.s);
1310 if (pstate & PS_SOURCING)
1311 sreset(FAL0);
1312 NYD_LEAVE;
1313 return rv;
1316 FL int
1317 (n_lex_input)(enum n_lexinput_flags lif, char const *prompt, char **linebuf,
1318 size_t *linesize, char const *string SMALLOC_DEBUG_ARGS){
1319 /* TODO readline: linebuf pool!; n_lex_input should return si64_t */
1320 FILE *ifile;
1321 bool_t doprompt, dotty;
1322 char const *iftype;
1323 int n, nold;
1324 NYD2_ENTER;
1326 /* Special case macro mode: never need to prompt, lines have always been
1327 * unfolded already */
1328 if(a_lex_input != NULL && (a_lex_input->li_flags & a_LEX_MACRO)){
1329 if(*linebuf != NULL)
1330 free(*linebuf);
1332 if((*linebuf = a_lex_input->li_lines[a_lex_input->li_loff]) == NULL){
1333 *linesize = 0;
1334 n = -1;
1335 goto jleave;
1338 ++a_lex_input->li_loff;
1339 *linesize = strlen(*linebuf);
1340 if(!(a_lex_input->li_flags & a_LEX_MACRO_FREE_DATA))
1341 *linebuf = sbufdup(*linebuf, *linesize);
1343 iftype = (a_lex_input->li_flags & a_LEX_MACRO_X_OPTION)
1344 ? "-X OPTION" : "MACRO";
1345 n = (int)*linesize;
1346 pstate |= PS_READLINE_NL;
1347 goto jhave_dat;
1349 pstate &= ~PS_READLINE_NL;
1351 iftype = (!(pstate & PS_STARTED) ? "LOAD"
1352 : (pstate & PS_SOURCING) ? "SOURCE" : "READ");
1353 doprompt = ((pstate & (PS_STARTED | PS_ROBOT)) == PS_STARTED &&
1354 (options & OPT_INTERACTIVE));
1355 dotty = (doprompt && !ok_blook(line_editor_disable));
1356 if(!doprompt)
1357 prompt = NULL;
1358 else if(prompt == NULL)
1359 prompt = getprompt();
1361 /* Ensure stdout is flushed first anyway */
1362 if(!dotty && prompt == NULL)
1363 fflush(stdout);
1365 ifile = (a_lex_input != NULL) ? a_lex_input->li_file : stdin;
1366 assert(ifile != NULL);
1368 for(nold = n = 0;;){
1369 if(dotty){
1370 assert(ifile == stdin);
1371 if(string != NULL && (n = (int)strlen(string)) > 0){
1372 if(*linesize > 0)
1373 *linesize += n +1;
1374 else
1375 *linesize = (size_t)n + LINESIZE +1;
1376 *linebuf = (srealloc)(*linebuf, *linesize SMALLOC_DEBUG_ARGSCALL);
1377 memcpy(*linebuf, string, (size_t)n +1);
1379 string = NULL;
1380 /* TODO if nold>0, don't redisplay the entire line!
1381 * TODO needs complete redesign ... */
1382 n = (n_tty_readline)(lif, prompt, linebuf, linesize, n
1383 SMALLOC_DEBUG_ARGSCALL);
1384 }else{
1385 if(prompt != NULL) {
1386 if(*prompt != '\0')
1387 fputs(prompt, stdout);
1388 fflush(stdout);
1391 n = (readline_restart)(ifile, linebuf, linesize, n
1392 SMALLOC_DEBUG_ARGSCALL);
1394 if(n > 0 && nold > 0){
1395 int i = 0;
1396 char const *cp = *linebuf + nold;
1398 while(blankspacechar(*cp) && nold + i < n)
1399 ++cp, ++i;
1400 if(i > 0){
1401 memmove(*linebuf + nold, cp, n - nold - i);
1402 n -= i;
1403 (*linebuf)[n] = '\0';
1408 if(n <= 0)
1409 break;
1411 /* POSIX says:
1412 * An unquoted <backslash> at the end of a command line shall
1413 * be discarded and the next line shall continue the command */
1414 if(!(lif & n_LEXINPUT_NL_ESC) || (*linebuf)[n - 1] != '\\'){
1415 if(dotty)
1416 pstate |= PS_READLINE_NL;
1417 break;
1419 /* Definitely outside of quotes, thus the quoting rules are so that an
1420 * uneven number of successive backslashs at EOL is a continuation */
1421 if(n > 1){
1422 size_t i, j;
1424 for(j = 1, i = (size_t)n - 1; i-- > 0; ++j)
1425 if((*linebuf)[i] != '\\')
1426 break;
1427 if(!(j & 1))
1428 break;
1430 (*linebuf)[nold = --n] = '\0';
1431 if(prompt != NULL && *prompt != '\0')
1432 prompt = ".. "; /* XXX PS2 .. */
1435 if(n < 0)
1436 goto jleave;
1437 (*linebuf)[*linesize = n] = '\0';
1439 jhave_dat:
1440 #if 0
1441 if(lif & n_LEXINPUT_DROP_TRAIL_SPC){
1442 char *cp, c;
1443 size_t i;
1445 for(cp = &(*linebuf)[i = (size_t)n];; --i){
1446 c = *--cp;
1447 if(!blankspacechar(c))
1448 break;
1450 (*linebuf)[n = (int)i] = '\0';
1453 if(lif & n_LEXINPUT_DROP_LEAD_SPC){
1454 char *cp, c;
1455 size_t j, i;
1457 for(cp = &(*linebuf)[0], j = (size_t)n, i = 0; i < j; ++i){
1458 c = *cp++;
1459 if(!blankspacechar(c))
1460 break;
1462 if(i > 0){
1463 memcpy(&(*linebuf)[0], &(*linebuf)[i], j -= i);
1464 (*linebuf)[n = (int)j] = '\0';
1467 #endif /* 0 (notyet - must take care for backslash escaped space) */
1469 if(options & OPT_D_VV)
1470 n_err(_("%s %d bytes <%s>\n"), iftype, n, *linebuf);
1471 jleave:
1472 if (pstate & PS_PSTATE_PENDMASK)
1473 a_lex_update_pstate();
1474 NYD2_LEAVE;
1475 return n;
1478 FL char *
1479 n_lex_input_cp(enum n_lexinput_flags lif, char const *prompt,
1480 char const *string){
1481 /* FIXME n_lex_input_cp_addhist(): leaks on sigjmp without linepool */
1482 size_t linesize;
1483 char *linebuf, *rv;
1484 int n;
1485 NYD2_ENTER;
1487 linesize = 0;
1488 linebuf = NULL;
1489 rv = NULL;
1491 n = n_lex_input(lif, prompt, &linebuf, &linesize, string);
1492 if(n > 0 && *(rv = savestrbuf(linebuf, (size_t)n)) != '\0' &&
1493 (lif & n_LEXINPUT_HIST_ADD) && (options & OPT_INTERACTIVE))
1494 n_tty_addhist(rv, ((lif & n_LEXINPUT_HIST_GABBY) != 0));
1496 if(linebuf != NULL)
1497 free(linebuf);
1498 NYD2_LEAVE;
1499 return rv;
1502 FL void
1503 n_load(char const *name){
1504 struct a_lex_input_stack *lip;
1505 size_t i;
1506 FILE *fip;
1507 NYD_ENTER;
1509 if(name == NULL || *name == '\0' || (fip = Fopen(name, "r")) == NULL)
1510 goto jleave;
1512 i = strlen(name) +1;
1513 lip = scalloc(1, sizeof(*lip) -
1514 VFIELD_SIZEOF(struct a_lex_input_stack, li_name) + i);
1515 lip->li_file = fip;
1516 lip->li_flags = a_LEX_FREE;
1517 memcpy(lip->li_name, name, i);
1519 a_lex_load(lip);
1520 pstate &= ~PS_EXIT;
1521 jleave:
1522 NYD_LEAVE;
1525 FL void
1526 n_load_Xargs(char const **lines){
1527 static char const name[] = "-X";
1529 ui8_t buf[sizeof(struct a_lex_input_stack) + sizeof name];
1530 char const *srcp, *xsrcp;
1531 char *cp;
1532 size_t imax, i, len;
1533 struct a_lex_input_stack *lip;
1534 NYD_ENTER;
1536 memset(buf, 0, sizeof buf);
1537 lip = (void*)buf;
1538 lip->li_flags = a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1539 a_LEX_MACRO_X_OPTION | a_LEX_SUPER_MACRO;
1540 memcpy(lip->li_name, name, sizeof name);
1542 /* The problem being that we want to support reverse solidus newline
1543 * escaping also within multiline -X, i.e., POSIX says:
1544 * An unquoted <backslash> at the end of a command line shall
1545 * be discarded and the next line shall continue the command
1546 * Therefore instead of "lip->li_lines = UNCONST(lines)", duplicate the
1547 * entire lines array and set _MACRO_FREE_DATA */
1548 for(imax = 0; lines[imax++] != NULL;)
1550 lip->li_lines = smalloc(sizeof(*lip->li_lines) * imax);
1552 /* For each of the input lines.. */
1553 for(i = len = 0, cp = NULL; (srcp = *lines) != NULL;){
1554 bool_t keep;
1555 size_t j;
1557 if((j = strlen(srcp)) == 0){
1558 ++lines;
1559 continue;
1562 /* Separate one line from a possible multiline input string */
1563 if((xsrcp = memchr(srcp, '\n', j)) != NULL){
1564 *lines = &xsrcp[1];
1565 j = PTR2SIZE(xsrcp - srcp);
1566 }else
1567 ++lines;
1569 /* The (separated) string may itself indicate soft newline escaping */
1570 if((keep = (srcp[j - 1] == '\\'))){
1571 size_t xj, xk;
1573 /* Need an uneven number of reverse solidus */
1574 for(xk = 1, xj = j - 1; xj-- > 0; ++xk)
1575 if(srcp[xj] != '\\')
1576 break;
1577 if(xk & 1)
1578 --j;
1579 else
1580 keep = FAL0;
1583 /* Strip any leading WS from follow lines, then */
1584 if(cp != NULL)
1585 while(j > 0 && blankspacechar(*srcp))
1586 ++srcp, --j;
1588 if(j > 0){
1589 if(i + 2 >= imax){ /* TODO need a vector (main.c, here, ++) */
1590 imax += 4;
1591 lip->li_lines = srealloc(lip->li_lines, sizeof(*lip->li_lines) *
1592 imax);
1594 lip->li_lines[i] = cp = srealloc(cp, len + j +1);
1595 memcpy(&cp[len], srcp, j);
1596 cp[len += j] = '\0';
1598 if(!keep)
1599 ++i;
1601 if(!keep)
1602 cp = NULL, len = 0;
1604 if(cp != NULL){
1605 assert(i + 1 < imax);
1606 lip->li_lines[i++] = cp;
1608 lip->li_lines[i] = NULL;
1610 a_lex_load(lip);
1611 if(pstate & PS_EXIT)
1612 exit(EXIT_OK);
1613 NYD_LEAVE;
1616 FL int
1617 c_source(void *v){
1618 int rv;
1619 NYD_ENTER;
1621 rv = (a_lex_source_file(*(char**)v, FAL0) == TRU1) ? 0 : 1;
1622 NYD_LEAVE;
1623 return rv;
1626 FL int
1627 c_source_if(void *v){ /* XXX obsolete?, support file tests in `if' etc.! */
1628 int rv;
1629 NYD_ENTER;
1631 rv = (a_lex_source_file(*(char**)v, TRU1) != FAL0) ? 0 : 1;
1632 NYD_LEAVE;
1633 return rv;
1636 FL bool_t
1637 n_source_macro(enum n_lexinput_flags lif, char const *name, char **lines){
1638 struct a_lex_input_stack *lip;
1639 size_t i;
1640 int rv;
1641 NYD_ENTER;
1643 lip = smalloc(sizeof(*lip) -
1644 VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1645 (i = strlen(name) +1));
1646 lip->li_outer = a_lex_input;
1647 lip->li_file = NULL;
1648 lip->li_cond = condstack_release();
1649 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1650 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1651 ? a_LEX_SUPER_MACRO : 0);
1652 lip->li_loff = 0;
1653 lip->li_lines = lines;
1654 memcpy(lip->li_name, name, i);
1656 pstate |= PS_ROBOT;
1657 a_lex_input = lip;
1658 rv = a_commands_recursive(lif);
1659 NYD_LEAVE;
1660 return rv;
1663 FL bool_t
1664 n_source_command(enum n_lexinput_flags lif, char const *cmd){
1665 struct a_lex_input_stack *lip;
1666 size_t i, ial;
1667 bool_t rv;
1668 NYD_ENTER;
1670 i = strlen(cmd);
1671 cmd = sbufdup(cmd, i++);
1672 ial = n_ALIGN(i);
1674 lip = smalloc(sizeof(*lip) -
1675 VFIELD_SIZEOF(struct a_lex_input_stack, li_name) +
1676 ial + 2*sizeof(char*));
1677 lip->li_outer = a_lex_input;
1678 lip->li_file = NULL;
1679 lip->li_cond = condstack_release();
1680 lip->li_flags = a_LEX_FREE | a_LEX_MACRO | a_LEX_MACRO_FREE_DATA |
1681 a_LEX_MACRO_CMD |
1682 (a_lex_input == NULL || (a_lex_input->li_flags & a_LEX_SUPER_MACRO)
1683 ? a_LEX_SUPER_MACRO : 0);
1684 lip->li_loff = 0;
1685 lip->li_lines = (void*)(lip->li_name + ial);
1686 lip->li_lines[0] = UNCONST(cmd); /* dup'ed above */
1687 lip->li_lines[1] = NULL;
1688 memcpy(lip->li_name, cmd, i);
1690 pstate |= PS_ROBOT;
1691 a_lex_input = lip;
1692 rv = a_commands_recursive(lif);
1693 NYD_LEAVE;
1694 return rv;
1697 FL bool_t
1698 n_source_may_yield_control(void){
1699 return ((options & OPT_INTERACTIVE) &&
1700 (pstate & PS_STARTED) &&
1701 (!(pstate & PS_ROBOT) || (pstate & PS_RECURSED)) && /* Ok for ~: */
1702 (a_lex_input == NULL || a_lex_input->li_outer == NULL));
1705 /* s-it-mode */