richrs 0.2.1

A Rust port of the Rich Python library for beautiful terminal output
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
// Static regex patterns use unwrap() on known-valid patterns - this is safe at compile time
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]

//! Highlighter for automatic text highlighting.
//!
//! This module provides automatic highlighting of patterns in text,
//! such as URLs, numbers, strings, and keywords.
//!
//! # Example
//!
//! ```ignore
//! use richrs::highlighter::{Highlighter, ReprHighlighter};
//!
//! let highlighter = ReprHighlighter::new();
//! let segments = highlighter.highlight("value = 42, url = https://example.com");
//! ```

use crate::segment::{Segment, Segments};
use crate::style::Style;
use regex::Regex;
use std::sync::LazyLock;

/// A trait for highlighting text patterns.
pub trait Highlighter {
    /// Highlights the given text and returns styled segments.
    fn highlight(&self, text: &str) -> Segments;
}

/// A highlighter for repr-style output (numbers, strings, booleans, None).
///
/// This highlighter is similar to Python Rich's `ReprHighlighter` and
/// automatically highlights common programming patterns.
#[derive(Debug, Clone)]
pub struct ReprHighlighter {
    /// Style for numbers.
    number_style: Style,
    /// Style for strings.
    string_style: Style,
    /// Style for boolean values.
    bool_style: Style,
    /// Style for None/null values.
    none_style: Style,
    /// Style for attribute names.
    attr_style: Style,
    /// Style for URLs.
    url_style: Style,
    /// Style for UUIDs.
    uuid_style: Style,
}

impl Default for ReprHighlighter {
    fn default() -> Self {
        Self::new()
    }
}

impl ReprHighlighter {
    /// Creates a new ReprHighlighter with default styles.
    #[must_use]
    pub fn new() -> Self {
        Self {
            number_style: Style::default().bold(),
            string_style: Style::default().italic(),
            bool_style: Style::default().italic().bold(),
            none_style: Style::default().italic().bold(),
            attr_style: Style::default(),
            url_style: Style::default().underline(),
            uuid_style: Style::default().bold(),
        }
    }

    /// Sets the style for numbers.
    #[must_use]
    pub fn number_style(mut self, style: Style) -> Self {
        self.number_style = style;
        self
    }

    /// Sets the style for strings.
    #[must_use]
    pub fn string_style(mut self, style: Style) -> Self {
        self.string_style = style;
        self
    }

    /// Sets the style for boolean values.
    #[must_use]
    pub fn bool_style(mut self, style: Style) -> Self {
        self.bool_style = style;
        self
    }

    /// Sets the style for None/null values.
    #[must_use]
    pub fn none_style(mut self, style: Style) -> Self {
        self.none_style = style;
        self
    }

    /// Sets the style for attribute names.
    #[must_use]
    pub fn attr_style(mut self, style: Style) -> Self {
        self.attr_style = style;
        self
    }

    /// Sets the style for URLs.
    #[must_use]
    pub fn url_style(mut self, style: Style) -> Self {
        self.url_style = style;
        self
    }

    /// Sets the style for UUIDs.
    #[must_use]
    pub fn uuid_style(mut self, style: Style) -> Self {
        self.uuid_style = style;
        self
    }
}

// Regex patterns for highlighting
static NUMBER_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?x)
        (?P<number>
            # Hex numbers
            0x[0-9a-fA-F]+
            |
            # Binary numbers
            0b[01]+
            |
            # Octal numbers
            0o[0-7]+
            |
            # Float with exponent
            -?[0-9]+\.?[0-9]*(?:e[+-]?[0-9]+)?
            |
            # Regular integers
            -?[0-9]+
        )
    ",
    )
    .unwrap()
});

static STRING_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"(?P<string>"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')"#).unwrap());

static BOOL_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b(?P<bool>true|false|True|False)\b").unwrap());

static NONE_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b(?P<none>None|null|nil|NULL)\b").unwrap());

