rpi-tui 0.3.9

Terminal User Interface for pi-rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
//! Markdown component for rendering markdown text.
//!
//! Provides ANSI-aware markdown rendering that wraps to the available width
//! without panicking on multibyte (CJK/emoji/box-drawing) characters or
//! leaking escape sequences. Reuses the shared utilities in [`crate::utils`].

use std::any::Any;
use std::sync::Mutex;

use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};

use super::component::Component;
use super::mermaid::Mermaid;
use crate::ansi::{bold, italic, underline};
use crate::theme::theme;
use crate::utils::{
    apply_background_to_line, truncate_to_width, visible_width, wrap_text_with_ansi,
};

/// Markdown rendering options.
#[derive(Debug, Clone)]
pub struct MarkdownOptions {
    /// Indentation for code blocks.
    pub code_block_indent: usize,
    /// Maximum width for wrapping (None = use the render width passed in).
    pub max_width: Option<usize>,
    /// Base SGR sequence applied to every rendered line (e.g. the dim italic
    /// style used for thinking blocks). Empty means no base style. The sequence
    /// is re-applied after every nested SGR reset so inner spans (inline code,
    /// links, headings) do not permanently drop the enclosing style.
    pub base_style: String,
}

impl Default for MarkdownOptions {
    fn default() -> Self {
        Self {
            code_block_indent: 2,
            max_width: None,
            base_style: String::new(),
        }
    }
}

/// Markdown - A component that renders markdown text.
pub struct Markdown {
    content: Mutex<String>,
    options: MarkdownOptions,
    padding_x: usize,
    padding_y: usize,
    /// Render cache keyed by (content, width). Markdown parsing + inline
    /// pulldown-cmark work is the dominant per-frame cost of a long transcript;
    /// a finalized message is re-rendered on every frame the transcript is
    /// repainted, so caching the parsed lines is what keeps that O(1) per
    /// unchanged message. Mirrors upstream `Markdown.cachedText/cachedLines`.
    cache: Mutex<Option<MarkdownCache>>,
}

#[derive(Clone)]
struct MarkdownCache {
    content: String,
    width: usize,
    theme_revision: u64,
    lines: Vec<String>,
}

impl Markdown {
    /// Create a new markdown component.
    pub fn new(content: impl Into<String>, padding_x: usize, padding_y: usize) -> Self {
        Self {
            content: Mutex::new(content.into()),
            options: MarkdownOptions::default(),
            padding_x,
            padding_y,
            cache: Mutex::new(None),
        }
    }

    /// Create with options.
    pub fn with_options(
        content: impl Into<String>,
        options: MarkdownOptions,
        padding_x: usize,
        padding_y: usize,
    ) -> Self {
        Self {
            content: Mutex::new(content.into()),
            options,
            padding_x,
            padding_y,
            cache: Mutex::new(None),
        }
    }

    /// Apply a base SGR sequence (for example the dim italic ``\x1b[3m\x1b[38;5;244m``
    /// style) to every rendered line. The base style is re-opened after each
    /// nested SGR reset so inner spans like inline code or links do not drop it
    /// for the remainder of the line.
    pub fn with_base_style(mut self, base_style: impl Into<String>) -> Self {
        self.options.base_style = base_style.into();
        self.clear_cache();
        self
    }

    /// Wrap one rendered line with the configured base style, re-opening the
    /// base after every nested `SGR 0` reset. Returns the line unchanged when
    /// no base style is configured.
    fn apply_base_style(&self, line: &str) -> String {
        let base = self.options.base_style.as_str();
        if base.is_empty() {
            return line.to_string();
        }
        let reset = "\x1b[0m";
        let mut out = String::with_capacity(line.len() + base.len() * 4 + reset.len());
        out.push_str(base);
        let mut rest = line;
        while let Some(idx) = rest.find(reset) {
            out.push_str(&rest[..idx + reset.len()]);
            out.push_str(base);
            rest = &rest[idx + reset.len()..];
        }
        out.push_str(rest);
        // Terminate the line so the base style cannot bleed into the next row
        // (rendered lines are written back-to-back with no implicit reset).
        out.push_str(reset);
        out
    }

    /// Set the content.
    pub fn set_content(&self, content: impl Into<String>) {
        if let Ok(mut c) = self.content.lock() {
            *c = content.into();
        }
        self.clear_cache();
    }

    /// Drop the cached render output.
    fn clear_cache(&self) {
        if let Ok(mut cache) = self.cache.lock() {
            *cache = None;
        }
    }

    /// Get the content.
    pub fn get_content(&self) -> String {
        self.content.lock().map(|c| c.clone()).unwrap_or_default()
    }

    /// The left-pad prefix applied to every rendered line.
    fn pad(&self) -> String {
        " ".repeat(self.padding_x)
    }

    /// Available content width accounting for horizontal padding.
    fn content_width(&self, width: usize) -> usize {
        width.saturating_sub(self.padding_x * 2)
    }

