atomcode-tuix 4.23.1

Open-source terminal AI coding 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
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
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
// crates/atomcode-tuix/src/markdown.rs
//
// Line-oriented markdown renderer. Handles:
//   **bold** / *italic* / `code` (inline)
//   # / ## / ### headings
//   - / * bullet lists
//   ```fenced code blocks``` (state-tracked)
//   --- horizontal rules
// Tables are passed through as raw text (pipes show literally).

use crate::highlight::theme;
use crate::terminal::TerminalCaps;

/// Parser state maintained across lines of a streamed response.
#[derive(Default)]
pub struct MdState {
    pub in_code_block: bool,
    /// Accumulates consecutive `|…|` rows; flushed as an aligned block
    /// when a non-table line arrives.
    pub table_buf: Vec<String>,
    /// Lines accumulated between an opening and closing code fence.
    /// Flushed through `highlight::highlight_block` on close fence so
    /// the syntax highlighter sees the whole block at once. Code thus
    /// appears in one chunk at fence close rather than streaming
    /// line-by-line.
    pub code_buf: Vec<String>,
    /// Language tag captured from the opening fence (`"rust"` from
    /// ```` ```rust ````). `None` for fences with no tag.
    pub code_lang: Option<String>,
}

impl MdState {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn reset(&mut self) {
        self.in_code_block = false;
        self.table_buf.clear();
        self.code_buf.clear();
        self.code_lang = None;
    }
}

/// Render one complete line with block- and inline-level markdown applied.
/// Returns None if the line should be omitted from output (e.g., a fence
/// marker ``` that toggles code-block state but isn't itself visible text).
pub fn render_line(line: &str, state: &mut MdState, caps: TerminalCaps) -> Option<String> {
    render_line_with_width(line, state, caps, 0)
}

/// Width-aware variant of [`render_line`]. When `max_width > 0`, a flushed
/// table's column widths are capped so every line fits the budget — otherwise
/// `wrap_cells_to_width` downstream chops long rows and shatters the table's
/// border structure. `max_width = 0` keeps legacy behaviour.
pub fn render_line_with_width(
    line: &str,
    state: &mut MdState,
    caps: TerminalCaps,
    max_width: usize,
) -> Option<String> {
    let trimmed = line.trim();

    // Table row: buffer and defer emit until block ends.
    if !state.in_code_block && trimmed.starts_with('|') {
        state.table_buf.push(trimmed.to_string());
        return None;
    }

    // Pre-drawn Unicode box-drawing table row (`┌─┬─┐ │ ├─┼─┤ └─┴─┘`).
    // Some models — usually weaker ones mimicking earlier-turn output that
    // we ourselves rendered — emit tables fully drawn in box characters
    // instead of `|`-form markdown. Without detection, those rows fall
    // through to the inline-only branch and `push_markdown_body`'s
    // wrap-at-cell-level chops them at terminal width, shattering the
    // borders (the macOS overflow case in the screenshot). Convert each
    // row to the equivalent pipe form (│ → |, ─ → -, junctions → |) and
    // route through the same buffer + flush path the `|`-form takes;
    // `flush_aligned_table_with_width` then enforces flat-mode fallback
    // for narrow terminals exactly like a real markdown table would get.
    if !state.in_code_block {
        if let Some(converted) = box_drawing_table_row(trimmed) {
            state.table_buf.push(converted);
            return None;
        }
    }

    // Non-table line arriving after buffered rows: flush as aligned block.
    let prefix = if !state.table_buf.is_empty() {
        let t = flush_aligned_table_with_width(&state.table_buf, caps, max_width);
        state.table_buf.clear();
        Some(t)
    } else {
        None
    };
    let prepend = |body: String| -> String {
        match prefix.as_ref() {
            Some(p) => format!("{}\n{}", p, body),
            None => body,
        }
    };
    let prefix_only = || -> Option<String> { prefix.as_ref().map(|p| p.clone()) };

    // Fenced code block fence (``` or ~~~).
    //
    // OPEN fence: capture the language tag (e.g., `rust` in ```rust),
    // start buffering body lines into `state.code_buf`. We don't emit
    // anything for the body until close fence — the syntax highlighter
    // needs the whole block at once to classify multi-line strings /
    // block comments correctly.
    //
    // CLOSE fence: flush the buffered block through `highlight::highlight_block`,
    // which handles caps gating (no-color path returns plain 2-space-indented
    // text, matching the pre-existing CC-style behavior).
    if is_fence(trimmed) {
        if state.in_code_block {
            // CLOSE
            let source = state.code_buf.join("\n");
            let highlighted = crate::highlight::highlight_block(
                state.code_lang.as_deref(),
                &source,
                caps,
            );
            state.in_code_block = false;
            state.code_buf.clear();
            state.code_lang = None;
            return Some(prepend(highlighted));
        } else {
            // OPEN — extract optional language tag.
            state.in_code_block = true;
            state.code_lang = parse_fence_lang(trimmed);
            state.code_buf.clear();
            return prefix_only();
        }
    }

    // Inside code block: buffer the line, defer rendering until close fence.
    // No per-line output; the highlighter needs full context.
    if state.in_code_block {
        state.code_buf.push(line.to_string());
        return prefix_only();
    }

    // Horizontal rule — render as a blank separator line, not a visible
    // rule. A horizontal bar overwhelms the surrounding prose; a blank line
    // communicates the same thematic break far more gracefully.
    if is_hrule(trimmed) {
        return Some(prepend(String::new()));
    }

    // Heading — H1-H3 get bold + bright cyan (Palette::ACCENT, SGR 96)
    // so headings sit on their own colour layer above the default-colour
    // body. Bright cyan was chosen over bright magenta (BRAND, 95)
    // because terminals that remap bright white (97, used by inline code
    // and code blocks) to lavender — Catppuccin / Tokyo Night / similar
    // — typically remap bright magenta to the same lavender, which
    // would collapse heading colour into the inline-code colour.
    // Cyan stays hue-distinct on those palettes and on plain ANSI.
    // H4+ keeps italic-only so the deep-hierarchy levels still read as
    // "weaker than a real heading" without adding a third colour tier.
    if let Some((level, rest)) = parse_heading(line) {
        let inner = render_inline(rest, caps);
        let body = if !caps.colors {
            format!("{} {}", "#".repeat(level as usize), inner)
        } else {
            match level {
                1 | 2 | 3 => format!("{}{}{}", theme::md_heading_open(), inner, theme::MD_HEADING_CLOSE),
                _ => format!("{}{}{}", theme::MD_ITALIC_OPEN, inner, theme::MD_ITALIC_CLOSE),
            }
        };
        return Some(prepend(body));
    }

    // List (unordered or ordered): `- text` / `* text` / `1. text`
    // Marker (• / 1.) rendered in muted gray so it sits quietly next to
    // the default-fg body text — visually distinct without adding another
    // bright colour tier. The space after the marker keeps readability.
    if let Some(item) = parse_list_item(line) {
        let inner = render_inline(&item.rest, caps);
        let indent = " ".repeat(item.indent);
        let body = if caps.colors {
            format!(
                "{}{}{}{}{}",
                indent, theme::MD_MUTED_OPEN, item.marker, theme::MD_MUTED_CLOSE, inner
            )
        } else {
            format!("{}{} {}", indent, item.marker, inner)
        };
        return Some(prepend(body));
    }

    // Default: inline-only
    Some(prepend(render_inline(line, caps)))
}

