matrixcode-tui 0.4.13

MatrixCode TUI - Terminal UI library for AI Code Agent
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
use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use std::sync::OnceLock;
use unicode_width::UnicodeWidthStr;

/// Lazy-loaded syntax set for code highlighting
static SYNTAX_SET: OnceLock<syntect::parsing::SyntaxSet> = OnceLock::new();
/// Lazy-loaded theme set for code highlighting
static THEME_SET: OnceLock<syntect::highlighting::ThemeSet> = OnceLock::new();

fn get_syntax_set() -> &'static syntect::parsing::SyntaxSet {
    SYNTAX_SET.get_or_init(syntect::parsing::SyntaxSet::load_defaults_newlines)
}

fn get_theme_set() -> &'static syntect::highlighting::ThemeSet {
    THEME_SET.get_or_init(syntect::highlighting::ThemeSet::load_defaults)
}

/// Inline code style for `code`
fn inline_code_style() -> Style {
    Style::default().fg(Color::Yellow).bg(Color::DarkGray)
}

/// Math formula style
fn math_style() -> Style {
    Style::default().fg(Color::LightMagenta).bg(Color::DarkGray)
}

/// Heading style for # ## ### etc.
fn heading_style(level: HeadingLevel) -> Style {
    let color = match level {
        HeadingLevel::H1 => Color::Cyan,
        HeadingLevel::H2 => Color::LightCyan,
        HeadingLevel::H3 => Color::White,
        _ => Color::Gray,
    };
    Style::default().fg(color).add_modifier(Modifier::BOLD)
}

/// Bold text style
fn bold_style() -> Style {
    Style::default()
        .fg(Color::White)
        .add_modifier(Modifier::BOLD)
}

/// Italic text style
fn italic_style() -> Style {
    Style::default()
        .fg(Color::Gray)
        .add_modifier(Modifier::ITALIC)
}

/// Strikethrough style
fn strikethrough_style() -> Style {
    Style::default()
        .fg(Color::Gray)
        .add_modifier(Modifier::CROSSED_OUT)
}

/// Link style
fn link_style() -> Style {
    Style::default()
        .fg(Color::Blue)
        .add_modifier(Modifier::UNDERLINED)
}

/// Normal text style
fn text_style() -> Style {
    Style::default().fg(Color::Gray)
}

/// List bullet style
fn bullet_style() -> Style {
    Style::default().fg(Color::DarkGray)
}

/// Render markdown text with proper code block handling
/// Returns a vector of Lines for rendering in ratatui
pub fn render_markdown(text: &str, max_width: usize) -> Vec<Line<'static>> {
    if text.is_empty() {
        return Vec::new();
    }

    // Enable all extensions for better markdown support
    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TASKLISTS);
    options.insert(Options::ENABLE_MATH);

    let parser = Parser::new_ext(text, options);
    let mut renderer = MarkdownRenderer::new(max_width);
    renderer.render(parser);
    renderer.lines
}

/// Markdown renderer state
struct MarkdownRenderer {
    lines: Vec<Line<'static>>,
    current_spans: Vec<Span<'static>>,
    style_stack: Vec<Style>,
    in_code_block: bool,
    code_block_lang: Option<String>,
    code_block_content: String,
    list_depth: usize,
    max_width: usize,
    current_line_width: usize,
    // Table support
    in_table_cell: bool,
    current_table_row: Vec<String>,
    current_cell_content: String,
    table_header: Vec<String>,
    table_rows: Vec<Vec<String>>,
    in_table_header: bool,
}

impl MarkdownRenderer {
    fn new(max_width: usize) -> Self {
        Self {
            lines: Vec::new(),
            current_spans: Vec::new(),
            style_stack: vec![text_style()],
            in_code_block: false,
            code_block_lang: None,
            code_block_content: String::new(),
            list_depth: 0,
            max_width,
            current_line_width: 0,
            in_table_cell: false,
            current_table_row: Vec::new(),
            current_cell_content: String::new(),
            table_header: Vec::new(),
            table_rows: Vec::new(),
            in_table_header: false,
        }
    }

    fn current_style(&self) -> Style {
        *self.style_stack.last().unwrap_or(&text_style())
    }

    fn push_style(&mut self, style: Style) {
        self.style_stack.push(style);
    }

    fn pop_style(&mut self) {
        if self.style_stack.len() > 1 {
            self.style_stack.pop();
        }
    }

