doing-ops 0.2.4

Domain operations for the doing CLI
Documentation
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
use std::borrow::Cow;

use doing_config::SearchConfig;
use doing_taskpaper::Entry;
use regex::Regex;
use sublime_fuzzy::best_match;

/// How text comparisons handle letter case.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CaseSensitivity {
  Ignore,
  Sensitive,
}

/// A single token inside a [`SearchMode::Pattern`] query.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PatternToken {
  /// Token must NOT appear in the text.
  Exclude(String),
  /// Token must appear in the text.
  Include(String),
  /// Quoted phrase that must appear as-is.
  Phrase(String),
}

/// The kind of text matching to apply.
#[derive(Clone, Debug)]
pub enum SearchMode {
  /// Exact literal substring match (triggered by `'` prefix).
  Exact(String),
  /// Fuzzy character-order match with a maximum gap distance.
  Fuzzy(String, u32),
  /// Space-separated tokens with `+require`, `-exclude`, and `"quoted phrase"` support.
  Pattern(Vec<PatternToken>),
  /// Full regular expression (triggered by `/pattern/` syntax).
  Regex(Regex),
}

/// Test whether `text` matches the given search mode and case sensitivity.
pub fn matches(text: &str, mode: &SearchMode, case: CaseSensitivity) -> bool {
  match mode {
    SearchMode::Exact(literal) => matches_exact(text, literal, case),
    SearchMode::Fuzzy(pattern, distance) => matches_fuzzy(text, pattern, *distance, case),
    SearchMode::Pattern(tokens) => matches_pattern(text, tokens, case),
    SearchMode::Regex(rx) => rx.is_match(text),
  }
}

/// Test whether an entry matches the given search mode and case sensitivity.
///
/// Searches the entry title, tag names, and optionally the note lines when
/// `include_notes` is `true`. Returns `true` if any of these match.
pub fn matches_entry(entry: &Entry, mode: &SearchMode, case: CaseSensitivity, include_notes: bool) -> bool {
  if matches(entry.title(), mode, case) {
    return true;
  }

  for tag in entry.tags().iter() {
    if matches(tag.name(), mode, case) {
      return true;
    }
  }

  if include_notes && !entry.note().is_empty() {
    // Check each line individually to avoid joining into a temporary String.
    // Fall back to a joined string only for modes that need cross-line matching.
    let note = entry.note();
    match mode {
      SearchMode::Regex(_) | SearchMode::Fuzzy(..) => {
        // These modes may need to match across line boundaries
        let note_text = note.lines().join(" ");
        if matches(&note_text, mode, case) {
          return true;
        }
      }
      _ => {
        for line in note.lines() {
          if matches(line, mode, case) {
            return true;
          }
        }
      }
    }
  }

  false
}

/// Build a [`SearchMode`] and [`CaseSensitivity`] from a raw query string and config.
pub fn parse_query(query: &str, config: &SearchConfig) -> Option<(SearchMode, CaseSensitivity)> {
  let query = query.trim();
  if query.is_empty() {
    return None;
  }

  let case = resolve_case(query, config);
  let mode = detect_mode(query, config, case);

  Some((mode, case))
}

/// Build a compiled regex, applying case-insensitivity flag when needed.
fn build_regex(pattern: &str, original_query: &str, config: &SearchConfig) -> Result<Regex, regex::Error> {
  let case = resolve_case(original_query, config);
  let full_pattern = match case {
    CaseSensitivity::Ignore => format!("(?i){pattern}"),
    CaseSensitivity::Sensitive => pattern.to_string(),
  };
  Regex::new(&full_pattern)
}

