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