    fn flush_line(&mut self) {
        if !self.current_spans.is_empty() {
            self.lines.push(Line::from(self.current_spans.clone()));
            self.current_spans.clear();
            self.current_line_width = 0;
        }
    }

    fn add_text(&mut self, text: &str) {
        let style = self.current_style();

        // Handle width-based wrapping
        for word in text.split_whitespace() {
            let word_width = word.width();

            // If word itself is too long, split it
            if word_width > self.max_width {
                // Add as much as fits, then flush and continue
                let mut remaining = word;
                while !remaining.is_empty() {
                    let available = self.max_width.saturating_sub(self.current_line_width);
                    if available == 0 {
                        self.flush_line();
                        continue;
                    }

                    // Find how many chars fit
                    let mut chars_len = 0;
                    let mut fit_width = 0;
                    for ch in remaining.chars() {
                        let ch_w = if ch > '\u{7F}' { 2 } else { 1 };
                        if fit_width + ch_w > available {
                            break;
                        }
                        chars_len += ch.len_utf8();
                        fit_width += ch_w;
                    }

                    if chars_len > 0 {
                        self.current_spans
                            .push(Span::styled(remaining[..chars_len].to_string(), style));
                        self.current_line_width += fit_width;
                        remaining = &remaining[chars_len..];
                    }

                    if !remaining.is_empty() {
                        self.flush_line();
                    }
                }
            } else {
                // Word fits within max_width
                // Need space if not first word on line
                let needs_space = self.current_line_width > 0;
                let total_width = word_width + if needs_space { 1 } else { 0 };

                if self.current_line_width + total_width > self.max_width {
                    // Word doesn't fit on current line, start new line
                    self.flush_line();
                    self.current_spans
                        .push(Span::styled(word.to_string(), style));
                    self.current_line_width = word_width;
                } else {
                    // Word fits
                    if needs_space {
                        self.current_spans
                            .push(Span::styled(" ".to_string(), style));
                        self.current_line_width += 1;
                    }
                    self.current_spans
                        .push(Span::styled(word.to_string(), style));
                    self.current_line_width += word_width;
                }
            }
        }
    }

    fn render(&mut self, parser: Parser) {
        for event in parser {
            match event {
                Event::Start(tag) => self.handle_start(tag),
                Event::End(tag_end) => self.handle_end(tag_end),
                Event::Text(text) => {
                    if self.in_code_block {
                        self.code_block_content.push_str(&text);
                    } else if self.in_table_cell {
                        self.current_cell_content.push_str(&text);
                    } else {
                        self.add_text(&text);
                    }
                }
                Event::Code(code) => {
                    if self.in_table_cell {
                        // In table cell: collect content as plain text
                        self.current_cell_content.push_str(&code);
                    } else {
                        self.current_spans
                            .push(Span::styled(code.to_string(), inline_code_style()));
                    }
                }
                Event::InlineMath(math) => {
                    // Inline math: $formula$
                    if self.in_table_cell {
                        self.current_cell_content.push_str(&format!("${}$", math));
                    } else {
                        self.current_spans
                            .push(Span::styled(format!("${}$", math), math_style()));
                    }
                }
                Event::DisplayMath(math) => {
                    // Display math: $$formula$$ - render as separate block
                    self.flush_line();
                    self.lines
                        .push(Line::styled(format!("  $${}$$", math), math_style()));
                }
                Event::Html(html) => {
                    if self.in_table_cell {
                        self.current_cell_content.push_str(&html);
                    } else {
                        self.add_text(&html);
                    }
                }
                Event::InlineHtml(html) => {
                    if self.in_table_cell {
                        self.current_cell_content.push_str(&html);
                    } else {
                        self.add_text(&html);
                    }
                }
                Event::SoftBreak => self.add_text(" "),
                Event::HardBreak => self.flush_line(),
                Event::Rule => {
                    self.flush_line();
                    self.lines.push(Line::styled(
                        "".repeat(40),
                        Style::default().fg(Color::DarkGray),
                    ));
                }
                Event::FootnoteReference(_) | Event::TaskListMarker(_) => {}
            }
        }
        self.flush_line();
    }