/// Detect the search mode from the query string and config.
///
/// Detection order:
/// 1. `'` prefix → exact mode
/// 2. `/pattern/` → regex mode
/// 3. Config `matching` == `fuzzy` → fuzzy mode
/// 4. Otherwise → pattern mode
fn detect_mode(query: &str, config: &SearchConfig, case: CaseSensitivity) -> SearchMode {
  if let Some(literal) = query.strip_prefix('\'') {
    return SearchMode::Exact(maybe_lowercase(literal, case));
  }

  if let Some(inner) = try_extract_regex(query)
    && let Ok(rx) = build_regex(&inner, query, config)
  {
    return SearchMode::Regex(rx);
  }

  if config.matching == "fuzzy" {
    return SearchMode::Fuzzy(maybe_lowercase(query, case), config.distance);
  }

  SearchMode::Pattern(parse_pattern_tokens(query, case))
}

/// Check whether `text` contains the exact literal substring.
///
/// The `literal` is expected to be pre-lowercased when `case` is `Ignore`.
fn matches_exact(text: &str, literal: &str, case: CaseSensitivity) -> bool {
  match case {
    CaseSensitivity::Sensitive => text.contains(literal),
    CaseSensitivity::Ignore => text.to_lowercase().contains(literal),
  }
}

/// Check whether `text` matches a fuzzy pattern using `sublime_fuzzy`.
///
/// Characters in `pattern` must appear in `text` in order, but gaps are allowed.
/// The `distance` parameter sets the maximum allowed gap between consecutive
/// matched characters. A distance of 0 disables the gap check.
///
/// The `pattern` is expected to be pre-lowercased when `case` is `Ignore`.
fn matches_fuzzy(text: &str, pattern: &str, distance: u32, case: CaseSensitivity) -> bool {
  let haystack: Cow<str> = match case {
    CaseSensitivity::Sensitive => Cow::Borrowed(text),
    CaseSensitivity::Ignore => Cow::Owned(text.to_lowercase()),
  };

  let result = match best_match(pattern, &haystack) {
    Some(m) => m,
    None => return false,
  };

  if distance == 0 {
    return true;
  }

  let positions: Vec<usize> = result
    .continuous_matches()
    .flat_map(|cm| cm.start()..cm.start() + cm.len())
    .collect();
  positions.windows(2).all(|w| (w[1] - w[0] - 1) as u32 <= distance)
}

/// Check whether `text` matches all pattern tokens.
///
/// - Include: word must appear anywhere in text.
/// - Exclude: word must NOT appear in text.
/// - Phrase: exact substring must appear in text.
///
/// Tokens are expected to be pre-lowercased when `case` is `Ignore`.
fn matches_pattern(text: &str, tokens: &[PatternToken], case: CaseSensitivity) -> bool {
  let lowered;
  let haystack = match case {
    CaseSensitivity::Ignore => {
      lowered = text.to_lowercase();
      &lowered
    }
    CaseSensitivity::Sensitive => text,
  };

  for token in tokens {
    let needle = match token {
      PatternToken::Exclude(word) | PatternToken::Include(word) | PatternToken::Phrase(word) => word.as_str(),
    };
    let found = haystack.contains(needle);
    match token {
      PatternToken::Exclude(_) if found => return false,
      PatternToken::Include(_) | PatternToken::Phrase(_) if !found => return false,
      _ => {}
    }
  }
  true
}

/// Parse a pattern-mode query into tokens.
///
/// Supports:
/// - `"quoted phrase"` → Phrase token
/// - `+word` → Include token (required)
/// - `-word` → Exclude token (excluded)
/// - bare `word` → Include token
fn maybe_lowercase(s: &str, case: CaseSensitivity) -> String {
  match case {
    CaseSensitivity::Ignore => s.to_lowercase(),
    CaseSensitivity::Sensitive => s.to_string(),
  }
}

