File: compile.c

package info (click to toggle)
neomutt 20250510%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 23,372 kB
  • sloc: ansic: 171,730; sh: 5,357; perl: 1,121; tcl: 1,065; python: 443; makefile: 48
file content (1155 lines) | stat: -rw-r--r-- 28,819 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
/**
 * @file
 * Compile a Pattern
 *
 * @authors
 * Copyright (C) 2020 R Primus <rprimus@gmail.com>
 * Copyright (C) 2020-2022 Pietro Cerutti <gahr@gahr.ch>
 * Copyright (C) 2020-2023 Richard Russon <rich@flatcap.org>
 *
 * @copyright
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @page pattern_compile Compile a Pattern
 *
 * Compile a Pattern
 */

#include "config.h"
#include <ctype.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include "private.h"
#include "mutt/lib.h"
#include "address/lib.h"
#include "config/lib.h"
#include "core/lib.h"
#include "lib.h"
#include "parse/lib.h"
#include "mview.h"

struct Menu;

// clang-format off
typedef uint16_t ParseDateRangeFlags; ///< Flags for parse_date_range(), e.g. #MUTT_PDR_MINUS
#define MUTT_PDR_NO_FLAGS       0  ///< No flags are set
#define MUTT_PDR_MINUS    (1 << 0) ///< Pattern contains a range
#define MUTT_PDR_PLUS     (1 << 1) ///< Extend the range using '+'
#define MUTT_PDR_WINDOW   (1 << 2) ///< Extend the range in both directions using '*'
#define MUTT_PDR_ABSOLUTE (1 << 3) ///< Absolute pattern range
#define MUTT_PDR_DONE     (1 << 4) ///< Pattern parse successfully
#define MUTT_PDR_ERROR    (1 << 8) ///< Invalid pattern
// clang-format on

#define MUTT_PDR_ERRORDONE (MUTT_PDR_ERROR | MUTT_PDR_DONE)

/**
 * eat_regex - Parse a regex - Implements ::eat_arg_t - @ingroup eat_arg_api
 */
static bool eat_regex(struct Pattern *pat, PatternCompFlags flags,
                      struct Buffer *s, struct Buffer *err)
{
  struct Buffer *buf = buf_pool_get();
  bool rc = false;
  char *pexpr = s->dptr;
  if ((parse_extract_token(buf, s, TOKEN_PATTERN | TOKEN_COMMENT) != 0) || !buf->data)
  {
    buf_printf(err, _("Error in expression: %s"), pexpr);
    goto out;
  }
  if (buf_is_empty(buf))
  {
    buf_addstr(err, _("Empty expression"));
    goto out;
  }

  if (pat->string_match)
  {
    pat->p.str = mutt_str_dup(buf->data);
    pat->ign_case = mutt_mb_is_lower(buf->data);
  }
  else if (pat->group_match)
  {
    pat->p.group = mutt_pattern_group(buf->data);
  }
  else
  {
    pat->p.regex = MUTT_MEM_CALLOC(1, regex_t);
#ifdef USE_DEBUG_GRAPHVIZ
    pat->raw_pattern = mutt_str_dup(buf->data);
#endif
    uint16_t case_flags = mutt_mb_is_lower(buf->data) ? REG_ICASE : 0;
    int rc2 = REG_COMP(pat->p.regex, buf->data, REG_NEWLINE | REG_NOSUB | case_flags);
    if (rc2 != 0)
    {
      char errmsg[256] = { 0 };
      regerror(rc2, pat->p.regex, errmsg, sizeof(errmsg));
      buf_printf(err, "'%s': %s", buf->data, errmsg);
      FREE(&pat->p.regex);
      goto out;
    }
  }

  rc = true;

out:
  buf_pool_release(&buf);
  return rc;
}

/**
 * add_query_msgid - Parse a Message-Id and add it to a list - Implements ::mutt_file_map_t - @ingroup mutt_file_map_api
 * @retval true Always
 */
static bool add_query_msgid(char *line, int line_num, void *user_data)
{
  struct ListHead *msgid_list = (struct ListHead *) (user_data);
  char *nows = mutt_str_skip_whitespace(line);
  if (*nows == '\0')
    return true;
  mutt_str_remove_trailing_ws(nows);
  mutt_list_insert_tail(msgid_list, mutt_str_dup(nows));
  return true;
}

