fix configure script to avoid polluting LDFLAGS/LIBS/LDADD/...
[apps/madmutt.git] / pattern.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>, and others
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9
10 #include <lib-lib/lib-lib.h>
11
12 #include <lib-mime/mime.h>
13 #include <lib-ui/enter.h>
14 #include <lib-ui/curses.h>
15 #include <lib-mx/mx.h>
16 #include <imap/imap.h>
17
18 #include "pattern.h"
19 #include "alias.h"
20 #include "crypt.h"
21 #include "handler.h"
22 #include "keymap.h"
23 #include "copy.h"
24
25 static int eat_regexp (pattern_t * pat, BUFFER *, BUFFER *);
26 static int eat_date (pattern_t * pat, BUFFER *, BUFFER *);
27 static int eat_range (pattern_t * pat, BUFFER *, BUFFER *);
28 static int patmatch (const pattern_t* pat, const char* buf);
29
30 static struct pattern_flags {
31   int tag;                      /* character used to represent this op */
32   int op;                       /* operation to perform */
33   int class;
34   int (*eat_arg)(pattern_t *, BUFFER *, BUFFER *);
35 } const Flags[] = {
36   {'A', M_ALL, 0, NULL},
37   {'b', M_BODY, M_FULL_MSG, eat_regexp},
38   {'B', M_WHOLE_MSG, M_FULL_MSG, eat_regexp},
39   {'c', M_CC, 0, eat_regexp},
40   {'C', M_RECIPIENT, 0, eat_regexp},
41   {'d', M_DATE, 0, eat_date},
42   {'D', M_DELETED, 0, NULL},
43   {'e', M_SENDER, 0, eat_regexp},
44   {'E', M_EXPIRED, 0, NULL},
45   {'f', M_FROM, 0, eat_regexp},
46   {'F', M_FLAG, 0, NULL},
47   {'g', M_CRYPT_SIGN, 0, NULL},
48   {'G', M_CRYPT_ENCRYPT, 0, NULL},
49   {'h', M_HEADER, M_FULL_MSG, eat_regexp},
50   {'H', M_HORMEL, 0, eat_regexp},
51   {'i', M_ID, 0, eat_regexp},
52   {'k', M_PGP_KEY, 0, NULL},
53   {'L', M_ADDRESS, 0, eat_regexp},
54   {'l', M_LIST, 0, NULL},
55   {'m', M_MESSAGE, 0, eat_range},
56   {'M', M_MULTIPART, 0, NULL},
57   {'n', M_SCORE, 0, eat_range},
58   {'N', M_NEW, 0, NULL},
59   {'O', M_OLD, 0, NULL},
60   {'p', M_PERSONAL_RECIP, 0, NULL},
61   {'P', M_PERSONAL_FROM, 0, NULL},
62   {'Q', M_REPLIED, 0, NULL},
63   {'R', M_READ, 0, NULL},
64   {'r', M_DATE_RECEIVED, 0, eat_date},
65   {'s', M_SUBJECT, 0, eat_regexp},
66   {'S', M_SUPERSEDED, 0, NULL},
67   {'T', M_TAG, 0, NULL},
68   {'t', M_TO, 0, eat_regexp},
69   {'U', M_UNREAD, 0, NULL},
70   {'u', M_SUBSCRIBED_LIST, 0, NULL},
71   {'v', M_COLLAPSED, 0, NULL},
72   {'V', M_CRYPT_VERIFIED, 0, NULL},
73 #ifdef USE_NNTP
74   {'w', M_NEWSGROUPS, 0, eat_regexp},
75 #endif
76   {'x', M_REFERENCE, 0, eat_regexp},
77   {'X', M_MIMEATTACH, 0, eat_range},
78   {'y', M_XLABEL, 0, eat_regexp},
79   {'z', M_SIZE, 0, eat_range},
80   {'=', M_DUPLICATED, 0, NULL},
81   {'$', M_UNREFERENCED, 0, NULL},
82   {'*', M_REALNAME, 0, NULL},
83   {0, 0, 0, NULL}
84 };
85
86 static pattern_t *SearchPattern = NULL; /* current search pattern */
87 static char LastSearch[STRING] = { 0 }; /* last pattern searched for */
88 static char LastSearchExpn[LONG_STRING] = { 0 };        /* expanded version of
89                                                            LastSearch */
90
91 #define M_MAXRANGE -1
92
93 /* constants for parse_date_range() */
94 #define M_PDR_NONE      0x0000
95 #define M_PDR_MINUS     0x0001
96 #define M_PDR_PLUS      0x0002
97 #define M_PDR_WINDOW    0x0004
98 #define M_PDR_ABSOLUTE  0x0008
99 #define M_PDR_DONE      0x0010
100 #define M_PDR_ERROR     0x0100
101 #define M_PDR_ERRORDONE (M_PDR_ERROR | M_PDR_DONE)
102
103 void pattern_wipe(pattern_t *pat)
104 {
105     if (pat->rx) {
106         regfree (pat->rx);
107         p_delete(&pat->rx);
108     }
109     p_delete(&pat->str);
110     pattern_list_wipe(&pat->child);
111 }
112
113 /* if no uppercase letters are given, do a case-insensitive search */
114 int mutt_which_case (const char *s)
115 {
116   while (*s) {
117     if (isalpha ((unsigned char) *s) && isupper ((unsigned char) *s))
118       return 0;                 /* case-sensitive */
119     s++;
120   }
121   return REG_ICASE;             /* case-insensitive */
122 }
123
124 static int
125 msg_search (CONTEXT *ctx, pattern_t* pat, int msgno)
126 {
127   char tempfile[_POSIX_PATH_MAX];
128   MESSAGE *msg = NULL;
129   STATE s;
130   struct stat st;
131   FILE *fp = NULL;
132   long lng = 0;
133   int match = 0;
134   HEADER *h = ctx->hdrs[msgno];
135   char* buf;
136   ssize_t blen;
137
138   if ((msg = mx_open_message (ctx, msgno)) != NULL) {
139     if (option (OPTTHOROUGHSRC)) {
140       /* decode the header / body */
141       p_clear(&s, 1);
142       s.fpin = msg->fp;
143       s.flags = M_CHARCONV;
144       s.fpout = m_tempfile(tempfile, sizeof(tempfile), NONULL(MCore.tmpdir), NULL);
145       if (!s.fpout) {
146         mutt_error(_("Could not create temporary file"));
147         return (0);
148       }
149
150       if (pat->op != M_BODY)
151         mutt_copy_header (msg->fp, h, s.fpout, CH_FROM | CH_DECODE, NULL);
152
153       if (pat->op != M_HEADER) {
154         mutt_parse_mime_message (ctx, h);
155         fseeko (msg->fp, h->offset, 0);
156         mutt_body_handler (h->content, &s);
157       }
158
159       fp = s.fpout;
160       fflush (fp);
161       fseeko (fp, 0, 0);
162       fstat (fileno (fp), &st);
163       lng = (long) st.st_size;
164     }
165     else {
166       /* raw header / body */
167       fp = msg->fp;
168       if (pat->op != M_BODY) {
169         fseeko (fp, h->offset, 0);
170         lng = h->content->offset - h->offset;
171       }
172       if (pat->op != M_HEADER) {
173         if (pat->op == M_BODY)
174           fseeko (fp, h->content->offset, 0);
175         lng += h->content->length;
176       }
177     }
178
179     buf = p_new(char, blen = STRING);
180
181     /* search the file "fp" */
182     while (lng > 0) {
183       if (pat->op == M_HEADER) {
184         if (!mutt_read_rfc822_line(fp, &buf, &blen))
185           break;
186       } else if (fgets (buf, blen - 1, fp) == NULL)
187         break;                  /* don't loop forever */
188       if (patmatch (pat, buf) == 0) {
189         match = 1;
190         break;
191       }
192       lng -= m_strlen(buf);
193     }
194
195     p_delete(&buf);
196
197     mx_close_message (&msg);
198
199     if (option (OPTTHOROUGHSRC)) {
200       m_fclose(&fp);
201       unlink (tempfile);
202     }
203   }
204
205   return match;
206 }
207
208 int eat_regexp (pattern_t * pat, BUFFER * s, BUFFER * err)
209 {
210   BUFFER buf;
211   int r;
212
213   p_clear(&buf, 1);
214
215   if (mutt_extract_token (&buf, s, M_TOKEN_PATTERN | M_TOKEN_COMMENT) != 0 ||
216       !buf.data) {
217     snprintf (err->data, err->dsize, _("Error in expression: %s"), s->dptr);
218     return (-1);
219   }
220
221   if (!*buf.data) {
222     snprintf (err->data, err->dsize, _("Empty expression"));
223     return (-1);
224   }
225
226   if (pat->stringmatch) {
227     pat->str = m_strdup(buf.data);
228     p_delete(&buf.data);
229   } else {
230     pat->rx = p_new(regex_t, 1);
231     r = REGCOMP (pat->rx, buf.data, REG_NEWLINE | REG_NOSUB | mutt_which_case (buf.data));
232     p_delete(&buf.data);
233     if (r) {
234       regerror (r, pat->rx, err->data, err->dsize);
235       regfree (pat->rx);
236       p_delete(&pat->rx);
237       return (-1);
238     }
239   }
240   return 0;
241 }
242
243 static int patmatch (const pattern_t* pat, const char* buf) {
244   if (pat->stringmatch)
245     return !strstr (buf, pat->str);
246   else
247     return regexec (pat->rx, buf, 0, NULL, 0);
248 }
249
250 int eat_range (pattern_t * pat, BUFFER * s, BUFFER * err __attribute__ ((unused)))
251 {
252   char *tmp;
253   int do_exclusive = 0;
254   int skip_quote = 0;
255
256   /*
257    * If simple_search is set to "~m %s", the range will have double quotes 
258    * around it...
259    */
260   if (*s->dptr == '"') {
261     s->dptr++;
262     skip_quote = 1;
263   }
264   if (*s->dptr == '<')
265     do_exclusive = 1;
266   if ((*s->dptr != '-') && (*s->dptr != '<')) {
267     /* range minimum */
268     if (*s->dptr == '>') {
269       pat->max = M_MAXRANGE;
270       pat->min = strtol (s->dptr + 1, &tmp, 0) + 1;     /* exclusive range */
271     }
272     else
273       pat->min = strtol (s->dptr, &tmp, 0);
274     if (toupper ((unsigned char) *tmp) == 'K') {        /* is there a prefix? */
275       pat->min *= 1024;
276       tmp++;
277     }
278     else if (toupper ((unsigned char) *tmp) == 'M') {
279       pat->min *= 1048576;
280       tmp++;
281     }
282     if (*s->dptr == '>') {
283       s->dptr = tmp;
284       return 0;
285     }
286     if (*tmp != '-') {
287       /* exact value */
288       pat->max = pat->min;
289       s->dptr = tmp;
290       return 0;
291     }
292     tmp++;
293   }
294   else {
295     s->dptr++;
296     tmp = s->dptr;
297   }
298
299   if (isdigit ((unsigned char) *tmp)) {
300     /* range maximum */
301     pat->max = strtol (tmp, &tmp, 0);
302     if (toupper ((unsigned char) *tmp) == 'K') {
303       pat->max *= 1024;
304       tmp++;
305     }
306     else if (toupper ((unsigned char) *tmp) == 'M') {
307       pat->max *= 1048576;
308       tmp++;
309     }
310     if (do_exclusive)
311       (pat->max)--;
312   }
313   else
314     pat->max = M_MAXRANGE;
315
316   if (skip_quote && *tmp == '"')
317     tmp++;
318
319   s->dptr = vskipspaces(tmp);
320   return 0;
321 }
322
323 static const char *getDate (const char *s, struct tm *t, BUFFER * err)
324 {
325   char *p;
326   time_t now = time (NULL);
327   struct tm *tm = localtime (&now);
328
329   t->tm_mday = strtol (s, &p, 10);
330   if (t->tm_mday < 1 || t->tm_mday > 31) {
331     snprintf (err->data, err->dsize, _("Invalid day of month: %s"), s);
332     return NULL;
333   }
334   if (*p != '/') {
335     /* fill in today's month and year */
336     t->tm_mon = tm->tm_mon;
337     t->tm_year = tm->tm_year;
338     return p;
339   }
340   p++;
341   t->tm_mon = strtol (p, &p, 10) - 1;
342   if (t->tm_mon < 0 || t->tm_mon > 11) {
343     snprintf (err->data, err->dsize, _("Invalid month: %s"), p);
344     return NULL;
345   }
346   if (*p != '/') {
347     t->tm_year = tm->tm_year;
348     return p;
349   }
350   p++;
351   t->tm_year = strtol (p, &p, 10);
352   if (t->tm_year < 70)          /* year 2000+ */
353     t->tm_year += 100;
354   else if (t->tm_year > 1900)
355     t->tm_year -= 1900;
356   return p;
357 }
358
359 /* Ny   years
360    Nm   months
361    Nw   weeks
362    Nd   days */
363 static const char *get_offset (struct tm *tm, const char *s, int sign)
364 {
365   char *ps;
366   int offset = strtol (s, &ps, 0);
367
368   if ((sign < 0 && offset > 0) || (sign > 0 && offset < 0))
369     offset = -offset;
370
371   switch (*ps) {
372   case 'y':
373     tm->tm_year += offset;
374     break;
375   case 'm':
376     tm->tm_mon += offset;
377     break;
378   case 'w':
379     tm->tm_mday += 7 * offset;
380     break;
381   case 'd':
382     tm->tm_mday += offset;
383     break;
384   default:
385     return s;
386   }
387   mutt_normalize_time (tm);
388   return (ps + 1);
389 }
390
391 static void adjust_date_range (struct tm *min, struct tm *max)
392 {
393   if (min->tm_year > max->tm_year
394       || (min->tm_year == max->tm_year && min->tm_mon > max->tm_mon)
395       || (min->tm_year == max->tm_year && min->tm_mon == max->tm_mon
396           && min->tm_mday > max->tm_mday)) {
397     int tmp;
398
399     tmp = min->tm_year;
400     min->tm_year = max->tm_year;
401     max->tm_year = tmp;
402
403     tmp = min->tm_mon;
404     min->tm_mon = max->tm_mon;
405     max->tm_mon = tmp;
406
407     tmp = min->tm_mday;
408     min->tm_mday = max->tm_mday;
409     max->tm_mday = tmp;
410
411     min->tm_hour = min->tm_min = min->tm_sec = 0;
412     max->tm_hour = 23;
413     max->tm_min = max->tm_sec = 59;
414   }
415 }
416
417 static const char *parse_date_range (const char *pc, struct tm *min,
418                                      struct tm *max, int haveMin,
419                                      struct tm *baseMin, BUFFER * err)
420 {
421   int flag = M_PDR_NONE;
422
423   while (*pc && ((flag & M_PDR_DONE) == 0)) {
424     const char *pt;
425     char ch = *pc++;
426
427     pc = vskipspaces(pc);
428     switch (ch) {
429     case '-':
430       {
431         /* try a range of absolute date minus offset of Ndwmy */
432         pt = get_offset (min, pc, -1);
433         if (pc == pt) {
434           if (flag == M_PDR_NONE) {     /* nothing yet and no offset parsed => absolute date? */
435             if (!getDate (pc, max, err))
436               flag |= (M_PDR_ABSOLUTE | M_PDR_ERRORDONE);       /* done bad */
437             else {
438               /* reestablish initial base minimum if not specified */
439               if (!haveMin)
440                 memcpy (min, baseMin, sizeof (struct tm));
441               flag |= (M_PDR_ABSOLUTE | M_PDR_DONE);    /* done good */
442             }
443           }
444           else
445             flag |= M_PDR_ERRORDONE;
446         }
447         else {
448           pc = pt;
449           if (flag == M_PDR_NONE && !haveMin) { /* the very first "-3d" without a previous absolute date */
450             max->tm_year = min->tm_year;
451             max->tm_mon = min->tm_mon;
452             max->tm_mday = min->tm_mday;
453           }
454           flag |= M_PDR_MINUS;
455         }
456       }
457       break;
458     case '+':
459       {                         /* enlarge plusRange */
460         pt = get_offset (max, pc, 1);
461         if (pc == pt)
462           flag |= M_PDR_ERRORDONE;
463         else {
464           pc = pt;
465           flag |= M_PDR_PLUS;
466         }
467       }
468       break;
469     case '*':
470       {                         /* enlarge window in both directions */
471         pt = get_offset (min, pc, -1);
472         if (pc == pt)
473           flag |= M_PDR_ERRORDONE;
474         else {
475           pc = get_offset (max, pc, 1);
476           flag |= M_PDR_WINDOW;
477         }
478       }
479       break;
480     default:
481       flag |= M_PDR_ERRORDONE;
482     }
483     pc = vskipspaces(pc);
484   }
485   if ((flag & M_PDR_ERROR) && !(flag & M_PDR_ABSOLUTE)) {       /* getDate has its own error message, don't overwrite it here */
486     snprintf (err->data, err->dsize, _("Invalid relative date: %s"), pc - 1);
487   }
488   return ((flag & M_PDR_ERROR) ? NULL : pc);
489 }
490
491 static int eat_date (pattern_t * pat, BUFFER * s, BUFFER * err)
492 {
493   BUFFER buffer;
494   struct tm min, max;
495
496   p_clear(&buffer, 1);
497   if (mutt_extract_token (&buffer, s, M_TOKEN_COMMENT | M_TOKEN_PATTERN) != 0
498       || !buffer.data) {
499     m_strcpy(err->data, err->dsize, _("error in expression"));
500     return (-1);
501   }
502
503   p_clear(&min, 1);
504   /* the `0' time is Jan 1, 1970 UTC, so in order to prevent a negative time
505      when doing timezone conversion, we use Jan 2, 1970 UTC as the base
506      here */
507   min.tm_mday = 2;
508   min.tm_year = 70;
509
510   p_clear(&max, 1);
511
512   /* Arbitrary year in the future.  Don't set this too high
513      or mutt_mktime() returns something larger than will
514      fit in a time_t on some systems */
515   max.tm_year = 130;
516   max.tm_mon = 11;
517   max.tm_mday = 31;
518   max.tm_hour = 23;
519   max.tm_min = 59;
520   max.tm_sec = 59;
521
522   if (strchr ("<>=", buffer.data[0])) {
523     /* offset from current time
524        <3d      less than three days ago
525        >3d      more than three days ago
526        =3d      exactly three days ago */
527     time_t now = time (NULL);
528     struct tm *tm = localtime (&now);
529     int exact = 0;
530
531     if (buffer.data[0] == '<') {
532       memcpy (&min, tm, sizeof (min));
533       tm = &min;
534     }
535     else {
536       memcpy (&max, tm, sizeof (max));
537       tm = &max;
538
539       if (buffer.data[0] == '=')
540         exact++;
541     }
542     tm->tm_hour = 23;
543     tm->tm_min = tm->tm_sec = 59;
544
545     /* force negative offset */
546     get_offset (tm, buffer.data + 1, -1);
547
548     if (exact) {
549       /* start at the beginning of the day in question */
550       memcpy (&min, &max, sizeof (max));
551       min.tm_hour = min.tm_sec = min.tm_min = 0;
552     }
553   }
554   else {
555     const char *pc = buffer.data;
556
557     int haveMin = FALSE;
558     int untilNow = FALSE;
559
560     if (isdigit ((unsigned char) *pc)) {
561       /* mininum date specified */
562       if ((pc = getDate (pc, &min, err)) == NULL) {
563         p_delete(&buffer.data);
564         return (-1);
565       }
566       haveMin = TRUE;
567       pc = vskipspaces(pc);
568       if (*pc == '-') {
569         const char *pt;
570
571         pt = skipspaces(pc + 1);
572         untilNow = (*pt == '\0');
573       }
574     }
575
576     if (!untilNow) {            /* max date or relative range/window */
577
578       struct tm baseMin;
579
580       if (!haveMin) {           /* save base minimum and set current date, e.g. for "-3d+1d" */
581         time_t now = time (NULL);
582         struct tm *tm = localtime (&now);
583
584         memcpy (&baseMin, &min, sizeof (baseMin));
585         memcpy (&min, tm, sizeof (min));
586         min.tm_hour = min.tm_sec = min.tm_min = 0;
587       }
588
589       /* preset max date for relative offsets,
590          if nothing follows we search for messages on a specific day */
591       max.tm_year = min.tm_year;
592       max.tm_mon = min.tm_mon;
593       max.tm_mday = min.tm_mday;
594
595       if (!parse_date_range (pc, &min, &max, haveMin, &baseMin, err)) { /* bail out on any parsing error */
596         p_delete(&buffer.data);
597         return (-1);
598       }
599     }
600   }
601
602   /* Since we allow two dates to be specified we'll have to adjust that. */
603   adjust_date_range (&min, &max);
604
605   pat->min = mutt_mktime (&min, 1);
606   pat->max = mutt_mktime (&max, 1);
607
608   p_delete(&buffer.data);
609
610   return 0;
611 }
612
613 static const struct pattern_flags *lookup_tag (char tag)
614 {
615   int i;
616
617   for (i = 0; Flags[i].tag; i++)
618     if (Flags[i].tag == tag)
619       return (&Flags[i]);
620   return NULL;
621 }
622
623 static const char *find_matching_paren (const char *s)
624 {
625     int level = 1;
626
627     for (; *s; s++) {
628         level += (*s == '(') - (*s == ')');
629         if (!level)
630             break;
631     }
632     return s;
633 }
634
635 pattern_t *mutt_pattern_comp(const char *s, int flags, BUFFER *err)
636 {
637   pattern_t *curlist = NULL;
638   pattern_t *tmp;
639   pattern_t *last = NULL;
640   int not = 0;
641   int alladdr = 0;
642   int or = 0;
643   int implicit = 1;             /* used to detect logical AND operator */
644   const struct pattern_flags *entry;
645   char *p;
646   char *buf;
647   BUFFER ps;
648
649   p_clear(&ps, 1);
650   ps.dptr  = s;
651   ps.dsize = m_strlen(s);
652
653   while (*ps.dptr) {
654     ps.dptr = vskipspaces(ps.dptr);
655     switch (*ps.dptr) {
656     case '^':
657       ps.dptr++;
658       alladdr = !alladdr;
659       break;
660     case '!':
661       ps.dptr++;
662       not = !not;
663       break;
664     case '|':
665       if (!or) {
666         if (!curlist) {
667           snprintf (err->data, err->dsize, _("error in pattern at: %s"),
668                     ps.dptr);
669           return NULL;
670         }
671         if (curlist->next) {
672           /* A & B | C == (A & B) | C */
673           tmp = pattern_new();
674           tmp->op = M_AND;
675           tmp->child = curlist;
676
677           curlist = tmp;
678           last = curlist;
679         }
680
681         or = 1;
682       }
683       ps.dptr++;
684       implicit = 0;
685       not = 0;
686       alladdr = 0;
687       break;
688     case '=':
689       /* fallthrough */
690     case '~':
691       if (implicit && or) {
692         /* A | B & C == (A | B) & C */
693         tmp = pattern_new();
694         tmp->op = M_OR;
695         tmp->child = curlist;
696         curlist = tmp;
697         last = tmp;
698         or = 0;
699       }
700
701       tmp = pattern_new();
702       tmp->not = not;
703       tmp->alladdr = alladdr;
704       tmp->stringmatch = (*ps.dptr == '=') ? 1 : 0;
705       not = 0;
706       alladdr = 0;
707
708       if (last)
709         last->next = tmp;
710       else
711         curlist = tmp;
712       last = tmp;
713
714       ps.dptr++;                /* move past the ~ */
715       if ((entry = lookup_tag (*ps.dptr)) == NULL) {
716         snprintf (err->data, err->dsize, _("%c: invalid command"), *ps.dptr);
717         pattern_list_wipe(&curlist);
718         return NULL;
719       }
720       if (entry->class && (flags & entry->class) == 0) {
721         snprintf (err->data, err->dsize, _("%c: not supported in this mode"),
722                   *ps.dptr);
723         pattern_list_wipe(&curlist);
724         return NULL;
725       }
726       tmp->op = entry->op;
727
728       ps.dptr = vskipspaces(ps.dptr + 1);
729
730       if (entry->eat_arg) {
731         if (!*ps.dptr) {
732           snprintf (err->data, err->dsize, _("missing parameter"));
733           pattern_list_wipe(&curlist);
734           return NULL;
735         }
736         if (entry->eat_arg (tmp, &ps, err) == -1) {
737           pattern_list_wipe(&curlist);
738           return NULL;
739         }
740       }
741       implicit = 1;
742       break;
743     case '(':
744       p = find_matching_paren (ps.dptr + 1);
745       if (*p != ')') {
746         snprintf (err->data, err->dsize, _("mismatched parenthesis: %s"),
747                   ps.dptr);
748         pattern_list_wipe(&curlist);
749         return NULL;
750       }
751       /* compile the sub-expression */
752       buf = p_dupstr(ps.dptr + 1, p - ps.dptr - 1);
753       if ((tmp = mutt_pattern_comp (buf, flags, err)) == NULL) {
754         p_delete(&buf);
755         pattern_list_wipe(&curlist);
756         return NULL;
757       }
758       p_delete(&buf);
759       if (last)
760         last->next = tmp;
761       else
762         curlist = tmp;
763       last = tmp;
764       tmp->not ^= not;
765       tmp->alladdr |= alladdr;
766       not = 0;
767       alladdr = 0;
768       ps.dptr = p + 1;          /* restore location */
769       break;
770     default:
771       snprintf (err->data, err->dsize, _("error in pattern at: %s"), ps.dptr);
772       pattern_list_wipe(&curlist);
773       return NULL;
774     }
775   }
776   if (!curlist) {
777     m_strcpy(err->data, err->dsize, _("empty pattern"));
778     return NULL;
779   }
780   if (curlist->next) {
781     tmp = pattern_new();
782     tmp->op = or ? M_OR : M_AND;
783     tmp->child = curlist;
784     curlist = tmp;
785   }
786   return (curlist);
787 }
788
789 static int
790 perform_and (pattern_t * pat, pattern_exec_flag flags, CONTEXT * ctx,
791              HEADER * hdr)
792 {
793   for (; pat; pat = pat->next)
794     if (mutt_pattern_exec (pat, flags, ctx, hdr) <= 0)
795       return 0;
796   return 1;
797 }
798
799 static int
800 perform_or (struct pattern_t *pat, pattern_exec_flag flags, CONTEXT * ctx,
801             HEADER * hdr)
802 {
803   for (; pat; pat = pat->next)
804     if (mutt_pattern_exec (pat, flags, ctx, hdr) > 0)
805       return 1;
806   return 0;
807 }
808
809 static int match_adrlist (pattern_t* pat, int match_personal, int alladdr __attribute__ ((unused)),
810                           int n, ...)
811 {
812   va_list ap;
813   address_t *a;
814
815   va_start (ap, n);
816   for (; n; n--) {
817     for (a = va_arg (ap, address_t *); a; a = a->next) {
818       if (pat->alladdr ^
819           ((a->mailbox && patmatch (pat, a->mailbox) == 0) ||
820            (match_personal && a->personal &&
821             patmatch (pat, a->personal) == 0))) {
822         va_end (ap);
823         return (!pat->alladdr);      /* Found match, or non-match if alladdr */
824       }
825     }
826   }
827   va_end (ap);
828   return pat->alladdr;               /* No matches, or all matches if alladdr */
829 }
830
831 static int match_reference (pattern_t* pat, string_list_t * refs)
832 {
833   for (; refs; refs = refs->next)
834     if (patmatch (pat, refs->data) == 0)
835       return 1;
836   return 0;
837 }
838
839 int mutt_is_list_recipient (int alladdr, address_t * a1, address_t * a2)
840 {
841   for (; a1; a1 = a1->next)
842     if (alladdr ^ mutt_is_subscribed_list (a1))
843       return (!alladdr);
844   for (; a2; a2 = a2->next)
845     if (alladdr ^ mutt_is_subscribed_list (a2))
846       return (!alladdr);
847   return alladdr;
848 }
849
850 int mutt_is_list_cc (int alladdr, address_t * a1, address_t * a2)
851 {
852   for (; a1; a1 = a1->next)
853     if (alladdr ^ mutt_is_mail_list (a1))
854       return (!alladdr);
855   for (; a2; a2 = a2->next)
856     if (alladdr ^ mutt_is_mail_list (a2))
857       return (!alladdr);
858   return alladdr;
859 }
860
861 static int match_user (int alladdr, address_t * a1, address_t * a2)
862 {
863   for (; a1; a1 = a1->next)
864     if (alladdr ^ mutt_addr_is_user (a1))
865       return (!alladdr);
866   for (; a2; a2 = a2->next)
867     if (alladdr ^ mutt_addr_is_user (a2))
868       return (!alladdr);
869   return alladdr;
870 }
871
872 /* test if name is considered a real name, i.e. consists of at least 2
873  * space-separated words of which none may end in a dot
874  */
875 static int valid_realname (const char *name)
876 {
877   const char *p = name;
878   int ret = 0;
879
880   while (*p) {
881     if (isspace (*p))
882       ret++;
883     else if (*p == '.')
884       /* skip abbr. parts of names (e.g. 'J. User') */
885       ret--;
886     p++;
887   }
888   return (ret >= 1);
889 }
890
891 /* flags
892         M_MATCH_FULL_ADDRESS    match both personal and machine address */
893 int
894 mutt_pattern_exec (struct pattern_t *pat, pattern_exec_flag flags,
895                    CONTEXT * ctx, HEADER * h)
896 {
897   switch (pat->op) {
898   case M_AND:
899     return (pat->not ^ (perform_and (pat->child, flags, ctx, h) > 0));
900   case M_OR:
901     return (pat->not ^ (perform_or (pat->child, flags, ctx, h) > 0));
902   case M_ALL:
903     return (!pat->not);
904   case M_EXPIRED:
905     return (pat->not ^ h->expired);
906   case M_SUPERSEDED:
907     return (pat->not ^ h->superseded);
908   case M_FLAG:
909     return (pat->not ^ h->flagged);
910   case M_TAG:
911     return (pat->not ^ h->tagged);
912   case M_NEW:
913     return (pat->not ? h->old || h->read : !(h->old || h->read));
914   case M_UNREAD:
915     return (pat->not ? h->read : !h->read);
916   case M_REPLIED:
917     return (pat->not ^ h->replied);
918   case M_OLD:
919     return (pat->not ? (!h->old || h->read) : (h->old && !h->read));
920   case M_READ:
921     return (pat->not ^ h->read);
922   case M_DELETED:
923     return (pat->not ^ h->deleted);
924   case M_MESSAGE:
925     return (pat->not ^ (h->msgno >= pat->min - 1 && (pat->max == M_MAXRANGE ||
926                                                      h->msgno <=
927                                                      pat->max - 1)));
928   case M_DATE:
929     return (pat->
930             not ^ (h->date_sent >= pat->min && h->date_sent <= pat->max));
931   case M_DATE_RECEIVED:
932     return (pat->not ^ (h->received >= pat->min && h->received <= pat->max));
933   case M_BODY:
934   case M_HEADER:
935   case M_WHOLE_MSG:
936     /* IMAP search sets h->matched at search compile time */
937     if (ctx->magic == M_IMAP && pat->stringmatch)
938       return (h->matched);
939     return (pat->not ^ msg_search (ctx, pat, h->msgno));
940   case M_SENDER:
941     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
942                                       pat->alladdr, 1, h->env->sender));
943   case M_FROM:
944     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
945                                       pat->alladdr, 1, h->env->from));
946   case M_TO:
947     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
948                                       pat->alladdr, 1, h->env->to));
949   case M_CC:
950     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
951                                       pat->alladdr, 1, h->env->cc));
952   case M_SUBJECT:
953     return (pat->
954             not ^ (h->env && h->env->subject
955                    && patmatch (pat, h->env->subject) == 0));
956   case M_ID:
957     return (pat->
958             not ^ (h->env && h->env->message_id
959                    && patmatch (pat, h->env->message_id) == 0));
960   case M_SCORE:
961     return (pat->not ^ (h->score >= pat->min && (pat->max == M_MAXRANGE ||
962                                                  h->score <= pat->max)));
963   case M_SIZE:
964     return (pat->
965             not ^ (h->content->length >= pat->min
966                    && (pat->max == M_MAXRANGE
967                        || h->content->length <= pat->max)));
968   case M_REFERENCE:
969     return (pat->not ^ match_reference (pat, h->env->references));
970   case M_ADDRESS:
971     return (pat->
972             not ^ (h->env
973                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
974                                      pat->alladdr, 4, h->env->from,
975                                      h->env->sender, h->env->to,
976                                      h->env->cc)));
977   case M_RECIPIENT:
978     return (pat->
979             not ^ (h->env
980                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
981                                      pat->alladdr, 2, h->env->to,
982                                      h->env->cc)));
983   case M_LIST:
984     return (pat->
985             not ^ (h->env
986                    && mutt_is_list_cc (pat->alladdr, h->env->to,
987                                        h->env->cc)));
988   case M_SUBSCRIBED_LIST:
989     return (pat->
990             not ^ (h->env
991                    && mutt_is_list_recipient (pat->alladdr, h->env->to,
992                                               h->env->cc)));
993   case M_PERSONAL_RECIP:
994     return (pat->
995             not ^ (h->env
996                    && match_user (pat->alladdr, h->env->to, h->env->cc)));
997   case M_PERSONAL_FROM:
998     return (pat->
999             not ^ (h->env && match_user (pat->alladdr, h->env->from, NULL)));
1000   case M_COLLAPSED:
1001     return (pat->not ^ (h->collapsed && h->num_hidden > 1));
1002   case M_CRYPT_SIGN:
1003     return (pat->not ^ ((h->security & SIGN) ? 1 : 0));
1004   case M_CRYPT_VERIFIED:
1005     return (pat->not ^ ((h->security & GOODSIGN) ? 1 : 0));
1006   case M_CRYPT_ENCRYPT:
1007     return (pat->not ^ ((h->security & ENCRYPT) ? 1 : 0));
1008   case M_PGP_KEY:
1009     return (pat->not ^ ((h->security & APPLICATION_PGP)
1010                         && (h->security & PGPKEY)));
1011   case M_XLABEL:
1012     return (pat->
1013             not ^ (h->env->x_label
1014                    && patmatch (pat, h->env->x_label) == 0));
1015   case M_HORMEL:
1016     return (pat->
1017             not ^ (h->env->spam && h->env->spam->data
1018                    && patmatch (pat, h->env->spam->data) == 0));
1019   case M_DUPLICATED:
1020     return (pat->not ^ (h->thread && h->thread->duplicate_thread));
1021
1022   case M_MIMEATTACH:
1023     {
1024       int count;
1025       
1026       if (h->content->parts)
1027         count = mutt_count_body_parts(h, 0);
1028       else {
1029         mutt_parse_mime_message(ctx, h);
1030         count = mutt_count_body_parts(h, 0);
1031         body_list_wipe(&h->content->parts);
1032       }
1033       
1034       return (pat->not ^ (count >= pat->min && (pat->max == M_MAXRANGE ||
1035                                                 count <= pat->max)));
1036     }
1037
1038   case M_UNREFERENCED:
1039     return (pat->not ^ (h->thread && !h->thread->child));
1040   case M_MULTIPART:
1041     return (pat->not ^ (h->content && h->content->type == TYPEMULTIPART));
1042   case M_REALNAME:
1043     /* realname filter:
1044      * we have a match if
1045      * - From: matches $alternates
1046      * - or we have an alias for current address
1047      * - or From: contains valid email address _and_ name has >= 2 fields
1048      */
1049     return (h->env && h->env->from
1050         && (mutt_addr_is_user(h->env->from)
1051             || alias_reverse_lookup(h->env->from)
1052             || (h->env->from->personal
1053                 && valid_realname(h->env-> from->personal)
1054                 && h->env->from->mailbox)
1055            )) ^ pat->not;
1056 #ifdef USE_NNTP
1057   case M_NEWSGROUPS:
1058     return (pat->
1059             not ^ (h->env->newsgroups
1060                    && patmatch (pat, h->env->newsgroups) == 0));
1061 #endif
1062   }
1063   mutt_error (_("error: unknown op %d (report this error)."), pat->op);
1064   return (-1);
1065 }
1066
1067 static void quote_simple (char *tmp, ssize_t len, const char *p)
1068 {
1069   ssize_t i = 0;
1070
1071   tmp[i++] = '"';
1072   while (*p && i < len - 3) {
1073     if (*p == '\\' || *p == '"')
1074       tmp[i++] = '\\';
1075     tmp[i++] = *p++;
1076   }
1077   tmp[i++] = '"';
1078   tmp[i] = 0;
1079 }
1080
1081 /* convert a simple search into a real request */
1082 void mutt_check_simple (char *s, ssize_t len, const char *simple)
1083 {
1084   char tmp[LONG_STRING];
1085
1086   /* XXX - is ascii_strcasecmp() right here, or should we use locale's
1087    * equivalences?
1088    */
1089
1090   if (!strchr (s, '~') && !strchr (s, '=')) {       /* yup, so spoof a real request */
1091     /* convert old tokens into the new format */
1092     if (ascii_strcasecmp ("all", s) == 0 || !m_strcmp("^", s) || !m_strcmp(".", s))     /* ~A is more efficient */
1093       m_strcpy(s, len, "~A");
1094     else if (ascii_strcasecmp ("del", s) == 0)
1095       m_strcpy(s, len, "~D");
1096     else if (ascii_strcasecmp ("flag", s) == 0)
1097       m_strcpy(s, len, "~F");
1098     else if (ascii_strcasecmp ("new", s) == 0)
1099       m_strcpy(s, len, "~N");
1100     else if (ascii_strcasecmp ("old", s) == 0)
1101       m_strcpy(s, len, "~O");
1102     else if (ascii_strcasecmp ("repl", s) == 0)
1103       m_strcpy(s, len, "~Q");
1104     else if (ascii_strcasecmp ("read", s) == 0)
1105       m_strcpy(s, len, "~R");
1106     else if (ascii_strcasecmp ("tag", s) == 0)
1107       m_strcpy(s, len, "~T");
1108     else if (ascii_strcasecmp ("unread", s) == 0)
1109       m_strcpy(s, len, "~U");
1110     else {
1111       quote_simple (tmp, sizeof (tmp), s);
1112       m_file_fmt(s, len, simple, tmp);
1113     }
1114   }
1115 }
1116
1117 int mutt_pattern_func (int op, char *prompt)
1118 {
1119   pattern_t *pat;
1120   char buf[LONG_STRING] = "", *simple, error[STRING];
1121   BUFFER err;
1122   int i;
1123
1124   m_strcpy(buf, sizeof(buf), NONULL(Context->pattern));
1125   if (prompt || op != M_LIMIT)
1126     if (mutt_get_field (prompt, buf, sizeof (buf), M_PATTERN | M_CLEAR) != 0 || !buf[0])
1127       return (-1);
1128
1129   mutt_message _("Compiling search pattern...");
1130
1131   simple = m_strdup(buf);
1132   mutt_check_simple (buf, sizeof (buf), NONULL (SimpleSearch));
1133
1134   err.data = error;
1135   err.dsize = sizeof (error);
1136   if ((pat = mutt_pattern_comp (buf, M_FULL_MSG, &err)) == NULL) {
1137     p_delete(&simple);
1138     mutt_error ("%s", err.data);
1139     return (-1);
1140   }
1141
1142   if (Context->magic == M_IMAP && imap_search (Context, pat) < 0)
1143     return -1;
1144
1145   mutt_message _("Executing command on matching messages...");
1146
1147 #define THIS_BODY Context->hdrs[i]->content
1148
1149   if (op == M_LIMIT) {
1150     Context->vcount = 0;
1151     Context->vsize = 0;
1152     Context->collapsed = 0;
1153
1154     for (i = 0; i < Context->msgcount; i++) {
1155       /* new limit pattern implicitly uncollapses all threads */
1156       Context->hdrs[i]->virtual = -1;
1157       Context->hdrs[i]->limited = 0;
1158       Context->hdrs[i]->collapsed = 0;
1159       Context->hdrs[i]->num_hidden = 0;
1160       if (mutt_pattern_exec
1161           (pat, M_MATCH_FULL_ADDRESS, Context, Context->hdrs[i])) {
1162         Context->hdrs[i]->virtual = Context->vcount;
1163         Context->hdrs[i]->limited = 1;
1164         Context->v2r[Context->vcount] = i;
1165         Context->vcount++;
1166         Context->vsize += THIS_BODY->length + THIS_BODY->offset -
1167           THIS_BODY->hdr_offset;
1168       }
1169     }
1170   }
1171   else {
1172     for (i = 0; i < Context->vcount; i++) {
1173       if (mutt_pattern_exec
1174           (pat, M_MATCH_FULL_ADDRESS, Context,
1175            Context->hdrs[Context->v2r[i]])) {
1176         switch (op) {
1177         case M_UNDELETE:
1178           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_PURGED,
1179                          0);
1180         case M_DELETE:
1181           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_DELETE,
1182                          (op == M_DELETE));
1183           break;
1184         case M_TAG:
1185         case M_UNTAG:
1186           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_TAG,
1187                          (op == M_TAG));
1188           break;
1189         }
1190       }
1191     }
1192   }
1193
1194 #undef THIS_BODY
1195
1196   mutt_clear_error ();
1197
1198   if (op == M_LIMIT) {
1199     /* drop previous limit pattern */
1200     p_delete(&Context->pattern);
1201     if (Context->limit_pattern)
1202       pattern_list_wipe(&Context->limit_pattern);
1203     if (Context->msgcount && !Context->vcount) {
1204       mutt_error _("No messages matched criteria.");
1205     }
1206
1207     /* record new limit pattern, unless match all */
1208     if (m_strncmp(buf, "~A", 2) != 0) {
1209       Context->pattern = simple;
1210       simple = NULL;            /* don't clobber it */
1211       Context->limit_pattern = mutt_pattern_comp (buf, M_FULL_MSG, &err);
1212     }
1213   }
1214   p_delete(&simple);
1215   pattern_list_wipe(&pat);
1216   return 0;
1217 }
1218
1219 int mutt_search_command (int cur, int op)
1220 {
1221   int i, j;
1222   char buf[STRING];
1223   char temp[LONG_STRING];
1224   char error[STRING];
1225   BUFFER err;
1226   int incr;
1227   HEADER *h;
1228
1229   if (op != OP_SEARCH_NEXT && op != OP_SEARCH_OPPOSITE) {
1230     m_strcpy(buf, sizeof(buf), LastSearch);
1231     if (mutt_get_field ((op == OP_SEARCH) ? _("Search for: ") :
1232                         _("Reverse search for: "), buf, sizeof (buf),
1233                         M_CLEAR | M_PATTERN) != 0 || !buf[0])
1234       return (-1);
1235
1236     if (op == OP_SEARCH)
1237       unset_option (OPTSEARCHREVERSE);
1238     else
1239       set_option (OPTSEARCHREVERSE);
1240
1241     /* compare the *expanded* version of the search pattern in case 
1242        $simple_search has changed while we were searching */
1243     m_strcpy(temp, sizeof(temp), buf);
1244     mutt_check_simple (temp, sizeof (temp), NONULL (SimpleSearch));
1245
1246     if (!SearchPattern || m_strcmp(temp, LastSearchExpn)) {
1247       set_option (OPTSEARCHINVALID);
1248       m_strcpy(LastSearch, sizeof(LastSearch), buf);
1249       mutt_message _("Compiling search pattern...");
1250
1251       pattern_list_wipe(&SearchPattern);
1252       err.data = error;
1253       err.dsize = sizeof (error);
1254       if ((SearchPattern =
1255            mutt_pattern_comp (temp, M_FULL_MSG, &err)) == NULL) {
1256         mutt_error ("%s", error);
1257         return (-1);
1258       }
1259       mutt_clear_error ();
1260     }
1261   }
1262   else if (!SearchPattern) {
1263     mutt_error _("No search pattern.");
1264
1265     return (-1);
1266   }
1267
1268   if (option (OPTSEARCHINVALID)) {
1269     for (i = 0; i < Context->msgcount; i++)
1270       Context->hdrs[i]->searched = 0;
1271     if (Context->magic == M_IMAP && imap_search (Context, SearchPattern) < 0)
1272       return -1;
1273     unset_option (OPTSEARCHINVALID);
1274   }
1275
1276   incr = (option (OPTSEARCHREVERSE)) ? -1 : 1;
1277   if (op == OP_SEARCH_OPPOSITE)
1278     incr = -incr;
1279
1280   for (i = cur + incr, j = 0; j != Context->vcount; j++) {
1281     if (i > Context->vcount - 1) {
1282       i = 0;
1283       if (option (OPTWRAPSEARCH))
1284         mutt_message (_("Search wrapped to top."));
1285
1286       else {
1287         mutt_message _("Search hit bottom without finding match");
1288
1289         return (-1);
1290       }
1291     }
1292     else if (i < 0) {
1293       i = Context->vcount - 1;
1294       if (option (OPTWRAPSEARCH))
1295         mutt_message (_("Search wrapped to bottom."));
1296
1297       else {
1298         mutt_message _("Search hit top without finding match");
1299
1300         return (-1);
1301       }
1302     }
1303
1304     h = Context->hdrs[Context->v2r[i]];
1305     if (h->searched) {
1306       /* if we've already evaulated this message, use the cached value */
1307       if (h->matched)
1308         return i;
1309     }
1310     else {
1311       /* remember that we've already searched this message */
1312       h->searched = 1;
1313       if ((h->matched =
1314            (mutt_pattern_exec
1315             (SearchPattern, M_MATCH_FULL_ADDRESS, Context, h) > 0)))
1316         return i;
1317     }
1318
1319     if (SigInt) {
1320       mutt_error _("Search interrupted.");
1321
1322       SigInt = 0;
1323       return (-1);
1324     }
1325
1326     i += incr;
1327   }
1328
1329   mutt_error _("Not found.");
1330
1331   return (-1);
1332 }