2 ** pick.c -- search for messages by content
4 ** This code is Copyright (c) 2002, 2008, by the authors of nmh. See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
12 #include <h/scansbr.h>
13 #include <h/fmt_scan.h>
20 #ifdef HAVE_SYS_TIME_H
21 # include <sys/time.h>
25 static struct swit switches[] = {
39 { "date pattern", 0 },
41 { "from pattern", 0 },
43 { "search pattern", 0 },
45 { "subject pattern", 0 },
49 { "-othercomponent pattern", 0 },
55 { "datefield field", 5 }, /* 5 chars required to differ from -date */
57 { "sequence name", 0 },
71 { "format format", 0 },
73 { "width columns", 0 },
85 char *version=VERSION;
88 boolean (*action)(struct field *, int, void *);
89 void (*free)(struct nexus **);
90 void (*debug)(void *, size_t);
95 static struct nexus *head;
96 static boolean body = FALSE;
101 static int pcompile(char **, char *);
102 static int pmatches(FILE *, int);
103 static struct nexus * createonethread(char *);
104 static struct nexus * createpickthread(char *);
105 static void scan_mbox(char *, char *, int);
108 static int listsw = -1;
112 static void printmsg(FILE *, struct msgs *, int, char *, int);
115 main(int argc, char **argv)
117 int publicsw = -1, zerosw = 1, vecp = 0, width = 0;
118 unsigned int seqp = 0;
120 char *maildir, *folder = NULL, buf[100];
121 char *cp, **argp, **arguments;
122 char *seqs[NUMATTRS + 1], *vec[MAXARGS];
123 struct msgs_array msgs = { 0, 0, NULL };
130 if (atexit(putzero_done) != 0) {
131 adios(EX_OSERR, NULL, "atexit failed");
134 setlocale(LC_ALL, "");
135 invo_name = mhbasename(argv[0]);
137 /* read user profile/context */
140 arguments = getarguments(invo_name, argc, argv, 1);
143 if (strcmp(invo_name, "scan")==0) {
147 while ((cp = *argp++)) {
153 switch (smatch(cp, switches)) {
155 ambigsw(cp, switches);
156 listsw = 0; /* HACK */
159 adios(EX_USAGE, NULL, "-%s unknown", cp);
162 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
163 print_help(buf, switches, 1);
164 listsw = 0; /* HACK */
165 exit(argc == 2 ? EX_OK : EX_USAGE);
167 print_version(invo_name);
168 listsw = 0; /* HACK */
169 exit(argc == 2 ? EX_OK : EX_USAGE);
183 if (!(cp = *argp++)) /* allow -xyz arguments */
184 adios(EX_USAGE, NULL, "missing argument to %s",
189 adios(EX_SOFTWARE, NULL, "internal error!");
200 if (!(cp = *argp++) || *cp == '-')
201 adios(EX_USAGE, NULL, "missing argument to %s",
204 /* check if too many sequences specified */
205 if (seqp >= NUMATTRS)
206 adios(EX_USAGE, NULL, "too many sequences (more than %d) specified", NUMATTRS);
233 if (!(form = *argp++) || *form == '-') {
234 adios(EX_USAGE, NULL, "missing argument to %s", argp[-2]);
238 if (!(cp = *argp++) || *cp == '-') {
239 adios(EX_USAGE, NULL, "missing argument to %s",
245 if (!(cp = *argp++) || (cp[0] == '-' && cp[1])) {
246 adios(EX_USAGE, NULL, "missing argument to %s",
249 if (strcmp(file = cp, "-")!=0) {
250 file = mh_xstrdup(expanddir(cp));
255 if (*cp == '+' || *cp == '@') {
257 adios(EX_USAGE, NULL, "only one folder at a time!");
259 folder = mh_xstrdup(expandfol(cp));
261 app_msgarg(&msgs, cp);
265 fmtstr = new_fs(form, "pick.default");
269 adios(EX_USAGE, NULL, "\"+folder\" not allowed with -file");
272 adios(EX_USAGE, NULL, "\"msgs\" not allowed with -file");
275 adios(EX_USAGE, NULL, "section arguments not allowed with -file");
278 scan_mbox(file, fmtstr, width);
283 ** If we didn't specify which messages to search,
284 ** then search the whole folder.
287 app_msgarg(&msgs, seq_all);
290 folder = getcurfol();
291 maildir = toabsdir(folder);
293 if (chdir(maildir) == NOTOK)
294 adios(EX_OSERR, maildir, "unable to change directory to");
296 /* read folder and create message structure */
297 if (!(mp = folder_read(folder)))
298 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
300 /* check for empty folder */
302 adios(EX_DATAERR, NULL, "no messages in %s", folder);
304 /* parse all the message ranges/sequences and set SELECTED */
305 for (msgnum = 0; msgnum < msgs.size; msgnum++)
306 if (!m_convert(mp, msgs.msgs[msgnum]))
308 seq_setprev(mp); /* set the previous-sequence */
311 ** If we aren't saving the results to a sequence,
312 ** we default to list the results.
317 if (publicsw == 1 && is_readonly(mp))
318 adios(EX_NOPERM, NULL, "folder %s is read-only, so -public not allowed",
321 if (!pcompile(vec, NULL))
328 ** If printing message numbers to standard out,
329 ** force line buffering on.
332 setvbuf(stdout, NULL, _IOLBF, 0);
335 ** Scan through all the SELECTED messages and check for a
336 ** match. If the message does not match, then unselect it.
338 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
339 if (is_selected(mp, msgnum)) {
340 if ((fp = fopen(cp = m_name(msgnum), "r")) == NULL)
341 admonish(cp, "unable to read message");
342 if (fp && pmatches(fp, msgnum)) {
349 printmsg(fp, mp, msgnum, fmtstr, width);
352 /* if it doesn't match, then unselect it */
353 unset_selected(mp, msgnum);
368 adios(EX_DATAERR, NULL, "no messages match specification");
373 ** Add the matching messages to sequences
375 for (seqp = 0; seqs[seqp]; seqp++)
376 if (!seq_addsel(mp, seqs[seqp], publicsw, zerosw))
380 ** Print total matched if not printing each matched message number.
383 printf("%d hit%s\n", mp->numsel, mp->numsel == 1 ? "" : "s");
386 context_replace(curfolder, folder); /* update current folder */
387 seq_save(mp); /* synchronize message sequences */
388 context_save(); /* save the context file */
389 folder_free(mp); /* free folder/message structure */
390 listsw = 0; /* HACK */
395 scan_mbox(char *file, char *fmtstr, int width)
401 if (strcmp(file, "-") == 0) {
404 } else if (!(in = fopen(file, "r"))) {
405 adios(EX_IOERR, file, "unable to open");
408 for (msgnum = 1; ;msgnum++) {
409 state = scan(in, msgnum, SCN_MBOX, fmtstr, width, 0, 0);
410 if (state != SCNMSG) {
421 if (listsw && !isatty(fileno(stdout)))
426 printmsg(FILE *f, struct msgs *mp, int msgnum, char *fmtstr, int width)
430 boolean unseen = FALSE;
432 fseek(f, 0L, SEEK_SET);
434 seqnum = seq_getnum(mp, seq_unseen);
435 unseen = in_sequence(mp, seqnum, msgnum);
437 switch (state = scan(f, msgnum, SCN_FOLD, fmtstr,
438 width, msgnum==mp->curmsg, unseen)) {
443 advise(NULL, "message %d: empty", msgnum);
446 adios(EX_SOFTWARE, NULL, "scan() botch(%d)", state);
451 static struct swit parswit[] = {
465 { "date pattern", 0 },
467 { "from pattern", 0 },
469 { "search pattern", 0 },
471 { "subject pattern", 0 },
475 { "-othercomponent pattern", 15 },
479 { "before date", 0 },
481 { "datefield field", 5 },
487 /* DEFINITIONS FOR PATTERN MATCHING */
490 ** We really should be using re_comp() and re_exec() here. Unfortunately,
491 ** pick advertises that lowercase characters matches characters of both
492 ** cases. Since re_exec() doesn't exhibit this behavior, we are stuck
493 ** with this version. Furthermore, we need to be able to save and restore
494 ** the state of the pattern matcher in order to do things "efficiently".
496 ** The matching power of this algorithm isn't as powerful as the re_xxx()
497 ** routines (no \(xxx\) and \n constructs). Such is life.
513 ** DEFINITIONS FOR NEXUS
516 #define nxtarg() (*argp ? *argp++ : NULL)
517 #define prvarg() argp--
519 #define padvise if (!talked++) advise
533 enum nexus_type type;
553 static int pdebug = 0;
560 ** prototypes for date routines
562 static struct tws *tws_parse(char *, int);
563 static struct tws *tws_special(char *);
568 static int gcompile(struct grep_data *, const char *);
569 static int tcompile(char *, struct tws *, int);
571 static struct nexus *parse(void);
572 static struct nexus *nexp1(void);
573 static struct nexus *nexp2(void);
574 static struct nexus *nexp3(void);
575 static struct nexus *newnexus(enum nexus_type);
577 static boolean BINaction(struct field *, int, void *);
578 static boolean NOTaction(struct field *, int, void *);
579 static boolean GREPaction(struct field *, int, void *);
580 static boolean DATEaction(struct field *, int, void *);
582 static void BINfree(struct nexus **);
583 static void GREPfree(struct nexus **);
584 static void DATEfree(struct nexus **);
586 static void BINdebug(void *, size_t);
587 static void GREPdebug(void *, size_t);
588 static void DATEdebug(void *, size_t);
591 pcompile(char **vec, char *date)
595 if ((cp = getenv("MHPDEBUG")) && *cp)
599 if ((datesw = date) == NULL)
603 if ((head = parse()) == NULL)
604 return (talked ? 0 : 1);
607 padvise(NULL, "%s unexpected", *argp);
615 static struct nexus *
620 struct bin_data *bin;
622 if ((n = nexp1()) == NULL || (cp = nxtarg()) == NULL)
626 padvise(NULL, "%s unexpected", cp);
632 switch (smatch(cp, parswit)) {
634 ambigsw(cp, parswit);
638 fprintf(stderr, "-%s unknown\n", cp);
643 o = newnexus(TYPE_OR);
646 if ((bin->right = parse()))
648 padvise(NULL, "missing disjunctive");
658 static struct nexus *
663 struct bin_data *bin;
665 if ((n = nexp2()) == NULL || (cp = nxtarg()) == NULL)
669 padvise(NULL, "%s unexpected", cp);
675 switch (smatch(cp, parswit)) {
677 ambigsw(cp, parswit);
681 fprintf(stderr, "-%s unknown\n", cp);
686 o = newnexus(TYPE_AND);
689 if ((bin->right = nexp1()))
691 padvise(NULL, "missing conjunctive");
702 static struct nexus *
707 struct bin_data *bin;
709 if ((cp = nxtarg()) == NULL)
719 switch (smatch(cp, parswit)) {
721 ambigsw(cp, parswit);
725 fprintf(stderr, "-%s unknown\n", cp);
730 n = newnexus(TYPE_NOT);
732 if ((bin->left = nexp3()))
734 padvise(NULL, "missing negation");
744 static struct nexus *
749 char buffer[BUFSIZ], temp[64];
751 struct grep_data *gdata;
752 struct date_data *twsd;
754 if ((cp = nxtarg()) == NULL)
758 padvise(NULL, "%s unexpected", cp);
766 switch (i = smatch(cp, parswit)) {
768 ambigsw(cp, parswit);
772 fprintf(stderr, "-%s unknown\n", cp);
777 if ((n = parse()) == NULL) {
778 padvise(NULL, "missing group");
781 if ((cp = nxtarg()) == NULL) {
782 padvise(NULL, "missing -rbrace");
785 if (*cp++ == '-' && smatch(cp, parswit) == PRRBR)
787 padvise(NULL, "%s unexpected", --cp);
795 if (!(cp = nxtarg())) { /* allow -xyz arguments */
796 padvise(NULL, "missing argument to %s", argp[-2]);
798 return createpickthread(cp);
804 strncpy(temp, parswit[i].sw, sizeof(temp));
805 temp[sizeof(temp) - 1] = '\0';
806 dp = *brkstring(temp, " ", NULL);
808 if (!(cp = nxtarg())) { /* allow -xyz arguments */
809 padvise(NULL, "missing argument to %s", argp[-2]);
812 n = newnexus(TYPE_GREP);
814 gdata->header = mh_xstrdup(dp);
815 snprintf(buffer, sizeof(buffer), "%s", cp);
820 n = newnexus(TYPE_GREP);
822 gdata->header = NULL;
824 if (!(cp = nxtarg())) { /* allow -xyz arguments */
825 padvise(NULL, "missing argument to %s", argp[-2]);
830 if (!gcompile(gdata, dp)) {
831 padvise("regcomp", "pattern error in %s %s", argp[-2], cp);
837 padvise(NULL, "internal error!");
841 if (!(datesw = nxtarg()) || *datesw == '-') {
842 padvise(NULL, "missing argument to %s",
850 if (!(cp = nxtarg())) { /* allow -xyz arguments */
851 padvise(NULL, "missing argument to %s", argp[-2]);
854 n = newnexus(TYPE_DATE);
856 twsd->datef = datesw;
857 if (!tcompile(cp, &twsd->tws, twsd->after = i == PRAFTR)) {
858 padvise(NULL, "unable to parse %s %s", argp[-2], cp);
866 static struct nexus *
867 newnexus(enum nexus_type t)
869 struct nexus *p = NULL;
870 struct bin_data *bin;
872 p = mh_xcalloc(1, sizeof(struct nexus));
876 p->action = NOTaction;
879 p->data = bin = mh_xcalloc(1, sizeof(struct bin_data));
884 p->action = BINaction;
887 p->data = bin = mh_xcalloc(1, sizeof(struct bin_data));
891 p->action = GREPaction;
892 p->debug = GREPdebug;
894 p->data = mh_xcalloc(1, sizeof(struct grep_data));
897 p->action = DATEaction;
898 p->debug = DATEdebug;
900 p->data = mh_xcalloc(1, sizeof(struct date_data));
903 adios(EX_SOFTWARE, NULL, "unknown nexus type %d", t);
911 pmatches(FILE *fp, int msgnum)
913 struct field f = {{0}};
919 if (!talked++ && pdebug && head->debug) {
920 head->debug(head->data, 0);
923 while (s == FLD2 || s == BODY2) {
924 switch (s = m_getfld2(s, &f, fp)) {
929 if (head->action(&f, msgnum, head->data)) {
937 if (head->action(&f, msgnum, head->data)) {
942 advise(NULL, "IOERR in message %d\n", msgnum);
947 adios(EX_SOFTWARE, "m_getfld2", "returned unknown state %d at message %d", s, msgnum);
954 print_debug_level(size_t level)
958 for (i = 0; i < level; i++) {
964 BINdebug(void *data, size_t level)
966 struct bin_data *bd = data;
968 print_debug_level(level);
972 fputs("OR\n", stderr);
975 fputs("AND\n", stderr);
978 fputs("NOT\n", stderr);
981 advise(NULL, "binary nexus has unknown type: %d\n", bd->type);
985 if (bd->left && bd->left->debug) {
986 bd->left->debug(bd->left->data, level+1);
988 print_debug_level(level+1);
989 fputs("can't debug left child\n", stderr);
992 if (bd->right && bd->right->debug) {
993 bd->right->debug(bd->right->data, level+1);
994 } else if (bd->type != TYPE_NOT) {
995 print_debug_level(level+1);
996 fputs("can't debug right child\n", stderr);
1001 NOTaction(struct field *f, int msgnum, void *data)
1003 struct bin_data *bin = data;
1004 return !bin->left->action(f, msgnum, bin->left->data);
1008 BINaction(struct field *f, int msgnum, void *data)
1010 struct bin_data *bin = data;
1012 if (bin->oldmsgnum != msgnum) {
1013 bin->oldmsgnum = msgnum;
1015 bin->leftmatch = FALSE;
1016 bin->rightmatch = FALSE;
1023 bin->leftmatch = bin->leftmatch || bin->left->action(f, msgnum, bin->left->data);
1024 bin->rightmatch = bin->rightmatch || bin->right->action(f, msgnum, bin->right->data);
1026 switch (bin->type) {
1028 bin->match = bin->leftmatch || bin->rightmatch;
1031 bin->match = bin->leftmatch && bin->rightmatch;
1034 adios(EX_SOFTWARE, NULL, "unknown nexus type: %d\n", bin->type);
1041 BINfree(struct nexus **n)
1043 struct bin_data *bd;
1051 if (bd->left && bd->left->free) {
1052 bd->left->free(&bd->left);
1054 advise(NULL, "BUG: can't free left child");
1057 if (bd->right && bd->right->free) {
1058 bd->right->free(&bd->right);
1060 advise(NULL, "BUG: can't free right child");
1067 gcompile(struct grep_data *g, const char *astr)
1069 regex_t *preg = mh_xcalloc(1, sizeof(regex_t));
1074 g->pattern = mh_xstrdup(astr);
1075 ret = regcomp(preg, astr, REG_ICASE | REG_NOSUB);
1077 buf = mh_xcalloc(BUFSIZ, sizeof(char));
1078 regerror(ret, g->preg, buf, BUFSIZ*sizeof(char));
1079 fprintf(stderr, "%s\n", buf);
1087 GREPaction(struct field *f, int msgnum, void *data)
1089 struct grep_data *g = data;
1093 if (!g->header && *f->name) {
1097 /* check for the right field */
1098 if (g->header && *g->header && mh_strcasecmp(g->header, f->name)==0) {
1102 ret = regexec(g->preg, f->value, 0, NULL, 0) == REG_NOMATCH;
1109 buf = mh_xcalloc(BUFSIZ, sizeof(char));
1110 regerror(ret, g->preg, buf, BUFSIZ*sizeof(char));
1111 fprintf(stderr, "%s\n", buf);
1118 GREPfree(struct nexus **n)
1120 struct grep_data *gd;
1125 mh_free0(&gd->header);
1131 GREPdebug(void *data, size_t level)
1133 struct grep_data *gd = data;
1134 char *buf, *buf2, *pbuf, *pbuf2;
1136 pbuf = pbuf2 = mh_xstrdup(gd->pattern);
1138 for (;*pbuf2; pbuf2++) {
1139 *pbuf2 = tolower(*pbuf2);
1142 print_debug_level(level);
1145 buf = buf2 = mh_xstrdup(gd->header);
1146 for (;*buf2; buf2++) {
1147 *buf2 = tolower(*buf2);
1149 fprintf(stderr, "PETTERN(%s) %s\n", buf, pbuf);
1151 fprintf(stderr, "PETTERN(BODY) %s\n", pbuf);
1158 tcompile(char *ap, struct tws *tb, int isafter)
1162 if ((tw = tws_parse(ap, isafter)) == NULL)
1171 tws_parse(char *ap, int isafter)
1173 char buffer[BUFSIZ];
1174 struct tws *tw, *ts;
1176 if ((tw = tws_special(ap)) != NULL) {
1177 tw->tw_sec = tw->tw_min = isafter ? 59 : 0;
1178 tw->tw_hour = isafter ? 23 : 0;
1181 if ((tw = dparsetime(ap)) != NULL)
1184 if ((ts = dlocaltimenow()) == NULL)
1187 snprintf(buffer, sizeof(buffer), "%s %s", ap, dtwszone(ts));
1188 if ((tw = dparsetime(buffer)) != NULL)
1191 snprintf(buffer, sizeof(buffer), "%s %02d:%02d:%02d %s", ap,
1192 ts->tw_hour, ts->tw_min, ts->tw_sec, dtwszone(ts));
1193 if ((tw = dparsetime(buffer)) != NULL)
1196 snprintf(buffer, sizeof(buffer), "%02d %s %04d %s",
1197 ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year, ap);
1198 if ((tw = dparsetime(buffer)) != NULL)
1201 snprintf(buffer, sizeof(buffer), "%02d %s %04d %s %s",
1202 ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year,
1204 if ((tw = dparsetime(buffer)) != NULL)
1212 tws_special(char *ap)
1219 if (!mh_strcasecmp(ap, "today"))
1220 return dlocaltime(&clock);
1221 if (!mh_strcasecmp(ap, "yesterday")) {
1222 clock -= (long) (60 * 60 * 24);
1223 return dlocaltime(&clock);
1225 if (!mh_strcasecmp(ap, "tomorrow")) {
1226 clock += (long) (60 * 60 * 24);
1227 return dlocaltime(&clock);
1230 for (i = 0; tw_ldotw[i]; i++)
1231 if (!mh_strcasecmp(ap, tw_ldotw[i]))
1234 if ((tw = dlocaltime(&clock)) == NULL)
1236 if ((i -= tw->tw_wday) > 0)
1242 else /* -ddd days ago */
1243 i = atoi(ap); /* we should error check this */
1245 clock += (long) ((60 * 60 * 24) * i);
1246 return dlocaltime(&clock);
1251 DATEaction(struct field *f, int msgnum, void *data)
1253 struct date_data *dd = data;
1254 boolean state = FALSE;
1258 if (mh_strcasecmp(f->name, dd->datef)!=0) {
1261 bp = mh_xstrdup(f->value);
1262 if ((tw = dparsetime(bp)) == NULL) {
1263 advise(NULL, "unable to parse %s field in message %d, not matching...", dd->datef, msgnum);
1265 } else if (dd->after) {
1266 state = twsort(tw, &dd->tws) > 0;
1268 state = twsort(tw, &dd->tws) < 0;
1277 DATEfree(struct nexus **n)
1279 struct date_data *dd;
1289 DATEdebug(void *data, size_t level)
1291 struct date_data *dd = data;
1292 print_debug_level(level);
1293 fprintf(stderr, "TEMPORAL(%s) %s: %s\n",dd->after ? "after" : "before", dd->datef, dasctime(&dd->tws));
1296 static struct nexus *
1297 createpickthread(char *msgs)
1299 char *folder = NULL;
1300 struct msgs_array msgarray = {0};
1301 struct msgs_array files = {0};
1302 struct nexus *ret = NULL;
1305 struct bin_data *bd;
1307 char **cp = brkstring(msgs, " \t", NULL);
1310 for (; cp && *cp; cp++) {
1318 folder = mh_xstrdup(*cp);
1321 app_msgarg(&msgarray, mh_xstrdup(*cp));
1325 parse_msgs(&msgarray, folder, &files);
1327 for (i = 0; i < files.size; i++) {
1328 buf = getthreadid(files.msgs[i]);
1333 c = createonethread(buf);
1341 or = newnexus(TYPE_OR);
1348 mh_free0(&(files.msgs));
1349 mh_free0(&(msgarray.msgs));
1354 static struct nexus *
1355 createonethread(char *c)
1357 struct nexus *ret = newnexus(TYPE_OR);
1358 struct nexus *left = newnexus(TYPE_GREP);
1359 struct nexus *right = newnexus(TYPE_GREP);
1360 struct bin_data *bd = ret->data;
1361 struct grep_data *gd = left->data;
1366 gd->header = "message-id";
1368 snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1369 if(!gcompile(gd, buf)) {
1370 padvise(NULL, "pattern error %s", c);
1375 gd->header = "references";
1377 snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1378 if(!gcompile(gd, buf)) {
1379 padvise(NULL, "pattern error in %s", c);