colour_table_create(): auto-enable $TERMs named "color" (Gavin Troy)
[s-mailx.git] / lex.c
blob615ca33d21a0df0cc1c8f3b3653eebb47d99d3dc
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ (Lexical processing of) Commands, and the (blocking) "event mainloop".
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2014 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
6 */
7 /*
8 * Copyright (c) 1980, 1993
9 * The Regents of the University of California. All rights reserved.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * SUCH DAMAGE.
40 #ifndef HAVE_AMALGAMATION
41 # include "nail.h"
42 #endif
44 #include <fcntl.h>
46 struct cmd {
47 char const *name; /* Name of command */
48 int (*func)(void*); /* Implementor of command */
49 enum argtype argtype; /* Arglist type (see below) */
50 short msgflag; /* Required flags of msgs */
51 short msgmask; /* Relevant flags of msgs */
52 #ifdef HAVE_DOCSTRINGS
53 int docid; /* Translation id of .doc */
54 char const *doc; /* One line doc for command */
55 #endif
57 /* Yechh, can't initialize unions */
58 #define minargs msgflag /* Minimum argcount for RAWLIST */
59 #define maxargs msgmask /* Max argcount for RAWLIST */
61 struct cmd_ghost {
62 struct cmd_ghost *next;
63 struct str cmd; /* Data follows after .name */
64 char name[VFIELD_SIZE(sizeof(size_t))];
67 static int *_msgvec;
68 static int _reset_on_stop; /* do a reset() if stopped */
69 static sighandler_type _oldpipe;
70 static struct cmd_ghost *_cmd_ghosts;
71 /* _cmd_tab[] after fun protos */
72 static int _lex_inithdr; /* am printing startup headers */
74 /* Update mailname (if name != NULL) and displayname, return wether displayname
75 * was large enough to swallow mailname */
76 static bool_t _update_mailname(char const *name);
77 #ifdef HAVE_C90AMEND1 /* TODO unite __narrow_suffix() into one fun! */
78 SINLINE size_t __narrow_suffix(char const *cp, size_t cpl, size_t maxl);
79 #endif
81 /* Isolate the command from the arguments */
82 static char * _lex_isolate(char const *comm);
84 /* Get first-fit, or NULL */
85 static struct cmd const * _lex(char const *comm);
87 /* Command ghost handling */
88 static int _ghost(void *v);
89 static int _unghost(void *v);
91 /* Print a list of all commands */
92 static int _pcmdlist(void *v);
93 static int __pcmd_cmp(void const *s1, void const *s2);
95 /* Print the binaries compiled-in features */
96 static int _features(void *v);
98 /* Print the binaries version number */
99 static int _version(void *v);
101 /* When we wake up after ^Z, reprint the prompt */
102 static void stop(int s);
104 /* Branch here on hangup signal and simulate "exit" */
105 static void hangup(int s);
107 /* List of all commands */
108 static struct cmd const _cmd_tab[] = {
109 #include "cmd_tab.h"
112 #ifdef HAVE_C90AMEND1
113 SINLINE size_t
114 __narrow_suffix(char const *cp, size_t cpl, size_t maxl)
116 int err;
117 size_t i, ok;
118 NYD_ENTER;
120 for (err = ok = i = 0; cpl > maxl || err;) {
121 int ml = mblen(cp, cpl);
122 if (ml < 0) { /* XXX _narrow_suffix(): mblen() error; action? */
123 (void)mblen(NULL, 0);
124 err = 1;
125 ml = 1;
126 } else {
127 if (!err)
128 ok = i;
129 err = 0;
130 if (ml == 0)
131 break;
133 cp += ml;
134 i += ml;
135 cpl -= ml;
137 NYD_LEAVE;
138 return ok;
140 #endif /* HAVE_C90AMEND1 */
142 static bool_t
143 _update_mailname(char const *name)
145 char tbuf[PATH_MAX], *mailp, *dispp;
146 size_t i, j;
147 bool_t rv = TRU1;
148 NYD_ENTER;
150 /* Don't realpath(3) if it's only an update request */
151 if (name != NULL) {
152 #ifdef HAVE_REALPATH
153 enum protocol p = which_protocol(name);
154 if (p == PROTO_FILE || p == PROTO_MAILDIR) {
155 if (realpath(name, mailname) == NULL) {
156 fprintf(stderr, tr(151, "Can't canonicalize `%s'\n"), name);
157 rv = FAL0;
158 goto jdocopy;
160 } else
161 jdocopy:
162 #endif
163 n_strlcpy(mailname, name, sizeof(mailname));
166 mailp = mailname;
167 dispp = displayname;
169 /* Don't display an absolute path but "+FOLDER" if under *folder* */
170 if (getfold(tbuf, sizeof tbuf)) {
171 i = strlen(tbuf);
172 if (i < sizeof(tbuf) -1)
173 tbuf[i++] = '/';
174 if (!strncmp(tbuf, mailp, i)) {
175 mailp += i;
176 *dispp++ = '+';
180 /* We want to see the name of the folder .. on the screen */
181 i = strlen(mailp);
182 if (i < sizeof(displayname) -1)
183 memcpy(dispp, mailp, i +1);
184 else {
185 rv = FAL0;
186 /* Avoid disrupting multibyte sequences (if possible) */
187 #ifndef HAVE_C90AMEND1
188 j = sizeof(displayname) / 3 - 1;
189 i -= sizeof(displayname) - (1/* + */ + 3) - j;
190 #else
191 j = field_detect_clip(sizeof(displayname) / 3, mailp, i);
192 i = j + __narrow_suffix(mailp + j, i - j,
193 sizeof(displayname) - (1/* + */ + 3 + 1) - j);
194 #endif
195 snprintf(dispp, sizeof(displayname), "%.*s...%s",
196 (int)j, mailp, mailp + i);
198 NYD_LEAVE;
199 return rv;
202 static char *
203 _lex_isolate(char const *comm)
205 NYD_ENTER;
206 while (*comm != '\0' &&
207 strchr("~|? \t0123456789&%@$^.:/-+*'\",;(`", *comm) == NULL)
208 ++comm;
209 NYD_LEAVE;
210 return UNCONST(comm);
213 static struct cmd const *
214 _lex(char const *comm) /* TODO **command hashtable**! linear list search!!! */
216 struct cmd const *cp;
217 NYD_ENTER;
219 for (cp = _cmd_tab; cp->name != NULL; ++cp)
220 if (*comm == *cp->name && is_prefix(comm, cp->name))
221 goto jleave;
222 cp = NULL;
223 jleave:
224 NYD_LEAVE;
225 return cp;
228 static int
229 _ghost(void *v)
231 char const **argv = v;
232 struct cmd_ghost *lcg, *cg;
233 size_t nl, cl;
234 NYD_ENTER;
236 /* Show the list? */
237 if (*argv == NULL) {
238 printf(tr(144, "Command ghosts are:\n"));
239 for (nl = 0, cg = _cmd_ghosts; cg != NULL; cg = cg->next) {
240 cl = strlen(cg->name) + 5 + cg->cmd.l + 3;
241 nl += cl;
242 if (UICMP(z, nl, >=, scrnwidth)) {
243 nl = cl;
244 printf("\n");
246 printf((cg->next != NULL ? "%s -> <%s>, " : "%s -> <%s>\n"),
247 cg->name, cg->cmd.s);
249 v = NULL;
250 goto jleave;
253 /* Request to add new ghost */
254 if (argv[1] == NULL || argv[1][0] == '\0' || argv[2] != NULL) {
255 fprintf(stderr, tr(159, "Usage: %s\n"),
256 tr(425, "Define a <ghost> of <command>, or list all ghosts"));
257 v = NULL;
258 goto jleave;
261 /* Check that we can deal with this one */
262 if (argv[0] == _lex_isolate(argv[0])) {
263 fprintf(stderr, tr(151, "Can't canonicalize `%s'\n"), argv[0]);
264 v = NULL;
265 goto jleave;
268 /* Always recreate */
269 for (lcg = NULL, cg = _cmd_ghosts; cg != NULL; lcg = cg, cg = cg->next)
270 if (!strcmp(cg->name, argv[0])) {
271 if (lcg != NULL)
272 lcg->next = cg->next;
273 else
274 _cmd_ghosts = cg->next;
275 free(cg);
276 break;
279 /* Need a new one */
280 nl = strlen(argv[0]) +1;
281 cl = strlen(argv[1]) +1;
282 cg = smalloc(sizeof(*cg) - VFIELD_SIZEOF(struct cmd_ghost, name) + nl + cl);
283 cg->next = _cmd_ghosts;
284 memcpy(cg->name, argv[0], nl);
285 cg->cmd.s = cg->name + nl;
286 cg->cmd.l = cl -1;
287 memcpy(cg->cmd.s, argv[1], cl);
289 _cmd_ghosts = cg;
290 jleave:
291 NYD_LEAVE;
292 return (v == NULL);
295 static int
296 _unghost(void *v)
298 int rv = 0;
299 char const **argv = v, *cp;
300 struct cmd_ghost *lcg, *cg;
301 NYD_ENTER;
303 while ((cp = *argv++) != NULL) {
304 for (lcg = NULL, cg = _cmd_ghosts; cg != NULL; lcg = cg, cg = cg->next)
305 if (!strcmp(cg->name, cp)) {
306 if (lcg != NULL)
307 lcg->next = cg->next;
308 else
309 _cmd_ghosts = cg->next;
310 free(cg);
311 goto jouter;
313 fprintf(stderr, tr(91, "Unknown command: `%s'\n"), cp);
314 rv = 1;
315 jouter:
318 NYD_LEAVE;
319 return rv;
322 static int
323 __pcmd_cmp(void const *s1, void const *s2)
325 struct cmd const * const *c1 = s1, * const *c2 = s2;
326 int rv;
327 NYD_ENTER;
329 rv = strcmp((*c1)->name, (*c2)->name);
330 NYD_LEAVE;
331 return rv;
334 static int
335 _pcmdlist(void *v)
337 struct cmd const **cpa, *cp, **cursor;
338 size_t i;
339 NYD_ENTER;
340 UNUSED(v);
342 for (i = 0; _cmd_tab[i].name != NULL; ++i)
344 ++i;
345 cpa = ac_alloc(sizeof(cp) * i);
347 for (i = 0; (cp = _cmd_tab + i)->name != NULL; ++i)
348 cpa[i] = cp;
349 cpa[i] = NULL;
351 qsort(cpa, i, sizeof(cp), &__pcmd_cmp);
353 printf(tr(14, "Commands are:\n"));
354 for (i = 0, cursor = cpa; (cp = *cursor++) != NULL;) {
355 size_t j;
356 if (cp->func == &c_cmdnotsupp)
357 continue;
358 j = strlen(cp->name) + 2;
359 if ((i += j) > 72) {
360 i = j;
361 printf("\n");
363 printf((*cursor != NULL ? "%s, " : "%s\n"), cp->name);
366 ac_free(cpa);
367 NYD_LEAVE;
368 return 0;
371 static int
372 _features(void *v)
374 NYD_ENTER;
375 UNUSED(v);
376 printf(tr(523, "Features: %s\n"), features);
377 NYD_LEAVE;
378 return 0;
381 static int
382 _version(void *v)
384 NYD_ENTER;
385 UNUSED(v);
386 printf(tr(111, "Version %s\n"), version);
387 NYD_LEAVE;
388 return 0;
391 static void
392 stop(int s)
394 sighandler_type old_action;
395 sigset_t nset;
396 NYD_X; /* Signal handler */
398 old_action = safe_signal(s, SIG_DFL);
400 sigemptyset(&nset);
401 sigaddset(&nset, s);
402 sigprocmask(SIG_UNBLOCK, &nset, NULL);
403 kill(0, s);
404 sigprocmask(SIG_BLOCK, &nset, NULL);
405 safe_signal(s, old_action);
406 if (_reset_on_stop) {
407 _reset_on_stop = 0;
408 reset(0);
412 static void
413 hangup(int s)
415 NYD_X; /* Signal handler */
416 UNUSED(s);
417 /* nothing to do? */
418 exit(1);
421 FL int
422 setfile(char const *name, int nmail) /* TODO oh my god */
424 static int shudclob;
426 struct stat stb;
427 struct flock flp;
428 FILE *ibuf = NULL;
429 int rv, i, compressed = 0, omsgCount = 0;
430 bool_t isedit;
431 char const *who;
432 size_t offset;
433 struct shortcut *sh;
434 NYD_ENTER;
436 /* Note we don't 'userid(myname) != getuid()', preliminary steps are usually
437 * necessary to make a mailbox accessible by a different user, and if that
438 * has happened, let's just let the usual file perms decide */
439 who = (name[1] != '\0') ? name + 1 : myname;
440 isedit = (*name != '%' && ((sh = get_shortcut(name)) == NULL ||
441 *sh->sh_long != '%'));
442 if ((name = expand(name)) == NULL)
443 goto jem1;
445 switch (which_protocol(name)) {
446 case PROTO_FILE:
447 break;
448 case PROTO_MAILDIR:
449 rv = maildir_setfile(name, nmail, isedit);
450 goto jleave;
451 #ifdef HAVE_POP3
452 case PROTO_POP3:
453 shudclob = 1;
454 rv = pop3_setfile(name, nmail, isedit);
455 goto jleave;
456 #endif
457 #ifdef HAVE_IMAP
458 case PROTO_IMAP:
459 shudclob = 1;
460 if (nmail && mb.mb_type == MB_CACHE)
461 rv = 1;
462 else
463 rv = imap_setfile(name, nmail, isedit);
464 goto jleave;
465 #endif
466 default:
467 fprintf(stderr, tr(217, "Cannot handle protocol: %s\n"), name);
468 goto jem1;
471 /* FIXME this FILE leaks if quit()->edstop() reset()s! This entire code
472 * FIXME here is total crap, below we open(2) the same name again just to
473 * FIXME close it right away etc. The normal thing would be to (1) finalize
474 * FIXME the current box and (2) open the new box; yet, since (2) may fail
475 * FIXME we terribly need our VOID box to make this logic order possible! */
476 if ((ibuf = Zopen(name, "r", &compressed)) == NULL) {
477 if ((!isedit && errno == ENOENT) || nmail) {
478 if (nmail)
479 goto jnonmail;
480 goto jnomail;
482 perror(name);
483 goto jem1;
486 if (fstat(fileno(ibuf), &stb) == -1) {
487 if (nmail)
488 goto jnonmail;
489 perror("fstat");
490 goto jem1;
493 if (S_ISREG(stb.st_mode) ||
494 ((options & OPT_BATCH_FLAG) && !strcmp(name, "/dev/null"))) {
495 /* EMPTY */
496 } else {
497 if (nmail)
498 goto jnonmail;
499 errno = S_ISDIR(stb.st_mode) ? EISDIR : EINVAL;
500 perror(name);
501 goto jem1;
504 /* Looks like all will be well. We must now relinquish our hold on the
505 * current set of stuff. Must hold signals while we are reading the new
506 * file, else we will ruin the message[] data structure */
508 hold_sigs(); /* TODO note on this one in quit.c:quit() */
509 if (shudclob && !nmail)
510 quit();
511 #ifdef HAVE_SOCKETS
512 if (!nmail && mb.mb_sock.s_fd >= 0)
513 sclose(&mb.mb_sock); /* TODO sorry? VMAILFS->close(), thank you */
514 #endif
516 /* Copy the messages into /tmp and set pointers */
517 flp.l_type = F_RDLCK;
518 flp.l_start = 0;
519 flp.l_whence = SEEK_SET;
520 if (!nmail) {
521 mb.mb_type = MB_FILE;
522 mb.mb_perm = (options & OPT_R_FLAG) ? 0 : MB_DELE | MB_EDIT;
523 mb.mb_compressed = compressed;
524 if (compressed) {
525 if (compressed & 0200)
526 mb.mb_perm = 0;
527 } else {
528 if ((i = open(name, O_WRONLY)) == -1)
529 mb.mb_perm = 0;
530 else
531 close(i);
533 if (shudclob) {
534 if (mb.mb_itf) {
535 fclose(mb.mb_itf);
536 mb.mb_itf = NULL;
538 if (mb.mb_otf) {
539 fclose(mb.mb_otf);
540 mb.mb_otf = NULL;
543 shudclob = 1;
544 edit = isedit;
545 initbox(name);
546 offset = 0;
547 flp.l_len = 0;
548 if (!edit && fcntl(fileno(ibuf), F_SETLKW, &flp) == -1) {/*TODO dotlock!*/
549 perror("Unable to lock mailbox");
550 rele_sigs();
551 goto jem1;
553 } else /* nmail */{
554 fseek(mb.mb_otf, 0L, SEEK_END);
555 fseek(ibuf, mailsize, SEEK_SET);
556 offset = mailsize;
557 omsgCount = msgCount;
558 flp.l_len = offset;
559 if (!edit && fcntl(fileno(ibuf), F_SETLKW, &flp) == -1) {/*TODO dotlock!*/
560 rele_sigs();
561 goto jnonmail;
564 mailsize = fsize(ibuf);
566 if (nmail && UICMP(z, mailsize, <=, offset)) {
567 rele_sigs();
568 goto jnonmail;
570 setptr(ibuf, offset);
571 setmsize(msgCount);
572 if (nmail && mb.mb_sorted) {
573 mb.mb_threaded = 0;
574 c_sort((void*)-1);
577 Fclose(ibuf);
578 ibuf = NULL;
579 rele_sigs();
580 if (!nmail)
581 sawcom = FAL0;
583 if ((!edit || nmail) && msgCount == 0) {
584 jnonmail:
585 if (!nmail) {
586 if (!ok_blook(emptystart))
587 jnomail:
588 fprintf(stderr, tr(88, "No mail for %s\n"), who);
590 rv = 1;
591 goto jleave;
593 if (nmail)
594 newmailinfo(omsgCount);
596 rv = 0;
597 jleave:
598 if (ibuf != NULL)
599 Fclose(ibuf);
600 NYD_LEAVE;
601 return rv;
602 jem1:
603 rv = -1;
604 goto jleave;
607 FL int
608 newmailinfo(int omsgCount)
610 int mdot, i;
611 NYD_ENTER;
613 for (i = 0; i < omsgCount; ++i)
614 message[i].m_flag &= ~MNEWEST;
615 if (msgCount > omsgCount) {
616 for (i = omsgCount; i < msgCount; ++i)
617 message[i].m_flag |= MNEWEST;
618 printf(tr(158, "New mail has arrived.\n"));
619 if ((i = msgCount - omsgCount) == 1)
620 printf(tr(214, "Loaded 1 new message.\n"));
621 else
622 printf(tr(215, "Loaded %d new messages.\n"), i);
623 } else
624 printf(tr(224, "Loaded %d messages.\n"), msgCount);
625 callhook(mailname, 1);
626 mdot = getmdot(1);
627 if (ok_blook(header))
628 print_headers(omsgCount + 1, msgCount, FAL0);
629 NYD_LEAVE;
630 return mdot;
633 FL void
634 commands(void)
636 struct eval_ctx ev;
637 int n;
638 NYD_ENTER;
640 if (!sourcing) {
641 if (safe_signal(SIGINT, SIG_IGN) != SIG_IGN)
642 safe_signal(SIGINT, onintr);
643 if (safe_signal(SIGHUP, SIG_IGN) != SIG_IGN)
644 safe_signal(SIGHUP, hangup);
645 /* TODO We do a lot of redundant signal handling, especially
646 * TODO with the command line editor(s); try to merge this */
647 safe_signal(SIGTSTP, stop);
648 safe_signal(SIGTTOU, stop);
649 safe_signal(SIGTTIN, stop);
651 _oldpipe = safe_signal(SIGPIPE, SIG_IGN);
652 safe_signal(SIGPIPE, _oldpipe);
654 memset(&ev, 0, sizeof ev);
656 setexit();
657 for (;;) {
658 interrupts = 0;
659 handlerstacktop = NULL;
661 if (!sourcing && (options & OPT_INTERACTIVE)) {
662 char *cp;
664 cp = ok_vlook(newmail);
665 if ((options & OPT_TTYIN) && (cp != NULL || mb.mb_type == MB_IMAP)) {
666 struct stat st;
668 n = (cp != NULL && strcmp(cp, "noimap") && strcmp(cp, "nopoll"));
669 if ((mb.mb_type == MB_FILE && !stat(mailname, &st) &&
670 st.st_size > mailsize) ||
671 #ifdef HAVE_IMAP
672 (mb.mb_type == MB_IMAP && imap_newmail(n) > (cp == NULL)) ||
673 #endif
674 (mb.mb_type == MB_MAILDIR && n != 0)) {
675 size_t odot = PTR2SIZE(dot - message);
676 bool_t odid = did_print_dot;
678 setfile(mailname, 1);
679 if (mb.mb_type != MB_IMAP) {
680 dot = message + odot;
681 did_print_dot = odid;
686 _reset_on_stop = 1;
687 exit_status = EXIT_OK;
690 #ifdef HAVE_COLOUR
691 colour_table = NULL; /* XXX intermediate hack */
692 #endif
693 if (temporary_localopts_store != NULL) /* XXX intermediate hack */
694 temporary_localopts_free(); /* XXX intermediate hack */
695 sreset(sourcing);
696 if (!sourcing) {
697 char *cp;
699 /* TODO Note: this buffer may contain a password. We should redefine
700 * TODO the code flow which has to do that */
701 if ((cp = termios_state.ts_linebuf) != NULL) {
702 termios_state.ts_linebuf = NULL;
703 termios_state.ts_linesize = 0;
704 free(cp); /* TODO pool give-back */
706 /* TODO Due to expand-on-tab of NCL the buffer may grow */
707 if (ev.ev_line.l > LINESIZE * 3) {
708 free(ev.ev_line.s); /* TODO pool! but what? */
709 ev.ev_line.s = NULL;
710 ev.ev_line.l = 0;
714 /* Read a line of commands and handle end of file specially */
715 jreadline:
716 ev.ev_line.l = ev.ev_line_size;
717 n = readline_input(NULL, TRU1, &ev.ev_line.s, &ev.ev_line.l,
718 ev.ev_new_content);
719 ev.ev_line_size = (ui32_t)ev.ev_line.l;
720 ev.ev_line.l = (ui32_t)n;
721 _reset_on_stop = 0;
722 if (n < 0) {
723 /* EOF */
724 if (loading)
725 break;
726 if (sourcing) {
727 unstack();
728 continue;
730 if ((options & OPT_INTERACTIVE) && ok_blook(ignoreeof)) {
731 printf(tr(89, "Use `quit' to quit.\n"));
732 continue;
734 break;
737 inhook = 0;
738 if (evaluate(&ev))
739 break;
740 if ((options & OPT_BATCH_FLAG) && ok_blook(batch_exit_on_error)) {
741 if (exit_status != EXIT_OK)
742 break;
743 /* TODO *batch-exit-on-error*: sourcing and loading MUST BE FLAGS!
744 * TODO the current behaviour is suboptimal AT BEST! */
745 if (exec_last_comm_error != 0 && !sourcing && !loading) {
746 exit_status = EXIT_ERR;
747 break;
750 if (!sourcing && (options & OPT_INTERACTIVE)) {
751 if (ev.ev_new_content != NULL)
752 goto jreadline;
753 tty_addhist(ev.ev_line.s, !ev.ev_add_history);
757 if (ev.ev_line.s != NULL)
758 free(ev.ev_line.s);
759 if (sourcing)
760 sreset(FAL0);
761 NYD_LEAVE;
764 FL int
765 execute(char *linebuf, int contxt, size_t linesize) /* XXX LEGACY */
767 struct eval_ctx ev;
768 #ifdef HAVE_COLOUR
769 struct colour_table *ct_save;
770 #endif
771 int rv;
772 NYD_ENTER;
774 /* TODO Maybe recursion from within collect.c! As long as we don't have
775 * TODO a value carrier that transports the entire state of a recursion
776 * TODO we need to save away also the colour table */
777 #ifdef HAVE_COLOUR
778 ct_save = colour_table;
779 colour_table = NULL;
780 #endif
782 memset(&ev, 0, sizeof ev);
783 ev.ev_line.s = linebuf;
784 ev.ev_line.l = linesize;
785 ev.ev_is_recursive = (contxt != 0);
786 rv = evaluate(&ev);
788 if (contxt)
789 tty_addhist(ev.ev_line.s, TRU1);
791 #ifdef HAVE_COLOUR
792 colour_table = ct_save;
793 #endif
794 NYD_LEAVE;
795 return rv;
798 FL int
799 evaluate(struct eval_ctx *evp)
801 struct str line;
802 char _wordbuf[2], *arglist[MAXARGC], *cp, *word;
803 struct cmd_ghost *cg = NULL;
804 struct cmd const *com = NULL;
805 int muvec[2], c, e = 1;
806 NYD_ENTER;
808 line = evp->ev_line; /* XXX don't change original (buffer pointer) */
809 evp->ev_add_history = FAL0;
810 evp->ev_new_content = NULL;
812 /* Command ghosts that refer to shell commands or macro expansion restart */
813 jrestart:
815 /* Strip the white space away from the beginning of the command */
816 for (cp = line.s; whitechar(*cp); ++cp)
818 line.l -= PTR2SIZE(cp - line.s);
820 /* Ignore comments */
821 if (*cp == '#')
822 goto jleave0;
824 /* Handle ! differently to get the correct lexical conventions */
825 if (*cp == '!') {
826 if (sourcing) {
827 fprintf(stderr, tr(90, "Can't `!' while sourcing\n"));
828 goto jleave;
830 c_shell(++cp);
831 evp->ev_add_history = TRU1;
832 goto jleave0;
835 /* Isolate the actual command; since it may not necessarily be
836 * separated from the arguments (as in `p1') we need to duplicate it to
837 * be able to create a NUL terminated version.
838 * We must be aware of several special one letter commands here */
839 arglist[0] = cp;
840 if ((cp = _lex_isolate(cp)) == arglist[0] &&
841 (*cp == '|' || *cp == '~' || *cp == '?'))
842 ++cp;
843 c = (int)PTR2SIZE(cp - arglist[0]);
844 line.l -= c;
845 word = UICMP(z, c, <, sizeof _wordbuf) ? _wordbuf : salloc(c +1);
846 memcpy(word, arglist[0], c);
847 word[c] = '\0';
849 /* Look up the command; if not found, bitch.
850 * Normally, a blank command would map to the first command in the
851 * table; while sourcing, however, we ignore blank lines to eliminate
852 * confusion; act just the same for ghosts */
853 if (*word == '\0') {
854 if (sourcing || cg != NULL)
855 goto jleave0;
856 com = _cmd_tab + 0;
857 goto jexec;
860 /* If this is the first evaluation, check command ghosts */
861 if (cg == NULL) {
862 /* TODO relink list head, so it's sorted on usage over time?
863 * TODO in fact, there should be one hashmap over all commands and ghosts
864 * TODO so that the lookup could be made much more efficient than it is
865 * TODO now (two adjacent list searches! */
866 for (cg = _cmd_ghosts; cg != NULL; cg = cg->next)
867 if (!strcmp(word, cg->name)) {
868 if (line.l > 0) {
869 size_t i = cg->cmd.l;
870 line.s = salloc(i + 1 + line.l +1);
871 memcpy(line.s, cg->cmd.s, i);
872 line.s[i++] = ' ';
873 memcpy(line.s + i, cp, line.l);
874 line.s[i += line.l] = '\0';
875 line.l = i;
876 } else {
877 line.s = cg->cmd.s;
878 line.l = cg->cmd.l;
880 goto jrestart;
884 if ((com = _lex(word)) == NULL || com->func == &c_cmdnotsupp) {
885 fprintf(stderr, tr(91, "Unknown command: `%s'\n"), word);
886 if (com != NULL) {
887 c_cmdnotsupp(NULL);
888 com = NULL;
890 goto jleave;
893 /* See if we should execute the command -- if a conditional we always
894 * execute it, otherwise, check the state of cond */
895 jexec:
896 if (!(com->argtype & ARG_F) && condstack_isskip())
897 goto jleave0;
899 /* Process the arguments to the command, depending on the type it expects,
900 * default to error. If we're sourcing an interactive command: error */
901 if ((options & OPT_SENDMODE) && !(com->argtype & ARG_M)) {
902 fprintf(stderr, tr(92, "May not execute `%s' while sending\n"),
903 com->name);
904 goto jleave;
906 if (sourcing && (com->argtype & ARG_I)) {
907 fprintf(stderr, tr(93, "May not execute `%s' while sourcing\n"),
908 com->name);
909 goto jleave;
911 if (!(mb.mb_perm & MB_DELE) && (com->argtype & ARG_W)) {
912 fprintf(stderr, tr(94, "May not execute `%s' -- "
913 "message file is read only\n"), com->name);
914 goto jleave;
916 if (evp->ev_is_recursive && (com->argtype & ARG_R)) {
917 fprintf(stderr, tr(95, "Cannot recursively invoke `%s'\n"), com->name);
918 goto jleave;
920 if (mb.mb_type == MB_VOID && (com->argtype & ARG_A)) {
921 fprintf(stderr, tr(257, "Cannot execute `%s' without active mailbox\n"),
922 com->name);
923 goto jleave;
926 if (com->argtype & ARG_V)
927 temporary_arg_v_store = NULL;
929 switch (com->argtype & ARG_ARGMASK) {
930 case ARG_MSGLIST:
931 /* Message list defaulting to nearest forward legal message */
932 if (_msgvec == NULL)
933 goto je96;
934 if ((c = getmsglist(cp, _msgvec, com->msgflag)) < 0)
935 break;
936 if (c == 0) {
937 *_msgvec = first(com->msgflag, com->msgmask);
938 if (*_msgvec != 0)
939 _msgvec[1] = 0;
941 if (*_msgvec == 0) {
942 if (!inhook)
943 printf(tr(97, "No applicable messages\n"));
944 break;
946 e = (*com->func)(_msgvec);
947 break;
949 case ARG_NDMLIST:
950 /* Message list with no defaults, but no error if none exist */
951 if (_msgvec == NULL) {
952 je96:
953 fprintf(stderr, tr(96, "Invalid use of `message list'\n"));
954 break;
956 if ((c = getmsglist(cp, _msgvec, com->msgflag)) < 0)
957 break;
958 e = (*com->func)(_msgvec);
959 break;
961 case ARG_STRLIST:
962 /* Just the straight string, with leading blanks removed */
963 while (whitechar(*cp))
964 ++cp;
965 e = (*com->func)(cp);
966 break;
968 case ARG_RAWLIST:
969 case ARG_ECHOLIST:
970 /* A vector of strings, in shell style */
971 if ((c = getrawlist(cp, line.l, arglist, NELEM(arglist),
972 ((com->argtype & ARG_ARGMASK) == ARG_ECHOLIST))) < 0)
973 break;
974 if (c < com->minargs) {
975 fprintf(stderr, tr(99, "`%s' requires at least %d arg(s)\n"),
976 com->name, com->minargs);
977 break;
979 if (c > com->maxargs) {
980 fprintf(stderr, tr(100, "`%s' takes no more than %d arg(s)\n"),
981 com->name, com->maxargs);
982 break;
984 e = (*com->func)(arglist);
985 break;
987 case ARG_NOLIST:
988 /* Just the constant zero, for exiting, eg. */
989 e = (*com->func)(0);
990 break;
992 default:
993 panic(tr(101, "Unknown argument type"));
996 if (e == 0 && (com->argtype & ARG_V) &&
997 (cp = temporary_arg_v_store) != NULL) {
998 temporary_arg_v_store = NULL;
999 evp->ev_new_content = cp;
1000 goto jleave0;
1002 if (!(com->argtype & ARG_H) && !list_saw_numbers)
1003 evp->ev_add_history = TRU1;
1005 jleave:
1006 /* Exit the current source file on error */
1007 if ((exec_last_comm_error = (e != 0))) {
1008 if (e < 0 || loading) {
1009 e = 1;
1010 goto jret;
1012 if (sourcing)
1013 unstack();
1014 goto jret0;
1016 if (com == NULL)
1017 goto jret0;
1018 if ((com->argtype & ARG_P) && ok_blook(autoprint))
1019 if (visible(dot)) {
1020 muvec[0] = (int)PTR2SIZE(dot - message + 1);
1021 muvec[1] = 0;
1022 c_type(muvec); /* TODO what if error? re-eval! */
1024 if (!sourcing && !inhook && !(com->argtype & ARG_T))
1025 sawcom = TRU1;
1026 jleave0:
1027 exec_last_comm_error = 0;
1028 jret0:
1029 e = 0;
1030 jret:
1031 NYD_LEAVE;
1032 return e;
1035 FL void
1036 setmsize(int sz)
1038 NYD_ENTER;
1039 if (_msgvec != NULL)
1040 free(_msgvec);
1041 _msgvec = scalloc(sz + 1, sizeof *_msgvec);
1042 NYD_LEAVE;
1045 FL void
1046 print_header_summary(char const *Larg)
1048 size_t bot, top, i, j;
1049 NYD_ENTER;
1051 if (Larg != NULL) {
1052 /* Avoid any messages XXX add a make_mua_silent() and use it? */
1053 if ((options & (OPT_VERB | OPT_HEADERSONLY)) == OPT_HEADERSONLY) {
1054 freopen("/dev/null", "w", stdout);
1055 freopen("/dev/null", "w", stderr);
1057 assert(_msgvec != NULL);
1058 i = (getmsglist(/*TODO make arg const */UNCONST(Larg), _msgvec, 0) <= 0);
1059 if (options & OPT_HEADERSONLY) {
1060 exit_status = (int)i;
1061 goto jleave;
1063 if (i)
1064 goto jleave;
1065 for (bot = msgCount, top = 0, i = 0; (j = _msgvec[i]) != 0; ++i) {
1066 if (bot > j)
1067 bot = j;
1068 if (top < j)
1069 top = j;
1071 } else
1072 bot = 1, top = msgCount;
1073 print_headers(bot, top, (Larg != NULL)); /* TODO should take iterator!! */
1074 jleave:
1075 NYD_LEAVE;
1078 FL void
1079 onintr(int s)
1081 NYD_X; /* Signal handler */
1083 if (handlerstacktop != NULL) {
1084 handlerstacktop(s);
1085 return;
1087 safe_signal(SIGINT, onintr);
1088 noreset = 0;
1089 if (!_lex_inithdr)
1090 sawcom = TRU1;
1091 _lex_inithdr = 0;
1092 while (sourcing)
1093 unstack();
1095 termios_state_reset();
1096 close_all_files();
1098 if (image >= 0) {
1099 close(image);
1100 image = -1;
1102 if (interrupts != 1)
1103 fprintf(stderr, tr(102, "Interrupt\n"));
1104 safe_signal(SIGPIPE, _oldpipe);
1105 reset(0);
1108 FL void
1109 announce(int printheaders)
1111 int vec[2], mdot;
1112 NYD_ENTER;
1114 mdot = newfileinfo();
1115 vec[0] = mdot;
1116 vec[1] = 0;
1117 dot = message + mdot - 1;
1118 if (printheaders && msgCount > 0 && ok_blook(header)) {
1119 ++_lex_inithdr;
1120 c_headers(vec); /* XXX errors? */
1121 _lex_inithdr = 0;
1123 NYD_LEAVE;
1126 FL int
1127 newfileinfo(void)
1129 struct message *mp;
1130 int u, n, mdot, d, s, hidden, moved;
1131 NYD_ENTER;
1133 if (mb.mb_type == MB_VOID) {
1134 mdot = 1;
1135 goto jleave;
1138 mdot = getmdot(0);
1139 s = d = hidden = moved =0;
1140 for (mp = message, n = 0, u = 0; PTRCMP(mp, <, message + msgCount); ++mp) {
1141 if (mp->m_flag & MNEW)
1142 ++n;
1143 if ((mp->m_flag & MREAD) == 0)
1144 ++u;
1145 if ((mp->m_flag & (MDELETED | MSAVED)) == (MDELETED | MSAVED))
1146 ++moved;
1147 if ((mp->m_flag & (MDELETED | MSAVED)) == MDELETED)
1148 ++d;
1149 if ((mp->m_flag & (MDELETED | MSAVED)) == MSAVED)
1150 ++s;
1151 if (mp->m_flag & MHIDDEN)
1152 ++hidden;
1155 /* If displayname gets truncated the user effectively has no option to see
1156 * the full pathname of the mailbox, so print it at least for '? fi' */
1157 printf(tr(103, "\"%s\": "),
1158 (_update_mailname(NULL) ? displayname : mailname));
1159 if (msgCount == 1)
1160 printf(tr(104, "1 message"));
1161 else
1162 printf(tr(105, "%d messages"), msgCount);
1163 if (n > 0)
1164 printf(tr(106, " %d new"), n);
1165 if (u-n > 0)
1166 printf(tr(107, " %d unread"), u);
1167 if (d > 0)
1168 printf(tr(108, " %d deleted"), d);
1169 if (s > 0)
1170 printf(tr(109, " %d saved"), s);
1171 if (moved > 0)
1172 printf(tr(136, " %d moved"), moved);
1173 if (hidden > 0)
1174 printf(tr(139, " %d hidden"), hidden);
1175 if (mb.mb_type == MB_CACHE)
1176 printf(" [Disconnected]");
1177 else if (mb.mb_perm == 0)
1178 printf(tr(110, " [Read only]"));
1179 printf("\n");
1180 jleave:
1181 NYD_LEAVE;
1182 return mdot;
1185 FL int
1186 getmdot(int nmail)
1188 struct message *mp;
1189 char *cp;
1190 int mdot;
1191 enum mflag avoid = MHIDDEN | MDELETED;
1192 NYD_ENTER;
1194 if (!nmail) {
1195 if (ok_blook(autothread))
1196 c_thread(NULL);
1197 else if ((cp = ok_vlook(autosort)) != NULL) {
1198 free(mb.mb_sorted);
1199 mb.mb_sorted = sstrdup(cp);
1200 c_sort(NULL);
1203 if (mb.mb_type == MB_VOID) {
1204 mdot = 1;
1205 goto jleave;
1208 if (nmail)
1209 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1210 if ((mp->m_flag & (MNEWEST | avoid)) == MNEWEST)
1211 break;
1213 if (!nmail || PTRCMP(mp, >=, message + msgCount)) {
1214 if (mb.mb_threaded) {
1215 for (mp = threadroot; mp != NULL; mp = next_in_thread(mp))
1216 if ((mp->m_flag & (MNEW | avoid)) == MNEW)
1217 break;
1218 } else {
1219 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1220 if ((mp->m_flag & (MNEW | avoid)) == MNEW)
1221 break;
1225 if ((mb.mb_threaded ? (mp == NULL) : PTRCMP(mp, >=, message + msgCount))) {
1226 if (mb.mb_threaded) {
1227 for (mp = threadroot; mp != NULL; mp = next_in_thread(mp))
1228 if (mp->m_flag & MFLAGGED)
1229 break;
1230 } else {
1231 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1232 if (mp->m_flag & MFLAGGED)
1233 break;
1237 if ((mb.mb_threaded ? (mp == NULL) : PTRCMP(mp, >=, message + msgCount))) {
1238 if (mb.mb_threaded) {
1239 for (mp = threadroot; mp != NULL; mp = next_in_thread(mp))
1240 if (!(mp->m_flag & (MREAD | avoid)))
1241 break;
1242 } else {
1243 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1244 if (!(mp->m_flag & (MREAD | avoid)))
1245 break;
1249 if ((mb.mb_threaded ? (mp != NULL) : PTRCMP(mp, <, message + msgCount)))
1250 mdot = (int)PTR2SIZE(mp - message + 1);
1251 else if (ok_blook(showlast)) {
1252 if (mb.mb_threaded) {
1253 for (mp = this_in_thread(threadroot, -1); mp;
1254 mp = prev_in_thread(mp))
1255 if (!(mp->m_flag & avoid))
1256 break;
1257 mdot = (mp != NULL) ? (int)PTR2SIZE(mp - message + 1) : msgCount;
1258 } else {
1259 for (mp = message + msgCount - 1; mp >= message; --mp)
1260 if (!(mp->m_flag & avoid))
1261 break;
1262 mdot = (mp >= message) ? (int)PTR2SIZE(mp - message + 1) : msgCount;
1264 } else if (mb.mb_threaded) {
1265 for (mp = threadroot; mp; mp = next_in_thread(mp))
1266 if (!(mp->m_flag & avoid))
1267 break;
1268 mdot = (mp != NULL) ? (int)PTR2SIZE(mp - message + 1) : 1;
1269 } else {
1270 for (mp = message; PTRCMP(mp, <, message + msgCount); ++mp)
1271 if (!(mp->m_flag & avoid))
1272 break;
1273 mdot = PTRCMP(mp, <, message + msgCount)
1274 ? (int)PTR2SIZE(mp - message + 1) : 1;
1276 jleave:
1277 NYD_LEAVE;
1278 return mdot;
1281 FL void
1282 initbox(char const *name)
1284 char *tempMesg;
1285 NYD_ENTER;
1287 if (mb.mb_type != MB_VOID)
1288 n_strlcpy(prevfile, mailname, PATH_MAX);
1290 _update_mailname((name != mailname) ? name : NULL);
1292 if ((mb.mb_otf = Ftmp(&tempMesg, "tmpbox", OF_WRONLY | OF_HOLDSIGS, 0600)) ==
1293 NULL) {
1294 perror(tr(87, "temporary mail message file"));
1295 exit(1);
1297 if ((mb.mb_itf = safe_fopen(tempMesg, "r", NULL)) == NULL) {
1298 perror(tr(87, "temporary mail message file"));
1299 exit(1);
1301 Ftmp_release(&tempMesg);
1303 message_reset();
1304 mb.mb_threaded = 0;
1305 if (mb.mb_sorted != NULL) {
1306 free(mb.mb_sorted);
1307 mb.mb_sorted = NULL;
1309 #ifdef HAVE_IMAP
1310 mb.mb_flags = MB_NOFLAGS;
1311 #endif
1312 prevdot = NULL;
1313 dot = NULL;
1314 did_print_dot = FAL0;
1315 NYD_LEAVE;
1318 #ifdef HAVE_DOCSTRINGS
1319 FL bool_t
1320 print_comm_docstr(char const *comm)
1322 bool_t rv = FAL0;
1323 struct cmd_ghost *cg;
1324 struct cmd const *cp;
1325 NYD_ENTER;
1327 /* Ghosts take precedence */
1328 for (cg = _cmd_ghosts; cg != NULL; cg = cg->next)
1329 if (!strcmp(comm, cg->name)) {
1330 printf("%s -> <%s>\n", comm, cg->cmd.s);
1331 rv = TRU1;
1332 goto jleave;
1335 for (cp = _cmd_tab; cp->name != NULL; ++cp) {
1336 if (cp->func == &c_cmdnotsupp)
1337 continue;
1338 if (!strcmp(comm, cp->name))
1339 printf("%s: %s\n", comm, tr(cp->docid, cp->doc));
1340 else if (is_prefix(comm, cp->name))
1341 printf("%s (%s): %s\n", comm, cp->name, tr(cp->docid, cp->doc));
1342 else
1343 continue;
1344 rv = TRU1;
1345 break;
1347 jleave:
1348 NYD_LEAVE;
1349 return rv;
1351 #endif
1353 /* vim:set fenc=utf-8:s-it-mode */