static URL_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#"(?P<url>https?://[^\s<>"')]+)"#).unwrap());

static UUID_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?P<uuid>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})",
    )
    .unwrap()
});

// Note: Attribute pattern with lookahead not supported in regex crate.
// We'll handle attribute highlighting differently.

impl Highlighter for ReprHighlighter {
    fn highlight(&self, text: &str) -> Segments {
        let mut segments = Segments::new();
        let mut last_end = 0;

        // Collect all matches with their positions
        let mut matches: Vec<(usize, usize, &str, Style)> = Vec::new();

        // Find all pattern matches
        for cap in URL_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("url") {
                matches.push((m.start(), m.end(), m.as_str(), self.url_style.clone()));
            }
        }

        for cap in UUID_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("uuid") {
                matches.push((m.start(), m.end(), m.as_str(), self.uuid_style.clone()));
            }
        }

        for cap in STRING_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("string") {
                matches.push((m.start(), m.end(), m.as_str(), self.string_style.clone()));
            }
        }

        for cap in BOOL_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("bool") {
                matches.push((m.start(), m.end(), m.as_str(), self.bool_style.clone()));
            }
        }

        for cap in NONE_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("none") {
                matches.push((m.start(), m.end(), m.as_str(), self.none_style.clone()));
            }
        }

        for cap in NUMBER_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("number") {
                matches.push((m.start(), m.end(), m.as_str(), self.number_style.clone()));
            }
        }

        // Handle attribute names manually (word followed by = or :)
        // This is a simple approach since regex crate doesn't support lookahead
        let attr_re = Regex::new(r"([a-zA-Z_][a-zA-Z0-9_]*)\s*[=:]").unwrap();
        for cap in attr_re.captures_iter(text) {
            if let Some(m) = cap.get(1) {
                // Only add if attr_style is not empty
                if !self.attr_style.is_empty() {
                    matches.push((m.start(), m.end(), m.as_str(), self.attr_style.clone()));
                }
            }
        }

        // Sort matches by start position
        matches.sort_by_key(|m| m.0);

        // Remove overlapping matches (keep earlier/longer ones)
        let mut filtered_matches: Vec<(usize, usize, &str, Style)> = Vec::new();
        for m in matches {
            if filtered_matches.last().map_or(true, |last| m.0 >= last.1) {
                filtered_matches.push(m);
            }
        }

        // Build segments
        for (start, end, matched_text, style) in filtered_matches {
            // Add any text before this match
            if start > last_end {
                segments.push(Segment::new(&text[last_end..start]));
            }

            // Add the highlighted match
            if style.is_empty() {
                segments.push(Segment::new(matched_text));
            } else {
                segments.push(Segment::styled(matched_text, style));
            }

            last_end = end;
        }

        // Add any remaining text
        if last_end < text.len() {
            segments.push(Segment::new(&text[last_end..]));
        }

        // Handle empty text
        if segments.is_empty() {
            segments.push(Segment::new(text));
        }

        segments
    }
}

/// A highlighter for ISO 8601 timestamps.
#[derive(Debug, Clone)]
pub struct ISOHighlighter {
    /// Style for the date part.
    date_style: Style,
    /// Style for the time part.
    time_style: Style,
    /// Style for the timezone.
    timezone_style: Style,
}

impl Default for ISOHighlighter {
    fn default() -> Self {
        Self::new()
    }
}

impl ISOHighlighter {
    /// Creates a new ISOHighlighter with default styles.
    #[must_use]
    pub fn new() -> Self {
        Self {
            date_style: Style::default().bold(),
            time_style: Style::default(),
            timezone_style: Style::default().dim(),
        }
    }

    /// Sets the style for the date part.
    #[must_use]
    pub fn date_style(mut self, style: Style) -> Self {
        self.date_style = style;
        self
    }

