ftui-text 0.4.0

Text layout, wrapping, and grapheme width for FrankenTUI.
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
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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
#![forbid(unsafe_code)]

//! Unicode-aware text search utilities.
//!
//! Feature-gated behind the `normalization` feature flag for normalization-aware
//! and case-folded search. Basic exact search is always available.
//!
//! # Policy-Aware Search
//!
//! When the `normalization` feature is enabled, [`search_with_policy`] provides a
//! unified entry point that combines configurable normalization form, case folding,
//! and width measurement into a single [`SearchPolicy`]. Results include display
//! column offsets computed under the chosen [`WidthMode`].
//!
//! # Example
//! ```
//! use ftui_text::search::{SearchResult, search_exact};
//!
//! let results = search_exact("hello world hello", "hello");
//! assert_eq!(results.len(), 2);
//! assert_eq!(results[0].range, 0..5);
//! assert_eq!(results[1].range, 12..17);
//! ```

use unicode_width::UnicodeWidthChar;

/// Unicode character width measurement mode for search results.
///
/// Controls how display column offsets are computed — in particular for East
/// Asian Ambiguous characters whose width differs between CJK and Western
/// terminals.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum WidthMode {
    /// Standard Unicode width: EA Ambiguous characters are single-width (1 cell).
    #[default]
    Standard,

    /// CJK-aware width: EA Ambiguous characters are double-width (2 cells).
    CjkAmbiguousWide,
}

impl WidthMode {
    /// Compute the terminal display width of a single Unicode scalar.
    #[inline]
    #[must_use]
    pub fn char_width(self, ch: char) -> usize {
        let w = match self {
            Self::Standard => UnicodeWidthChar::width(ch).unwrap_or(0),
            Self::CjkAmbiguousWide => UnicodeWidthChar::width_cjk(ch).unwrap_or(0),
        };
        w.min(2)
    }

    /// Compute the display width of a string by summing per-character widths.
    #[must_use]
    pub fn str_width(self, s: &str) -> usize {
        s.chars().map(|ch| self.char_width(ch)).sum()
    }
}

/// Compute the display column at a byte offset in a string.
///
/// Returns the sum of character widths for all characters before the given byte
/// offset, using the specified width mode.
///
/// # Panics
/// Panics if `byte_offset` is not at a char boundary in `s`.
#[must_use]
pub fn display_col_at(s: &str, byte_offset: usize, mode: WidthMode) -> usize {
    debug_assert!(s.is_char_boundary(byte_offset));
    s[..byte_offset].chars().map(|ch| mode.char_width(ch)).sum()
}

/// A single search match with its byte range in the source text.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchResult {
    /// Byte offset range of the match in the source string.
    pub range: std::ops::Range<usize>,
}

impl SearchResult {
    /// Create a new search result.
    #[must_use]
    pub fn new(start: usize, end: usize) -> Self {
        Self { range: start..end }
    }

    /// Extract the matched text from the source.
    #[must_use]
    pub fn text<'a>(&self, source: &'a str) -> &'a str {
        &source[self.range.clone()]
    }
}

/// Find all exact substring matches (byte-level, no normalization).
///
/// Returns non-overlapping matches from left to right.
#[must_use]
pub fn search_exact(haystack: &str, needle: &str) -> Vec<SearchResult> {
    if needle.is_empty() {
        return Vec::new();
    }
    let mut results = Vec::new();
    let mut start = 0;
    while let Some(pos) = haystack[start..].find(needle) {
        let abs_pos = start + pos;
        results.push(SearchResult::new(abs_pos, abs_pos + needle.len()));
        start = abs_pos + needle.len();
    }
    results
}

/// Find all exact substring matches, allowing overlapping results.
///
/// Advances by one byte after each match start.
#[must_use]
pub fn search_exact_overlapping(haystack: &str, needle: &str) -> Vec<SearchResult> {
    if needle.is_empty() {
        return Vec::new();
    }
    let mut results = Vec::new();
    let mut start = 0;
    while let Some(pos) = haystack[start..].find(needle) {
        let abs_pos = start + pos;
        results.push(SearchResult::new(abs_pos, abs_pos + needle.len()));
        // Advance by one char (not byte) to handle multi-byte chars correctly
        start = abs_pos + 1;
        // Ensure we're at a char boundary
        while start < haystack.len() && !haystack.is_char_boundary(start) {
            start += 1;
        }
    }
    results
}

/// Case-insensitive search using simple ASCII lowering.
///
/// For full Unicode case folding, use [`search_case_insensitive`] with the
/// `normalization` feature enabled.
#[must_use]
pub fn search_ascii_case_insensitive(haystack: &str, needle: &str) -> Vec<SearchResult> {
    if needle.is_empty() {
        return Vec::new();
    }
    let haystack_lower = haystack.to_ascii_lowercase();
    let needle_lower = needle.to_ascii_lowercase();
    let mut results = Vec::new();
    let mut start = 0;
    while let Some(pos) = haystack_lower[start..].find(&needle_lower) {
        let abs_pos = start + pos;
        results.push(SearchResult::new(abs_pos, abs_pos + needle.len()));
        start = abs_pos + needle.len();
    }
    results
}