/**
 * eat_query - Parse a query for an external search program - Implements ::eat_arg_t - @ingroup eat_arg_api
 * @param pat   Pattern to store the results in
 * @param flags Flags, e.g. #MUTT_PC_PATTERN_DYNAMIC
 * @param s     String to parse
 * @param err   Buffer for error messages
 * @param m     Mailbox
 * @retval true The pattern was read successfully
 */
static bool eat_query(struct Pattern *pat, PatternCompFlags flags,
                      struct Buffer *s, struct Buffer *err, struct Mailbox *m)
{
  struct Buffer *cmd_buf = buf_pool_get();
  struct Buffer *tok_buf = buf_pool_get();
  bool rc = false;

  FILE *fp = NULL;

  const char *const c_external_search_command = cs_subset_string(NeoMutt->sub, "external_search_command");
  if (!c_external_search_command)
  {
    buf_addstr(err, _("No search command defined"));
    goto out;
  }

  char *pexpr = s->dptr;
  if ((parse_extract_token(tok_buf, s, TOKEN_PATTERN | TOKEN_COMMENT) != 0) ||
      !tok_buf->data)
  {
    buf_printf(err, _("Error in expression: %s"), pexpr);
    goto out;
  }
  if (*tok_buf->data == '\0')
  {
    buf_addstr(err, _("Empty expression"));
    goto out;
  }

  buf_addstr(cmd_buf, c_external_search_command);
  buf_addch(cmd_buf, ' ');

  if (m)
  {
    char *escaped_folder = mutt_path_escape(mailbox_path(m));
    mutt_debug(LL_DEBUG2, "escaped folder path: %s\n", escaped_folder);
    buf_addch(cmd_buf, '\'');
    buf_addstr(cmd_buf, escaped_folder);
    buf_addch(cmd_buf, '\'');
  }
  else
  {
    buf_addch(cmd_buf, '/');
  }
  buf_addch(cmd_buf, ' ');
  buf_addstr(cmd_buf, tok_buf->data);

  mutt_message(_("Running search command: %s ..."), cmd_buf->data);
  pat->is_multi = true;
  mutt_list_clear(&pat->p.multi_cases);
  pid_t pid = filter_create(cmd_buf->data, NULL, &fp, NULL, NeoMutt->env);
  if (pid < 0)
  {
    buf_printf(err, "unable to fork command: %s\n", cmd_buf->data);
    goto out;
  }

  mutt_file_map_lines(add_query_msgid, &pat->p.multi_cases, fp, MUTT_RL_NO_FLAGS);
  mutt_file_fclose(&fp);
  filter_wait(pid);

  rc = true;

out:
  buf_pool_release(&cmd_buf);
  buf_pool_release(&tok_buf);
  return rc;
}

/**
 * get_offset - Calculate a symbolic offset
 * @param tm   Store the time here
 * @param s    string to parse
 * @param sign Sign of range, 1 for positive, -1 for negative
 * @retval ptr Next char after parsed offset
 *
 * - Ny years
 * - Nm months
 * - Nw weeks
 * - Nd days
 */
static const char *get_offset(struct tm *tm, const char *s, int sign)
{
  char *ps = NULL;
  int offset = strtol(s, &ps, 0);
  if (((sign < 0) && (offset > 0)) || ((sign > 0) && (offset < 0)))
    offset = -offset;

  switch (*ps)
  {
    case 'y':
      tm->tm_year += offset;
      break;
    case 'm':
      tm->tm_mon += offset;
      break;
    case 'w':
      tm->tm_mday += 7 * offset;
      break;
    case 'd':
      tm->tm_mday += offset;
      break;
    case 'H':
      tm->tm_hour += offset;
      break;
    case 'M':
      tm->tm_min += offset;
      break;
    case 'S':
      tm->tm_sec += offset;
      break;
    default:
      return s;
  }
  mutt_date_normalize_time(tm);
  return ps + 1;
}