    /// Render markdown to lines.
    fn render_markdown(&self, width: usize) -> Vec<String> {
        let content = self.content.lock().map(|c| c.clone()).unwrap_or_default();
        let colors = theme().colors;
        let mut lines: Vec<String> = Vec::new();
        let indent = " ".repeat(self.options.code_block_indent);
        let pad = self.pad();
        let cwidth = self.content_width(width);

        // Add top padding
        for _ in 0..self.padding_y {
            lines.push(String::new());
        }

        // Pre-scan for tables: collect consecutive table-ish lines.
        let raw_lines: Vec<&str> = content.lines().collect();
        let mut i = 0;
        // Markdown allows a list item's paragraph to continue on an indented
        // line. Keep the visual text offset so continuation lines don't jump
        // back to the left edge of the transcript.
        let mut list_continuation_indent: Option<usize> = None;

        // Code-fence state. Fenced blocks are rendered as a compact terminal
        // panel rather than echoing Markdown's literal ``` markers.
        let mut in_code_block = false;
        let mut code_fence_char = '`';
        let mut code_language = String::new();
        // Syntax highlighter for the current fenced block (highlight.js
        // analogue; see `syntax_highlight`). Carries block-comment state
        // across lines. `None` outside a code block.
        let mut code_highlighter: Option<crate::syntax_highlight::Highlighter> = None;
        let mut mermaid_source: Vec<String> = Vec::new();
        while i < raw_lines.len() {
            let line = raw_lines[i];

            // Streamed partial closing fences (pi #5825): while the assistant
            // streams the final ```` ``` ````, the tail arrives one char at a
            // time (``, ```` ``` ````…). Rendering those would flicker the block
            // (content shrinks, then the real fence closes) — and a lone ``
            // or `````` would be mis-rendered as ordinary text. Trim any line
            // that is a partial fence run (1-2 fence chars, whole line).
            if is_partial_fence(line) {
                i += 1;
                continue;
            }

            // ---- Code fences ----
            let fence = fence_info(line);
            if let Some((fence_char, lang)) = fence {
                list_continuation_indent = None;
                // Inside a block, only the matching fence closes it. This keeps
                // backticks embedded in a ~~~ block from collapsing the panel.
                if !in_code_block {
                    in_code_block = true;
                    code_fence_char = fence_char;
                    code_language = lang.to_ascii_lowercase();
                    code_highlighter =
                        Some(crate::syntax_highlight::Highlighter::new(&code_language));
                    mermaid_source.clear();
                    // Fence language names (for example `text`, `rust`, or
                    // `bash`) are metadata, not code content. Keep ordinary
                    // code blocks content-only; Mermaid renders its own
                    // diagram label when the matching fence closes.
                } else if fence_char == code_fence_char {
                    if code_language == "mermaid" {
                        let component = Mermaid::new(mermaid_source.join("\n"));
                        let mermaid_lines = component.render(cwidth);
                        lines.extend(mermaid_lines.into_iter().map(|line| format!("{pad}{line}")));
                    }
                    in_code_block = false;
                    code_language.clear();
                    code_highlighter = None;
                    mermaid_source.clear();
                    // The closing fence is structural only; do not draw a
                    // bottom border around the code surface.
                } else {
                    // A non-matching fence is code content.
                    push_code_line(
                        line,
                        &pad,
                        &indent,
                        cwidth,
                        &mut lines,
                        code_highlighter.as_mut(),
                    );
                }
                i += 1;
                continue;
            }

            if in_code_block {
                list_continuation_indent = None;
                if code_language == "mermaid" {
                    mermaid_source.push(line.to_string());
                    i += 1;
                    continue;
                }
                // Code is never reflowed: wrapping destroys indentation and
                // makes copied snippets invalid. Tabs are normalized and long
                // physical lines are clipped with an ellipsis.
                push_code_line(
                    line,
                    &pad,
                    &indent,
                    cwidth,
                    &mut lines,
                    code_highlighter.as_mut(),
                );
                i += 1;
                continue;
            }

            // ---- Tables ----
            if is_table_separator(raw_lines.get(i + 1)) && is_table_row(line) {
                list_continuation_indent = None;
                // Collect the table block.
                let mut table_lines: Vec<&str> = Vec::new();
                table_lines.push(line);
                i += 1;
                // skip separator
                table_lines.push(raw_lines[i]);
                i += 1;
                while i < raw_lines.len() && is_table_row(raw_lines[i]) {
                    table_lines.push(raw_lines[i]);
                    i += 1;
                }
                render_table(&table_lines, &pad, cwidth, &mut lines, |cell| {
                    self.render_inline(cell)
                });
                continue;
            }

            // ---- Headers ----
            // Headings are rendered with the mdHeading color and bold text;
            // h1/h2 are additionally underlined. Markdown markers are hidden.
            if let Some(rest) = strip_header(line, "######") {
                list_continuation_indent = None;
                let h = bold(&colors.md_heading.fg(&self.render_inline(rest)));
                push_wrapped(&pad, &h, cwidth, &mut lines);
            } else if let Some(rest) = strip_header(line, "#####") {
                list_continuation_indent = None;
                let h = bold(&colors.md_heading.fg(&self.render_inline(rest)));
                push_wrapped(&pad, &h, cwidth, &mut lines);
            } else if let Some(rest) = strip_header(line, "####") {
                list_continuation_indent = None;
                let h = bold(&colors.md_heading.fg(&self.render_inline(rest)));
                push_wrapped(&pad, &h, cwidth, &mut lines);
            } else if let Some(rest) = strip_header(line, "###") {
                list_continuation_indent = None;
                let h = bold(&colors.md_heading.fg(&self.render_inline(rest)));
                push_wrapped(&pad, &h, cwidth, &mut lines);
            } else if let Some(rest) = strip_header(line, "##") {
                list_continuation_indent = None;
                let h = colors
                    .md_heading
                    .fg(&bold(&underline(&self.render_inline(rest))));
                push_wrapped(&pad, &h, cwidth, &mut lines);
            } else if let Some(rest) = strip_header(line, "#") {
                list_continuation_indent = None;
                let h = colors
                    .md_heading
                    .fg(&bold(&underline(&self.render_inline(rest))));
                push_wrapped(&pad, &h, cwidth, &mut lines);
            } else if let Some(item) = parse_list_item(line) {
                let marker = match item.marker {
                    ListMarker::Bullet => colors.md_list_bullet.fg("•"),
                    ListMarker::Ordered(marker) => colors.md_list_bullet.fg(&marker),
                    ListMarker::Task(marker) => colors.md_list_bullet.fg(&marker.to_string()),
                };
                let prefix = format!("{}{} ", "  ".repeat(item.depth + 1), marker);
                list_continuation_indent = Some(visible_width(&prefix));
                push_wrapped_with_prefix(
                    &pad,
                    &prefix,
                    &self.render_inline(item.body),
                    cwidth,
                    &mut lines,
                );
            } else if let Some((depth, body)) = parse_blockquote(line) {
                list_continuation_indent = None;
                let border = colors.md_quote_border.fg("│");
                let prefix = format!("  {}", format!("{border} ").repeat(depth));
                let body = colors.md_quote.fg(&italic(&self.render_inline(body)));
                push_wrapped_with_prefix(&pad, &prefix, &body, cwidth, &mut lines);
            } else if line.trim().starts_with("---") || line.trim().starts_with("***") {
                list_continuation_indent = None;
                // Horizontal rule (capped like the TS reference), mdHr colored.
                let rule_w = width.min(80).saturating_sub(self.padding_x * 2);
                lines.push(format!(
                    "{pad}{}",
                    colors.md_hr.fg(&"─".repeat(rule_w.max(1)))
                ));
            } else if line.trim().is_empty() {
                list_continuation_indent = None;
                // Empty line — emit a (padded) blank so spacing is preserved.
                lines.push(String::new());
            } else if let Some(indent) =
                list_continuation_indent.filter(|_| line.starts_with(' ') || line.starts_with('\t'))
            {
                push_wrapped_with_prefix(
                    &pad,
                    &" ".repeat(indent),
                    &self.render_inline(line.trim()),
                    cwidth,
                    &mut lines,
                );
            } else {
                list_continuation_indent = None;
                // Regular text with inline formatting.
                push_wrapped(&pad, &self.render_inline(line), cwidth, &mut lines);
            }

            i += 1;
        }

        // Add bottom padding
        for _ in 0..self.padding_y {
            lines.push(String::new());
        }

        if lines.is_empty() {
            lines.push(String::new());
        }

        // Apply the configured base style (e.g. the dim italic thinking style)
        // per rendered line, re-opening it after every nested reset.
        if !self.options.base_style.is_empty() {
            for line in lines.iter_mut() {
                *line = self.apply_base_style(line);
            }
        }

        lines
    }