/// Case-insensitive search using full Unicode case folding.
///
/// Uses NFKC normalization + lowercase for both haystack and needle,
/// then maps result positions back to the original string.
#[cfg(feature = "normalization")]
#[must_use]
pub fn search_case_insensitive(haystack: &str, needle: &str) -> Vec<SearchResult> {
    if needle.is_empty() {
        return Vec::new();
    }
    let needle_norm = crate::normalization::normalize_for_search(needle);
    if needle_norm.is_empty() {
        return Vec::new();
    }

    use unicode_segmentation::UnicodeSegmentation;

    // Build mapping using grapheme clusters for correct normalization boundaries.
    // Track both start and end byte offsets for each normalized byte so
    // matches that land inside a grapheme expansion still map to a full
    // grapheme range in the original string.
    let mut norm_start_map: Vec<usize> = Vec::new();
    let mut norm_end_map: Vec<usize> = Vec::new();
    let mut normalized = String::new();

    for (orig_byte, grapheme) in haystack.grapheme_indices(true) {
        let chunk = crate::normalization::normalize_for_search(grapheme);
        if chunk.is_empty() {
            continue;
        }
        let orig_end = orig_byte + grapheme.len();
        for _ in chunk.bytes() {
            norm_start_map.push(orig_byte);
            norm_end_map.push(orig_end);
        }
        normalized.push_str(&chunk);
    }
    if normalized.is_empty() {
        return Vec::new();
    }

    let mut results = Vec::new();
    let mut start = 0;
    while let Some(pos) = normalized[start..].find(&needle_norm) {
        let norm_start = start + pos;
        let norm_end = norm_start + needle_norm.len();

        let orig_start = norm_start_map
            .get(norm_start)
            .copied()
            .unwrap_or(haystack.len());
        let orig_end = if norm_end == 0 {
            orig_start
        } else {
            norm_end_map
                .get(norm_end - 1)
                .copied()
                .unwrap_or(haystack.len())
        };

        // Avoid duplicate ranges when a single grapheme expands into multiple
        // normalized bytes (e.g., fullwidth "A" -> "a" under NFKC).
        if results
            .last()
            .is_some_and(|r: &SearchResult| r.range.start == orig_start && r.range.end == orig_end)
        {
            start = norm_end;
            continue;
        }

        results.push(SearchResult::new(orig_start, orig_end));
        start = norm_end;
    }
    results
}

/// Normalization-aware search: treats composed and decomposed forms as equal.
///
/// Normalizes both haystack and needle to the given form before searching,
/// then maps results back to original string positions using grapheme clusters.
#[cfg(feature = "normalization")]
#[must_use]
pub fn search_normalized(
    haystack: &str,
    needle: &str,
    form: crate::normalization::NormForm,
) -> Vec<SearchResult> {
    use crate::normalization::normalize;
    use unicode_segmentation::UnicodeSegmentation;

    if needle.is_empty() {
        return Vec::new();
    }
    let needle_norm = normalize(needle, form);
    if needle_norm.is_empty() {
        return Vec::new();
    }

    // Normalize per grapheme cluster to maintain position tracking.
    // Grapheme clusters are the correct unit because normalization
    // operates within grapheme boundaries.
    let mut norm_start_map: Vec<usize> = Vec::new();
    let mut norm_end_map: Vec<usize> = Vec::new();
    let mut normalized = String::new();

    for (orig_byte, grapheme) in haystack.grapheme_indices(true) {
        let chunk = normalize(grapheme, form);
        if chunk.is_empty() {
            continue;
        }
        let orig_end = orig_byte + grapheme.len();
        for _ in chunk.bytes() {
            norm_start_map.push(orig_byte);
            norm_end_map.push(orig_end);
        }
        normalized.push_str(&chunk);
    }
    if normalized.is_empty() {
        return Vec::new();
    }

    let mut results = Vec::new();
    let mut start = 0;
    while let Some(pos) = normalized[start..].find(&needle_norm) {
        let norm_start = start + pos;
        let norm_end = norm_start + needle_norm.len();

        let orig_start = norm_start_map
            .get(norm_start)
            .copied()
            .unwrap_or(haystack.len());
        let orig_end = if norm_end == 0 {
            orig_start
        } else {
            norm_end_map
                .get(norm_end - 1)
                .copied()
                .unwrap_or(haystack.len())
        };

        if results
            .last()
            .is_some_and(|r: &SearchResult| r.range.start == orig_start && r.range.end == orig_end)
        {
            start = norm_end;
            continue;
        }

        results.push(SearchResult::new(orig_start, orig_end));
        start = norm_end;
    }
    results
}

// =============================================================================
// Policy-aware search
// =============================================================================