/// Emit any still-buffered block (e.g., a table that ended without a
/// following non-table line). Call at stream end.
pub fn finalize(state: &mut MdState, caps: TerminalCaps) -> Option<String> {
    finalize_with_width(state, caps, 0)
}

/// Width-aware variant of [`finalize`]. See [`render_line_with_width`].
pub fn finalize_with_width(
    state: &mut MdState,
    caps: TerminalCaps,
    max_width: usize,
) -> Option<String> {
    // Two independent buffers can be open at stream end: a table waiting
    // for a separator row, or a code block whose close fence never came.
    // Both must be emitted so the user doesn't lose content.
    let table_part = if !state.table_buf.is_empty() {
        let t = flush_aligned_table_with_width(&state.table_buf, caps, max_width);
        state.table_buf.clear();
        Some(t)
    } else {
        None
    };

    let code_part = if state.in_code_block && !state.code_buf.is_empty() {
        let source = state.code_buf.join("\n");
        let highlighted = crate::highlight::highlight_block(
            state.code_lang.as_deref(),
            &source,
            caps,
        );
        state.in_code_block = false;
        state.code_buf.clear();
        state.code_lang = None;
        Some(highlighted)
    } else {
        None
    };

    match (table_part, code_part) {
        (None, None) => None,
        (Some(t), None) => Some(t),
        (None, Some(c)) => Some(c),
        (Some(t), Some(c)) => Some(format!("{}\n{}", t, c)),
    }
}