/**
 * get_date - Parse a (partial) date in dd/mm/yyyy format
 * @param s   String to parse
 * @param t   Store the time here
 * @param err Buffer for error messages
 * @retval ptr First character after the date
 *
 * This function parses a (partial) date separated by '/'.  The month and year
 * are optional and if the year is less than 70 it's assumed to be after 2000.
 *
 * Examples:
 * - "10"         = 10 of this month, this year
 * - "10/12"      = 10 of December,   this year
 * - "10/12/04"   = 10 of December,   2004
 * - "10/12/2008" = 10 of December,   2008
 * - "20081210"   = 10 of December,   2008
 */
static const char *get_date(const char *s, struct tm *t, struct Buffer *err)
{
  char *p = NULL;
  struct tm tm = mutt_date_localtime(mutt_date_now());
  bool iso8601 = true;

  for (int v = 0; v < 8; v++)
  {
    if (s[v] && (s[v] >= '0') && (s[v] <= '9'))
      continue;

    iso8601 = false;
    break;
  }

  if (iso8601)
  {
    int year = 0;
    int month = 0;
    int mday = 0;
    sscanf(s, "%4d%2d%2d", &year, &month, &mday);

    t->tm_year = year;
    if (t->tm_year > 1900)
      t->tm_year -= 1900;
    t->tm_mon = month - 1;
    t->tm_mday = mday;

    if ((t->tm_mday < 1) || (t->tm_mday > 31))
    {
      buf_printf(err, _("Invalid day of month: %s"), s);
      return NULL;
    }
    if ((t->tm_mon < 0) || (t->tm_mon > 11))
    {
      buf_printf(err, _("Invalid month: %s"), s);
      return NULL;
    }

    return (s + 8);
  }

  t->tm_mday = strtol(s, &p, 10);
  if ((t->tm_mday < 1) || (t->tm_mday > 31))
  {
    buf_printf(err, _("Invalid day of month: %s"), s);
    return NULL;
  }
  if (*p != '/')
  {
    /* fill in today's month and year */
    t->tm_mon = tm.tm_mon;
    t->tm_year = tm.tm_year;
    return p;
  }
  p++;
  t->tm_mon = strtol(p, &p, 10) - 1;
  if ((t->tm_mon < 0) || (t->tm_mon > 11))
  {
    buf_printf(err, _("Invalid month: %s"), p);
    return NULL;
  }
  if (*p != '/')
  {
    t->tm_year = tm.tm_year;
    return p;
  }
  p++;
  t->tm_year = strtol(p, &p, 10);
  if (t->tm_year < 70) /* year 2000+ */
    t->tm_year += 100;
  else if (t->tm_year > 1900)
    t->tm_year -= 1900;
  return p;
}

/**
 * parse_date_range - Parse a date range
 * @param pc       String to parse
 * @param min      Earlier date
 * @param max      Later date
 * @param have_min Do we have a base minimum date?
 * @param base_min Base minimum date
 * @param err      Buffer for error messages
 * @retval ptr First character after the date
 */