    /// Render inline CommonMark/GFM with terminal-specific ANSI styling.
    fn render_inline(&self, text: &str) -> String {
        let colors = theme().colors;
        let mut options = Options::empty();
        options.insert(Options::ENABLE_STRIKETHROUGH);

        // pulldown-cmark parses complete documents and has no inline-only
        // entry point. A plain prefix keeps block-looking text in inline
        // context; it is discarded from the first text event below.
        let source = format!("x {text}");
        let mut discard_prefix = true;
        let mut frames = vec![InlineFrame::root()];

        for event in Parser::new_ext(&source, options) {
            match event {
                Event::Start(Tag::Strong) => frames.push(InlineFrame::new(InlineKind::Bold)),
                Event::Start(Tag::Emphasis) => frames.push(InlineFrame::new(InlineKind::Italic)),
                Event::Start(Tag::Strikethrough) => {
                    frames.push(InlineFrame::new(InlineKind::Strike));
                }
                Event::Start(Tag::Link { dest_url, .. }) => {
                    frames.push(InlineFrame::new(InlineKind::Link(dest_url.into_string())))
                }
                Event::Start(Tag::Image { dest_url, .. }) => {
                    frames.push(InlineFrame::new(InlineKind::Image(dest_url.into_string())))
                }
                Event::End(
                    TagEnd::Strong
                    | TagEnd::Emphasis
                    | TagEnd::Strikethrough
                    | TagEnd::Link
                    | TagEnd::Image,
                ) => close_inline_frame(&mut frames, &colors),
                Event::Text(value) => {
                    let mut value = value.as_ref();
                    if discard_prefix {
                        value = value.strip_prefix("x ").unwrap_or(value);
                        discard_prefix = false;
                    }
                    frames
                        .last_mut()
                        .expect("root inline frame")
                        .text
                        .push_str(value);
                }
                Event::Code(code) => {
                    let chip = format!(" {} ", colors.md_code.fg(code.trim()));
                    frames
                        .last_mut()
                        .expect("root inline frame")
                        .text
                        .push_str(&colors.md_code_bg.bg(&chip));
                }
                Event::InlineMath(value) => frames
                    .last_mut()
                    .expect("root inline frame")
                    .text
                    .push_str(&format!("${value}$")),
                Event::DisplayMath(value) => frames
                    .last_mut()
                    .expect("root inline frame")
                    .text
                    .push_str(&format!("$${value}$$")),
                Event::Html(value) | Event::InlineHtml(value) => frames
                    .last_mut()
                    .expect("root inline frame")
                    .text
                    .push_str(&value),
                Event::FootnoteReference(label) => frames
                    .last_mut()
                    .expect("root inline frame")
                    .text
                    .push_str(&format!("[^{label}]")),
                Event::SoftBreak => frames.last_mut().expect("root inline frame").text.push(' '),
                Event::HardBreak => frames
                    .last_mut()
                    .expect("root inline frame")
                    .text
                    .push('\n'),
                Event::TaskListMarker(checked) => frames
                    .last_mut()
                    .expect("root inline frame")
                    .text
                    .push(if checked { '☒' } else { '☐' }),
                Event::Rule | Event::Start(_) | Event::End(_) => {}
            }
        }

        while frames.len() > 1 {
            close_inline_frame(&mut frames, &colors);
        }
        frames.pop().expect("root inline frame").text
    }
}