fn parse_pattern_tokens(query: &str, case: CaseSensitivity) -> Vec<PatternToken> {
  let mut tokens = Vec::new();
  let mut chars = query.chars().peekable();

  while let Some(&c) = chars.peek() {
    if c.is_whitespace() {
      chars.next();
      continue;
    }

    if c == '"' {
      chars.next(); // consume opening quote
      let phrase: String = chars.by_ref().take_while(|&ch| ch != '"').collect();
      if !phrase.is_empty() {
        tokens.push(PatternToken::Phrase(maybe_lowercase(&phrase, case)));
      }
    } else if c == '+' {
      chars.next(); // consume +
      let word: String = chars.by_ref().take_while(|ch| !ch.is_whitespace()).collect();
      if !word.is_empty() {
        tokens.push(PatternToken::Include(maybe_lowercase(&word, case)));
      }
    } else if c == '-' {
      chars.next(); // consume -
      let word: String = chars.by_ref().take_while(|ch| !ch.is_whitespace()).collect();
      if !word.is_empty() {
        tokens.push(PatternToken::Exclude(maybe_lowercase(&word, case)));
      }
    } else {
      let word: String = chars.by_ref().take_while(|ch| !ch.is_whitespace()).collect();
      if !word.is_empty() {
        tokens.push(PatternToken::Include(maybe_lowercase(&word, case)));
      }
    }
  }

  tokens
}

/// Determine case sensitivity from the query and config.
///
/// Smart mode: all-lowercase query → case-insensitive; any uppercase → case-sensitive.
/// The `search.case` config can override to `sensitive` or `ignore`.
fn resolve_case(query: &str, config: &SearchConfig) -> CaseSensitivity {
  match config.case.as_str() {
    "sensitive" => CaseSensitivity::Sensitive,
    "ignore" => CaseSensitivity::Ignore,
    _ => {
      // smart: any uppercase character triggers case-sensitive
      if query.chars().any(|c| c.is_uppercase()) {
        CaseSensitivity::Sensitive
      } else {
        CaseSensitivity::Ignore
      }
    }
  }
}

/// Try to extract a regex pattern from `/pattern/` syntax.
fn try_extract_regex(query: &str) -> Option<String> {
  let rest = query.strip_prefix('/')?;
  let inner = rest.strip_suffix('/')?;
  if inner.is_empty() {
    return None;
  }
  Some(inner.to_string())
}

#[cfg(test)]
mod test {
  use super::*;

  fn contains_word(text: &str, word: &str, case: CaseSensitivity) -> bool {
    match case {
      CaseSensitivity::Sensitive => text.contains(word),
      CaseSensitivity::Ignore => text.to_lowercase().contains(&word.to_lowercase()),
    }
  }

  fn default_config() -> SearchConfig {
    SearchConfig::default()
  }

  fn fuzzy_config() -> SearchConfig {
    SearchConfig {
      matching: "fuzzy".into(),
      ..SearchConfig::default()
    }
  }

  mod contains_word {
    use super::*;

    #[test]
    fn it_finds_case_insensitive_match() {
      assert!(super::contains_word("Hello World", "hello", CaseSensitivity::Ignore));
    }

    #[test]
    fn it_finds_case_sensitive_match() {
      assert!(super::contains_word("Hello World", "Hello", CaseSensitivity::Sensitive));
    }

    #[test]
    fn it_rejects_case_mismatch_when_sensitive() {
      assert!(!super::contains_word(
        "Hello World",
        "hello",
        CaseSensitivity::Sensitive
      ));
    }
  }

  mod detect_mode {
    use super::*;

    #[test]
    fn it_detects_exact_mode_with_quote_prefix() {
      let mode = super::super::detect_mode("'exact match", &default_config(), CaseSensitivity::Ignore);

      assert!(matches!(mode, SearchMode::Exact(s) if s == "exact match"));
    }

    #[test]
    fn it_detects_fuzzy_mode_from_config() {
      let mode = super::super::detect_mode("some query", &fuzzy_config(), CaseSensitivity::Ignore);

      assert!(matches!(mode, SearchMode::Fuzzy(s, 3) if s == "some query"));
    }

    #[test]
    fn it_detects_pattern_mode_by_default() {
      let mode = super::super::detect_mode("hello world", &default_config(), CaseSensitivity::Ignore);

      assert!(matches!(mode, SearchMode::Pattern(_)));
    }

    #[test]
    fn it_detects_regex_mode_with_slashes() {
      let mode = super::super::detect_mode("/foo.*bar/", &default_config(), CaseSensitivity::Ignore);

      assert!(matches!(mode, SearchMode::Regex(_)));
    }
  }