static const char *parse_date_range(const char *pc, struct tm *min, struct tm *max,
                                    bool have_min, struct tm *base_min, struct Buffer *err)
{
  ParseDateRangeFlags flags = MUTT_PDR_NO_FLAGS;
  while (*pc && ((flags & MUTT_PDR_DONE) == 0))
  {
    const char *pt = NULL;
    char ch = *pc++;
    SKIPWS(pc);
    switch (ch)
    {
      case '-':
      {
        /* try a range of absolute date minus offset of Ndwmy */
        pt = get_offset(min, pc, -1);
        if (pc == pt)
        {
          if (flags == MUTT_PDR_NO_FLAGS)
          { /* nothing yet and no offset parsed => absolute date? */
            if (!get_date(pc, max, err))
            {
              flags |= (MUTT_PDR_ABSOLUTE | MUTT_PDR_ERRORDONE); /* done bad */
            }
            else
            {
              /* reestablish initial base minimum if not specified */
              if (!have_min)
                memcpy(min, base_min, sizeof(struct tm));
              flags |= (MUTT_PDR_ABSOLUTE | MUTT_PDR_DONE); /* done good */
            }
          }
          else
          {
            flags |= MUTT_PDR_ERRORDONE;
          }
        }
        else
        {
          pc = pt;
          if ((flags == MUTT_PDR_NO_FLAGS) && !have_min)
          { /* the very first "-3d" without a previous absolute date */
            max->tm_year = min->tm_year;
            max->tm_mon = min->tm_mon;
            max->tm_mday = min->tm_mday;
          }
          flags |= MUTT_PDR_MINUS;
        }
        break;
      }
      case '+':
      { /* enlarge plus range */
        pt = get_offset(max, pc, 1);
        if (pc == pt)
        {
          flags |= MUTT_PDR_ERRORDONE;
        }
        else
        {
          pc = pt;
          flags |= MUTT_PDR_PLUS;
        }
        break;
      }
      case '*':
      { /* enlarge window in both directions */
        pt = get_offset(min, pc, -1);
        if (pc == pt)
        {
          flags |= MUTT_PDR_ERRORDONE;
        }
        else
        {
          pc = get_offset(max, pc, 1);
          flags |= MUTT_PDR_WINDOW;
        }
        break;
      }
      default:
        flags |= MUTT_PDR_ERRORDONE;
    }
    SKIPWS(pc);
  }
  if ((flags & MUTT_PDR_ERROR) && !(flags & MUTT_PDR_ABSOLUTE))
  { /* get_date has its own error message, don't overwrite it here */
    buf_printf(err, _("Invalid relative date: %s"), pc - 1);
  }
  return (flags & MUTT_PDR_ERROR) ? NULL : pc;
}

/**
 * adjust_date_range - Put a date range in the correct order
 * @param[in,out] min Earlier date
 * @param[in,out] max Later date
 */
static void adjust_date_range(struct tm *min, struct tm *max)
{
  if ((min->tm_year > max->tm_year) ||
      ((min->tm_year == max->tm_year) && (min->tm_mon > max->tm_mon)) ||
      ((min->tm_year == max->tm_year) && (min->tm_mon == max->tm_mon) &&
       (min->tm_mday > max->tm_mday)))
  {
    int tmp;

    tmp = min->tm_year;
    min->tm_year = max->tm_year;
    max->tm_year = tmp;

    tmp = min->tm_mon;
    min->tm_mon = max->tm_mon;
    max->tm_mon = tmp;

    tmp = min->tm_mday;
    min->tm_mday = max->tm_mday;
    max->tm_mday = tmp;

    min->tm_hour = 0;
    min->tm_min = 0;
    min->tm_sec = 0;
    max->tm_hour = 23;
    max->tm_min = 59;
    max->tm_sec = 59;
  }
}

/**
 * eval_date_minmax - Evaluate a date-range pattern against 'now'
 * @param pat Pattern to modify
 * @param s   Pattern string to use
 * @param err Buffer for error messages
 * @retval true  Pattern valid and updated
 * @retval false Pattern invalid
 */
