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