  mod matches_entry {
    use chrono::{Local, TimeZone};
    use doing_taskpaper::{Note, Tag, Tags};

    use super::*;

    fn sample_entry() -> Entry {
      Entry::new(
        Local.with_ymd_and_hms(2024, 3, 17, 14, 30, 0).unwrap(),
        "Working on search feature",
        Tags::new(),
        Note::from_text("Added fuzzy matching\nFixed regex parsing"),
        "Currently",
        None::<String>,
      )
    }

    fn tagged_entry() -> Entry {
      Entry::new(
        Local.with_ymd_and_hms(2024, 3, 17, 14, 30, 0).unwrap(),
        "Working on project",
        Tags::from_iter(vec![
          Tag::new("coding", None::<String>),
          Tag::new("rust", None::<String>),
        ]),
        Note::new(),
        "Currently",
        None::<String>,
      )
    }

    #[test]
    fn it_does_not_duplicate_results_for_title_and_tag_match() {
      let entry = Entry::new(
        Local.with_ymd_and_hms(2024, 3, 17, 14, 30, 0).unwrap(),
        "coding session",
        Tags::from_iter(vec![Tag::new("coding", None::<String>)]),
        Note::new(),
        "Currently",
        None::<String>,
      );
      let mode = SearchMode::Pattern(vec![PatternToken::Include("coding".into())]);

      assert!(super::super::matches_entry(
        &entry,
        &mode,
        CaseSensitivity::Ignore,
        false,
      ));
    }

    #[test]
    fn it_matches_note_when_include_notes_enabled() {
      let mode = SearchMode::Pattern(vec![PatternToken::Include("fuzzy".into())]);

      assert!(super::super::matches_entry(
        &sample_entry(),
        &mode,
        CaseSensitivity::Ignore,
        true,
      ));
    }

    #[test]
    fn it_does_not_match_across_tag_boundaries() {
      // Tags ["co", "ding"] should not match "co ding" since they are separate tags.
      let entry = Entry::new(
        Local.with_ymd_and_hms(2024, 3, 17, 14, 30, 0).unwrap(),
        "Some task",
        Tags::from_iter(vec![Tag::new("co", None::<String>), Tag::new("ding", None::<String>)]),
        Note::new(),
        "Currently",
        None::<String>,
      );
      let mode = SearchMode::Pattern(vec![PatternToken::Include("co ding".into())]);

      assert!(!super::super::matches_entry(
        &entry,
        &mode,
        CaseSensitivity::Ignore,
        false
      ));
    }

    #[test]
    fn it_does_not_match_tag_spanning_two_tags() {
      // Searching for "coding" should not match tags ["co", "ding"]
      let entry = Entry::new(
        Local.with_ymd_and_hms(2024, 3, 17, 14, 30, 0).unwrap(),
        "Some task",
        Tags::from_iter(vec![Tag::new("co", None::<String>), Tag::new("ding", None::<String>)]),
        Note::new(),
        "Currently",
        None::<String>,
      );
      let mode = SearchMode::Pattern(vec![PatternToken::Include("coding".into())]);

      assert!(!super::super::matches_entry(
        &entry,
        &mode,
        CaseSensitivity::Ignore,
        false
      ));
    }

    #[test]
    fn it_matches_tag_name() {
      let mode = SearchMode::Pattern(vec![PatternToken::Include("coding".into())]);

      assert!(super::super::matches_entry(
        &tagged_entry(),
        &mode,
        CaseSensitivity::Ignore,
        false,
      ));
    }

    #[test]
    fn it_matches_tag_name_without_at_prefix() {
      let mode = SearchMode::Pattern(vec![PatternToken::Include("rust".into())]);

      assert!(super::super::matches_entry(
        &tagged_entry(),
        &mode,
        CaseSensitivity::Ignore,
        false,
      ));
    }