#[derive(Debug)]
enum InlineKind {
    Root,
    Bold,
    Italic,
    Strike,
    Link(String),
    Image(String),
}

#[derive(Debug)]
struct InlineFrame {
    kind: InlineKind,
    text: String,
}

impl InlineFrame {
    fn root() -> Self {
        Self::new(InlineKind::Root)
    }

    fn new(kind: InlineKind) -> Self {
        Self {
            kind,
            text: String::new(),
        }
    }
}

fn close_inline_frame(frames: &mut Vec<InlineFrame>, colors: &crate::theme::ThemeColors) {
    let Some(frame) = (frames.len() > 1).then(|| frames.pop()).flatten() else {
        return;
    };
    let rendered = match frame.kind {
        InlineKind::Root => frame.text,
        InlineKind::Bold => bold(&frame.text),
        InlineKind::Italic => italic(&frame.text),
        InlineKind::Strike => format!("\x1b[9m{}\x1b[29m", frame.text),
        InlineKind::Link(url) => {
            let label = colors.md_link.fg(&underline(&frame.text));
            if crate::ansi::strip_ansi(&frame.text) == url {
                label
            } else {
                format!("{label}{}", colors.md_link_url.fg(&format!(" ({url})")))
            }
        }
        InlineKind::Image(url) => {
            let alt = if frame.text.is_empty() {
                "image".to_string()
            } else {
                frame.text
            };
            format!("{alt}{}", colors.md_link_url.fg(&format!(" ({url})")))
        }
    };
    frames
        .last_mut()
        .expect("root inline frame")
        .text
        .push_str(&rendered);
}

enum ListMarker {
    Bullet,
    Ordered(String),
    Task(char),
}

struct ListItem<'a> {
    depth: usize,
    marker: ListMarker,
    body: &'a str,
}

/// Parse a Markdown list item, including indented/nested lists. The parser is
/// deliberately strict about the marker's following whitespace so ordinary
/// numeric text without a list marker is not rendered as a list.
fn parse_list_item(line: &str) -> Option<ListItem<'_>> {
    let leading = line.len() - line.trim_start_matches([' ', '\t']).len();
    let content = &line[leading..];
    let depth = line[..leading]
        .chars()
        .fold(0usize, |width, ch| width + if ch == '\t' { 4 } else { 1 })
        / 2;

    let (marker, body) = if let Some(rest) = content
        .strip_prefix("- ")
        .or_else(|| content.strip_prefix("* "))
        .or_else(|| content.strip_prefix("+ "))
    {
        if let Some(task_body) = rest.strip_prefix("[ ]") {
            (ListMarker::Task('☐'), task_body.trim_start())
        } else if let Some(task_body) = rest
            .strip_prefix("[x]")
            .or_else(|| rest.strip_prefix("[X]"))
        {
            (ListMarker::Task('☒'), task_body.trim_start())
        } else {
            (ListMarker::Bullet, rest)
        }
    } else {
        let marker_end = content
            .bytes()
            .take_while(|byte| byte.is_ascii_digit())
            .count();
        if marker_end == 0 {
            return None;
        }
        let marker_char = content.as_bytes().get(marker_end)?;
        if !matches!(marker_char, b'.' | b')')
            || !content
                .as_bytes()
                .get(marker_end + 1)
                .is_some_and(u8::is_ascii_whitespace)
        {
            return None;
        }
        (
            ListMarker::Ordered(content[..marker_end + 1].to_string()),
            content[marker_end + 2..].trim_start(),
        )
    };

    Some(ListItem {
        depth,
        marker,
        body,
    })
}

/// Parse one or more quote markers, accepting `>quote`, `> quote`, and nested
/// `> > quote` forms used by CommonMark renderers.
fn parse_blockquote(line: &str) -> Option<(usize, &str)> {
    let mut body = line.trim_start_matches([' ', '\t']);
    let mut depth = 0;
    while let Some(rest) = body.strip_prefix('>') {
        depth += 1;
        body = rest.strip_prefix(' ').unwrap_or(rest);
    }
    (depth > 0).then_some((depth, body))
}