bool eval_date_minmax(struct Pattern *pat, const char *s, struct Buffer *err)
{
  /* the '0' time is Jan 1, 1970 UTC, so in order to prevent a negative time
   * when doing timezone conversion, we use Jan 2, 1970 UTC as the base here */
  struct tm min = { 0 };
  min.tm_mday = 2;
  min.tm_year = 70;

  /* Arbitrary year in the future.  Don't set this too high or
   * mutt_date_make_time() returns something larger than will fit in a time_t
   * on some systems */
  struct tm max = { 0 };
  max.tm_year = 130;
  max.tm_mon = 11;
  max.tm_mday = 31;
  max.tm_hour = 23;
  max.tm_min = 59;
  max.tm_sec = 59;

  if (strchr("<>=", s[0]))
  {
    /* offset from current time
     *  <3d  less than three days ago
     *  >3d  more than three days ago
     *  =3d  exactly three days ago */
    struct tm *tm = NULL;
    bool exact = false;

    if (s[0] == '<')
    {
      min = mutt_date_localtime(mutt_date_now());
      tm = &min;
    }
    else
    {
      max = mutt_date_localtime(mutt_date_now());
      tm = &max;

      if (s[0] == '=')
        exact = true;
    }

    /* Reset the HMS unless we are relative matching using one of those
     * offsets. */
    char *offset_type = NULL;
    strtol(s + 1, &offset_type, 0);
    if (!(*offset_type && strchr("HMS", *offset_type)))
    {
      tm->tm_hour = 23;
      tm->tm_min = 59;
      tm->tm_sec = 59;
    }

    /* force negative offset */
    get_offset(tm, s + 1, -1);

    if (exact)
    {
      /* start at the beginning of the day in question */
      memcpy(&min, &max, sizeof(max));
      min.tm_hour = 0;
      min.tm_sec = 0;
      min.tm_min = 0;
    }
  }
  else
  {
    const char *pc = s;

    bool have_min = false;
    bool until_now = false;
    if (isdigit((unsigned char) *pc))
    {
      /* minimum date specified */
      pc = get_date(pc, &min, err);
      if (!pc)
      {
        return false;
      }
      have_min = true;
      SKIPWS(pc);
      if (*pc == '-')
      {
        const char *pt = pc + 1;
        SKIPWS(pt);
        until_now = (*pt == '\0');
      }
    }

    if (!until_now)
    { /* max date or relative range/window */

      struct tm base_min = { 0 };

      if (!have_min)
      { /* save base minimum and set current date, e.g. for "-3d+1d" */
        memcpy(&base_min, &min, sizeof(base_min));
        min = mutt_date_localtime(mutt_date_now());
        min.tm_hour = 0;
        min.tm_sec = 0;
        min.tm_min = 0;
      }

      /* preset max date for relative offsets,
       * if nothing follows we search for messages on a specific day */
      max.tm_year = min.tm_year;
      max.tm_mon = min.tm_mon;
      max.tm_mday = min.tm_mday;

      if (!parse_date_range(pc, &min, &max, have_min, &base_min, err))
      { /* bail out on any parsing error */
        return false;
      }
    }
  }

  /* Since we allow two dates to be specified we'll have to adjust that. */
  adjust_date_range(&min, &max);

  pat->min = mutt_date_make_time(&min, true);
  pat->max = mutt_date_make_time(&max, true);

  return true;
}

/**
 * eat_range - Parse a number range - Implements ::eat_arg_t - @ingroup eat_arg_api
 */
static bool eat_range(struct Pattern *pat, PatternCompFlags flags,
                      struct Buffer *s, struct Buffer *err)
{
  char *tmp = NULL;
  bool do_exclusive = false;
  bool skip_quote = false;

  /* If simple_search is set to "~m %s", the range will have double quotes
   * around it...  */
  if (*s->dptr == '"')
  {
    s->dptr++;
    skip_quote = true;
  }
  if (*s->dptr == '<')
    do_exclusive = true;
  if ((*s->dptr != '-') && (*s->dptr != '<'))
  {
    /* range minimum */
    if (*s->dptr == '>')
    {
      pat->max = MUTT_MAXRANGE;
      pat->min = strtol(s->dptr + 1, &tmp, 0) + 1; /* exclusive range */
    }
    else
    {
      pat->min = strtol(s->dptr, &tmp, 0);
    }
    if (toupper((unsigned char) *tmp) == 'K') /* is there a prefix? */
    {
      pat->min *= 1024;
      tmp++;
    }
    else if (toupper((unsigned char) *tmp) == 'M')
    {
      pat->min *= 1048576;
      tmp++;
    }
    if (*s->dptr == '>')
    {
      s->dptr = tmp;
      return true;
    }
    if (*tmp != '-')
    {
      /* exact value */
      pat->max = pat->min;
      s->dptr = tmp;
      return true;
    }
    tmp++;
  }
  else
  {
    s->dptr++;
    tmp = s->dptr;
  }

  if (isdigit((unsigned char) *tmp))
  {
    /* range maximum */
    pat->max = strtol(tmp, &tmp, 0);
    if (toupper((unsigned char) *tmp) == 'K')
    {
      pat->max *= 1024;
      tmp++;
    }
    else if (toupper((unsigned char) *tmp) == 'M')
    {
      pat->max *= 1048576;
      tmp++;
    }
    if (do_exclusive)
      (pat->max)--;
  }
  else
  {
    pat->max = MUTT_MAXRANGE;
  }

  if (skip_quote && (*tmp == '"'))
    tmp++;

