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 },
83 char *version=VERSION;
86 boolean (*action)(struct field *, int, void *);
87 void (*free)(struct nexus **);
88 void (*debug)(void *, size_t);
93 static struct nexus *head;
94 static boolean body = FALSE;
99 static int pcompile(char **, char *);
100 static int pmatches(FILE *, int);
101 static struct nexus * createonethread(char *);
102 static struct nexus * createpickthread(char *);
105 static int listsw = -1;
109 static void printmsg(FILE *, struct msgs *, int, char *, int);
112 main(int argc, char **argv)
114 int publicsw = -1, zerosw = 1, vecp = 0, width = 0;
115 unsigned int seqp = 0;
117 char *maildir, *folder = NULL, buf[100];
118 char *cp, **argp, **arguments;
119 char *seqs[NUMATTRS + 1], *vec[MAXARGS];
120 struct msgs_array msgs = { 0, 0, NULL };
126 if (atexit(putzero_done) != 0) {
127 adios(EX_OSERR, NULL, "atexit failed");
130 setlocale(LC_ALL, "");
131 invo_name = mhbasename(argv[0]);
133 /* read user profile/context */
136 arguments = getarguments(invo_name, argc, argv, 1);
139 if (strcmp(invo_name, "scan")==0) {
143 while ((cp = *argp++)) {
149 switch (smatch(cp, switches)) {
151 ambigsw(cp, switches);
152 listsw = 0; /* HACK */
155 adios(EX_USAGE, NULL, "-%s unknown", cp);
158 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
159 print_help(buf, switches, 1);
160 listsw = 0; /* HACK */
161 exit(argc == 2 ? EX_OK : EX_USAGE);
163 print_version(invo_name);
164 listsw = 0; /* HACK */
165 exit(argc == 2 ? EX_OK : EX_USAGE);
179 if (!(cp = *argp++)) /* allow -xyz arguments */
180 adios(EX_USAGE, NULL, "missing argument to %s",
185 adios(EX_SOFTWARE, NULL, "internal error!");
196 if (!(cp = *argp++) || *cp == '-')
197 adios(EX_USAGE, NULL, "missing argument to %s",
200 /* check if too many sequences specified */
201 if (seqp >= NUMATTRS)
202 adios(EX_USAGE, NULL, "too many sequences (more than %d) specified", NUMATTRS);
229 if (!(form = *argp++) || *form == '-') {
230 adios(EX_USAGE, NULL, "missing argument to %s", argp[-2]);
234 if (!(cp = *argp++) || *cp == '-') {
235 adios(EX_USAGE, NULL, "missing argument to %s",
242 if (*cp == '+' || *cp == '@') {
244 adios(EX_USAGE, NULL, "only one folder at a time!");
246 folder = mh_xstrdup(expandfol(cp));
248 app_msgarg(&msgs, cp);
252 fmtstr = new_fs(form, "pick.default");
255 ** If we didn't specify which messages to search,
256 ** then search the whole folder.
259 app_msgarg(&msgs, seq_all);
262 folder = getcurfol();
263 maildir = toabsdir(folder);
265 if (chdir(maildir) == NOTOK)
266 adios(EX_OSERR, maildir, "unable to change directory to");
268 /* read folder and create message structure */
269 if (!(mp = folder_read(folder)))
270 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
272 /* check for empty folder */
274 adios(EX_DATAERR, NULL, "no messages in %s", folder);
276 /* parse all the message ranges/sequences and set SELECTED */
277 for (msgnum = 0; msgnum < msgs.size; msgnum++)
278 if (!m_convert(mp, msgs.msgs[msgnum]))
280 seq_setprev(mp); /* set the previous-sequence */
283 ** If we aren't saving the results to a sequence,
284 ** we default to list the results.
289 if (publicsw == 1 && is_readonly(mp))
290 adios(EX_NOPERM, NULL, "folder %s is read-only, so -public not allowed",
293 if (!pcompile(vec, NULL))
300 ** If printing message numbers to standard out,
301 ** force line buffering on.
304 setvbuf(stdout, NULL, _IOLBF, 0);
307 ** Scan through all the SELECTED messages and check for a
308 ** match. If the message does not match, then unselect it.
310 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
311 if (is_selected(mp, msgnum)) {
312 if ((fp = fopen(cp = m_name(msgnum), "r")) == NULL)
313 admonish(cp, "unable to read message");
314 if (fp && pmatches(fp, msgnum)) {
321 printmsg(fp, mp, msgnum, fmtstr, width);
324 /* if it doesn't match, then unselect it */
325 unset_selected(mp, msgnum);
340 adios(EX_DATAERR, NULL, "no messages match specification");
345 ** Add the matching messages to sequences
347 for (seqp = 0; seqs[seqp]; seqp++)
348 if (!seq_addsel(mp, seqs[seqp], publicsw, zerosw))
352 ** Print total matched if not printing each matched message number.
355 printf("%d hit%s\n", mp->numsel, mp->numsel == 1 ? "" : "s");
358 context_replace(curfolder, folder); /* update current folder */
359 seq_save(mp); /* synchronize message sequences */
360 context_save(); /* save the context file */
361 folder_free(mp); /* free folder/message structure */
362 listsw = 0; /* HACK */
370 if (listsw && !isatty(fileno(stdout)))
375 printmsg(FILE *f, struct msgs *mp, int msgnum, char *fmtstr, int width)
379 boolean unseen = FALSE;
381 fseek(f, 0L, SEEK_SET);
383 seqnum = seq_getnum(mp, seq_unseen);
384 unseen = in_sequence(mp, seqnum, msgnum);
386 switch (state = scan(f, msgnum, SCN_FOLD, fmtstr,
387 width, msgnum==mp->curmsg, unseen)) {
392 advise(NULL, "message %d: empty", msgnum);
395 adios(EX_SOFTWARE, NULL, "scan() botch(%d)", state);
400 static struct swit parswit[] = {
414 { "date pattern", 0 },
416 { "from pattern", 0 },
418 { "search pattern", 0 },
420 { "subject pattern", 0 },
424 { "-othercomponent pattern", 15 },
428 { "before date", 0 },
430 { "datefield field", 5 },
436 /* DEFINITIONS FOR PATTERN MATCHING */
439 ** We really should be using re_comp() and re_exec() here. Unfortunately,
440 ** pick advertises that lowercase characters matches characters of both
441 ** cases. Since re_exec() doesn't exhibit this behavior, we are stuck
442 ** with this version. Furthermore, we need to be able to save and restore
443 ** the state of the pattern matcher in order to do things "efficiently".
445 ** The matching power of this algorithm isn't as powerful as the re_xxx()
446 ** routines (no \(xxx\) and \n constructs). Such is life.
462 ** DEFINITIONS FOR NEXUS
465 #define nxtarg() (*argp ? *argp++ : NULL)
466 #define prvarg() argp--
468 #define padvise if (!talked++) advise
482 enum nexus_type type;
502 static int pdebug = 0;
509 ** prototypes for date routines
511 static struct tws *tws_parse(char *, int);
512 static struct tws *tws_special(char *);
517 static int gcompile(struct grep_data *, const char *);
518 static int tcompile(char *, struct tws *, int);
520 static struct nexus *parse(void);
521 static struct nexus *nexp1(void);
522 static struct nexus *nexp2(void);
523 static struct nexus *nexp3(void);
524 static struct nexus *newnexus(enum nexus_type);
526 static boolean BINaction(struct field *, int, void *);
527 static boolean NOTaction(struct field *, int, void *);
528 static boolean GREPaction(struct field *, int, void *);
529 static boolean DATEaction(struct field *, int, void *);
531 static void BINfree(struct nexus **);
532 static void GREPfree(struct nexus **);
533 static void DATEfree(struct nexus **);
535 static void BINdebug(void *, size_t);
536 static void GREPdebug(void *, size_t);
537 static void DATEdebug(void *, size_t);
540 pcompile(char **vec, char *date)
544 if ((cp = getenv("MHPDEBUG")) && *cp)
548 if ((datesw = date) == NULL)
552 if ((head = parse()) == NULL)
553 return (talked ? 0 : 1);
556 padvise(NULL, "%s unexpected", *argp);
564 static struct nexus *
569 struct bin_data *bin;
571 if ((n = nexp1()) == NULL || (cp = nxtarg()) == NULL)
575 padvise(NULL, "%s unexpected", cp);
581 switch (smatch(cp, parswit)) {
583 ambigsw(cp, parswit);
587 fprintf(stderr, "-%s unknown\n", cp);
592 o = newnexus(TYPE_OR);
595 if ((bin->right = parse()))
597 padvise(NULL, "missing disjunctive");
607 static struct nexus *
612 struct bin_data *bin;
614 if ((n = nexp2()) == NULL || (cp = nxtarg()) == NULL)
618 padvise(NULL, "%s unexpected", cp);
624 switch (smatch(cp, parswit)) {
626 ambigsw(cp, parswit);
630 fprintf(stderr, "-%s unknown\n", cp);
635 o = newnexus(TYPE_AND);
638 if ((bin->right = nexp1()))
640 padvise(NULL, "missing conjunctive");
651 static struct nexus *
656 struct bin_data *bin;
658 if ((cp = nxtarg()) == NULL)
668 switch (smatch(cp, parswit)) {
670 ambigsw(cp, parswit);
674 fprintf(stderr, "-%s unknown\n", cp);
679 n = newnexus(TYPE_NOT);
681 if ((bin->left = nexp3()))
683 padvise(NULL, "missing negation");
693 static struct nexus *
698 char buffer[BUFSIZ], temp[64];
700 struct grep_data *gdata;
701 struct date_data *twsd;
703 if ((cp = nxtarg()) == NULL)
707 padvise(NULL, "%s unexpected", cp);
715 switch (i = smatch(cp, parswit)) {
717 ambigsw(cp, parswit);
721 fprintf(stderr, "-%s unknown\n", cp);
726 if ((n = parse()) == NULL) {
727 padvise(NULL, "missing group");
730 if ((cp = nxtarg()) == NULL) {
731 padvise(NULL, "missing -rbrace");
734 if (*cp++ == '-' && smatch(cp, parswit) == PRRBR)
736 padvise(NULL, "%s unexpected", --cp);
744 if (!(cp = nxtarg())) { /* allow -xyz arguments */
745 padvise(NULL, "missing argument to %s", argp[-2]);
747 return createpickthread(cp);
753 strncpy(temp, parswit[i].sw, sizeof(temp));
754 temp[sizeof(temp) - 1] = '\0';
755 dp = *brkstring(temp, " ", NULL);
757 if (!(cp = nxtarg())) { /* allow -xyz arguments */
758 padvise(NULL, "missing argument to %s", argp[-2]);
761 n = newnexus(TYPE_GREP);
763 gdata->header = mh_xstrdup(dp);
764 snprintf(buffer, sizeof(buffer), "%s", cp);
769 n = newnexus(TYPE_GREP);
771 gdata->header = NULL;
773 if (!(cp = nxtarg())) { /* allow -xyz arguments */
774 padvise(NULL, "missing argument to %s", argp[-2]);
779 if (!gcompile(gdata, dp)) {
780 padvise("regcomp", "pattern error in %s %s", argp[-2], cp);
786 padvise(NULL, "internal error!");
790 if (!(datesw = nxtarg()) || *datesw == '-') {
791 padvise(NULL, "missing argument to %s",
799 if (!(cp = nxtarg())) { /* allow -xyz arguments */
800 padvise(NULL, "missing argument to %s", argp[-2]);
803 n = newnexus(TYPE_DATE);
805 twsd->datef = datesw;
806 if (!tcompile(cp, &twsd->tws, twsd->after = i == PRAFTR)) {
807 padvise(NULL, "unable to parse %s %s", argp[-2], cp);
815 static struct nexus *
816 newnexus(enum nexus_type t)
818 struct nexus *p = NULL;
819 struct bin_data *bin;
821 p = mh_xcalloc(1, sizeof(struct nexus));
825 p->action = NOTaction;
828 p->data = bin = mh_xcalloc(1, sizeof(struct bin_data));
833 p->action = BINaction;
836 p->data = bin = mh_xcalloc(1, sizeof(struct bin_data));
840 p->action = GREPaction;
841 p->debug = GREPdebug;
843 p->data = mh_xcalloc(1, sizeof(struct grep_data));
846 p->action = DATEaction;
847 p->debug = DATEdebug;
849 p->data = mh_xcalloc(1, sizeof(struct date_data));
852 adios(EX_SOFTWARE, NULL, "unknown nexus type %d", t);
860 pmatches(FILE *fp, int msgnum)
862 struct field f = {{0}};
868 if (!talked++ && pdebug && head->debug) {
869 head->debug(head->data, 0);
872 while (s == FLD2 || s == BODY2) {
873 switch (s = m_getfld2(s, &f, fp)) {
878 if (head->action(&f, msgnum, head->data)) {
886 if (head->action(&f, msgnum, head->data)) {
891 advise(NULL, "IOERR in message %d\n", msgnum);
896 adios(EX_SOFTWARE, "m_getfld2", "returned unknown state %d at message %d", s, msgnum);
903 print_debug_level(size_t level)
907 for (i = 0; i < level; i++) {
913 BINdebug(void *data, size_t level)
915 struct bin_data *bd = data;
917 print_debug_level(level);
921 fputs("OR\n", stderr);
924 fputs("AND\n", stderr);
927 fputs("NOT\n", stderr);
930 advise(NULL, "binary nexus has unknown type: %d\n", bd->type);
934 if (bd->left && bd->left->debug) {
935 bd->left->debug(bd->left->data, level+1);
937 print_debug_level(level+1);
938 fputs("can't debug left child\n", stderr);
941 if (bd->right && bd->right->debug) {
942 bd->right->debug(bd->right->data, level+1);
943 } else if (bd->type != TYPE_NOT) {
944 print_debug_level(level+1);
945 fputs("can't debug right child\n", stderr);
950 NOTaction(struct field *f, int msgnum, void *data)
952 struct bin_data *bin = data;
953 return !bin->left->action(f, msgnum, bin->left->data);
957 BINaction(struct field *f, int msgnum, void *data)
959 struct bin_data *bin = data;
961 if (bin->oldmsgnum != msgnum) {
962 bin->oldmsgnum = msgnum;
964 bin->leftmatch = FALSE;
965 bin->rightmatch = FALSE;
972 bin->leftmatch = bin->leftmatch || bin->left->action(f, msgnum, bin->left->data);
973 bin->rightmatch = bin->rightmatch || bin->right->action(f, msgnum, bin->right->data);
977 bin->match = bin->leftmatch || bin->rightmatch;
980 bin->match = bin->leftmatch && bin->rightmatch;
983 adios(EX_SOFTWARE, NULL, "unknown nexus type: %d\n", bin->type);
990 BINfree(struct nexus **n)
1000 if (bd->left && bd->left->free) {
1001 bd->left->free(&bd->left);
1003 advise(NULL, "BUG: can't free left child");
1006 if (bd->right && bd->right->free) {
1007 bd->right->free(&bd->right);
1009 advise(NULL, "BUG: can't free right child");
1016 gcompile(struct grep_data *g, const char *astr)
1018 regex_t *preg = mh_xcalloc(1, sizeof(regex_t));
1023 g->pattern = mh_xstrdup(astr);
1024 ret = regcomp(preg, astr, REG_ICASE | REG_NOSUB);
1026 buf = mh_xcalloc(BUFSIZ, sizeof(char));
1027 regerror(ret, g->preg, buf, BUFSIZ*sizeof(char));
1028 fprintf(stderr, "%s\n", buf);
1036 GREPaction(struct field *f, int msgnum, void *data)
1038 struct grep_data *g = data;
1042 if (!g->header && *f->name) {
1046 /* check for the right field */
1047 if (g->header && *g->header && mh_strcasecmp(g->header, f->name)==0) {
1051 ret = regexec(g->preg, f->value, 0, NULL, 0) == REG_NOMATCH;
1058 buf = mh_xcalloc(BUFSIZ, sizeof(char));
1059 regerror(ret, g->preg, buf, BUFSIZ*sizeof(char));
1060 fprintf(stderr, "%s\n", buf);
1067 GREPfree(struct nexus **n)
1069 struct grep_data *gd;
1074 mh_free0(&gd->header);
1080 GREPdebug(void *data, size_t level)
1082 struct grep_data *gd = data;
1083 char *buf, *buf2, *pbuf, *pbuf2;
1085 pbuf = pbuf2 = mh_xstrdup(gd->pattern);
1087 for (;*pbuf2; pbuf2++) {
1088 *pbuf2 = tolower(*pbuf2);
1091 print_debug_level(level);
1094 buf = buf2 = mh_xstrdup(gd->header);
1095 for (;*buf2; buf2++) {
1096 *buf2 = tolower(*buf2);
1098 fprintf(stderr, "PETTERN(%s) %s\n", buf, pbuf);
1100 fprintf(stderr, "PETTERN(BODY) %s\n", pbuf);
1107 tcompile(char *ap, struct tws *tb, int isafter)
1111 if ((tw = tws_parse(ap, isafter)) == NULL)
1120 tws_parse(char *ap, int isafter)
1122 char buffer[BUFSIZ];
1123 struct tws *tw, *ts;
1125 if ((tw = tws_special(ap)) != NULL) {
1126 tw->tw_sec = tw->tw_min = isafter ? 59 : 0;
1127 tw->tw_hour = isafter ? 23 : 0;
1130 if ((tw = dparsetime(ap)) != NULL)
1133 if ((ts = dlocaltimenow()) == NULL)
1136 snprintf(buffer, sizeof(buffer), "%s %s", ap, dtwszone(ts));
1137 if ((tw = dparsetime(buffer)) != NULL)
1140 snprintf(buffer, sizeof(buffer), "%s %02d:%02d:%02d %s", ap,
1141 ts->tw_hour, ts->tw_min, ts->tw_sec, dtwszone(ts));
1142 if ((tw = dparsetime(buffer)) != NULL)
1145 snprintf(buffer, sizeof(buffer), "%02d %s %04d %s",
1146 ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year, ap);
1147 if ((tw = dparsetime(buffer)) != NULL)
1150 snprintf(buffer, sizeof(buffer), "%02d %s %04d %s %s",
1151 ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year,
1153 if ((tw = dparsetime(buffer)) != NULL)
1161 tws_special(char *ap)
1168 if (!mh_strcasecmp(ap, "today"))
1169 return dlocaltime(&clock);
1170 if (!mh_strcasecmp(ap, "yesterday")) {
1171 clock -= (long) (60 * 60 * 24);
1172 return dlocaltime(&clock);
1174 if (!mh_strcasecmp(ap, "tomorrow")) {
1175 clock += (long) (60 * 60 * 24);
1176 return dlocaltime(&clock);
1179 for (i = 0; tw_ldotw[i]; i++)
1180 if (!mh_strcasecmp(ap, tw_ldotw[i]))
1183 if ((tw = dlocaltime(&clock)) == NULL)
1185 if ((i -= tw->tw_wday) > 0)
1191 else /* -ddd days ago */
1192 i = atoi(ap); /* we should error check this */
1194 clock += (long) ((60 * 60 * 24) * i);
1195 return dlocaltime(&clock);
1200 DATEaction(struct field *f, int msgnum, void *data)
1202 struct date_data *dd = data;
1203 boolean state = FALSE;
1207 if (mh_strcasecmp(f->name, dd->datef)!=0) {
1210 bp = mh_xstrdup(f->value);
1211 if ((tw = dparsetime(bp)) == NULL) {
1212 advise(NULL, "unable to parse %s field in message %d, not matching...", dd->datef, msgnum);
1214 } else if (dd->after) {
1215 state = twsort(tw, &dd->tws) > 0;
1217 state = twsort(tw, &dd->tws) < 0;
1226 DATEfree(struct nexus **n)
1228 struct date_data *dd;
1234 mh_free0(&dd->datef);
1239 DATEdebug(void *data, size_t level)
1241 struct date_data *dd = data;
1242 print_debug_level(level);
1243 fprintf(stderr, "TEMPORAL(%s) %s: %s\n",dd->after ? "after" : "before", dd->datef, dasctime(&dd->tws));
1246 static struct nexus *
1247 createpickthread(char *msgs)
1249 char *folder = NULL;
1250 struct msgs_array msgarray = {0};
1251 struct msgs_array files = {0};
1252 struct nexus *ret = NULL;
1255 struct bin_data *bd;
1257 char **cp = brkstring(msgs, " \t", NULL);
1260 for (; cp && *cp; cp++) {
1268 folder = mh_xstrdup(*cp);
1271 app_msgarg(&msgarray, mh_xstrdup(*cp));
1275 parse_msgs(&msgarray, folder, &files);
1277 for (i = 0; i < files.size; i++) {
1278 buf = getthreadid(files.msgs[i]);
1283 c = createonethread(buf);
1291 or = newnexus(TYPE_OR);
1298 mh_free0(&(files.msgs));
1299 mh_free0(&(msgarray.msgs));
1304 static struct nexus *
1305 createonethread(char *c)
1307 struct nexus *ret = newnexus(TYPE_OR);
1308 struct nexus *left = newnexus(TYPE_GREP);
1309 struct nexus *right = newnexus(TYPE_GREP);
1310 struct bin_data *bd = ret->data;
1311 struct grep_data *gd = left->data;
1316 gd->header = "message-id";
1318 snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1319 if(!gcompile(gd, buf)) {
1320 padvise(NULL, "pattern error %s", c);
1325 gd->header = "references";
1327 snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1328 if(!gcompile(gd, buf)) {
1329 padvise(NULL, "pattern error in %s", c);