/// If `line` is a ```` ``` ```` (or ```` ~~~ ````) fence, return the language
/// label (possibly empty). Returns `None` for non-fence lines.
fn fence_info(line: &str) -> Option<(char, String)> {
    let trimmed = line.trim_start();
    if trimmed.starts_with("```") {
        Some(('`', trimmed[3..].trim().to_string()))
    } else if trimmed.starts_with("~~~") {
        Some(('~', trimmed[3..].trim().to_string()))
    } else {
        None
    }
}

/// Render one physical code line on a subtle surface, without an outer frame.
fn push_code_line(
    line: &str,
    pad: &str,
    indent: &str,
    cwidth: usize,
    out: &mut Vec<String>,
    highlighter: Option<&mut crate::syntax_highlight::Highlighter>,
) {
    let colors = theme().colors;
    // `cwidth` excludes Markdown padding. The code surface starts after the
    // configured indent and fills the remaining width, including blank rows.
    let panel_width = cwidth.saturating_sub(visible_width(indent)).max(1);
    let body_width = panel_width.saturating_sub(2).max(1);
    let expanded = line.replace('\t', "    ");
    let clipped = truncate_to_width(&expanded, body_width, "…");
    // Syntax-highlight the clipped plain text, then apply the panel background.
    let styled = match highlighter {
        Some(h) => h.highlight(&clipped, &colors),
        None => colors.md_code_block.fg(&clipped),
    };
    let body = format!(" {styled}");
    let body =
        apply_background_to_line(&body, panel_width, |text| colors.md_code_block_bg.bg(text));
    out.push(format!("{pad}{indent}{body}"));
}

/// True when the whole line is a run of 1-2 fence chars (``/````/`~`/`~~`)
/// — a streamed, not-yet-complete closing fence. pi trims these (issue
/// #5825) so code blocks don't flicker/shrink while the final fence char
/// streams in; rendering them as text would also misrender the block tail.
fn is_partial_fence(line: &str) -> bool {
    let t = line.trim();
    if t.is_empty() || t.len() > 2 {
        return false;
    }
    t.chars().all(|c| c == '`' || c == '~')
}

/// Strip a leading `prefix` of `#`s followed by a space from `line`.
fn strip_header<'a>(line: &'a str, hashes: &str) -> Option<&'a str> {
    if line.starts_with(hashes) {
        let rest = &line[hashes.len()..];
        if let Some(stripped) = rest.strip_prefix(' ') {
            return Some(stripped);
        }
    }
    None
}

/// True if the line looks like a markdown table row (`| … | … |`).
fn is_table_row(line: &str) -> bool {
    let t = line.trim();
    t.starts_with('|') && t.ends_with('|') && t.len() > 1
}

/// True if the line is a table separator (`|---|---|`, `:--:` allowed).
fn is_table_separator(maybe: Option<&&str>) -> bool {
    match maybe {
        Some(line) => {
            let t = line.trim();
            if !t.contains('|') {
                return false;
            }
            let cell = |s: &str| {
                s.chars()
                    .all(|c| c == '-' || c == ':' || c == ' ' || c == '\t')
                    && s.contains('-')
            };
            let inner = t.trim_matches('|');
            inner.split('|').all(cell)
        }
        None => false,
    }
}

/// Parse a table into rendered lines with box-drawing borders.
fn render_table<F>(rows: &[&str], pad: &str, cwidth: usize, out: &mut Vec<String>, render_inline: F)
where
    F: Fn(&str) -> String,
{
    // Split each row into trimmed cells.
    let parse = |row: &str| -> Vec<String> {
        split_table_cells(row)
            .into_iter()
            .map(|cell| render_inline(cell.trim()))
            .collect()
    };
    if rows.len() < 2 {
        return;
    }
    let header = parse(rows[0]);
    let _separator = parse(rows[1]);
    let body: Vec<Vec<String>> = rows[2..].iter().map(|r| parse(r)).collect();
    let ncols = header.len();
    if ncols == 0 {
        return;
    }

    // Compute column visible widths from header + body.
    let mut col_w: Vec<usize> = (0..ncols)
        .map(|c| {
            std::iter::once(&header)
                .chain(body.iter())
                .map(|r| r.get(c).map(|s| visible_width(s)).unwrap_or(0))
                .max()
                .unwrap_or(0)
        })
        .collect();

    // Account for " | " separators + leading/trailing border usage.
    // We cap the total so the table fits within `cwidth`.
    let overhead = 3 * (ncols - 1) + 4; // approximate: "| " + " | "*n + " |"
    let budget = cwidth.saturating_sub(overhead);
    let total: usize = col_w.iter().sum();
    if total > budget {
        // Shrink proportionally (floor of 1 per column).
        let scale = budget as f64 / total as f64;
        for w in col_w.iter_mut() {
            *w = (*w as f64 * scale).round() as usize;
            if *w < 1 {
                *w = 1;
            }
        }
    }

    let join = |cells: &[String]| {
        cells
            .iter()
            .enumerate()
            .map(|(i, c)| {
                let w = col_w.get(i).copied().unwrap_or(0);
                let cell = truncate_to_width(c, w, "…");
                pad_cell(&cell, w)
            })
            .collect::<Vec<_>>()
            .join("│")
    };

    let border = |left: &str, mid: &str, joiner: &str, right: &str| -> String {
        let segs: Vec<String> = col_w.iter().map(|w| mid.repeat(*w)).collect();
        format!("{left}{}{right}", segs.join(joiner))
    };

    out.push(format!("{pad}{}", border("┌", "─", "┬", "┐")));
    out.push(format!("{pad}│{}│", join(&header)));
    out.push(format!("{pad}{}", border("├", "─", "┼", "┤")));
    for (row_index, row) in body.iter().enumerate() {
        let cells: Vec<String> = (0..ncols)
            .map(|c| row.get(c).cloned().unwrap_or_default())
            .collect();
        out.push(format!("{pad}│{}│", join(&cells)));
        // Keep the table grid visible between body rows as well as between the
        // header and the first row. This is especially useful for narrow
        // terminals where adjacent wrapped-looking rows are otherwise hard
        // to distinguish.
        if row_index + 1 < body.len() {
            out.push(format!("{pad}{}", border("├", "─", "┼", "┤")));
        }
    }
    out.push(format!("{pad}{}", border("└", "─", "┴", "┘")));
}