  SKIPWS(tmp);
  s->dptr = tmp;
  return true;
}

/**
 * eat_date - Parse a date pattern - Implements ::eat_arg_t - @ingroup eat_arg_api
 */
static bool eat_date(struct Pattern *pat, PatternCompFlags flags,
                     struct Buffer *s, struct Buffer *err)
{
  struct Buffer *tmp = buf_pool_get();
  bool rc = false;

  char *pexpr = s->dptr;
  if (parse_extract_token(tmp, s, TOKEN_COMMENT | TOKEN_PATTERN) != 0)
  {
    buf_printf(err, _("Error in expression: %s"), pexpr);
    goto out;
  }

  if (buf_is_empty(tmp))
  {
    buf_addstr(err, _("Empty expression"));
    goto out;
  }

  if (flags & MUTT_PC_PATTERN_DYNAMIC)
  {
    pat->dynamic = true;
    pat->p.str = mutt_str_dup(tmp->data);
  }

  rc = eval_date_minmax(pat, tmp->data, err);

out:
  buf_pool_release(&tmp);
  return rc;
}

/**
 * find_matching_paren - Find the matching parenthesis
 * @param s string to search
 * @retval ptr
 * - Matching close parenthesis
 * - End of string NUL, if not found
 */
static /* const */ char *find_matching_paren(/* const */ char *s)
{
  int level = 1;

  for (; *s; s++)
  {
    if (*s == '(')
    {
      level++;
    }
    else if (*s == ')')
    {
      level--;
      if (level == 0)
        break;
    }
  }
  return s;
}

/**
 * mutt_pattern_free - Free a Pattern
 * @param[out] pat Pattern to free
 */
void mutt_pattern_free(struct PatternList **pat)
{
  if (!pat || !*pat)
    return;

  struct Pattern *np = SLIST_FIRST(*pat);
  struct Pattern *next = NULL;

  while (np)
  {
    next = SLIST_NEXT(np, entries);

    if (np->is_multi)
    {
      mutt_list_free(&np->p.multi_cases);
    }
    else if (np->string_match || np->dynamic)
    {
      FREE(&np->p.str);
    }
    else if (np->group_match)
    {
      np->p.group = NULL;
    }
    else if (np->p.regex)
    {
      regfree(np->p.regex);
      FREE(&np->p.regex);
    }

#ifdef USE_DEBUG_GRAPHVIZ
    FREE(&np->raw_pattern);
#endif
    mutt_pattern_free(&np->child);
    FREE(&np);

    np = next;
  }

  FREE(pat);
}

/**
 * mutt_pattern_new - Create a new Pattern
 * @retval ptr Newly created Pattern
 */
static struct Pattern *mutt_pattern_new(void)
{
  return MUTT_MEM_CALLOC(1, struct Pattern);
}

/**
 * mutt_pattern_list_new - Create a new list containing a Pattern
 * @retval ptr Newly created list containing a single node with a Pattern
 */
static struct PatternList *mutt_pattern_list_new(void)
{
  struct PatternList *h = MUTT_MEM_CALLOC(1, struct PatternList);
  SLIST_INIT(h);
  struct Pattern *p = mutt_pattern_new();
  SLIST_INSERT_HEAD(h, p, entries);
  return h;
}

/**
 * attach_leaf - Attach a Pattern to a Pattern List
 * @param list Pattern List to attach to
 * @param leaf Pattern to attach
 * @retval ptr Attached leaf
 */
static struct Pattern *attach_leaf(struct PatternList *list, struct Pattern *leaf)
{
  struct Pattern *last = NULL;
  SLIST_FOREACH(last, list, entries)
  {
    // TODO - or we could use a doubly-linked list
    if (!SLIST_NEXT(last, entries))
    {
      SLIST_NEXT(last, entries) = leaf;
      break;
    }
  }
  return leaf;
}

/**
 * attach_new_root - Create a new Pattern as a parent for a List
 * @param curlist Pattern List
 * @retval ptr First Pattern in the original List
 *
 * @note curlist will be altered to the new root Pattern
 */
static struct Pattern *attach_new_root(struct PatternList **curlist)
{
  struct PatternList *root = mutt_pattern_list_new();
  struct Pattern *leaf = SLIST_FIRST(root);
  leaf->child = *curlist;
  *curlist = root;
  return leaf;
}