    /// Sets the style for the time part.
    #[must_use]
    pub fn time_style(mut self, style: Style) -> Self {
        self.time_style = style;
        self
    }

    /// Sets the style for the timezone.
    #[must_use]
    pub fn timezone_style(mut self, style: Style) -> Self {
        self.timezone_style = style;
        self
    }
}

static ISO_PATTERN: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?P<iso>(?P<date>\d{4}-\d{2}-\d{2})(?:T(?P<time>\d{2}:\d{2}:\d{2}(?:\.\d+)?)(?P<tz>Z|[+-]\d{2}:?\d{2})?)?)").unwrap()
});

impl Highlighter for ISOHighlighter {
    fn highlight(&self, text: &str) -> Segments {
        let mut segments = Segments::new();
        let mut last_end = 0;

        for cap in ISO_PATTERN.captures_iter(text) {
            if let Some(full_match) = cap.name("iso") {
                // Add text before the match
                if full_match.start() > last_end {
                    segments.push(Segment::new(&text[last_end..full_match.start()]));
                }

                // Add date part
                if let Some(date) = cap.name("date") {
                    segments.push(Segment::styled(date.as_str(), self.date_style.clone()));
                }

                // Add time part
                if let Some(time) = cap.name("time") {
                    segments.push(Segment::new("T"));
                    segments.push(Segment::styled(time.as_str(), self.time_style.clone()));
                }

                // Add timezone
                if let Some(tz) = cap.name("tz") {
                    segments.push(Segment::styled(tz.as_str(), self.timezone_style.clone()));
                }

                last_end = full_match.end();
            }
        }

        // Add remaining text
        if last_end < text.len() {
            segments.push(Segment::new(&text[last_end..]));
        }

        if segments.is_empty() {
            segments.push(Segment::new(text));
        }

        segments
    }
}

/// A highlighter for regular expressions with custom styles.
#[derive(Debug, Clone)]
pub struct RegexHighlighter {
    /// Patterns and their associated styles.
    patterns: Vec<(Regex, Style)>,
}

impl Default for RegexHighlighter {
    fn default() -> Self {
        Self::new()
    }
}

impl RegexHighlighter {
    /// Creates a new empty RegexHighlighter.
    #[must_use]
    pub fn new() -> Self {
        Self {
            patterns: Vec::new(),
        }
    }

    /// Adds a pattern with an associated style.
    ///
    /// # Panics
    ///
    /// Panics if the pattern is not a valid regex.
    #[must_use]
    pub fn pattern(mut self, pattern: &str, style: Style) -> Self {
        let regex = Regex::new(pattern).expect("Invalid regex pattern");
        self.patterns.push((regex, style));
        self
    }

    /// Adds a pattern with an associated style, returning an error on invalid regex.
    pub fn try_pattern(mut self, pattern: &str, style: Style) -> Result<Self, regex::Error> {
        let regex = Regex::new(pattern)?;
        self.patterns.push((regex, style));
        Ok(self)
    }
}

impl Highlighter for RegexHighlighter {
    fn highlight(&self, text: &str) -> Segments {
        let mut segments = Segments::new();
        let mut last_end = 0;

        // Collect all matches
        let mut matches: Vec<(usize, usize, Style)> = Vec::new();

        for (regex, style) in &self.patterns {
            for m in regex.find_iter(text) {
                matches.push((m.start(), m.end(), style.clone()));
            }
        }

        // Sort by position
        matches.sort_by_key(|m| m.0);

        // Remove overlaps
        let mut filtered: Vec<(usize, usize, Style)> = Vec::new();
        for m in matches {
            if filtered.last().map_or(true, |last| m.0 >= last.1) {
                filtered.push(m);
            }
        }

        // Build segments
        for (start, end, style) in filtered {
            if start > last_end {
                segments.push(Segment::new(&text[last_end..start]));
            }
            segments.push(Segment::styled(&text[start..end], style));
            last_end = end;
        }

        if last_end < text.len() {
            segments.push(Segment::new(&text[last_end..]));
        }

        if segments.is_empty() {
            segments.push(Segment::new(text));
        }

        segments
    }
}