    fn handle_start(&mut self, tag: Tag) {
        match tag {
            Tag::Heading { level, .. } => {
                self.flush_line();
                self.push_style(heading_style(level));
            }
            Tag::Paragraph => {
                self.flush_line();
            }
            Tag::CodeBlock(kind) => {
                self.flush_line();
                self.in_code_block = true;
                self.code_block_lang = match kind {
                    CodeBlockKind::Fenced(lang) => Some(lang.to_string()),
                    CodeBlockKind::Indented => None,
                };
            }
            Tag::List(_) => {
                self.flush_line();
                self.list_depth += 1;
            }
            Tag::Item => {
                self.flush_line();
                let indent = "  ".repeat(self.list_depth.saturating_sub(1));
                self.current_spans
                    .push(Span::styled(format!("{}", indent), bullet_style()));
            }
            Tag::BlockQuote(_) => {
                self.flush_line();
                self.push_style(Style::default().fg(Color::DarkGray));
                self.current_spans
                    .push(Span::styled("", Style::default().fg(Color::DarkGray)));
            }
            Tag::Strong => {
                if self.in_table_cell {
                    // In table: just collect text, no styling
                } else {
                    self.push_style(bold_style());
                }
            }
            Tag::Emphasis => {
                if self.in_table_cell {
                    // In table: just collect text, no styling
                } else {
                    self.push_style(italic_style());
                }
            }
            Tag::Strikethrough => {
                if self.in_table_cell {
                    // In table: just collect text, no styling
                } else {
                    self.push_style(strikethrough_style());
                }
            }
            Tag::Link { dest_url: _, .. } => {
                if self.in_table_cell {
                    // In table: just collect text, no link styling
                } else {
                    self.push_style(link_style());
                    self.current_spans
                        .push(Span::styled("[", Style::default().fg(Color::DarkGray)));
                }
            }
            Tag::Image { title, .. } => {
                self.add_text("📷 ");
                if !title.is_empty() {
                    self.add_text(&title);
                }
            }
            Tag::Table(_) => {
                self.flush_line();
                self.table_header.clear();
                self.table_rows.clear();
            }
            Tag::TableHead => {
                self.in_table_header = true;
            }
            Tag::TableRow => {
                self.current_table_row.clear();
            }
            Tag::TableCell => {
                self.current_cell_content.clear();
                self.in_table_cell = true;
            }
            Tag::FootnoteDefinition(_) => {}
            Tag::HtmlBlock => {}
            Tag::DefinitionList => {}
            Tag::DefinitionListTitle => {}
            Tag::DefinitionListDefinition => {}
            Tag::Superscript => self.push_style(Style::default().fg(Color::Gray)),
            Tag::Subscript => self.push_style(Style::default().fg(Color::Gray)),
            Tag::MetadataBlock(_) => {}
        }
    }

    fn handle_end(&mut self, tag_end: TagEnd) {
        match tag_end {
            TagEnd::Heading(_) => {
                self.flush_line();
                self.pop_style();
            }
            TagEnd::Paragraph => {
                self.flush_line();
                self.lines.push(Line::raw(""));
            }
            TagEnd::CodeBlock => {
                self.flush_code_block();
                self.in_code_block = false;
                self.code_block_lang = None;
                self.code_block_content.clear();
            }
            TagEnd::List(_) => {
                self.flush_line();
                self.list_depth = self.list_depth.saturating_sub(1);
            }
            TagEnd::Item => {
                self.flush_line();
            }
            TagEnd::BlockQuote(_) => {
                self.flush_line();
                self.pop_style();
            }
            TagEnd::Strong => {
                if !self.in_table_cell {
                    self.pop_style();
                }
            }
            TagEnd::Emphasis => {
                if !self.in_table_cell {
                    self.pop_style();
                }
            }
            TagEnd::Strikethrough => {
                if !self.in_table_cell {
                    self.pop_style();
                }
            }
            TagEnd::Link => {
                if !self.in_table_cell {
                    self.pop_style();
                    self.current_spans
                        .push(Span::styled("]", Style::default().fg(Color::DarkGray)));
                }
            }
            TagEnd::Image => {}
            TagEnd::Table => {
                self.flush_line();
                self.render_table();
            }
            TagEnd::TableHead => {
                // TableHead end: move collected cells to table_header
                self.table_header = self.current_table_row.clone();
                self.current_table_row.clear();
                self.in_table_header = false;
            }
            TagEnd::TableRow => {
                if self.in_table_header {
                    self.table_header = self.current_table_row.clone();
                } else {
                    self.table_rows.push(self.current_table_row.clone());
                }
                self.current_table_row.clear();
            }
            TagEnd::TableCell => {
                self.current_table_row
                    .push(self.current_cell_content.clone());
                self.current_cell_content.clear();
                self.in_table_cell = false;
            }
            TagEnd::FootnoteDefinition => {}
            TagEnd::HtmlBlock => {}
            TagEnd::DefinitionList => {}
            TagEnd::DefinitionListTitle => {}
            TagEnd::DefinitionListDefinition => {}
            TagEnd::Superscript => self.pop_style(),
            TagEnd::Subscript => self.pop_style(),
            TagEnd::MetadataBlock(_) => {}
        }
    }

