fast-rich 0.3.3

A Rust port of Python's Rich library for beautiful terminal formatting
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
//! Highlighters for pattern-based text styling.
//!
//! Provides regex-based highlighting and built-in highlighters for common patterns.

use crate::style::Style;
use crate::text::{Span, Text};
use regex::Regex;

/// Trait for text highlighters.
pub trait Highlighter {
    /// Highlight text and return styled spans.
    fn highlight(&self, text: &str) -> Vec<Span>;
}

/// A regex-based highlighter that applies styles to matched patterns.
#[derive(Debug, Clone)]
pub struct RegexHighlighter {
    patterns: Vec<(Regex, Style)>,
}

impl RegexHighlighter {
    /// Create a new empty regex highlighter.
    pub fn new() -> Self {
        RegexHighlighter {
            patterns: Vec::new(),
        }
    }

    /// Add a pattern with associated style.
    pub fn add_pattern(&mut self, pattern: &str, style: Style) -> Result<(), regex::Error> {
        let regex = Regex::new(pattern)?;
        self.patterns.push((regex, style));
        Ok(())
    }

    /// Builder method to add a pattern.
    pub fn with_pattern(mut self, pattern: &str, style: Style) -> Result<Self, regex::Error> {
        self.add_pattern(pattern, style)?;
        Ok(self)
    }

    /// Create a highlighter for URLs.
    pub fn url_highlighter(style: Style) -> Self {
        let mut hl = RegexHighlighter::new();
        // Simple URL pattern
        let _ = hl.add_pattern(r"https?://[^\s]+", style);
        hl
    }

    /// Create a highlighter for numbers.
    pub fn number_highlighter(style: Style) -> Self {
        let mut hl = RegexHighlighter::new();
        let _ = hl.add_pattern(r"\b\d+\.?\d*\b", style);
        hl
    }

    /// Create a highlighter for email addresses.
    pub fn email_highlighter(style: Style) -> Self {
        let mut hl = RegexHighlighter::new();
        let _ = hl.add_pattern(
            r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b",
            style,
        );
        hl
    }
}

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

impl Highlighter for RegexHighlighter {
    fn highlight(&self, text: &str) -> Vec<Span> {
        if self.patterns.is_empty() {
            return vec![Span::raw(text.to_string())];
        }

        // Find all matches across all patterns
        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));
            }
        }

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

        // Build spans, handling overlaps (first match wins)
        let mut spans = Vec::new();
        let mut last_end = 0;

        for (start, end, style) in matches {
            // Skip if this match overlaps with previous
            if start < last_end {
                continue;
            }

            // Add unstyled text before match
            if start > last_end {
                spans.push(Span::raw(text[last_end..start].to_string()));
            }

            // Add styled match
            spans.push(Span::styled(text[start..end].to_string(), style));
            last_end = end;
        }

        // Add remaining unstyled text
        if last_end < text.len() {
            spans.push(Span::raw(text[last_end..].to_string()));
        }

        if spans.is_empty() {
            vec![Span::raw(text.to_string())]
        } else {
            spans
        }
    }
}

/// Apply a highlighter to text and return a styled Text object.
pub fn highlight_text(text: &str, highlighter: &impl Highlighter) -> Text {
    let spans = highlighter.highlight(text);
    Text::from_spans(spans)
}

// =============================================================================
// JSON Highlighter
// =============================================================================

/// Highlighter specifically designed for JSON syntax.
///
/// Applies distinct colors to:
/// - Keys (strings followed by `:`)
/// - String values
/// - Numbers (including hex `0x...`)
/// - Booleans (`true`/`false`)
/// - Null
/// - Braces, brackets, and parentheses
#[derive(Debug, Clone)]
pub struct JsonHighlighter {
    string_re: Regex,
    number_re: Regex,
    bool_true_re: Regex,
    bool_false_re: Regex,
    null_re: Regex,
    brace_re: Regex,
    hex_re: Regex,
    key_style: Style,
    string_style: Style,
    number_style: Style,
    bool_true_style: Style,
    bool_false_style: Style,
    null_style: Style,
    brace_style: Style,
}

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