/// A highlighter for JSON-like data.
#[derive(Debug, Clone)]
pub struct JSONHighlighter {
    /// Style for keys.
    key_style: Style,
    /// Style for string values.
    string_style: Style,
    /// Style for number values.
    number_style: Style,
    /// Style for boolean values.
    bool_style: Style,
    /// Style for null.
    null_style: Style,
    /// Style for brackets.
    bracket_style: Style,
}

impl Default for JSONHighlighter {
    fn default() -> Self {
        Self::new()
    }
}

impl JSONHighlighter {
    /// Creates a new JSONHighlighter with default styles.
    #[must_use]
    pub fn new() -> Self {
        Self {
            key_style: Style::default().bold(),
            string_style: Style::default().italic(),
            number_style: Style::default().bold(),
            bool_style: Style::default().bold().italic(),
            null_style: Style::default().dim(),
            bracket_style: Style::default().bold(),
        }
    }

    /// Sets the style for JSON keys.
    #[must_use]
    pub fn key_style(mut self, style: Style) -> Self {
        self.key_style = style;
        self
    }

    /// Sets the style for string values.
    #[must_use]
    pub fn string_style(mut self, style: Style) -> Self {
        self.string_style = style;
        self
    }

    /// Sets the style for number values.
    #[must_use]
    pub fn number_style(mut self, style: Style) -> Self {
        self.number_style = style;
        self
    }

    /// Sets the style for boolean values.
    #[must_use]
    pub fn bool_style(mut self, style: Style) -> Self {
        self.bool_style = style;
        self
    }

    /// Sets the style for null values.
    #[must_use]
    pub fn null_style(mut self, style: Style) -> Self {
        self.null_style = style;
        self
    }

    /// Sets the style for brackets.
    #[must_use]
    pub fn bracket_style(mut self, style: Style) -> Self {
        self.bracket_style = style;
        self
    }
}

static JSON_KEY_PATTERN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r#""([^"\\]|\\.)*"\s*:"#).unwrap());

impl Highlighter for JSONHighlighter {
    fn highlight(&self, text: &str) -> Segments {
        let mut segments = Segments::new();
        let mut last_end = 0;

        // Collect matches
        let mut matches: Vec<(usize, usize, &str, Style)> = Vec::new();

        // Find JSON keys (strings followed by :)
        for m in JSON_KEY_PATTERN.find_iter(text) {
            let key_text = &text[m.start()..m.end() - 1]; // Exclude the :
            matches.push((m.start(), m.end() - 1, key_text, self.key_style.clone()));
        }

        // Find brackets
        for (i, c) in text.char_indices() {
            if matches!(c, '{' | '}' | '[' | ']') {
                // Check not inside a key region
                if !matches.iter().any(|(s, e, _, _)| i >= *s && i < *e) {
                    matches.push((i, i + 1, &text[i..i + 1], self.bracket_style.clone()));
                }
            }
        }

        // Find string values (not keys)
        for cap in STRING_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("string") {
                // Check it's not a key
                let is_key = text[m.end()..].trim_start().starts_with(':');
                if !is_key {
                    matches.push((m.start(), m.end(), m.as_str(), self.string_style.clone()));
                }
            }
        }