/// Split a table row without treating escaped pipes or pipes inside code spans
/// as column separators.
fn split_table_cells(row: &str) -> Vec<String> {
    let inner = row.trim().trim_matches('|');
    let mut cells = vec![String::new()];
    let mut escaped = false;
    let mut code_ticks = 0usize;

    for ch in inner.chars() {
        if escaped {
            cells.last_mut().expect("table has one cell").push(ch);
            escaped = false;
        } else if ch == '\\' {
            cells.last_mut().expect("table has one cell").push(ch);
            escaped = true;
        } else if ch == '`' {
            code_ticks ^= 1;
            cells.last_mut().expect("table has one cell").push(ch);
        } else if ch == '|' && code_ticks == 0 {
            cells.push(String::new());
        } else {
            cells.last_mut().expect("table has one cell").push(ch);
        }
    }
    cells
}

/// Left-pad/content a cell string to `w` columns (ANSI-aware).
fn pad_cell(cell: &str, w: usize) -> String {
    let vw = visible_width(cell);
    if vw >= w {
        cell.to_string()
    } else {
        format!("{cell}{}", " ".repeat(w - vw))
    }
}

/// Wrap `rendered` (an already-styled line possibly with leading pad) into the
/// available width and push each sub-line into `out`.
fn push_wrapped(pad: &str, rendered: &str, cwidth: usize, out: &mut Vec<String>) {
    if cwidth == 0 {
        out.push(rendered.to_string());
        return;
    }
    // Padding is layout chrome, not part of `rendered`; applying it here keeps
    // first and continuation lines aligned (the old renderer omitted padding
    // from the first line of ordinary paragraphs and headings).
    let wrapped = wrap_text_with_ansi(rendered, cwidth);
    if wrapped.is_empty() {
        out.push(String::new());
        return;
    }
    for sub in wrapped {
        out.push(format!("{pad}{sub}"));
    }
}

/// Wrap text after a semantic prefix (list bullet, quote border, etc.). The
/// first line gets the prefix; every continuation starts under the text rather
/// than under the marker, which makes long assistant responses much easier to
/// scan in a narrow terminal.
fn push_wrapped_with_prefix(
    pad: &str,
    prefix: &str,
    rendered: &str,
    cwidth: usize,
    out: &mut Vec<String>,
) {
    let prefix_width = visible_width(prefix);
    let body_width = cwidth.saturating_sub(prefix_width).max(1);
    let wrapped = wrap_text_with_ansi(rendered, body_width);
    if wrapped.is_empty() {
        out.push(format!("{pad}{prefix}"));
        return;
    }
    let continuation = " ".repeat(prefix_width);
    for (index, line) in wrapped.iter().enumerate() {
        let line_prefix = if index == 0 { prefix } else { &continuation };
        // `wrap_text_with_ansi` preserves the separating space at a wrap
        // boundary. It is useful for paragraphs, but here it would make a
        // continuation one column farther right than the list's text.
        let body = if index == 0 {
            line.as_str()
        } else {
            line.trim_start()
        };
        out.push(format!("{pad}{line_prefix}{body}"));
    }
}

impl Component for Markdown {
    fn render(&self, width: usize) -> Vec<String> {
        let content = self.content.lock().map(|c| c.clone()).unwrap_or_default();
        let theme_revision = crate::theme::theme_revision();

        if let Ok(cache) = self.cache.lock() {
            if let Some(cached) = cache.as_ref() {
                if cached.width == width
                    && cached.content == content
                    && cached.theme_revision == theme_revision
                {
                    return cached.lines.clone();
                }
            }
        }

        let lines = self.render_markdown(width);
        if let Ok(mut cache) = self.cache.lock() {
            *cache = Some(MarkdownCache {
                content,
                width,
                theme_revision,
                lines: lines.clone(),
            });
        }
        lines
    }