/**
 * attach_new_leaf - Attach a new Pattern to a List
 * @param curlist Pattern List
 * @retval ptr New Pattern in the original List
 *
 * @note curlist may be altered
 */
static struct Pattern *attach_new_leaf(struct PatternList **curlist)
{
  if (*curlist)
  {
    return attach_leaf(*curlist, mutt_pattern_new());
  }
  else
  {
    return attach_new_root(curlist);
  }
}

/**
 * mutt_pattern_comp - Create a Pattern
 * @param mv    Mailbox view
 * @param menu  Current Menu
 * @param s     Pattern string
 * @param flags Flags, e.g. #MUTT_PC_FULL_MSG
 * @param err   Buffer for error messages
 * @retval ptr Newly allocated Pattern
 */
struct PatternList *mutt_pattern_comp(struct MailboxView *mv, struct Menu *menu,
                                      const char *s, PatternCompFlags flags,
                                      struct Buffer *err)
{
  /* curlist when assigned will always point to a list containing at least one node
   * with a Pattern value.  */
  struct PatternList *curlist = NULL;
  bool pat_not = false;
  bool all_addr = false;
  bool pat_or = false;
  bool implicit = true; /* used to detect logical AND operator */
  bool is_alias = false;
  const struct PatternFlags *entry = NULL;
  char *p = NULL;
  char *buf = NULL;
  struct Mailbox *m = mv ? mv->mailbox : NULL;

  if (!s || (s[0] == '\0'))
  {
    buf_strcpy(err, _("empty pattern"));
    return NULL;
  }

  struct Buffer *ps = buf_pool_get();
  buf_strcpy(ps, s);
  buf_seek(ps, 0);