impl JsonHighlighter {
    /// Create a new JSON highlighter with default colors.
    pub fn new() -> Self {
        use crate::style::Color;

        JsonHighlighter {
            // Regex patterns
            string_re: Regex::new(r#""(?:[^"\\]|\\.)*""#).unwrap(),
            number_re: Regex::new(r"-?\b\d+\.?\d*(?:[eE][+-]?\d+)?\b").unwrap(),
            bool_true_re: Regex::new(r"\btrue\b").unwrap(),
            bool_false_re: Regex::new(r"\bfalse\b").unwrap(),
            null_re: Regex::new(r"\bnull\b").unwrap(),
            // Include parentheses in braces (matching Python rich)
            brace_re: Regex::new(r"[\{\}\[\]\(\)]").unwrap(),
            // Hex numbers matching Python rich's JSONHighlighter
            hex_re: Regex::new(r"0x[0-9a-fA-F]+\b").unwrap(),
            // Styles
            key_style: Style::new().foreground(Color::Blue).bold(),
            string_style: Style::new().foreground(Color::Green),
            number_style: Style::new().foreground(Color::Cyan),
            bool_true_style: Style::new().foreground(Color::BrightGreen),
            bool_false_style: Style::new().foreground(Color::BrightRed),
            null_style: Style::new().foreground(Color::Magenta).italic(),
            brace_style: Style::new().foreground(Color::White).dim(),
        }
    }

    /// Set custom key style.
    pub fn key_style(mut self, style: Style) -> Self {
        self.key_style = style;
        self
    }

    /// Set custom string style.
    pub fn string_style(mut self, style: Style) -> Self {
        self.string_style = style;
        self
    }

    /// Set custom number style.
    pub fn number_style(mut self, style: Style) -> Self {
        self.number_style = style;
        self
    }
}

impl Highlighter for JsonHighlighter {
    fn highlight(&self, text: &str) -> Vec<Span> {
        // Collect all matches with their positions and styles
        let mut matches: Vec<(usize, usize, Style)> = Vec::new();

        // Find all string literals
        for m in self.string_re.find_iter(text) {
            // Check if this string is a key (followed by ":")
            let rest = &text[m.end()..];
            let is_key = rest.trim_start().starts_with(':');
            let style = if is_key {
                self.key_style
            } else {
                self.string_style
            };
            matches.push((m.start(), m.end(), style));
        }

        // Find numbers (only if not inside a string)
        for m in self.number_re.find_iter(text) {
            let overlaps = matches
                .iter()
                .any(|(s, e, _)| m.start() >= *s && m.end() <= *e);
            if !overlaps {
                matches.push((m.start(), m.end(), self.number_style));
            }
        }

        // Find true
        for m in self.bool_true_re.find_iter(text) {
            let overlaps = matches
                .iter()
                .any(|(s, e, _)| m.start() >= *s && m.end() <= *e);
            if !overlaps {
                matches.push((m.start(), m.end(), self.bool_true_style));
            }
        }

        // Find false
        for m in self.bool_false_re.find_iter(text) {
            let overlaps = matches
                .iter()
                .any(|(s, e, _)| m.start() >= *s && m.end() <= *e);
            if !overlaps {
                matches.push((m.start(), m.end(), self.bool_false_style));
            }
        }

        // Find null
        for m in self.null_re.find_iter(text) {
            let overlaps = matches
                .iter()
                .any(|(s, e, _)| m.start() >= *s && m.end() <= *e);
            if !overlaps {
                matches.push((m.start(), m.end(), self.null_style));
            }
        }

        // Find hex numbers
        for m in self.hex_re.find_iter(text) {
            let overlaps = matches
                .iter()
                .any(|(s, e, _)| m.start() >= *s && m.end() <= *e);
            if !overlaps {
                matches.push((m.start(), m.end(), self.number_style));
            }
        }

        // Find braces
        for m in self.brace_re.find_iter(text) {
            let overlaps = matches
                .iter()
                .any(|(s, e, _)| m.start() >= *s && m.end() <= *e);
            if !overlaps {
                matches.push((m.start(), m.end(), self.brace_style));
            }
        }

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

        // Build spans
        let mut spans = Vec::new();
        let mut last_end = 0;

        for (start, end, style) in matches {
            // Skip overlapping matches
            if start < last_end {
                continue;
            }

            // Add unstyled text before match
            if start > last_end {
                spans.push(Span::raw(text[last_end..start].to_string()));
            }

            // Add styled match
            spans.push(Span::styled(text[start..end].to_string(), style));
            last_end = end;
        }

        // Add remaining text
        if last_end < text.len() {
            spans.push(Span::raw(text[last_end..].to_string()));
        }

        if spans.is_empty() {
            vec![Span::raw(text.to_string())]
        } else {
            spans
        }
    }
}

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

    #[test]
    fn test_regex_highlighter() {
        let mut hl = RegexHighlighter::new();
        hl.add_pattern(r"\d+", Style::new().foreground(Color::Cyan))
            .unwrap();

        let spans = hl.highlight("Port 8080 is open");
        assert_eq!(spans.len(), 3); // "Port ", "8080", " is open"
    }

    #[test]
    fn test_url_highlighter() {
        let hl = RegexHighlighter::url_highlighter(Style::new().foreground(Color::Blue));
        let spans = hl.highlight("Visit https://example.com for info");
        assert!(spans.len() > 1);
    }