    fn flush_code_block(&mut self) {
        let lang = self.code_block_lang.as_deref().unwrap_or("");
        let code = &self.code_block_content;

        // Optional: show language label on first line
        if !lang.is_empty() {
            self.lines.push(Line::styled(
                format!("// {}", lang),
                Style::default().fg(Color::DarkGray),
            ));
        }

        for line_spans in self.highlight_code_with_colors(lang, code) {
            // Check total width and wrap if needed
            let total_width: usize = line_spans.iter().map(|s| s.content.width()).sum();

            if total_width <= self.max_width || self.max_width < 10 {
                // Line fits, add directly
                self.lines.push(Line::from(line_spans));
            } else {
                // Line too long, need to wrap
                let mut current_spans: Vec<Span> = Vec::new();
                let mut current_width = 0;

                for span in line_spans {
                    let span_width = span.content.width();

                    if current_width + span_width <= self.max_width {
                        // Span fits
                        current_spans.push(span);
                        current_width += span_width;
                    } else {
                        // Span doesn't fit, need to split
                        let available = self.max_width.saturating_sub(current_width);

                        if available > 0 {
                            // Split span content
                            let mut fit_len = 0;
                            let mut fit_width = 0;
                            for ch in span.content.chars() {
                                let ch_w = if ch > '\u{7F}' { 2 } else { 1 };
                                if fit_width + ch_w > available {
                                    break;
                                }
                                fit_len += ch.len_utf8();
                                fit_width += ch_w;
                            }

                            if fit_len > 0 {
                                current_spans.push(Span::styled(
                                    span.content[..fit_len].to_string(),
                                    span.style,
                                ));

                                // Flush current line
                                self.lines.push(Line::from(current_spans.clone()));
                                current_spans.clear();
                                current_width = 0;

                                // Handle remaining part of span
                                let remaining = &span.content[fit_len..];
                                if remaining.width() > self.max_width {
                                    // Remaining still too long, split further
                                    let mut rest = remaining;
                                    while !rest.is_empty() {
                                        let mut r_len = 0;
                                        let mut r_width = 0;
                                        for ch in rest.chars() {
                                            let ch_w = if ch > '\u{7F}' { 2 } else { 1 };
                                            if r_width + ch_w > self.max_width {
                                                break;
                                            }
                                            r_len += ch.len_utf8();
                                            r_width += ch_w;
                                        }
                                        if r_len > 0 {
                                            self.lines.push(Line::from(vec![Span::styled(
                                                rest[..r_len].to_string(),
                                                span.style,
                                            )]));
                                            rest = &rest[r_len..];
                                        } else {
                                            break;
                                        }
                                    }
                                } else {
                                    current_spans
                                        .push(Span::styled(remaining.to_string(), span.style));
                                    current_width = remaining.width();
                                }
                            }
                        } else {
                            // No space on current line, flush and add span
                            if !current_spans.is_empty() {
                                self.lines.push(Line::from(current_spans.clone()));
                                current_spans.clear();
                            }

                            // Handle span that might be longer than max_width
                            if span_width > self.max_width {
                                let content = &span.content;
                                let style = span.style;
                                let mut pos = 0;
                                while pos < content.len() {
                                    let mut r_len = 0;
                                    let mut r_width = 0;
                                    for ch in content[pos..].chars() {
                                        let ch_w = if ch > '\u{7F}' { 2 } else { 1 };
                                        if r_width + ch_w > self.max_width {
                                            break;
                                        }
                                        r_len += ch.len_utf8();
                                        r_width += ch_w;
                                    }
                                    if r_len > 0 {
                                        self.lines.push(Line::from(vec![Span::styled(
                                            content[pos..pos + r_len].to_string(),
                                            style,
                                        )]));
                                        pos += r_len;
                                    } else {
                                        break;
                                    }
                                }
                            } else {
                                current_spans.push(span);
                                current_width = span_width;
                            }
                        }
                    }
                }

                // Flush remaining spans
                if !current_spans.is_empty() {
                    self.lines.push(Line::from(current_spans));
                }
            }
        }
    }