  SKIPWS(ps->dptr);
  while (*ps->dptr)
  {
    switch (*ps->dptr)
    {
      case '^':
        ps->dptr++;
        all_addr = !all_addr;
        break;
      case '!':
        ps->dptr++;
        pat_not = !pat_not;
        break;
      case '@':
        ps->dptr++;
        is_alias = !is_alias;
        break;
      case '|':
        if (!pat_or)
        {
          if (!curlist)
          {
            buf_printf(err, _("error in pattern at: %s"), ps->dptr);
            buf_pool_release(&ps);
            return NULL;
          }

          struct Pattern *pat = SLIST_FIRST(curlist);
          if (SLIST_NEXT(pat, entries))
          {
            /* A & B | C == (A & B) | C */
            struct Pattern *root = attach_new_root(&curlist);
            root->op = MUTT_PAT_AND;
          }

          pat_or = true;
        }
        ps->dptr++;
        implicit = false;
        pat_not = false;
        all_addr = false;
        is_alias = false;
        break;
      case '%':
      case '=':
      case '~':
      {
        if (ps->dptr[1] == '\0')
        {
          buf_printf(err, _("missing pattern: %s"), ps->dptr);
          goto cleanup;
        }
        short thread_op = 0;
        if (ps->dptr[1] == '(')
          thread_op = MUTT_PAT_THREAD;
        else if ((ps->dptr[1] == '<') && (ps->dptr[2] == '('))
          thread_op = MUTT_PAT_PARENT;
        else if ((ps->dptr[1] == '>') && (ps->dptr[2] == '('))
          thread_op = MUTT_PAT_CHILDREN;
        if (thread_op != 0)
        {
          ps->dptr++; /* skip ~ */
          if ((thread_op == MUTT_PAT_PARENT) || (thread_op == MUTT_PAT_CHILDREN))
            ps->dptr++;
          p = find_matching_paren(ps->dptr + 1);
          if (p[0] != ')')
          {
            buf_printf(err, _("mismatched parentheses: %s"), ps->dptr);
            goto cleanup;
          }
          struct Pattern *leaf = attach_new_leaf(&curlist);
          leaf->op = thread_op;
          leaf->pat_not = pat_not;
          leaf->all_addr = all_addr;
          leaf->is_alias = is_alias;
          pat_not = false;
          all_addr = false;
          is_alias = false;
          /* compile the sub-expression */
          buf = mutt_strn_dup(ps->dptr + 1, p - (ps->dptr + 1));
          leaf->child = mutt_pattern_comp(mv, menu, buf, flags, err);
          if (!leaf->child)
          {
            FREE(&buf);
            goto cleanup;
          }
          FREE(&buf);
          ps->dptr = p + 1; /* restore location */
          break;
        }
        if (implicit && pat_or)
        {
          /* A | B & C == (A | B) & C */
          struct Pattern *root = attach_new_root(&curlist);
          root->op = MUTT_PAT_OR;
          pat_or = false;
        }

        entry = lookup_tag(ps->dptr[1]);
        if (!entry)
        {
          buf_printf(err, _("%c: invalid pattern modifier"), *ps->dptr);
          goto cleanup;
        }
        if (entry->flags && ((flags & entry->flags) == 0))
        {
          buf_printf(err, _("%c: not supported in this mode"), *ps->dptr);
          goto cleanup;
        }

        struct Pattern *leaf = attach_new_leaf(&curlist);
        leaf->pat_not = pat_not;
        leaf->all_addr = all_addr;
        leaf->is_alias = is_alias;
        leaf->string_match = (ps->dptr[0] == '=');
        leaf->group_match = (ps->dptr[0] == '%');
        leaf->sendmode = (flags & MUTT_PC_SEND_MODE_SEARCH);
        leaf->op = entry->op;
        pat_not = false;
        all_addr = false;
        is_alias = false;

        ps->dptr++; /* move past the ~ */
        ps->dptr++; /* eat the operator and any optional whitespace */
        SKIPWS(ps->dptr);
        if (entry->eat_arg)
        {
          if (ps->dptr[0] == '\0')
          {
            buf_addstr(err, _("missing parameter"));
            goto cleanup;
          }
          switch (entry->eat_arg)
          {
            case EAT_REGEX:
              if (!eat_regex(leaf, flags, ps, err))
                goto cleanup;
              break;
            case EAT_DATE:
              if (!eat_date(leaf, flags, ps, err))
                goto cleanup;
              break;
            case EAT_RANGE:
              if (!eat_range(leaf, flags, ps, err))
                goto cleanup;
              break;
            case EAT_MESSAGE_RANGE:
              if (!eat_message_range(leaf, flags, ps, err, mv))
                goto cleanup;
              break;
            case EAT_QUERY:
              if (!eat_query(leaf, flags, ps, err, m))
                goto cleanup;
              break;
            default:
              break;
          }
        }
        implicit = true;
        break;
      }

      case '(':
      {
        p = find_matching_paren(ps->dptr + 1);
        if (p[0] != ')')
        {
          buf_printf(err, _("mismatched parentheses: %s"), ps->dptr);
          goto cleanup;
        }
        /* compile the sub-expression */
        buf = mutt_strn_dup(ps->dptr + 1, p - (ps->dptr + 1));
        struct PatternList *sub = mutt_pattern_comp(mv, menu, buf, flags, err);
        FREE(&buf);
        if (!sub)
          goto cleanup;
        struct Pattern *leaf = SLIST_FIRST(sub);
        if (curlist)
        {
          attach_leaf(curlist, leaf);
          FREE(&sub);
        }
        else
        {
          curlist = sub;
        }
        leaf->pat_not ^= pat_not;
        leaf->all_addr |= all_addr;
        leaf->is_alias |= is_alias;
        pat_not = false;
        all_addr = false;
        is_alias = false;
        ps->dptr = p + 1; /* restore location */
        break;
      }

      default:
        buf_printf(err, _("error in pattern at: %s"), ps->dptr);
        goto cleanup;
    }
    SKIPWS(ps->dptr);
  }
  buf_pool_release(&ps);

  if (!curlist)
  {
    buf_strcpy(err, _("empty pattern"));
    return NULL;
  }

  if (SLIST_NEXT(SLIST_FIRST(curlist), entries))
  {
    struct Pattern *root = attach_new_root(&curlist);
    root->op = pat_or ? MUTT_PAT_OR : MUTT_PAT_AND;
  }

  return curlist;

cleanup:
  mutt_pattern_free(&curlist);
  buf_pool_release(&ps);
  return NULL;
}