/// Search policy controlling normalization, case folding, and width measurement.
///
/// Bundles the three knobs a terminal search feature needs:
/// 1. Which Unicode normalization form to apply before matching.
/// 2. Whether to fold case (Unicode-aware lowercase after normalization).
/// 3. Which width mode to use for computing display column offsets in results.
///
/// # Presets
///
/// | Preset | Norm | Case | Width |
/// |--------|------|------|-------|
/// | [`STANDARD`](Self::STANDARD) | NFKC | insensitive | Standard |
/// | [`CJK`](Self::CJK) | NFKC | insensitive | CjkAmbiguousWide |
/// | [`EXACT_NFC`](Self::EXACT_NFC) | NFC | sensitive | Standard |
#[cfg(feature = "normalization")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SearchPolicy {
    /// Normalization form applied to both haystack and needle before matching.
    pub norm_form: crate::normalization::NormForm,
    /// If `true`, apply Unicode case folding (lowercase) after normalization.
    pub case_insensitive: bool,
    /// Width mode for computing [`PolicySearchResult::col_start`] / [`PolicySearchResult::col_end`].
    pub width_mode: WidthMode,
}

#[cfg(feature = "normalization")]
impl SearchPolicy {
    /// Default Western terminal preset: NFKC + case-insensitive + standard width.
    pub const STANDARD: Self = Self {
        norm_form: crate::normalization::NormForm::Nfkc,
        case_insensitive: true,
        width_mode: WidthMode::Standard,
    };

    /// CJK terminal preset: NFKC + case-insensitive + CJK ambiguous-wide.
    pub const CJK: Self = Self {
        norm_form: crate::normalization::NormForm::Nfkc,
        case_insensitive: true,
        width_mode: WidthMode::CjkAmbiguousWide,
    };

    /// Exact NFC matching: NFC + case-sensitive + standard width.
    pub const EXACT_NFC: Self = Self {
        norm_form: crate::normalization::NormForm::Nfc,
        case_insensitive: false,
        width_mode: WidthMode::Standard,
    };
}

/// A search result enriched with display-column offsets.
///
/// Extends [`SearchResult`] with terminal column positions computed under the
/// [`WidthMode`] specified by the [`SearchPolicy`].
#[cfg(feature = "normalization")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PolicySearchResult {
    /// Byte offset range of the match in the source string.
    pub range: std::ops::Range<usize>,
    /// Display column (0-indexed) where the match starts.
    pub col_start: usize,
    /// Display column (0-indexed) where the match ends (exclusive).
    pub col_end: usize,
}

#[cfg(feature = "normalization")]
impl PolicySearchResult {
    /// Extract the matched text from the source.
    #[must_use]
    pub fn text<'a>(&self, source: &'a str) -> &'a str {
        &source[self.range.clone()]
    }

    /// Display width of the matched text (col_end - col_start).
    #[must_use]
    pub fn display_width(&self) -> usize {
        self.col_end - self.col_start
    }
}

