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