    #[test]
    fn it_matches_title() {
      let mode = SearchMode::Pattern(vec![PatternToken::Include("search".into())]);

      assert!(super::super::matches_entry(
        &sample_entry(),
        &mode,
        CaseSensitivity::Ignore,
        false,
      ));
    }

    #[test]
    fn it_returns_false_when_nothing_matches() {
      let mode = SearchMode::Pattern(vec![PatternToken::Include("nonexistent".into())]);

      assert!(!super::super::matches_entry(
        &sample_entry(),
        &mode,
        CaseSensitivity::Ignore,
        true,
      ));
    }

    #[test]
    fn it_skips_note_when_include_notes_disabled() {
      let mode = SearchMode::Pattern(vec![PatternToken::Include("fuzzy".into())]);

      assert!(!super::super::matches_entry(
        &sample_entry(),
        &mode,
        CaseSensitivity::Ignore,
        false,
      ));
    }
  }

  mod matches_exact {
    use super::*;

    #[test]
    fn it_matches_case_insensitive_substring() {
      assert!(super::super::matches_exact(
        "Working on Project",
        "on project",
        CaseSensitivity::Ignore,
      ));
    }

    #[test]
    fn it_matches_case_sensitive_substring() {
      assert!(super::super::matches_exact(
        "Working on Project",
        "on Project",
        CaseSensitivity::Sensitive,
      ));
    }

    #[test]
    fn it_rejects_missing_substring() {
      assert!(!super::super::matches_exact(
        "Working on Project",
        "missing",
        CaseSensitivity::Ignore,
      ));
    }
  }

  mod matches_fuzzy {
    use super::*;

    #[test]
    fn it_matches_characters_in_order_with_gaps() {
      assert!(super::super::matches_fuzzy(
        "Working on project",
        "wop",
        0,
        CaseSensitivity::Ignore
      ));
    }

    #[test]
    fn it_matches_when_gap_within_distance() {
      assert!(super::super::matches_fuzzy("a__b", "ab", 3, CaseSensitivity::Sensitive));
    }

    #[test]
    fn it_rejects_characters_out_of_order() {
      assert!(!super::super::matches_fuzzy(
        "abc",
        "cab",
        0,
        CaseSensitivity::Sensitive
      ));
    }

    #[test]
    fn it_rejects_when_gap_exceeds_distance() {
      assert!(!super::super::matches_fuzzy(
        "a____b",
        "ab",
        2,
        CaseSensitivity::Sensitive
      ));
    }

    #[test]
    fn it_skips_distance_check_when_zero() {
      assert!(super::super::matches_fuzzy(
        "a______________b",
        "ab",
        0,
        CaseSensitivity::Sensitive
      ));
    }
  }

  mod matches_pattern {
    use super::*;

    #[test]
    fn it_matches_all_include_tokens() {
      let tokens = vec![
        PatternToken::Include("hello".into()),
        PatternToken::Include("world".into()),
      ];

      assert!(super::super::matches_pattern(
        "hello beautiful world",
        &tokens,
        CaseSensitivity::Ignore,
      ));
    }

    #[test]
    fn it_matches_quoted_phrase() {
      let tokens = vec![PatternToken::Phrase("hello world".into())];

      assert!(super::super::matches_pattern(
        "say hello world today",
        &tokens,
        CaseSensitivity::Ignore,
      ));
    }

    #[test]
    fn it_rejects_when_exclude_token_found() {
      let tokens = vec![
        PatternToken::Include("hello".into()),
        PatternToken::Exclude("world".into()),
      ];

      assert!(!super::super::matches_pattern(
        "hello world",
        &tokens,
        CaseSensitivity::Ignore,
      ));
    }

    #[test]
    fn it_rejects_when_include_token_missing() {
      let tokens = vec![PatternToken::Include("missing".into())];

      assert!(!super::super::matches_pattern(
        "hello world",
        &tokens,
        CaseSensitivity::Ignore,
      ));
    }
  }

  mod parse_pattern_tokens {
    use pretty_assertions::assert_eq;

    use super::*;

