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