    // =============================================================================
    // JSON Highlighter Tests
    // =============================================================================

    #[test]
    fn test_json_highlighter_keys() {
        let hl = JsonHighlighter::new();
        let spans = hl.highlight(r#"{"name": "value"}"#);

        // Find the key span ("name")
        let key_span = spans.iter().find(|s| s.text == r#""name""#).unwrap();
        assert!(key_span.style.bold, "Key should be bold");
        assert_eq!(
            key_span.style.foreground,
            Some(Color::Blue),
            "Key should be blue"
        );
    }

    #[test]
    fn test_json_highlighter_string_values() {
        let hl = JsonHighlighter::new();
        let spans = hl.highlight(r#"{"key": "value"}"#);

        // Find the value span ("value")
        let value_span = spans.iter().find(|s| s.text == r#""value""#).unwrap();
        assert_eq!(
            value_span.style.foreground,
            Some(Color::Green),
            "String value should be green"
        );
        assert!(!value_span.style.bold, "String value should not be bold");
    }

    #[test]
    fn test_json_highlighter_numbers() {
        let hl = JsonHighlighter::new();

        // Test integer
        let spans = hl.highlight(r#"{"count": 42}"#);
        let num_span = spans.iter().find(|s| s.text == "42").unwrap();
        assert_eq!(
            num_span.style.foreground,
            Some(Color::Cyan),
            "Number should be cyan"
        );

        // Test float
        let spans = hl.highlight(r#"{"pi": 3.14}"#);
        let num_span = spans.iter().find(|s| s.text == "3.14").unwrap();
        assert_eq!(
            num_span.style.foreground,
            Some(Color::Cyan),
            "Float should be cyan"
        );

        // Test negative number
        let spans = hl.highlight(r#"{"temp": -10}"#);
        let num_span = spans.iter().find(|s| s.text == "-10").unwrap();
        assert_eq!(
            num_span.style.foreground,
            Some(Color::Cyan),
            "Negative number should be cyan"
        );

        // Test scientific notation
        let spans = hl.highlight(r#"{"big": 1.5e10}"#);
        let num_span = spans.iter().find(|s| s.text == "1.5e10").unwrap();
        assert_eq!(
            num_span.style.foreground,
            Some(Color::Cyan),
            "Scientific notation should be cyan"
        );
    }

    #[test]
    fn test_json_highlighter_hex_numbers() {
        let hl = JsonHighlighter::new();
        let spans = hl.highlight(r#"{"hex": 0x1A2B}"#);

        let hex_span = spans.iter().find(|s| s.text == "0x1A2B").unwrap();
        assert_eq!(
            hex_span.style.foreground,
            Some(Color::Cyan),
            "Hex number should be cyan"
        );
    }

    #[test]
    fn test_json_highlighter_booleans() {
        let hl = JsonHighlighter::new();

        // Test true
        let spans = hl.highlight(r#"{"active": true}"#);
        let true_span = spans.iter().find(|s| s.text == "true").unwrap();
        assert_eq!(
            true_span.style.foreground,
            Some(Color::BrightGreen),
            "true should be bright green"
        );

        // Test false
        let spans = hl.highlight(r#"{"active": false}"#);
        let false_span = spans.iter().find(|s| s.text == "false").unwrap();
        assert_eq!(
            false_span.style.foreground,
            Some(Color::BrightRed),
            "false should be bright red"
        );
    }

    #[test]
    fn test_json_highlighter_null() {
        let hl = JsonHighlighter::new();
        let spans = hl.highlight(r#"{"value": null}"#);

        let null_span = spans.iter().find(|s| s.text == "null").unwrap();
        assert_eq!(
            null_span.style.foreground,
            Some(Color::Magenta),
            "null should be magenta"
        );
        assert!(null_span.style.italic, "null should be italic");
    }

    #[test]
    fn test_json_highlighter_braces() {
        let hl = JsonHighlighter::new();
        let spans = hl.highlight(r#"{"arr": [1, 2], "obj": {}}"#);

        // Check that braces/brackets are styled
        let brace_chars = ["{", "}", "[", "]"];
        for ch in &brace_chars {
            let brace_span = spans.iter().find(|s| s.text == *ch);
            assert!(
                brace_span.is_some(),
                "Brace/bracket '{}' should be found",
                ch
            );
            let brace_span = brace_span.unwrap();
            assert_eq!(
                brace_span.style.foreground,
                Some(Color::White),
                "Brace should be white"
            );
            assert!(brace_span.style.dim, "Brace should be dim");
        }
    }

    #[test]
    fn test_json_highlighter_parentheses() {
        let hl = JsonHighlighter::new();
        let spans = hl.highlight(r#"{"func": (value)}"#);

        // Check that parentheses are styled (matching Python rich)
        let paren_span = spans.iter().find(|s| s.text == "(");
        assert!(paren_span.is_some(), "Opening parenthesis should be found");
        let paren_span = paren_span.unwrap();
        assert_eq!(
            paren_span.style.foreground,
            Some(Color::White),
            "Parenthesis should be white"
        );
        assert!(paren_span.style.dim, "Parenthesis should be dim");
    }

    #[test]
    fn test_json_highlighter_no_highlight_in_strings() {
        let hl = JsonHighlighter::new();
        // The string contains "true", "false", "null", and "123" but they should not be highlighted
        // because they are inside a string value
        let spans = hl.highlight(r#"{"text": "true false null 123"}"#);

        // Find the value span which should contain the entire string including the content
        let value_span = spans
            .iter()
            .find(|s| s.text == r#""true false null 123""#)
            .unwrap();
        assert_eq!(
            value_span.style.foreground,
            Some(Color::Green),
            "String content should be green"
        );

        // Ensure "true", "false", "null", "123" are NOT styled separately when inside the string
        // They should be part of the single string span
        let separate_true = spans
            .iter()
            .any(|s| s.text == "true" && s.style.foreground == Some(Color::BrightGreen));
        let separate_false = spans
            .iter()
            .any(|s| s.text == "false" && s.style.foreground == Some(Color::BrightRed));
        let separate_null = spans
            .iter()
            .any(|s| s.text == "null" && s.style.foreground == Some(Color::Magenta));
        let separate_num = spans
            .iter()
            .any(|s| s.text == "123" && s.style.foreground == Some(Color::Cyan));

        assert!(
            !separate_true,
            "Keywords inside strings should not be highlighted separately"
        );
        assert!(
            !separate_false,
            "Keywords inside strings should not be highlighted separately"
        );
        assert!(
            !separate_null,
            "Keywords inside strings should not be highlighted separately"
        );
        assert!(
            !separate_num,
            "Numbers inside strings should not be highlighted separately"
        );
    }

    #[test]
    fn test_json_highlighter_complex_json() {
        let hl = JsonHighlighter::new();
        let json =
            r#"{"name": "John", "age": 30, "active": true, "data": null, "items": [1, 2, 3]}"#;
        let spans = hl.highlight(json);

        // Verify we have multiple spans (not just one raw span)
        assert!(
            spans.len() > 1,
            "Complex JSON should have multiple styled spans"
        );

        // Verify key is styled as key
        let name_key = spans.iter().find(|s| s.text == r#""name""#).unwrap();
        assert!(name_key.style.bold, "Key should be bold");

        // Verify string value
        let name_value = spans.iter().find(|s| s.text == r#""John""#).unwrap();
        assert_eq!(
            name_value.style.foreground,
            Some(Color::Green),
            "String value should be green"
        );

        // Verify number
        let age_value = spans.iter().find(|s| s.text == "30").unwrap();
        assert_eq!(
            age_value.style.foreground,
            Some(Color::Cyan),
            "Number should be cyan"
        );

        // Verify boolean
        let active_value = spans.iter().find(|s| s.text == "true").unwrap();
        assert_eq!(
            active_value.style.foreground,
            Some(Color::BrightGreen),
            "Boolean true should be bright green"
        );

        // Verify null
        let null_value = spans.iter().find(|s| s.text == "null").unwrap();
        assert_eq!(
            null_value.style.foreground,
            Some(Color::Magenta),
            "null should be magenta"
        );
    }

    #[test]
    fn test_json_highlighter_custom_styles() {
        let custom_key_style = Style::new().foreground(Color::Yellow);
        let custom_string_style = Style::new().foreground(Color::Red);
        let custom_number_style = Style::new().foreground(Color::Magenta);

        let hl = JsonHighlighter::new()
            .key_style(custom_key_style)
            .string_style(custom_string_style)
            .number_style(custom_number_style);

        let spans = hl.highlight(r#"{"key": "value", "num": 42}"#);

        // Verify custom key style
        let key_span = spans.iter().find(|s| s.text == r#""key""#).unwrap();
        assert_eq!(
            key_span.style.foreground,
            Some(Color::Yellow),
            "Custom key style should be yellow"
        );

        // Verify custom string style
        let value_span = spans.iter().find(|s| s.text == r#""value""#).unwrap();
        assert_eq!(
            value_span.style.foreground,
            Some(Color::Red),
            "Custom string style should be red"
        );

        // Verify custom number style
        let num_span = spans.iter().find(|s| s.text == "42").unwrap();
        assert_eq!(
            num_span.style.foreground,
            Some(Color::Magenta),
            "Custom number style should be magenta"
        );
    }
}