    fn parse_pattern_tokens_sensitive(query: &str) -> Vec<PatternToken> {
      super::super::parse_pattern_tokens(query, CaseSensitivity::Sensitive)
    }

    #[test]
    fn it_parses_bare_words_as_include() {
      let tokens = parse_pattern_tokens_sensitive("hello world");

      assert_eq!(
        tokens,
        vec![
          PatternToken::Include("hello".into()),
          PatternToken::Include("world".into()),
        ]
      );
    }

    #[test]
    fn it_parses_exclude_tokens() {
      let tokens = parse_pattern_tokens_sensitive("hello -world");

      assert_eq!(
        tokens,
        vec![
          PatternToken::Include("hello".into()),
          PatternToken::Exclude("world".into()),
        ]
      );
    }

    #[test]
    fn it_parses_include_tokens() {
      let tokens = parse_pattern_tokens_sensitive("+hello +world");

      assert_eq!(
        tokens,
        vec![
          PatternToken::Include("hello".into()),
          PatternToken::Include("world".into()),
        ]
      );
    }

    #[test]
    fn it_parses_mixed_tokens() {
      let tokens = parse_pattern_tokens_sensitive("+required -excluded bare \"exact phrase\"");

      assert_eq!(
        tokens,
        vec![
          PatternToken::Include("required".into()),
          PatternToken::Exclude("excluded".into()),
          PatternToken::Include("bare".into()),
          PatternToken::Phrase("exact phrase".into()),
        ]
      );
    }

    #[test]
    fn it_parses_quoted_phrases() {
      let tokens = parse_pattern_tokens_sensitive("\"hello world\"");

      assert_eq!(tokens, vec![PatternToken::Phrase("hello world".into())]);
    }
  }

  mod parse_query {
    use super::*;

    #[test]
    fn it_returns_none_for_empty_query() {
      assert!(super::super::parse_query("", &default_config()).is_none());
    }

    #[test]
    fn it_returns_none_for_whitespace_query() {
      assert!(super::super::parse_query("   ", &default_config()).is_none());
    }

    #[test]
    fn it_returns_pattern_mode_by_default() {
      let (mode, _) = super::super::parse_query("hello", &default_config()).unwrap();

      assert!(matches!(mode, SearchMode::Pattern(_)));
    }
  }

  mod resolve_case {
    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn it_returns_ignore_for_all_lowercase() {
      let case = super::super::resolve_case("hello world", &default_config());

      assert_eq!(case, CaseSensitivity::Ignore);
    }

    #[test]
    fn it_returns_ignore_when_config_is_ignore() {
      let config = SearchConfig {
        case: "ignore".into(),
        ..SearchConfig::default()
      };

      let case = super::super::resolve_case("Hello", &config);

      assert_eq!(case, CaseSensitivity::Ignore);
    }

    #[test]
    fn it_returns_sensitive_for_mixed_case() {
      let case = super::super::resolve_case("Hello world", &default_config());

      assert_eq!(case, CaseSensitivity::Sensitive);
    }

    #[test]
    fn it_returns_sensitive_when_config_is_sensitive() {
      let config = SearchConfig {
        case: "sensitive".into(),
        ..SearchConfig::default()
      };

      let case = super::super::resolve_case("hello", &config);

      assert_eq!(case, CaseSensitivity::Sensitive);
    }
  }

  mod try_extract_regex {
    use pretty_assertions::assert_eq;

    #[test]
    fn it_extracts_pattern_from_slashes() {
      let result = super::super::try_extract_regex("/foo.*bar/");

      assert_eq!(result, Some("foo.*bar".into()));
    }

    #[test]
    fn it_returns_none_for_empty_pattern() {
      assert!(super::super::try_extract_regex("//").is_none());
    }

    #[test]
    fn it_returns_none_for_no_slashes() {
      assert!(super::super::try_extract_regex("hello").is_none());
    }

    #[test]
    fn it_returns_none_for_single_slash() {
      assert!(super::super::try_extract_regex("/hello").is_none());
    }
  }
}