        // Find numbers
        for cap in NUMBER_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("number") {
                matches.push((m.start(), m.end(), m.as_str(), self.number_style.clone()));
            }
        }

        // Find booleans and null
        for cap in BOOL_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("bool") {
                matches.push((m.start(), m.end(), m.as_str(), self.bool_style.clone()));
            }
        }

        for cap in NONE_PATTERN.captures_iter(text) {
            if let Some(m) = cap.name("none") {
                matches.push((m.start(), m.end(), m.as_str(), self.null_style.clone()));
            }
        }

        // Sort and filter overlaps
        matches.sort_by_key(|m| m.0);
        let mut filtered: Vec<(usize, usize, &str, Style)> = Vec::new();
        for m in matches {
            if filtered.last().map_or(true, |last| m.0 >= last.1) {
                filtered.push(m);
            }
        }

        // Build segments
        for (start, end, matched_text, style) in filtered {
            if start > last_end {
                segments.push(Segment::new(&text[last_end..start]));
            }
            segments.push(Segment::styled(matched_text, style));
            last_end = end;
        }

        if last_end < text.len() {
            segments.push(Segment::new(&text[last_end..]));
        }

        if segments.is_empty() {
            segments.push(Segment::new(text));
        }

        segments
    }
}

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

    #[test]
    fn test_repr_highlighter_new() {
        let highlighter = ReprHighlighter::new();
        assert!(!highlighter.number_style.is_empty());
    }

    #[test]
    fn test_repr_highlighter_number() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("value = 42");
        let output = segments.to_ansi();
        assert!(output.contains("42"));
    }

    #[test]
    fn test_repr_highlighter_string() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("name = \"hello\"");
        let output = segments.to_ansi();
        assert!(output.contains("hello"));
    }

    #[test]
    fn test_repr_highlighter_bool() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("flag = true");
        let output = segments.to_ansi();
        assert!(output.contains("true"));
    }

    #[test]
    fn test_repr_highlighter_none() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("value = None");
        let output = segments.to_ansi();
        assert!(output.contains("None"));
    }

    #[test]
    fn test_repr_highlighter_url() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("Visit https://example.com");
        let output = segments.to_ansi();
        assert!(output.contains("https://example.com"));
    }

    #[test]
    fn test_repr_highlighter_uuid() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("id = 123e4567-e89b-12d3-a456-426614174000");
        let output = segments.to_ansi();
        assert!(output.contains("123e4567"));
    }

    #[test]
    fn test_repr_highlighter_hex() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("color = 0xff00ff");
        let output = segments.to_ansi();
        assert!(output.contains("0xff00ff"));
    }

    #[test]
    fn test_iso_highlighter_new() {
        let highlighter = ISOHighlighter::new();
        assert!(!highlighter.date_style.is_empty());
    }

    #[test]
    fn test_iso_highlighter_date() {
        let highlighter = ISOHighlighter::new();
        let segments = highlighter.highlight("Created 2024-01-15");
        let output = segments.to_ansi();
        assert!(output.contains("2024-01-15"));
    }

    #[test]
    fn test_iso_highlighter_datetime() {
        let highlighter = ISOHighlighter::new();
        let segments = highlighter.highlight("Time: 2024-01-15T10:30:00Z");
        let output = segments.to_ansi();
        assert!(output.contains("2024-01-15"));
        assert!(output.contains("10:30:00"));
    }

    #[test]
    fn test_regex_highlighter_new() {
        let highlighter = RegexHighlighter::new();
        assert!(highlighter.patterns.is_empty());
    }

    #[test]
    fn test_regex_highlighter_pattern() {
        let highlighter = RegexHighlighter::new().pattern(r"\bERROR\b", Style::default().bold());
        let segments = highlighter.highlight("ERROR: something failed");
        let output = segments.to_ansi();
        assert!(output.contains("ERROR"));
    }

    #[test]
    fn test_regex_highlighter_try_pattern() {
        let result = RegexHighlighter::new().try_pattern(r"\bWARN\b", Style::default());
        assert!(result.is_ok());
    }

    #[test]
    fn test_regex_highlighter_invalid_pattern() {
        let result = RegexHighlighter::new().try_pattern(r"[invalid", Style::default());
        assert!(result.is_err());
    }

    #[test]
    fn test_json_highlighter_new() {
        let highlighter = JSONHighlighter::new();
        assert!(!highlighter.key_style.is_empty());
    }

    #[test]
    fn test_json_highlighter_key() {
        let highlighter = JSONHighlighter::new();
        let segments = highlighter.highlight(r#"{"name": "value"}"#);
        let output = segments.to_ansi();
        assert!(output.contains("name"));
    }

    #[test]
    fn test_json_highlighter_number() {
        let highlighter = JSONHighlighter::new();
        let segments = highlighter.highlight(r#"{"count": 42}"#);
        let output = segments.to_ansi();
        assert!(output.contains("42"));
    }

    #[test]
    fn test_json_highlighter_bool() {
        let highlighter = JSONHighlighter::new();
        let segments = highlighter.highlight(r#"{"active": true}"#);
        let output = segments.to_ansi();
        assert!(output.contains("true"));
    }

    #[test]
    fn test_json_highlighter_null() {
        let highlighter = JSONHighlighter::new();
        let segments = highlighter.highlight(r#"{"value": null}"#);
        let output = segments.to_ansi();
        assert!(output.contains("null"));
    }

    #[test]
    fn test_empty_text() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("");
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_no_matches() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("just plain text");
        let output = segments.to_ansi();
        assert_eq!(output, "just plain text");
    }

    #[test]
    fn test_repr_highlighter_default() {
        let highlighter = ReprHighlighter::default();
        assert!(!highlighter.number_style.is_empty());
    }

    #[test]
    fn test_repr_highlighter_custom_styles() {
        let highlighter = ReprHighlighter::new()
            .number_style(Style::default().bold())
            .string_style(Style::default().italic())
            .bool_style(Style::default().underline())
            .none_style(Style::default().dim())
            .attr_style(Style::default())
            .url_style(Style::default().underline())
            .uuid_style(Style::default().bold());

        let segments = highlighter.highlight("num = 42, str = \"test\", url = https://x.com");
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_repr_highlighter_binary() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("binary = 0b101010");
        let output = segments.to_ansi();
        assert!(output.contains("0b101010"));
    }

    #[test]
    fn test_repr_highlighter_octal() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("octal = 0o755");
        let output = segments.to_ansi();
        assert!(output.contains("0o755"));
    }

    #[test]
    fn test_repr_highlighter_float() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("float = 42.5");
        let output = segments.to_ansi();
        assert!(output.contains("42.5"));
    }

    #[test]
    fn test_repr_highlighter_negative() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("negative = -42");
        let output = segments.to_ansi();
        assert!(output.contains("-42"));
    }

    #[test]
    fn test_repr_highlighter_scientific() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("scientific = 1e10");
        let output = segments.to_ansi();
        assert!(output.contains("1e10"));
    }

    #[test]
    fn test_repr_highlighter_single_quote_string() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("name = 'hello'");
        let output = segments.to_ansi();
        assert!(output.contains("hello"));
    }

    #[test]
    fn test_repr_highlighter_false_bool() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("flag = false");
        let output = segments.to_ansi();
        assert!(output.contains("false"));
    }

    #[test]
    fn test_repr_highlighter_true_python_style() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("flag = True");
        let output = segments.to_ansi();
        assert!(output.contains("True"));
    }

    #[test]
    fn test_repr_highlighter_null() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("value = null");
        let output = segments.to_ansi();
        assert!(output.contains("null"));
    }

    #[test]
    fn test_repr_highlighter_nil() {
        let highlighter = ReprHighlighter::new();
        let segments = highlighter.highlight("value = nil");
        let output = segments.to_ansi();
        assert!(output.contains("nil"));
    }

    #[test]
    fn test_repr_highlighter_attr_style() {
        let highlighter = ReprHighlighter::new().attr_style(Style::default().bold());
        let segments = highlighter.highlight("name = test");
        // Should have styled attribute
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_iso_highlighter_default() {
        let highlighter = ISOHighlighter::default();
        assert!(!highlighter.date_style.is_empty());
    }

    #[test]
    fn test_iso_highlighter_custom_styles() {
        let highlighter = ISOHighlighter::new()
            .date_style(Style::default().bold())
            .time_style(Style::default().italic())
            .timezone_style(Style::default().dim());

        let segments = highlighter.highlight("2024-01-15T10:30:00Z");
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_iso_highlighter_with_offset() {
        let highlighter = ISOHighlighter::new();
        let segments = highlighter.highlight("Time: 2024-01-15T10:30:00+05:30");
        let output = segments.to_ansi();
        assert!(output.contains("2024-01-15"));
        assert!(output.contains("10:30:00"));
        assert!(output.contains("+05:30"));
    }

    #[test]
    fn test_iso_highlighter_date_only() {
        let highlighter = ISOHighlighter::new();
        let segments = highlighter.highlight("2024-01-15");
        let output = segments.to_ansi();
        assert!(output.contains("2024-01-15"));
    }

    #[test]
    fn test_iso_highlighter_no_match() {
        let highlighter = ISOHighlighter::new();
        let segments = highlighter.highlight("not a date");
        let output = segments.to_ansi();
        assert_eq!(output, "not a date");
    }

    #[test]
    fn test_iso_highlighter_empty() {
        let highlighter = ISOHighlighter::new();
        let segments = highlighter.highlight("");
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_regex_highlighter_default() {
        let highlighter = RegexHighlighter::default();
        assert!(highlighter.patterns.is_empty());
    }

    #[test]
    fn test_regex_highlighter_multiple_patterns() {
        let highlighter = RegexHighlighter::new()
            .pattern(r"\bERROR\b", Style::default().bold())
            .pattern(r"\bWARN\b", Style::default().italic());

        let segments = highlighter.highlight("ERROR and WARN messages");
        let output = segments.to_ansi();
        assert!(output.contains("ERROR"));
        assert!(output.contains("WARN"));
    }

    #[test]
    fn test_regex_highlighter_no_match() {
        let highlighter = RegexHighlighter::new().pattern(r"\bERROR\b", Style::default());
        let segments = highlighter.highlight("no errors here");
        let output = segments.to_ansi();
        assert_eq!(output, "no errors here");
    }

    #[test]
    fn test_regex_highlighter_empty() {
        let highlighter = RegexHighlighter::new();
        let segments = highlighter.highlight("");
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_json_highlighter_default() {
        let highlighter = JSONHighlighter::default();
        assert!(!highlighter.key_style.is_empty());
    }

    #[test]
    fn test_json_highlighter_custom_styles() {
        let highlighter = JSONHighlighter::new()
            .key_style(Style::default().bold())
            .string_style(Style::default().italic())
            .number_style(Style::default().bold())
            .bool_style(Style::default().underline())
            .null_style(Style::default().dim())
            .bracket_style(Style::default().bold());

        let segments = highlighter.highlight(r#"{"key": "value"}"#);
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_json_highlighter_brackets() {
        let highlighter = JSONHighlighter::new();
        let segments = highlighter.highlight(r#"{"arr": [1, 2]}"#);
        let output = segments.to_ansi();
        assert!(output.contains("{"));
        assert!(output.contains("["));
    }

    #[test]
    fn test_json_highlighter_string_value() {
        let highlighter = JSONHighlighter::new();
        let segments = highlighter.highlight(r#"{"name": "Alice"}"#);
        let output = segments.to_ansi();
        assert!(output.contains("Alice"));
    }

    #[test]
    fn test_json_highlighter_empty() {
        let highlighter = JSONHighlighter::new();
        let segments = highlighter.highlight("");
        assert!(!segments.is_empty());
    }

    #[test]
    fn test_json_highlighter_no_match() {
        let highlighter = JSONHighlighter::new();
        let segments = highlighter.highlight("plain text");
        let output = segments.to_ansi();
        assert!(output.contains("plain text"));
    }
}