    fn highlight_code_with_colors(&self, lang: &str, code: &str) -> Vec<Vec<Span<'static>>> {
        let ss = get_syntax_set();
        let ts = get_theme_set();

        let syntax = ss
            .find_syntax_by_token(lang)
            .or_else(|| ss.find_syntax_by_extension(lang))
            .unwrap_or_else(|| ss.find_syntax_plain_text());

        let theme = ts
            .themes
            .get("base16-eighties.dark")
            .or_else(|| ts.themes.get("Solarized (dark)"))
            .or_else(|| ts.themes.get("base16-mono.dark"))
            .or_else(|| ts.themes.values().next())
            .expect("theme set should always have at least one theme");

        use syntect::easy::HighlightLines;
        let mut highlighter = HighlightLines::new(syntax, theme);

        code.lines()
            .map(|line| {
                let highlighted = highlighter.highlight_line(line, ss).unwrap_or_default();
                highlighted
                    .iter()
                    .map(|(style, text)| {
                        let fg = syntect_color_to_ratatui(style.foreground);
                        Span::styled(text.to_string(), Style::default().fg(fg))
                    })
                    .collect()
            })
            .collect()
    }

    fn render_table(&mut self) {
        if self.table_header.is_empty() {
            return;
        }

        // Calculate column widths: content width + 2 (1 space padding on each side)
        let mut widths: Vec<usize> = self.table_header.iter().map(|c| c.width() + 2).collect();

        for row in &self.table_rows {
            for (i, cell) in row.iter().enumerate() {
                if i < widths.len() {
                    widths[i] = widths[i].max(cell.width() + 2);
                }
            }
        }

        // Build borders with matching widths
        // Top: ┌───┬───┐
        let top_border = format!(
            "{}",
            widths
                .iter()
                .map(|w| "".repeat(*w))
                .collect::<Vec<_>>()
                .join("")
        );

        // Separator: ├───┼───┤
        let row_sep = format!(
            "{}",
            widths
                .iter()
                .map(|w| "".repeat(*w))
                .collect::<Vec<_>>()
                .join("")
        );

        // Bottom: └───┴───┘
        let bottom_border = format!(
            "{}",
            widths
                .iter()
                .map(|w| "".repeat(*w))
                .collect::<Vec<_>>()
                .join("")
        );

        // Top border
        self.lines.push(Line::styled(
            top_border,
            Style::default().fg(Color::DarkGray),
        ));

        // Header row: │ A │ B │
        let header_line = format!(
            "{}",
            widths
                .iter()
                .enumerate()
                .map(|(i, w)| self.pad_cell(&self.table_header[i], *w))
                .collect::<Vec<_>>()
                .join("")
        );
        self.lines.push(Line::styled(
            header_line,
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ));

        // Separator after header
        self.lines.push(Line::styled(
            row_sep.clone(),
            Style::default().fg(Color::DarkGray),
        ));

        // Data rows
        for (idx, row) in self.table_rows.iter().enumerate() {
            let row_line = format!(
                "{}",
                widths
                    .iter()
                    .enumerate()
                    .map(|(i, w)| self.pad_cell(&row[i], *w))
                    .collect::<Vec<_>>()
                    .join("")
            );
            self.lines
                .push(Line::styled(row_line, Style::default().fg(Color::Gray)));

            // Add separator between rows (but not after last row)
            if idx < self.table_rows.len() - 1 {
                self.lines.push(Line::styled(
                    row_sep.clone(),
                    Style::default().fg(Color::DarkGray),
                ));
            }
        }

        // Bottom border
        self.lines.push(Line::styled(
            bottom_border,
            Style::default().fg(Color::DarkGray),
        ));
    }

    fn pad_cell(&self, content: &str, width: usize) -> String {
        // Pad content to fit in width (width includes 2 padding spaces)
        let content_width = content.width();
        let padding = width.saturating_sub(content_width);
        let left_pad = padding / 2;
        let right_pad = padding - left_pad;
        format!(
            "{}{}{}",
            " ".repeat(left_pad),
            content,
            " ".repeat(right_pad)
        )
    }
}