/// Search with explicit policy controlling normalization, case folding, and width
/// measurement.
///
/// This is the unified entry point for policy-aware search. It:
/// 1. Normalizes both haystack and needle to [`SearchPolicy::norm_form`].
/// 2. Optionally applies Unicode case folding.
/// 3. Finds all non-overlapping matches.
/// 4. Computes display column offsets using [`SearchPolicy::width_mode`].
///
/// # Example
/// ```
/// use ftui_text::search::{SearchPolicy, search_with_policy};
///
/// let results = search_with_policy("Hello World", "hello", &SearchPolicy::STANDARD);
/// assert_eq!(results.len(), 1);
/// assert_eq!(results[0].col_start, 0);
/// assert_eq!(results[0].col_end, 5);
/// ```
#[cfg(feature = "normalization")]
#[must_use]
pub fn search_with_policy(
    haystack: &str,
    needle: &str,
    policy: &SearchPolicy,
) -> Vec<PolicySearchResult> {
    use crate::normalization::normalize;
    use unicode_segmentation::UnicodeSegmentation;

    if needle.is_empty() {
        return Vec::new();
    }

    // Normalize the needle.
    let needle_norm = if policy.case_insensitive {
        normalize(needle, policy.norm_form).to_lowercase()
    } else {
        normalize(needle, policy.norm_form)
    };
    if needle_norm.is_empty() {
        return Vec::new();
    }

    // Normalize haystack per grapheme cluster and build byte-offset mapping.
    let mut norm_start_map: Vec<usize> = Vec::new();
    let mut norm_end_map: Vec<usize> = Vec::new();
    let mut normalized = String::new();

    for (orig_byte, grapheme) in haystack.grapheme_indices(true) {
        let chunk = if policy.case_insensitive {
            normalize(grapheme, policy.norm_form).to_lowercase()
        } else {
            normalize(grapheme, policy.norm_form)
        };
        if chunk.is_empty() {
            continue;
        }
        let orig_end = orig_byte + grapheme.len();
        for _ in chunk.bytes() {
            norm_start_map.push(orig_byte);
            norm_end_map.push(orig_end);
        }
        normalized.push_str(&chunk);
    }
    if normalized.is_empty() {
        return Vec::new();
    }

    // Find matches in normalized text.
    let mut results = Vec::new();
    let mut start = 0;
    while let Some(pos) = normalized[start..].find(&needle_norm) {
        let norm_start = start + pos;
        let norm_end = norm_start + needle_norm.len();

        let orig_start = norm_start_map
            .get(norm_start)
            .copied()
            .unwrap_or(haystack.len());
        let orig_end = if norm_end == 0 {
            orig_start
        } else {
            norm_end_map
                .get(norm_end - 1)
                .copied()
                .unwrap_or(haystack.len())
        };

        // Deduplicate when a grapheme expansion produces duplicate ranges.
        if results.last().is_some_and(|r: &PolicySearchResult| {
            r.range.start == orig_start && r.range.end == orig_end
        }) {
            start = norm_end;
            continue;
        }

        let col_start = display_col_at(haystack, orig_start, policy.width_mode);
        let col_end = display_col_at(haystack, orig_end, policy.width_mode);

        results.push(PolicySearchResult {
            range: orig_start..orig_end,
            col_start,
            col_end,
        });
        start = norm_end;
    }
    results
}

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

    // ==========================================================
    // Exact search
    // ==========================================================

    #[test]
    fn exact_basic() {
        let results = search_exact("hello world hello", "hello");
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].range, 0..5);
        assert_eq!(results[1].range, 12..17);
    }

    #[test]
    fn exact_no_match() {
        let results = search_exact("hello world", "xyz");
        assert!(results.is_empty());
    }

    #[test]
    fn exact_empty_needle() {
        let results = search_exact("hello", "");
        assert!(results.is_empty());
    }

    #[test]
    fn exact_empty_haystack() {
        let results = search_exact("", "hello");
        assert!(results.is_empty());
    }

    #[test]
    fn exact_needle_equals_haystack() {
        let results = search_exact("hello", "hello");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].range, 0..5);
    }

    #[test]
    fn exact_needle_longer() {
        let results = search_exact("hi", "hello");
        assert!(results.is_empty());
    }

    #[test]
    fn exact_adjacent_matches() {
        let results = search_exact("aaa", "a");
        assert_eq!(results.len(), 3);
    }

    #[test]
    fn exact_text_extraction() {
        let haystack = "foo bar baz";
        let results = search_exact(haystack, "bar");
        assert_eq!(results[0].text(haystack), "bar");
    }

    #[test]
    fn exact_unicode() {
        let results = search_exact("café résumé café", "café");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn exact_cjk() {
        let results = search_exact("你好世界你好", "你好");
        assert_eq!(results.len(), 2);
    }

    // ==========================================================
    // Overlapping search
    // ==========================================================

    #[test]
    fn overlapping_basic() {
        let results = search_exact_overlapping("aaa", "aa");
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].range, 0..2);
        assert_eq!(results[1].range, 1..3);
    }

    #[test]
    fn overlapping_no_overlap() {
        let results = search_exact_overlapping("abcabc", "abc");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn overlapping_empty_needle() {
        let results = search_exact_overlapping("abc", "");
        assert!(results.is_empty());
    }

    // ==========================================================
    // ASCII case-insensitive search
    // ==========================================================

    #[test]
    fn ascii_ci_basic() {
        let results = search_ascii_case_insensitive("Hello World HELLO", "hello");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn ascii_ci_mixed_case() {
        let results = search_ascii_case_insensitive("FoO BaR fOo", "foo");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn ascii_ci_no_match() {
        let results = search_ascii_case_insensitive("hello", "xyz");
        assert!(results.is_empty());
    }

    // ==========================================================
    // Valid range property tests
    // ==========================================================

    #[test]
    fn results_have_valid_ranges() {
        let test_cases = [
            ("hello world", "o"),
            ("aaaa", "aa"),
            ("", "x"),
            ("x", ""),
            ("café", "é"),
            ("🌍 world 🌍", "🌍"),
        ];
        for (haystack, needle) in test_cases {
            let results = search_exact(haystack, needle);
            for r in &results {
                assert!(
                    r.range.start <= r.range.end,
                    "Invalid range for '{needle}' in '{haystack}'"
                );
                assert!(
                    r.range.end <= haystack.len(),
                    "Out of bounds for '{needle}' in '{haystack}'"
                );
                assert!(
                    haystack.is_char_boundary(r.range.start),
                    "Not char boundary at start"
                );
                assert!(
                    haystack.is_char_boundary(r.range.end),
                    "Not char boundary at end"
                );
            }
        }
    }

    #[test]
    fn emoji_search() {
        let results = search_exact("hello 🌍 world 🌍 end", "🌍");
        assert_eq!(results.len(), 2);
        for r in &results {
            assert_eq!(&"hello 🌍 world 🌍 end"[r.range.clone()], "🌍");
        }
    }
}

#[cfg(all(test, feature = "normalization"))]
mod normalization_tests {
    use super::*;

    #[test]
    fn case_insensitive_unicode() {
        // Case-insensitive search finds "Strasse" (literal match in haystack)
        // Note: ß does NOT fold to ss with to_lowercase(); this tests the literal match
        let results = search_case_insensitive("Straße Strasse", "strasse");
        assert!(
            !results.is_empty(),
            "Should find literal case-insensitive match"
        );
    }

    #[test]
    fn case_insensitive_expansion_range_maps_to_grapheme() {
        // Test that grapheme boundaries are preserved in results
        // Note: ß does NOT case-fold to ss (that would require Unicode case folding)
        let haystack = "STRAßE";
        let results = search_case_insensitive(haystack, "straße");
        assert_eq!(results.len(), 1);
        let result = &results[0];
        assert_eq!(result.text(haystack), "STRAßE");
        assert!(haystack.is_char_boundary(result.range.start));
        assert!(haystack.is_char_boundary(result.range.end));
    }

    #[test]
    fn case_insensitive_accented() {
        let results = search_case_insensitive("CAFÉ café Café", "café");
        // All three should match
        assert_eq!(results.len(), 3);
    }

    #[test]
    fn case_insensitive_empty() {
        let results = search_case_insensitive("hello", "");
        assert!(results.is_empty());
    }

    #[test]
    fn case_insensitive_fullwidth() {
        // Fullwidth "HELLO" should match "hello" under NFKC normalization
        let results = search_case_insensitive("\u{FF28}\u{FF25}\u{FF2C}\u{FF2C}\u{FF2F}", "hello");
        assert!(!results.is_empty(), "Fullwidth should match via NFKC");
    }

    #[test]
    fn normalized_composed_vs_decomposed() {
        use crate::normalization::NormForm;
        // Search for composed é in text with decomposed e+combining acute
        let haystack = "caf\u{0065}\u{0301}"; // e + combining acute
        let needle = "caf\u{00E9}"; // precomposed é
        let results = search_normalized(haystack, needle, NormForm::Nfc);
        assert_eq!(results.len(), 1, "Should find NFC-equivalent match");
    }

    #[test]
    fn normalized_no_false_positive() {
        use crate::normalization::NormForm;
        let results = search_normalized("hello", "world", NormForm::Nfc);
        assert!(results.is_empty());
    }

    #[test]
    fn normalized_result_ranges_valid() {
        use crate::normalization::NormForm;
        let haystack = "café résumé café";
        let needle = "café";
        let results = search_normalized(haystack, needle, NormForm::Nfc);
        for r in &results {
            assert!(r.range.start <= r.range.end);
            assert!(r.range.end <= haystack.len());
            assert!(haystack.is_char_boundary(r.range.start));
            assert!(haystack.is_char_boundary(r.range.end));
        }
    }

    #[test]
    fn case_insensitive_result_ranges_valid() {
        let haystack = "Hello WORLD hello";
        let results = search_case_insensitive(haystack, "hello");
        for r in &results {
            assert!(r.range.start <= r.range.end);
            assert!(r.range.end <= haystack.len());
            assert!(haystack.is_char_boundary(r.range.start));
            assert!(haystack.is_char_boundary(r.range.end));
        }
    }
}

// =============================================================================
// Policy-aware search tests
// =============================================================================

#[cfg(all(test, feature = "normalization"))]
mod policy_tests {
    use super::*;
    use crate::normalization::NormForm;

    // ── WidthMode basic tests ──────────────────────────────────────────

    #[test]
    fn width_mode_ascii_is_one() {
        for ch in ['a', 'Z', '0', ' ', '~'] {
            assert_eq!(WidthMode::Standard.char_width(ch), 1);
            assert_eq!(WidthMode::CjkAmbiguousWide.char_width(ch), 1);
        }
    }

    #[test]
    fn width_mode_cjk_ideograph_is_two() {
        for ch in ['', '', ''] {
            assert_eq!(WidthMode::Standard.char_width(ch), 2);
            assert_eq!(WidthMode::CjkAmbiguousWide.char_width(ch), 2);
        }
    }

    #[test]
    fn width_mode_ea_ambiguous_differs() {
        // Box drawing: EA Ambiguous
        for ch in ['', '', ''] {
            assert_eq!(WidthMode::Standard.char_width(ch), 1, "Standard: {ch:?}");
            assert_eq!(
                WidthMode::CjkAmbiguousWide.char_width(ch),
                2,
                "CjkWide: {ch:?}"
            );
        }
        // Arrows: EA Ambiguous
        for ch in ['', '', '', ''] {
            assert_eq!(WidthMode::Standard.char_width(ch), 1);
            assert_eq!(WidthMode::CjkAmbiguousWide.char_width(ch), 2);
        }
        // Misc symbols: EA Ambiguous
        for ch in ['°', '×', '®'] {
            assert_eq!(WidthMode::Standard.char_width(ch), 1);
            assert_eq!(WidthMode::CjkAmbiguousWide.char_width(ch), 2);
        }
    }

    #[test]
    fn width_mode_combining_marks_zero() {
        for ch in ['\u{0300}', '\u{0301}', '\u{0302}'] {
            assert_eq!(WidthMode::Standard.char_width(ch), 0);
            assert_eq!(WidthMode::CjkAmbiguousWide.char_width(ch), 0);
        }
    }

    #[test]
    fn width_mode_str_width() {
        assert_eq!(WidthMode::Standard.str_width("hello"), 5);
        assert_eq!(WidthMode::Standard.str_width("中国"), 4);
        assert_eq!(WidthMode::CjkAmbiguousWide.str_width("hello"), 5);
        // Arrow + space + CJK: 2+1+2 = 5 in CJK mode
        assert_eq!(WidthMode::CjkAmbiguousWide.str_width("→ 中"), 5);
        assert_eq!(WidthMode::Standard.str_width("→ 中"), 4); // 1+1+2
    }

    #[test]
    fn width_mode_default_is_standard() {
        assert_eq!(WidthMode::default(), WidthMode::Standard);
    }

    // ── display_col_at tests ───────────────────────────────────────────

    #[test]
    fn display_col_at_ascii() {
        let s = "hello world";
        assert_eq!(display_col_at(s, 0, WidthMode::Standard), 0);
        assert_eq!(display_col_at(s, 5, WidthMode::Standard), 5);
        assert_eq!(display_col_at(s, 11, WidthMode::Standard), 11);
    }

    #[test]
    fn display_col_at_cjk() {
        let s = "你好world";
        // "你" = 3 bytes, "好" = 3 bytes, each 2 cells wide
        assert_eq!(display_col_at(s, 0, WidthMode::Standard), 0);
        assert_eq!(display_col_at(s, 3, WidthMode::Standard), 2); // after 你
        assert_eq!(display_col_at(s, 6, WidthMode::Standard), 4); // after 好
        assert_eq!(display_col_at(s, 11, WidthMode::Standard), 9); // after world
    }

    #[test]
    fn display_col_at_ea_ambiguous_differs() {
        let s = "─→text";
        // ─ is 3 bytes, → is 3 bytes
        let after_box = 3; // byte offset after ─
        let after_arrow = 6; // byte offset after →
        assert_eq!(display_col_at(s, after_box, WidthMode::Standard), 1);
        assert_eq!(display_col_at(s, after_box, WidthMode::CjkAmbiguousWide), 2);
        assert_eq!(display_col_at(s, after_arrow, WidthMode::Standard), 2);
        assert_eq!(
            display_col_at(s, after_arrow, WidthMode::CjkAmbiguousWide),
            4
        );
    }

    #[test]
    fn display_col_at_combining_marks() {
        // "e" + combining acute: the combining mark has 0 width
        let s = "e\u{0301}x";
        // e = 1 byte, combining = 2 bytes, x = 1 byte
        assert_eq!(display_col_at(s, 0, WidthMode::Standard), 0);
        assert_eq!(display_col_at(s, 1, WidthMode::Standard), 1); // after e
        assert_eq!(display_col_at(s, 3, WidthMode::Standard), 1); // after combining
        assert_eq!(display_col_at(s, 4, WidthMode::Standard), 2); // after x
    }

    // ── SearchPolicy preset tests ──────────────────────────────────────

    #[test]
    fn policy_standard_preset() {
        let p = SearchPolicy::STANDARD;
        assert_eq!(p.norm_form, NormForm::Nfkc);
        assert!(p.case_insensitive);
        assert_eq!(p.width_mode, WidthMode::Standard);
    }

    #[test]
    fn policy_cjk_preset() {
        let p = SearchPolicy::CJK;
        assert_eq!(p.norm_form, NormForm::Nfkc);
        assert!(p.case_insensitive);
        assert_eq!(p.width_mode, WidthMode::CjkAmbiguousWide);
    }

    #[test]
    fn policy_exact_nfc_preset() {
        let p = SearchPolicy::EXACT_NFC;
        assert_eq!(p.norm_form, NormForm::Nfc);
        assert!(!p.case_insensitive);
        assert_eq!(p.width_mode, WidthMode::Standard);
    }

    // ── search_with_policy: basic matching ─────────────────────────────

    #[test]
    fn policy_search_basic_ascii() {
        let results = search_with_policy("hello world", "hello", &SearchPolicy::STANDARD);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].range, 0..5);
        assert_eq!(results[0].col_start, 0);
        assert_eq!(results[0].col_end, 5);
    }

    #[test]
    fn policy_search_case_insensitive() {
        let results = search_with_policy("Hello WORLD hello", "hello", &SearchPolicy::STANDARD);
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].text("Hello WORLD hello"), "Hello");
        assert_eq!(results[1].text("Hello WORLD hello"), "hello");
    }

    #[test]
    fn policy_search_case_sensitive() {
        let results = search_with_policy("Hello hello", "hello", &SearchPolicy::EXACT_NFC);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].range.start, 6);
    }

    #[test]
    fn policy_search_empty_needle() {
        let results = search_with_policy("hello", "", &SearchPolicy::STANDARD);
        assert!(results.is_empty());
    }

    #[test]
    fn policy_search_empty_haystack() {
        let results = search_with_policy("", "hello", &SearchPolicy::STANDARD);
        assert!(results.is_empty());
    }

    #[test]
    fn policy_search_no_match() {
        let results = search_with_policy("hello", "world", &SearchPolicy::STANDARD);
        assert!(results.is_empty());
    }

    // ── search_with_policy: normalization alignment ────────────────────

    #[test]
    fn policy_search_composed_vs_decomposed() {
        // Composed é in haystack, decomposed e+acute in needle
        let haystack = "caf\u{00E9}";
        let needle = "caf\u{0065}\u{0301}";
        let results = search_with_policy(haystack, needle, &SearchPolicy::EXACT_NFC);
        assert_eq!(
            results.len(),
            1,
            "NFC should equate composed and decomposed"
        );
    }

    #[test]
    fn policy_search_fullwidth_nfkc() {
        // Fullwidth "HELLO" matches "hello" under NFKC + case-insensitive
        let haystack = "\u{FF28}\u{FF25}\u{FF2C}\u{FF2C}\u{FF2F}";
        let results = search_with_policy(haystack, "hello", &SearchPolicy::STANDARD);
        assert!(!results.is_empty(), "Fullwidth should match via NFKC");
    }

    #[test]
    fn policy_search_nfc_does_not_match_compatibility() {
        // fi ligature (U+FB01) should NOT match "fi" under NFC (only NFKC decomposes it)
        let haystack = "\u{FB01}le";
        let results = search_with_policy(haystack, "file", &SearchPolicy::EXACT_NFC);
        assert!(
            results.is_empty(),
            "NFC should not decompose compatibility chars"
        );
    }

    #[test]
    fn policy_search_nfkc_matches_compatibility() {
        // fi ligature should match "file" under NFKC
        let haystack = "\u{FB01}le";
        let results = search_with_policy(haystack, "file", &SearchPolicy::STANDARD);
        assert!(!results.is_empty(), "NFKC should decompose fi ligature");
    }

    // ── search_with_policy: column offsets with CJK text ───────────────

    #[test]
    fn policy_search_cjk_column_offsets() {
        // "你好world你好" — search for "world"
        let haystack = "你好world你好";
        let results = search_with_policy(haystack, "world", &SearchPolicy::STANDARD);
        assert_eq!(results.len(), 1);
        // "你" = 2 cols, "好" = 2 cols → world starts at col 4
        assert_eq!(results[0].col_start, 4);
        assert_eq!(results[0].col_end, 9); // 4 + 5 = 9
    }

    #[test]
    fn policy_search_cjk_in_cjk() {
        // Search for CJK in CJK
        let haystack = "你好世界你好";
        let results = search_with_policy(haystack, "世界", &SearchPolicy::STANDARD);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].col_start, 4); // 你(2) + 好(2) = 4
        assert_eq!(results[0].col_end, 8); // 4 + 世(2) + 界(2) = 8
    }

    // ── search_with_policy: EA Ambiguous differs by width mode ─────────

    #[test]
    fn policy_search_ea_ambiguous_column_divergence() {
        // "→hello" — arrow is EA Ambiguous
        let haystack = "→hello";
        let standard = search_with_policy(haystack, "hello", &SearchPolicy::STANDARD);
        let cjk = search_with_policy(haystack, "hello", &SearchPolicy::CJK);

        assert_eq!(standard.len(), 1);
        assert_eq!(cjk.len(), 1);
        // Same byte range
        assert_eq!(standard[0].range, cjk[0].range);
        // Different column offsets
        assert_eq!(standard[0].col_start, 1); // → = 1 col in Standard
        assert_eq!(cjk[0].col_start, 2); // → = 2 cols in CJK
        assert_eq!(standard[0].col_end, 6);
        assert_eq!(cjk[0].col_end, 7);
    }

    #[test]
    fn policy_search_box_drawing_column_divergence() {
        // "──text" — box drawing chars are EA Ambiguous
        let haystack = "──text";
        let standard = search_with_policy(haystack, "text", &SearchPolicy::STANDARD);
        let cjk = search_with_policy(haystack, "text", &SearchPolicy::CJK);

        assert_eq!(standard[0].col_start, 2); // 2 × 1 = 2
        assert_eq!(cjk[0].col_start, 4); // 2 × 2 = 4
    }

    // ── search_with_policy: combining marks and column offsets ──────────

    #[test]
    fn policy_search_combining_mark_offsets() {
        // "café" with composed é — search for "fé"
        let haystack = "café";
        let results = search_with_policy(haystack, "", &SearchPolicy::STANDARD);
        assert_eq!(results.len(), 1);
        // c=1, a=1 → fé starts at col 2
        assert_eq!(results[0].col_start, 2);
        // f=1, é=1 → ends at col 4
        assert_eq!(results[0].col_end, 4);
    }

    #[test]
    fn policy_search_decomposed_combining_offsets() {
        // "cafe\u{0301}" — decomposed é
        let haystack = "cafe\u{0301}";
        let needle = "f\u{00E9}"; // composed fé
        let results = search_with_policy(haystack, needle, &SearchPolicy::EXACT_NFC);
        assert_eq!(results.len(), 1);
        // c=1, a=1 → starts at col 2
        assert_eq!(results[0].col_start, 2);
        // f=1, e=1, combining=0 → ends at col 4
        assert_eq!(results[0].col_end, 4);
    }

    // ── search_with_policy: display_width on PolicySearchResult ────────

    #[test]
    fn policy_result_display_width() {
        let haystack = "你好hello";
        let results = search_with_policy(haystack, "hello", &SearchPolicy::STANDARD);
        assert_eq!(results[0].display_width(), 5);
    }

    #[test]
    fn policy_result_display_width_cjk_match() {
        let haystack = "abc你好def";
        let results = search_with_policy(haystack, "你好", &SearchPolicy::STANDARD);
        assert_eq!(results[0].display_width(), 4); // 2 + 2
    }

    // ── search_with_policy: text extraction ────────────────────────────

    #[test]
    fn policy_result_text_extraction() {
        let haystack = "Hello World";
        let results = search_with_policy(haystack, "world", &SearchPolicy::STANDARD);
        assert_eq!(results[0].text(haystack), "World");
    }

    // ── search_with_policy: multiple matches ───────────────────────────

    #[test]
    fn policy_search_multiple_matches() {
        let haystack = "foo bar foo baz foo";
        let results = search_with_policy(haystack, "foo", &SearchPolicy::STANDARD);
        assert_eq!(results.len(), 3);
        assert_eq!(results[0].col_start, 0);
        assert_eq!(results[1].col_start, 8);
        assert_eq!(results[2].col_start, 16);
    }

    // ── search_with_policy: range validity invariant ───────────────────

    #[test]
    fn policy_search_ranges_always_valid() {
        let test_cases = [
            ("hello world", "o", SearchPolicy::STANDARD),
            ("CAFÉ café", "café", SearchPolicy::STANDARD),
            ("你好世界", "", SearchPolicy::CJK),
            ("─→text", "text", SearchPolicy::CJK),
            ("\u{FB01}le", "file", SearchPolicy::STANDARD),
            ("e\u{0301}", "\u{00E9}", SearchPolicy::EXACT_NFC),
        ];
        for (haystack, needle, policy) in &test_cases {
            let results = search_with_policy(haystack, needle, policy);
            for r in &results {
                assert!(
                    r.range.start <= r.range.end,
                    "Invalid range for '{needle}' in '{haystack}'"
                );
                assert!(
                    r.range.end <= haystack.len(),
                    "Out of bounds for '{needle}' in '{haystack}'"
                );
                assert!(
                    haystack.is_char_boundary(r.range.start),
                    "Not char boundary at start"
                );
                assert!(
                    haystack.is_char_boundary(r.range.end),
                    "Not char boundary at end"
                );
                assert!(
                    r.col_start <= r.col_end,
                    "col_start > col_end for '{needle}' in '{haystack}'"
                );
            }
        }
    }

    // ── search_with_policy: column monotonicity ────────────────────────

    #[test]
    fn policy_search_columns_monotonically_increasing() {
        let haystack = "aa bb aa cc aa";
        let results = search_with_policy(haystack, "aa", &SearchPolicy::STANDARD);
        assert_eq!(results.len(), 3);
        for w in results.windows(2) {
            assert!(
                w[0].col_end <= w[1].col_start,
                "Non-overlapping matches should have monotonically increasing columns"
            );
        }
    }

    // ── search_with_policy: custom policy construction ─────────────────

    #[test]
    fn policy_custom_nfd_case_sensitive() {
        let policy = SearchPolicy {
            norm_form: NormForm::Nfd,
            case_insensitive: false,
            width_mode: WidthMode::Standard,
        };
        // NFD decomposes é → e+combining acute
        let haystack = "\u{00E9}"; // composed é
        let needle = "e\u{0301}"; // decomposed
        let results = search_with_policy(haystack, needle, &policy);
        assert_eq!(results.len(), 1, "NFD should match decomposed forms");
    }

    #[test]
    fn policy_custom_nfkd_case_insensitive() {
        let policy = SearchPolicy {
            norm_form: NormForm::Nfkd,
            case_insensitive: true,
            width_mode: WidthMode::CjkAmbiguousWide,
        };
        // fi ligature should match "FI" under NFKD + case-insensitive
        let haystack = "\u{FB01}";
        let results = search_with_policy(haystack, "FI", &policy);
        assert!(!results.is_empty(), "NFKD + CI should match fi ligature");
    }

    // ── search_with_policy: consistency with existing functions ─────────

    #[test]
    fn policy_search_agrees_with_search_case_insensitive() {
        let test_cases = [
            ("Hello World HELLO", "hello"),
            ("CAFÉ café Café", "café"),
            ("\u{FF28}\u{FF25}\u{FF2C}\u{FF2C}\u{FF2F}", "hello"),
        ];
        for (haystack, needle) in &test_cases {
            let old = search_case_insensitive(haystack, needle);
            let new = search_with_policy(haystack, needle, &SearchPolicy::STANDARD);
            assert_eq!(
                old.len(),
                new.len(),
                "Match count mismatch for '{needle}' in '{haystack}'"
            );
            for (o, n) in old.iter().zip(new.iter()) {
                assert_eq!(
                    o.range, n.range,
                    "Byte range mismatch for '{needle}' in '{haystack}'"
                );
            }
        }
    }

    #[test]
    fn policy_search_agrees_with_search_normalized() {
        let haystack = "caf\u{0065}\u{0301} résumé";
        let needle = "caf\u{00E9}";
        let old = search_normalized(haystack, needle, NormForm::Nfc);
        let new = search_with_policy(haystack, needle, &SearchPolicy::EXACT_NFC);
        assert_eq!(old.len(), new.len());
        for (o, n) in old.iter().zip(new.iter()) {
            assert_eq!(o.range, n.range);
        }
    }
}