    fn invalidate(&self) {
        self.clear_cache();
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

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

    #[test]
    fn test_markdown_headers() {
        let md = Markdown::new("# H1\n## H2\n### H3\n#### H4\n##### H5\n###### H6", 0, 0);
        let lines = md.render(80);
        let plain: Vec<String> = lines
            .iter()
            .map(|line| crate::ansi::strip_ansi(line))
            .collect();
        assert_eq!(plain, vec!["H1", "H2", "H3", "H4", "H5", "H6"]);
    }

    #[test]
    fn test_commonmark_inline_parser_handles_nested_spans_and_images() {
        let md = Markdown::new(
            "This is ***nested***, ``a ` b``, <https://example.com>, ![plot](plot.png)",
            0,
            0,
        );
        let rendered = md.render(120).join("\n");
        let plain = crate::ansi::strip_ansi(&rendered);

        assert_eq!(
            plain,
            "This is nested,  a ` b , https://example.com, plot (plot.png)"
        );
        assert!(rendered.contains("\x1b[1m"), "nested strong style missing");
        assert!(rendered.contains("\x1b[3m"), "nested emphasis missing");
        assert!(
            rendered.contains("\x1b[48;2;48;52;59m"),
            "multi-backtick code span should use the code chip"
        );
    }

    #[test]
    fn test_markdown_inline() {
        let md = Markdown::new("This is **bold** and *italic* text", 0, 0);
        let lines = md.render(80);
        assert!(!lines[0].is_empty());
    }

    #[test]
    fn test_markdown_code() {
        let md = Markdown::new("Use `code` here", 0, 0);
        let lines = md.render(80);
        assert!(!lines[0].is_empty());
        assert!(
            lines[0].contains("\x1b[48;2;48;52;59m"),
            "inline code should use the theme chip background"
        );
    }

    #[test]
    fn test_markdown_no_panic_on_wide_cjk() {
        // A CJK + bold line at a narrow width used to panic via the byte-slice
        // truncation in the old renderer (markdown.rs:136).
        let md = Markdown::new("**你好世界**这是一段很长的中文内容需要自动换行", 1, 0);
        let lines = md.render(10);
        // Must not panic and must produce more than one wrapped line.
        assert!(lines.len() > 1);
    }

    #[test]
    fn test_markdown_wraps_long_line() {
        let long = "a".repeat(100);
        let md = Markdown::new(long, 0, 0);
        let lines = md.render(20);
        assert!(lines.len() > 1, "a 100-col line at width 20 should wrap");
    }

    #[test]
    fn test_markdown_code_block_has_background_without_frame() {
        let md = Markdown::new("```rust\nlet x = 1;\n```", 0, 0);
        let joined = md.render(80).join("\n");
        let plain = crate::ansi::strip_ansi(&joined);
        assert!(!plain.contains("rust"), "language label leaked: {plain}");
        assert!(plain.contains(" let x = 1;"), "missing code body: {plain}");
        assert!(
            !plain.contains(['╭', '╰', '│']),
            "code block must not draw an outer frame: {plain}"
        );
        assert!(
            joined.contains("\x1b[48;2;40;44;52m"),
            "code panel background missing: {joined:?}"
        );
        assert!(
            !plain.contains("```"),
            "literal fences should be hidden: {plain}"
        );
    }

    #[test]
    fn code_fence_language_metadata_is_not_rendered() {
        let md = Markdown::new(
            "```text\nplain block\n```\n\n```bash\necho hello\n```",
            0,
            0,
        );
        let plain = crate::ansi::strip_ansi(&md.render(80).join("\n"));
        assert!(plain.contains("plain block"));
        assert!(plain.contains("echo hello"));
        assert!(!plain.contains("text"), "text label leaked: {plain}");
        assert!(!plain.contains("bash"), "bash label leaked: {plain}");
    }

    #[test]
    fn test_mermaid_fence_uses_diagram_renderer() {
        let md = Markdown::new("```mermaid\nflowchart LR\nA[Start] --> B[End]\n```", 0, 0);
        let plain = crate::ansi::strip_ansi(&md.render(80).join("\n"));
        assert!(plain.contains("mermaid"));
        assert!(
            plain.contains("Start ──▶ End"),
            "diagram body missing: {plain}"
        );
        assert!(
            !plain.contains("flowchart LR"),
            "raw mermaid header leaked: {plain}"
        );
    }

    #[test]
    fn test_markdown_padding_applies_to_first_and_wrapped_lines() {
        let md = Markdown::new("abcdefgh", 2, 0);
        let lines = md.render(6);
        assert_eq!(lines, vec!["  ab", "  cd", "  ef", "  gh"]);
    }

    #[test]
    fn test_markdown_code_expands_tabs_and_clips() {
        let md = Markdown::new("```\n\tlet value = 123456;\n```", 0, 0);
        let lines = md.render(14);
        let plain: Vec<String> = lines
            .iter()
            .map(|line| crate::ansi::strip_ansi(line))
            .collect();
        assert!(
            plain[0].starts_with("       let"),
            "tab/indent lost: {plain:?}"
        );
        assert!(
            plain[0].contains('…'),
            "long code line should clip: {plain:?}"
        );
        assert!(plain.iter().all(|line| visible_width(line) <= 14));
    }

    #[test]
    fn test_markdown_task_list_checkbox() {
        let md = Markdown::new("- [x] done\n- [ ] todo", 0, 0);
        let joined = md.render(80).join("\n");
        assert!(joined.contains('☒'), "checked marker missing");
        assert!(joined.contains('☐'), "unchecked marker missing");
    }

    #[test]
    fn test_markdown_table_renders_borders() {
        let md = Markdown::new("| a | b |\n|---|---|\n| 1 | 2 |", 0, 0);
        let joined = md.render(80).join("\n");
        assert!(joined.contains('┌'), "missing top-left");
        assert!(joined.contains('┬'), "missing top-mid");
        assert!(joined.contains('┐'), "missing top-right");
        assert!(joined.contains('└'), "missing bottom-left");
    }

    #[test]
    fn test_markdown_table_has_internal_horizontal_lines() {
        let md = Markdown::new(
            "| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n| 5 | 6 |",
            0,
            0,
        );
        let plain = crate::ansi::strip_ansi(&md.render(80).join("\n"));
        assert_eq!(
            plain.matches('├').count(),
            3,
            "missing internal row lines: {plain}"
        );
        assert_eq!(
            plain.matches('┼').count(),
            3,
            "missing internal separators: {plain}"
        );
    }

    #[test]
    fn test_markdown_double_underscore_is_bold() {
        let md = Markdown::new("__strong__", 0, 0);
        let joined = md.render(80).join("\n");
        // `\x1b[1m` is the bold SGR; `\x1b[4m` is underline.
        assert!(joined.contains("\x1b[1m"), "`__` should render bold");
        assert!(
            !joined.contains("\x1b[4m"),
            "`__` should NOT render underline"
        );
    }

    #[test]
    fn test_markdown_hr_capped() {
        let md = Markdown::new("---", 0, 0);
        let lines = md.render(200);
        // HR is capped at 80 cols, not the full 200.
        assert_eq!(visible_width(&lines[0]), 80);
    }

    #[test]
    fn test_markdown_h4_does_not_fall_through() {
        let md = Markdown::new("#### nested", 0, 0);
        let joined = md.render(80).join("\n");
        assert!(joined.contains("\x1b[1m"), "h4 should be bold");
    }

    #[test]
    fn test_markdown_nested_lists_keep_their_text_indent_when_wrapped() {
        let md = Markdown::new(
            "- parent item that wraps over several terminal columns\n  - child item\n    child continuation",
            0,
            0,
        );
        let plain: Vec<String> = md
            .render(20)
            .iter()
            .map(|line| crate::ansi::strip_ansi(line))
            .collect();

        assert!(
            plain[0].starts_with("  • "),
            "root marker missing: {plain:?}"
        );
        assert!(
            plain.iter().any(|line| line.starts_with("    wraps")),
            "wrapped root text should align after its marker: {plain:?}"
        );
        assert!(
            plain.iter().any(|line| line.starts_with("    • child")),
            "nested marker missing: {plain:?}"
        );
        assert!(
            plain.iter().any(|line| line.starts_with("      child")),
            "continuation should align after nested marker: {plain:?}"
        );
    }

    #[test]
    fn test_markdown_nested_blockquote_and_unclosed_inline_are_literal() {
        let md = Markdown::new(
            "> > nested quote\ntext with *an unfinished emphasis and `unfinished code",
            0,
            0,
        );
        let plain: Vec<String> = md
            .render(80)
            .iter()
            .map(|line| crate::ansi::strip_ansi(line))
            .collect();
        assert!(plain[0].starts_with("  │ │ nested quote"), "{plain:?}");
        assert_eq!(
            plain[1],
            "text with *an unfinished emphasis and `unfinished code"
        );
    }

    #[test]
    fn test_markdown_table_preserves_pipes_in_inline_code() {
        let md = Markdown::new("| Name | Value |\n|---|---|\n| **bold** | `a|b` |", 0, 0);
        let plain = crate::ansi::strip_ansi(&md.render(80).join("\n"));
        assert_eq!(
            plain.matches('┬').count(),
            1,
            "table columns split incorrectly: {plain}"
        );
        assert!(plain.contains("bold"), "inline formatting lost: {plain}");
        assert!(
            plain.contains("a|b"),
            "code pipe split a table cell: {plain}"
        );
    }

    #[test]
    fn test_base_style_reopened_after_inline_code_reset() {
        // Regression: inline code (and other colored spans) terminate with an
        // `SGR 0` reset, which used to drop the enclosing base style for the
        // rest of the line. The base must be re-opened after that reset.
        let base = "\x1b[3m\x1b[38;5;244m";
        let md = Markdown::new("think `code` after", 0, 0).with_base_style(base);
        let rendered = md.render(80).join("\n");
        let after = rendered
            .split("code")
            .nth(1)
            .expect("inline code not rendered");
        assert!(
            after.contains("\x1b[38;5;244m"),
            "base style not reopened after inline code: {rendered:?}"
        );
        assert!(
            rendered.ends_with("\x1b[0m"),
            "rendered line must be reset-terminated: {rendered:?}"
        );
    }

    #[test]
    fn test_base_style_applies_to_every_line() {
        // Multi-paragraph thinking must carry the base style on every line,
        // not just the first text run.
        let base = "\x1b[3m\x1b[38;5;244m";
        let md = Markdown::new("first thought\n\nsecond thought", 0, 0).with_base_style(base);
        let lines = md.render(80);
        for line in lines.iter().filter(|l| !l.is_empty()) {
            assert!(
                line.contains("\x1b[38;5;244m"),
                "base style missing on line: {line:?}"
            );
        }
    }
}