fn syntect_color_to_ratatui(c: syntect::highlighting::Color) -> Color {
    let r = c.r;
    let g = c.g;
    let b = c.b;

    let max = r.max(g).max(b);
    let min = r.min(g).min(b);
    if max - min < 20 {
        if r < 80 {
            return Color::DarkGray;
        }
        if r < 160 {
            return Color::Gray;
        }
        return Color::White;
    }

    if r >= g && r >= b && r > 150 {
        if g > 100 && b < 100 {
            return Color::Yellow;
        }
        if b > 100 && g < 100 {
            return Color::Magenta;
        }
        return Color::Red;
    }
    if g >= r && g >= b && g > 150 {
        if b > 100 && r < 100 {
            return Color::Cyan;
        }
        return Color::Green;
    }
    if b >= r && b >= g && b > 150 {
        return Color::Blue;
    }

    Color::Rgb(r, g, b)
}

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

    #[test]
    fn test_plain_text() {
        let result = render_markdown("Hello world", 80);
        assert!(!result.is_empty());
        let text = result[0]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<String>();
        assert!(text.contains("Hello"));
    }

    #[test]
    fn test_heading() {
        let result = render_markdown("# Title", 80);
        assert!(!result.is_empty());
        let text = result[0]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<String>();
        assert!(text.contains("Title"));
    }

    #[test]
    fn test_table() {
        let md = "| A | B |\n|---|---|\n| 1 | 2 |";
        let result = render_markdown(md, 80);
        assert!(!result.is_empty());
    }

    #[test]
    fn test_math() {
        let md = "Inline: $E=mc^2$";
        let result = render_markdown(md, 80);
        assert!(!result.is_empty());
        let text = result[0]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<String>();
        assert!(text.contains("$E=mc^2$"));
    }
}

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

    #[test]
    fn debug_table() {
        let md = "| A | B |\n|---|---|\n| 1 | 2 |";
        println!("\n=== Simple Table ===");
        let lines = render_markdown(md, 60);
        for (i, line) in lines.iter().enumerate() {
            let text = line
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>();
            println!("[{}] '{}'", i, text);
        }
    }

    #[test]
    fn debug_table_chinese() {
        let md = "| 名称 | 数值 |\n|------|------|\n| 测试 | 123 |\n| 数据 | 456 |";
        println!("\n=== Chinese Table ===");
        let lines = render_markdown(md, 80);
        for (i, line) in lines.iter().enumerate() {
            let text = line
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>();
            println!("[{}] '{}'", i, text);
        }
    }

    #[test]
    fn debug_table_multi_row() {
        let md = "| Col1 | Col2 | Col3 |\n|------|------|------|\n| A1 | B1 | C1 |\n| A2 | B2 | C2 |\n| A3 | B3 | C3 |";
        println!("\n=== Multi-row Table ===");
        let lines = render_markdown(md, 80);
        for (i, line) in lines.iter().enumerate() {
            let text = line
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>();
            println!("[{}] '{}'", i, text);
        }
    }

    #[test]
    fn debug_table_complex() {
        // Table with code, links, long content
        let md = "| Name | Description | Link |\n|------|-------------|------|\n| `code` | This has **bold** text | [click](url) |\n| item2 | normal text | none |";
        println!("\n=== Complex Table ===");
        let lines = render_markdown(md, 80);
        for (i, line) in lines.iter().enumerate() {
            let text = line
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>();
            println!("[{}] '{}'", i, text);
        }
    }

    #[test]
    fn debug_table_events() {
        let md = "| A | B |\n|---|---|\n| 1 | 2 |";
        println!("\n=== Table Events (pulldown-cmark 0.13) ===");
        let mut options = Options::empty();
        options.insert(Options::ENABLE_TABLES);
        let parser = Parser::new_ext(md, options);
        for (i, event) in parser.enumerate() {
            println!("[{}] {:?}", i, event);
        }
    }

    #[test]
    fn debug_math() {
        let md = "Inline: $E=mc^2$\n\nBlock:\n$$\\sum_{i=1}^n i$$";
        println!("\n=== Math ===");
        let lines = render_markdown(md, 80);
        for (i, line) in lines.iter().enumerate() {
            let text = line
                .spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>();
            println!("[{}] '{}'", i, text);
        }
    }
}