/// Recognise a pre-drawn Unicode box-drawing table line and return the
/// equivalent `|`-pipe form so it can join the same buffering path as
/// real markdown tables. Returns None for lines that aren't part of a box
/// table.
///
/// Two row shapes accepted:
///   1. **Data row** — starts with `│`. Each `│` becomes `|`; cell content
///      passes through unchanged. Caller buffers the result and the
///      existing flush logic splits on `|` and trims as usual.
///   2. **Border row** — starts with `┌`/`├`/`└` AND every char is in the
///      box-drawing set (`─┌┬┐├┼┤└┴┘`) plus spaces. Junctions become `|`
///      and `─` becomes `-`, producing a `|---|---|`-style separator that
///      `flush_aligned_table_with_width`'s `is_sep` matcher already
///      recognises (its predicate is `[-: ]+` per cell).
///
/// The "every char is box-drawing" guard on border rows defends against
/// false positives: a stray paragraph that happens to begin with `├` for
/// some unrelated reason would NOT match (it has letters too).
fn box_drawing_table_row(trimmed: &str) -> Option<String> {
    let first = trimmed.chars().next()?;
    match first {
        '' => Some(trimmed.replace('', "|")),
        '' | '' | '' => {
            if trimmed.chars().all(|c| {
                matches!(
                    c,
                    '' | '' | '' | '' | '' | '' | '' | '' | '' | '' | ' '
                )
            }) {
                let converted: String = trimmed
                    .chars()
                    .map(|c| match c {
                        '' | '' | '' | '' | '' | '' | '' | '' | '' => '|',
                        '' => '-',
                        other => other,
                    })
                    .collect();
                Some(converted)
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Flush a buffered markdown table as a column-aligned block. Computes the
/// max display width per column, pads every cell accordingly, renders with
/// `│`/`┼`/`─` box chars in muted gray. Inline markdown inside cells is
/// honoured.
pub fn flush_aligned_table(rows: &[String], caps: TerminalCaps) -> String {
    flush_aligned_table_with_width(rows, caps, 0)
}

/// Width-aware variant. When `max_width > 0` and the table can't fit at its
/// natural column widths, fall back to a flat key/value record format
/// (`header: cell` per line, blank line between rows) so no information is
/// lost to per-cell truncation. `max_width = 0` keeps box-table rendering
/// at natural widths regardless of size.
pub fn flush_aligned_table_with_width(
    rows: &[String],
    caps: TerminalCaps,
    max_width: usize,
) -> String {
    // Parse each row: strip leading/trailing '|', split by '|', trim cells.
    let parsed: Vec<Vec<String>> = rows
        .iter()
        .map(|r| {
            let s = r.trim_start_matches('|').trim_end_matches('|');
            s.split('|').map(|c| c.trim().to_string()).collect()
        })
        .collect();

    // Identify separator row(s) — cells match `[-: ]+` only.
    let is_sep = |row: &[String]| -> bool {
        row.iter()
            .all(|c| !c.is_empty() && c.chars().all(|ch| matches!(ch, '-' | ':' | ' ')))
    };

    let ncols = parsed.iter().map(|r| r.len()).max().unwrap_or(0);
    if ncols == 0 {
        return String::new();
    }

    // Compute natural column widths from non-separator rows. We do NOT cap
    // these — the cap-and-truncate-with-… approach the previous code took
    // chopped real content out of cells and made wide tables in narrow
    // terminals unreadable. Instead, if the natural table doesn't fit, the
    // flat-mode fallback below renders every cell in full.
    let mut col_widths = vec![0usize; ncols];
    for row in &parsed {
        if is_sep(row) {
            continue;
        }
        for (j, cell) in row.iter().enumerate() {
            if j >= ncols {
                break;
            }
            let plain = strip_md_for_width(cell);
            let w = crate::width::display_width(&plain);
            col_widths[j] = col_widths[j].max(w);
        }
    }

    // Total width of one rendered row at natural widths:
    //   `│` + per-col ` cell ` + `│` between/after each col
    //   = 1 + sum(w + 3 for w in col_widths)
    // If this exceeds the terminal budget, switch to flat mode.
    let natural_row_width: usize = 1 + col_widths.iter().map(|w| w + 3).sum::<usize>();
    if max_width > 0 && natural_row_width > max_width {
        return render_flat_table(&parsed, caps);
    }

    // Bright-black / DarkGrey (SGR 90) — table borders are chrome,
    // not content. Cyan (SGR 96) made them collide with the input
    // box separator and the inline-code colour, collapsing the
    // visual hierarchy. Gray reads as quiet structure and lets
    // header text + cell content carry the visual weight.
    let border_on = if caps.colors { theme::MD_MUTED_OPEN } else { "" };
    let border_off = if caps.colors { theme::MD_MUTED_CLOSE } else { "" };

    // Draw a horizontal rule row with given connector characters.
    let rule = |left: char, mid: char, right: char| -> String {
        let mut s = String::new();
        s.push_str(border_on);
        s.push(left);
        for (j, w) in col_widths.iter().enumerate() {
            for _ in 0..(w + 2) {
                s.push('');
            }
            if j + 1 < col_widths.len() {
                s.push(mid);
            }
        }
        s.push(right);
        s.push_str(border_off);
        s
    };

    let data_rows: Vec<&Vec<String>> = parsed.iter().filter(|r| !is_sep(r)).collect();

    let mut out = String::new();
    // Top border: ┌─┬─┐
    out.push_str(&rule('', '', ''));
    out.push('\n');

    for (i, row) in data_rows.iter().enumerate() {
        // Data row: │ cell │ cell │
        out.push_str(border_on);
        out.push('');
        out.push_str(border_off);
        for (j, w) in col_widths.iter().enumerate() {
            let cell = row.get(j).map(|s| s.as_str()).unwrap_or("");
            let plain_w = crate::width::display_width(&strip_md_for_width(cell));
            let body = render_inline(cell, caps);
            out.push(' ');
            out.push_str(&body);
            let pad = w.saturating_sub(plain_w);
            for _ in 0..pad {
                out.push(' ');
            }
            out.push(' ');
            out.push_str(border_on);
            out.push('');
            out.push_str(border_off);
        }
        out.push('\n');

        // Separator between every pair of rows: ├─┼─┤
        if i + 1 < data_rows.len() {
            out.push_str(&rule('', '', ''));
            out.push('\n');
        }
    }

    // Bottom border: └─┴─┘
    out.push_str(&rule('', '', ''));
    out
}

/// Narrow-terminal fallback for tables that can't fit at natural column
/// widths. Each data row is expanded into N lines of `header:cell` (one
/// per column), with a blank line between successive rows. Soft-wrapping
/// of long lines is left to the caller's downstream wrap stage so the
/// terminal width budget is honoured without losing any cell content.
fn render_flat_table(parsed: &[Vec<String>], caps: TerminalCaps) -> String {
    let is_sep = |row: &[String]| -> bool {
        row.iter()
            .all(|c| !c.is_empty() && c.chars().all(|ch| matches!(ch, '-' | ':' | ' ')))
    };
    let has_sep = parsed.iter().any(|r| is_sep(r));
    let mut data_iter = parsed.iter().filter(|r| !is_sep(r));

    // First non-sep row is treated as headers when a separator exists.
    // Without a separator the source isn't a real markdown table (it's
    // just `|` lines); fall back to printing every cell with no label.
    let headers: Vec<String> = if has_sep {
        match data_iter.next() {
            Some(h) => h.clone(),
            None => return String::new(),
        }
    } else {
        Vec::new()
    };

    let ncols = parsed.iter().map(|r| r.len()).max().unwrap_or(0);
    let mut out = String::new();
    let mut first = true;
    for row in data_iter {
        if !first {
            out.push('\n');
        }
        first = false;
        for j in 0..ncols {
            let cell = row.get(j).map(|s| s.as_str()).unwrap_or("");
            let cell_rendered = render_inline(cell, caps);
            if let Some(header) = headers.get(j) {
                let h_rendered = render_inline(header, caps);
                out.push_str(&h_rendered);
                out.push('');
                out.push_str(&cell_rendered);
            } else {
                out.push_str(&cell_rendered);
            }
            out.push('\n');
        }
    }
    // Drop the trailing newline so the caller's `format!("{}\n{}", t, body)`
    // doesn't sprinkle an extra blank line after the block.
    if out.ends_with('\n') {
        out.pop();
    }
    out
}

fn strip_md_for_width(s: &str) -> String {
    // Remove markdown markers that add bytes but no display width.
    s.replace("**", "").replace('`', "")
}

/// Legacy single-line inline renderer — kept for direct callers (tests,
/// simple assistant lines). Does not track block state.
pub fn render_inline_line(line: &str, caps: TerminalCaps) -> String {
    render_inline(line, caps)
}

// ─── Helpers ───

fn render_inline(line: &str, caps: TerminalCaps) -> String {
    if !caps.colors {
        return line.to_string();
    }
    let mut out = String::with_capacity(line.len() + 16);
    let mut chars = line.chars().peekable();

    while let Some(c) = chars.next() {
        match c {
            '*' => {
                if chars.peek() == Some(&'*') {
                    chars.next();
                    let mut inner = String::new();
                    let mut closed = false;
                    while let Some(&p) = chars.peek() {
                        if p == '*' {
                            chars.next();
                            if chars.peek() == Some(&'*') {
                                chars.next();
                                closed = true;
                                break;
                            } else {
                                inner.push('*');
                            }
                        } else {
                            chars.next();
                            inner.push(p);
                        }
                    }
                    if closed && !inner.is_empty() {
                        out.push_str(theme::MD_BOLD_OPEN);
                        out.push_str(&inner);
                        out.push_str(theme::MD_BOLD_CLOSE);
                    } else {
                        out.push_str("**");
                        out.push_str(&inner);
                    }
                } else {
                    let mut inner = String::new();
                    let mut closed = false;
                    while let Some(&p) = chars.peek() {
                        chars.next();
                        if p == '*' {
                            closed = true;
                            break;
                        }
                        inner.push(p);
                    }
                    if closed && !inner.is_empty() {
                        out.push_str(theme::MD_ITALIC_OPEN);
                        out.push_str(&inner);
                        out.push_str(theme::MD_ITALIC_CLOSE);
                    } else {
                        out.push('*');
                        out.push_str(&inner);
                    }
                }
            }
            '`' => {
                let mut inner = String::new();
                let mut closed = false;
                while let Some(&p) = chars.peek() {
                    chars.next();
                    if p == '`' {
                        closed = true;
                        break;
                    }
                    inner.push(p);
                }
                if closed && !inner.is_empty() {
                    // Bold + bright cyan (SGR 1;96). Earlier iterations
                    // used bold-only (`\x1b[1m`), bright-white
                    // (`\x1b[1;97m`), and truecolor blue-500
                    // (`\x1b[1;38;2;59;130;246m`). Bold-only was too
                    // subtle — in long mixed output, inline code
                    // `path/to/foo.rs` was visually indistinguishable
                    // from **bold** prose. Bright cyan (96) matches the
                    // heading and code-block accent colour; it's a 16-colour
                    // SGR interpreted by the terminal's own theme palette,
                    // so it adapts to both light and dark backgrounds
                    // (same reason `Palette::CODE` uses SGR 96). The
                    // close sequence `\x1b[22;39m` resets both bold
                    // (SGR 22) and fg (SGR 39) so neither bleeds into
                    // the next span.
                    out.push_str(theme::md_inline_code_open());
                    out.push_str(&inner);
                    out.push_str(theme::MD_INLINE_CODE_CLOSE);
                } else {
                    out.push('`');
                    out.push_str(&inner);
                }
            }
            _ => out.push(c),
        }
    }
    out
}

fn is_fence(trimmed: &str) -> bool {
    let mut chars = trimmed.chars();
    match chars.next() {
        Some('`') => {
            trimmed.len() >= 3 && trimmed.as_bytes()[1] == b'`' && trimmed.as_bytes()[2] == b'`'
        }
        Some('~') => {
            trimmed.len() >= 3 && trimmed.as_bytes()[1] == b'~' && trimmed.as_bytes()[2] == b'~'
        }
        _ => false,
    }
}

/// Extract the language tag from an opening fence line. Handles both
/// backtick and tilde fences; returns `None` if no tag is present or
/// the line is just the fence character.
///
/// Examples:
///   "```rust"        -> Some("rust")
///   "```rust  "      -> Some("rust")
///   "```Rust"        -> Some("rust")     ← lowercased
///   "```"            -> None
///   "~~~python"      -> Some("python")
fn parse_fence_lang(trimmed: &str) -> Option<String> {
    let after = trimmed
        .trim_start_matches('`')
        .trim_start_matches('~')
        .trim();
    if after.is_empty() {
        None
    } else {
        Some(after.to_lowercase())
    }
}

fn is_hrule(trimmed: &str) -> bool {
    if trimmed.len() < 3 {
        return false;
    }
    let first = trimmed.chars().next().unwrap();
    if first != '-' && first != '*' && first != '_' {
        return false;
    }
    let mut n = 0;
    for c in trimmed.chars() {
        if c == first {
            n += 1;
        } else if !c.is_whitespace() {
            return false;
        }
    }
    n >= 3
}

fn parse_heading(line: &str) -> Option<(u8, &str)> {
    let line = line.trim_start();
    let mut level = 0u8;
    for c in line.chars() {
        if c == '#' && level < 6 {
            level += 1;
        } else if level > 0 && c == ' ' {
            let content = &line[(level as usize) + 1..];
            return Some((level, content));
        } else {
            return None;
        }
    }
    None
}

/// Parsed list item: indent level, the marker string (e.g. "•", "1."),
/// and the remaining text after the marker.
struct ParsedListItem {
    indent: usize,
    marker: String,
    rest: String,
}

fn parse_list_item(line: &str) -> Option<ParsedListItem> {
    let indent = line.chars().take_while(|c| *c == ' ').count();
    let rest = &line[indent..];

    // Unordered: "- text" / "* text"
    if let Some(r) = rest.strip_prefix("- ").or_else(|| rest.strip_prefix("* ")) {
        return Some(ParsedListItem {
            indent,
            marker: "".to_string(),
            rest: r.to_string(),
        });
    }

    // Ordered: "1. text" / "12. text" — one or more digits followed by ". "
    let digits_end = rest.chars().take_while(|c| c.is_ascii_digit()).count();
    if digits_end > 0 {
        let after_digits = &rest[digits_end..];
        if let Some(r) = after_digits.strip_prefix(". ") {
            let marker = &rest[..digits_end]; // "1", "12", etc.
            return Some(ParsedListItem {
                indent,
                marker: format!("{}.", marker),
                rest: r.to_string(),
            });
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::highlight::theme;
    use crate::terminal::{EnvView, TerminalCaps};

    fn caps() -> TerminalCaps {
        TerminalCaps::from_env(EnvView {
            is_stdout_tty: true,
            term: Some("xterm-256color".to_string()),
            colorterm: Some("truecolor".to_string()),
            lang: Some("en_US.UTF-8".to_string()),
            ..Default::default()
        })
    }
    fn plain_caps() -> TerminalCaps {
        TerminalCaps::from_env(EnvView {
            is_stdout_tty: true,
            no_color: true,
            term: Some("xterm".to_string()),
            lang: Some("en_US.UTF-8".to_string()),
            ..Default::default()
        })
    }

    #[test]
    fn inline_bold() {
        assert_eq!(
            render_inline_line("**bold**", caps()),
            format!("{}bold{}", theme::MD_BOLD_OPEN, theme::MD_BOLD_CLOSE)
        );
    }

    #[test]
    fn inline_italic() {
        assert_eq!(render_inline_line("*em*", caps()), format!("{}em{}", theme::MD_ITALIC_OPEN, theme::MD_ITALIC_CLOSE));
    }

    #[test]
    fn inline_code() {
        // Inline code uses bold + bright cyan. This matches
        // the heading and code-block accent colour. The close sequence
        // resets both bold and fg.
        let rendered = render_inline_line("`x`", caps());
        assert!(
            rendered.contains(theme::md_inline_code_open()),
            "inline code must open with MD_INLINE_CODE_OPEN: {}",
            rendered
        );
        assert!(
            rendered.contains(theme::MD_INLINE_CODE_CLOSE),
            "inline code must close with MD_INLINE_CODE_CLOSE: {}",
            rendered
        );
        assert!(
            !rendered.contains("\x1b[1;97m"),
            "inline code must NOT include bright-white SGR 97: {}",
            rendered
        );
        assert!(
            !rendered.contains("\x1b[1;38;2;"),
            "inline code must NOT include truecolor RGB: {}",
            rendered
        );
    }

    #[test]
    fn fenced_code_block_colors_off_renders_plain_indented() {
        // With NO_COLOR / non-TTY caps, code blocks remain plain 2-space-indented
        // text with NO ANSI bytes. Pins the no-color invariant.
        let mut state = MdState::new();
        let _ = render_line("```", &mut state, plain_caps()); // open fence, no lang
        assert!(render_line("let x = 1;", &mut state, plain_caps()).is_none());
        let out = render_line("```", &mut state, plain_caps()).unwrap();
        assert!(
            out.contains("  let x = 1;"),
            "code body must appear with 2-space indent: {:?}",
            out
        );
        assert!(
            !out.contains('\x1b'),
            "colors-off must emit zero ANSI bytes: {:?}",
            out
        );
        assert!(!out.contains(''), "no `│` gutter glyph: {:?}", out);
    }

    #[test]
    fn fenced_code_block_colors_on_emits_truecolor_for_known_lang() {
        // With colors enabled and a known language tag, the close-fence
        // flush must include at least one truecolor SGR (theme color).
        // We don't assert exact bytes — the palette is intentionally
        // free to evolve in `highlight::theme`.
        let mut state = MdState::new();
        let _ = render_line("```rust", &mut state, caps());
        assert!(render_line("fn main() {}", &mut state, caps()).is_none());
        let out = render_line("```", &mut state, caps()).unwrap();
        assert!(out.contains("  "), "indent preserved: {:?}", out);
        assert!(
            out.contains("\x1b[38;2;"),
            "expected at least one truecolor SGR, got: {:?}",
            out
        );
    }

    #[test]
    fn fenced_code_block_unknown_lang_falls_back_to_plain_indent() {
        // Unknown lang tag → syntect's find_syntax_by_token returns None
        // → dispatch falls through to plain indent. No ANSI emitted even
        // though caps.colors is true. Matches the design's "no fallback
        // module" decision (syntect's lookup is the gate).
        let mut state = MdState::new();
        let _ = render_line("```frobnicate", &mut state, caps());
        assert!(render_line(r#"x = "hello""#, &mut state, caps()).is_none());
        let out = render_line("```", &mut state, caps()).unwrap();
        assert!(
            out.contains(r#"x = "hello""#),
            "unknown-lang body must survive verbatim: {:?}",
            out
        );
        assert!(
            !out.contains("\x1b["),
            "unknown lang must emit zero ANSI: {:?}",
            out
        );
    }

    #[test]
    fn plain_pass_through() {
        assert_eq!(render_inline_line("**b**", plain_caps()), "**b**");
    }

    #[test]
    fn heading_styled() {
        let mut st = MdState::new();
        let out = render_line("## Hello", &mut st, caps()).unwrap();
        assert!(out.contains("Hello"));
        // H1-H3 use the heading colour so they sit on a separate
        // colour layer from default-colour body text.
        assert!(out.contains(theme::md_heading_open()), "H2 should use MD_HEADING_OPEN, got: {:?}", out);
    }

    #[test]
    fn heading_h4_uses_italic_not_color() {
        let mut st = MdState::new();
        let out = render_line("#### Sub-deep", &mut st, caps()).unwrap();
        assert!(out.contains("Sub-deep"));
        // H4+ keeps italic-only — distinct from coloured H1-H3 without
        // adding a third colour tier.
        assert!(out.contains(theme::MD_ITALIC_OPEN), "H4 should use MD_ITALIC_OPEN, got: {:?}", out);
        assert!(!out.contains(theme::md_heading_open()), "H4 must not pick up the H1-H3 heading colour");
    }

    #[test]
    fn heading_plain_keeps_hashes() {
        let mut st = MdState::new();
        let out = render_line("### Sub", &mut st, plain_caps()).unwrap();
        assert_eq!(out, "### Sub");
    }

    #[test]
    fn fence_toggles_state_open_close_with_buffering() {
        // Updated for buffer-and-flush:
        //   - open fence sets in_code_block, returns None (no body yet)
        //   - body lines return None and accumulate to code_buf
        //   - inline markdown inside a buffered line is preserved verbatim
        //     (we flush as code, not as inline markdown)
        //   - close fence flushes everything, resets state, returns Some(...)
        let mut st = MdState::new();
        assert!(render_line("```rust", &mut st, plain_caps()).is_none());
        assert!(st.in_code_block);

        // Body lines are buffered, not emitted.
        assert!(render_line("let x = 1;", &mut st, plain_caps()).is_none());
        assert!(render_line("**not bold**", &mut st, plain_caps()).is_none());
        assert_eq!(st.code_buf.len(), 2);

        // Close fence flushes — final output contains both body lines,
        // and the **not bold** markdown is preserved literally (not interpreted).
        // Using plain_caps so substring assertions aren't broken by ANSI interleave.
        let out = render_line("```", &mut st, plain_caps()).unwrap();
        assert!(out.contains("let x = 1;"));
        assert!(
            out.contains("**not bold**"),
            "inline markdown inside code must be preserved literally: {:?}",
            out
        );
        assert!(!st.in_code_block);
        assert!(st.code_buf.is_empty());
    }

    #[test]
    fn hrule_becomes_blank_line() {
        // Horizontal rules now render as blank lines (thematic break), not
        // visible rules — a line of "─" chars is visually noisier than the
        // blank separator it's supposed to stand in for.
        let mut st = MdState::new();
        let out = render_line("---", &mut st, caps()).unwrap();
        assert_eq!(out, "");
    }

    #[test]
    fn list_bullets() {
        let mut st = MdState::new();
        let out = render_line("- item", &mut st, caps()).unwrap();
        // Bullet marker rendered in muted colour.
        assert!(
            out.contains(&format!("{}{}", theme::MD_MUTED_OPEN, theme::MD_MUTED_CLOSE)),
            "bullet must use MD_MUTED colour: {:?}",
            out
        );
        assert!(out.contains("item"));
    }

    #[test]
    fn list_bullets_plain_caps_no_ansi() {
        let mut st = MdState::new();
        let out = render_line("- item", &mut st, plain_caps()).unwrap();
        // No colour → plain "• item" without any SGR.
        assert_eq!(out, "• item");
    }

    #[test]
    fn list_nested_indent() {
        let mut st = MdState::new();
        let out = render_line("  - nested", &mut st, caps()).unwrap();
        assert!(out.starts_with(&format!("  {}{}", theme::MD_MUTED_OPEN, theme::MD_MUTED_CLOSE)), "nested bullet with indent: {:?}", out);
    }

    #[test]
    fn ordered_list_single_digit() {
        let mut st = MdState::new();
        let out = render_line("1. first item", &mut st, caps()).unwrap();
        assert!(
            out.contains(&format!("{}1.{}", theme::MD_MUTED_OPEN, theme::MD_MUTED_CLOSE)),
            "ordered marker must use MD_MUTED colour: {:?}",
            out
        );
        assert!(out.contains("first item"));
    }

    #[test]
    fn ordered_list_double_digit() {
        let mut st = MdState::new();
        let out = render_line("12. twelfth item", &mut st, caps()).unwrap();
        assert!(
            out.contains(&format!("{}12.{}", theme::MD_MUTED_OPEN, theme::MD_MUTED_CLOSE)),
            "double-digit marker must use MD_MUTED colour: {:?}",
            out
        );
        assert!(out.contains("twelfth item"));
    }

    #[test]
    fn ordered_list_plain_caps_no_ansi() {
        let mut st = MdState::new();
        let out = render_line("3. third", &mut st, plain_caps()).unwrap();
        // No colour → plain "3. third" without any SGR.
        assert_eq!(out, "3. third");
    }

    #[test]
    fn ordered_list_nested() {
        let mut st = MdState::new();
        let out = render_line("  5. nested ordered", &mut st, caps()).unwrap();
        assert!(
            out.starts_with(&format!("  {}5.{}", theme::MD_MUTED_OPEN, theme::MD_MUTED_CLOSE)),
            "nested ordered with indent: {:?}",
            out
        );
        assert!(out.contains("nested ordered"));
    }

    #[test]
    fn number_dot_without_space_is_not_list() {
        // "3.text" (no space after dot) should NOT be parsed as a list item.
        let mut st = MdState::new();
        let out = render_line("3.text", &mut st, caps()).unwrap();
        assert!(!out.contains(theme::MD_MUTED_OPEN), "no muted marker: {:?}", out);
        assert!(out.contains("3.text"));
    }

    #[test]
    fn cjk_bold() {
        assert_eq!(
            render_inline_line("**你好**", caps()),
            format!("{}你好{}", theme::MD_BOLD_OPEN, theme::MD_BOLD_CLOSE)
        );
    }

    /// Wide-enough terminal: render as a normal box-drawing table at the
    /// table's natural column widths. No truncation, no ellipsis.
    #[test]
    fn wide_table_renders_as_box_at_natural_widths() {
        let rows = vec![
            "| Feature | Status |".to_string(),
            "|---------|--------|".to_string(),
            "| login   | done   |".to_string(),
            "| signup  | wip    |".to_string(),
        ];
        // Plenty of room — natural width is well under 80.
        let out = flush_aligned_table_with_width(&rows, plain_caps(), 80);
        assert!(out.contains(''));
        assert!(out.contains(''));
        assert!(out.contains(''));
        // Cell contents survive in full.
        assert!(out.contains("login"));
        assert!(out.contains("signup"));
        // No ellipsis introduced.
        assert!(!out.contains(''));
    }

    /// Narrow terminal: table can't fit at natural widths → fall back to
    /// flat `header:cell` records so no cell content is lost. Mirrors the
    /// CC narrow-mode rendering the user requested.
    #[test]
    fn narrow_terminal_falls_back_to_flat_records() {
        let rows = vec![
            "| 能力 | AtomCode Air | Cursor | Copilot |".to_string(),
            "|------|--------------|--------|---------|".to_string(),
            "| 开源 | ✅ | ❌ | ❌ |".to_string(),
            "| 多语言运行 | ✅ Python+ | 🟡 | ❌ |".to_string(),
        ];
        // Tight budget — the natural box layout needs > 40 cols.
        let out = flush_aligned_table_with_width(&rows, plain_caps(), 40);

        // Flat mode: no box-drawing characters anywhere.
        assert!(!out.contains(''), "narrow output must not contain border │");
        assert!(!out.contains(''), "narrow output must not contain top corner");

        // Every cell value survives in full — no truncation.
        assert!(out.contains("AtomCode Air"));
        assert!(out.contains("Python+"));

        // Each header label appears once per data row.
        let count_neng_li = out.matches("能力").count();
        assert_eq!(count_neng_li, 2, "header `能力` should label both data rows");
        let count_cursor = out.matches("Cursor").count();
        assert_eq!(count_cursor, 2, "header `Cursor` should label both data rows");

        // Records are separated by a blank line.
        assert!(
            out.contains("\n\n"),
            "expected blank line between flat records"
        );
    }

    /// Threshold transition: the same table in a slightly different
    /// terminal width should switch modes cleanly.
    #[test]
    fn flat_mode_kicks_in_when_natural_width_exceeds_budget() {
        let rows = vec![
            "| A | B | C |".to_string(),
            "|---|---|---|".to_string(),
            "| short | also short | x |".to_string(),
        ];
        // Natural width ~ 1 + (5+3) + (10+3) + (1+3) = 26.
        let wide = flush_aligned_table_with_width(&rows, plain_caps(), 80);
        assert!(wide.contains(''), "80 cols should render as box");

        let narrow = flush_aligned_table_with_width(&rows, plain_caps(), 20);
        assert!(!narrow.contains(''), "20 cols should fall back to flat");
    }

    /// Pre-drawn Unicode box-drawing tables (the `┌─┬─┐ │ ├─┼─┤ └─┴─┘`
    /// shape some weak models emit instead of `|`-form markdown) must
    /// route through the same flat-mode-aware flush path: at narrow widths
    /// they collapse to `header:cell` records — no box characters survive.
    /// This is the macOS-overflow regression captured in the screenshot.
    #[test]
    fn box_drawing_table_collapses_to_flat_when_narrow() {
        let mut st = MdState::new();
        let lines = [
            "┌──────────────┬──────────────────────────────────────────┐",
            "│ 场景         │ 作用                                     │",
            "├──────────────┼──────────────────────────────────────────┤",
            "│ 多文件并行编辑 │ parallel_edit_files 工具触发时分发给子智能体 │",
            "├──────────────┼──────────────────────────────────────────┤",
            "│ 弹性预算控制 │ 每个 SubAgent 有初始 4 轮对话预算          │",
            "└──────────────┴──────────────────────────────────────────┘",
            "", // boundary line triggers flush
        ];
        let mut out = String::new();
        for line in &lines {
            if let Some(r) = render_line_with_width(line, &mut st, plain_caps(), 30) {
                out.push_str(&r);
                out.push('\n');
            }
        }
        // Narrow → flat-mode kicks in. No box corners survive.
        assert!(
            !out.contains('') && !out.contains(''),
            "narrow box-drawing table must collapse to flat:\n{out}"
        );
        // Each header label appears once per data row (2 data rows here).
        assert_eq!(
            out.matches("场景").count(),
            2,
            "header `场景` should label each data record:\n{out}"
        );
        assert_eq!(out.matches("作用").count(), 2);
        // Cell content survives in full — no truncation.
        assert!(out.contains("parallel_edit_files"));
        assert!(out.contains("初始 4 轮"));
    }

    /// Wide terminal: a box-drawing table re-renders as a clean box at
    /// natural widths (the input is converted to pipe form, then
    /// `flush_aligned_table_with_width` re-emits its own box drawing).
    #[test]
    fn box_drawing_table_re_renders_as_box_when_fits() {
        let mut st = MdState::new();
        let lines = [
            "┌─────┬─────┐",
            "│ a   │ b   │",
            "├─────┼─────┤",
            "│ 1   │ 2   │",
            "└─────┴─────┘",
            "",
        ];
        let mut out = String::new();
        for line in &lines {
            if let Some(r) = render_line_with_width(line, &mut st, plain_caps(), 80) {
                out.push_str(&r);
                out.push('\n');
            }
        }
        assert!(out.contains(''), "wide terminal should keep box rendering:\n{out}");
        assert!(out.contains(''));
        assert!(out.contains("a") && out.contains("2"));
    }

    /// False-positive guard: a paragraph whose first character happens to
    /// be `├` (or any junction) but has surrounding prose must NOT be
    /// pulled into the box-table buffer. The border-row matcher requires
    /// the entire trimmed line to consist of box-drawing chars + spaces.
    #[test]
    fn box_drawing_detection_does_not_swallow_prose_with_stray_box_char() {
        let mut st = MdState::new();
        // Prose that starts with `├` followed by regular words. Real-world
        // probability is near-zero but the guard matters.
        let line = "├ hello, this is not a table line";
        let out = render_line_with_width(line, &mut st, plain_caps(), 80);
        // Must render inline (Some), not buffer (None).
        assert!(out.is_some(), "prose with stray junction must not buffer");
        assert!(st.table_buf.is_empty(), "table_buf must stay empty");
    }

    #[test]
    fn mdstate_default_has_empty_code_buf_and_no_lang() {
        let s = MdState::new();
        assert!(s.code_buf.is_empty(), "code_buf must start empty");
        assert!(s.code_lang.is_none(), "code_lang must start None");
    }

    #[test]
    fn mdstate_reset_clears_code_buf_and_lang() {
        let mut s = MdState::new();
        s.code_buf.push("dirty".into());
        s.code_lang = Some("rust".into());
        s.in_code_block = true;
        s.reset();
        assert!(s.code_buf.is_empty(), "reset must clear code_buf");
        assert!(s.code_lang.is_none(), "reset must clear code_lang");
        assert!(!s.in_code_block, "reset must clear in_code_block");
    }

    #[test]
    fn fence_open_with_lang_captures_lang_and_buffers_lines() {
        let mut st = MdState::new();
        // Open fence with `rust` tag — language captured, no body output yet.
        assert!(render_line("```rust", &mut st, caps()).is_none());
        assert_eq!(st.code_lang.as_deref(), Some("rust"));
        assert!(st.in_code_block);

        // Body lines accumulate to code_buf, no output emitted yet.
        assert!(render_line("let x = 1;", &mut st, caps()).is_none());
        assert!(render_line("let y = 2;", &mut st, caps()).is_none());
        assert_eq!(st.code_buf.len(), 2);
    }

    #[test]
    fn fence_close_flushes_buffered_block_as_one_chunk() {
        // Use plain_caps so the substring checks see the literal source text
        // — with truecolor caps, syntect interleaves ANSI escapes between
        // every token boundary (keywords/identifiers/operators each get
        // their own SGR pair), so `out.contains("let x = 1;")` won't match.
        // The colored path is covered separately by
        // `fence_close_with_colors_produces_truecolor_ansi`.
        let mut st = MdState::new();
        assert!(render_line("```rust", &mut st, plain_caps()).is_none());
        assert!(render_line("let x = 1;", &mut st, plain_caps()).is_none());
        assert!(render_line("let y = 2;", &mut st, plain_caps()).is_none());

        // Close fence -> highlighted block returned; state reset.
        let out = render_line("```", &mut st, plain_caps()).expect("close fence flushes");
        assert!(out.contains("let x = 1;"));
        assert!(out.contains("let y = 2;"));
        // Output is a single multi-line string (two indented lines + newline between).
        assert!(out.split('\n').count() >= 2);
        // State is reset for the next block.
        assert!(!st.in_code_block);
        assert!(st.code_buf.is_empty());
        assert!(st.code_lang.is_none());
    }

    #[test]
    fn fence_close_with_colors_produces_truecolor_ansi() {
        let mut st = MdState::new();
        render_line("```rust", &mut st, caps());
        render_line("fn main() {}", &mut st, caps());
        let out = render_line("```", &mut st, caps()).unwrap();
        assert!(
            out.contains("\x1b[38;2;"),
            "tinted output must contain a truecolor SGR, got: {:?}",
            out
        );
    }

    #[test]
    fn fence_close_with_no_color_caps_emits_plain_indent_no_ansi() {
        let mut st = MdState::new();
        render_line("```rust", &mut st, plain_caps());
        render_line("let x = 1;", &mut st, plain_caps());
        let out = render_line("```", &mut st, plain_caps()).unwrap();
        assert!(out.contains("  let x = 1;"));
        assert!(!out.contains('\x1b'), "plain_caps must emit zero ANSI, got: {:?}", out);
    }

    #[test]
    fn fence_open_with_no_lang_tag_buffers_with_none_lang() {
        let mut st = MdState::new();
        assert!(render_line("```", &mut st, caps()).is_none());
        assert_eq!(st.code_lang, None);
        assert!(st.in_code_block);
    }

    #[test]
    fn lang_tag_with_trailing_whitespace_is_trimmed() {
        let mut st = MdState::new();
        render_line("```rust  ", &mut st, caps());
        assert_eq!(st.code_lang.as_deref(), Some("rust"));
    }

    #[test]
    fn finalize_emits_unclosed_code_block_as_fallback() {
        // Stream cuts off before close fence — finalize must still emit
        // the buffered body, otherwise the user's last few lines vanish.
        let mut st = MdState::new();
        render_line("```rust", &mut st, caps());
        render_line("let x = 1;", &mut st, caps());
        render_line("let y = 2;", &mut st, caps());
        // No close fence.

        let out = finalize(&mut st, caps()).expect("unclosed block must emit something");
        // Use plain caps for substring check: syntect interleaves ANSI between
        // tokens so "let x = 1;" never appears contiguously in tinted output.
        // The colored-output path is already covered by Task 6's tests; here we
        // just verify the body survives at all.
        let mut st_plain = MdState::new();
        render_line("```rust", &mut st_plain, plain_caps());
        render_line("let x = 1;", &mut st_plain, plain_caps());
        render_line("let y = 2;", &mut st_plain, plain_caps());
        let out_plain = finalize(&mut st_plain, plain_caps()).expect("unclosed block must emit");
        assert!(out_plain.contains("let x = 1;"), "got: {:?}", out_plain);
        assert!(out_plain.contains("let y = 2;"), "got: {:?}", out_plain);

        // Tinted path: at least some output (non-empty) and state cleared.
        assert!(!out.is_empty());
        assert!(st.code_buf.is_empty());
        assert!(!st.in_code_block);
    }

    #[test]
    fn finalize_with_no_active_block_returns_none() {
        // Existing behavior: no buffered table / code → returns None.
        let mut st = MdState::new();
        assert!(finalize(&mut st, caps()).is_none());
    }
}