rab-agent 0.1.5

rab is a lightweight, extensible, Rust-based 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
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
#![allow(clippy::type_complexity, clippy::arc_with_non_send_sync)]

//! Markdown rendering using comrak's tree-based AST.
//!
//! Two-phase approach:
//!   1. Parse with comrak → mutable tree AST
//!   2. AST manipulation: float headings/code blocks/blockquotes out of lists
//!      (prevents progressive nesting from LLM output artifacts)
//!   3. Render tree → styled ANSI lines
//!   4. Wrap + pad → final output

use std::sync::Arc;

use comrak::nodes::{AstNode, ListType, NodeCodeBlock, NodeTable, NodeValue};
use comrak::{Arena, Options, parse_document};

use crate::tui::Component;
use crate::tui::util::{visible_width, wrap_text_with_ansi};

// ── Type aliases ────────────────────────────────────────────────

/// Type alias for markdown theme styling functions.
pub type StyleFn = Arc<dyn Fn(&str) -> String>;
/// Type alias for code highlighting function.
pub type HighlightFn = Arc<dyn Fn(&str, Option<&str>) -> Vec<String>>;

// ── Code block indent ───────────────────────────────────────────

/// Indent prefix applied to each code line inside a fenced code block.
/// Defaults to two spaces for visual inset from the backtick fence.
pub const CODE_BLOCK_INDENT: &str = "  ";

// ── MarkdownTheme ───────────────────────────────────────────────

/// Theme functions for markdown elements.
/// Each function takes text and returns styled text with ANSI codes.
pub struct MarkdownTheme {
    pub heading: StyleFn,
    pub link: StyleFn,
    pub link_url: StyleFn,
    pub code: StyleFn,
    pub code_block: StyleFn,
    pub code_block_border: StyleFn,
    pub quote: StyleFn,
    pub quote_border: StyleFn,
    pub hr: StyleFn,
    pub list_bullet: StyleFn,
    pub bold: StyleFn,
    pub italic: StyleFn,
    pub strikethrough: StyleFn,
    pub underline: StyleFn,
    /// If set, used for syntax-highlighted code blocks.
    pub highlight_code: Option<HighlightFn>,
    /// Indent prefix applied to each code line inside a fenced code block.
    /// Defaults to two spaces for visual inset from the backtick fence.
    pub code_block_indent: String,
}

impl MarkdownTheme {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        heading: StyleFn,
        link: StyleFn,
        link_url: StyleFn,
        code: StyleFn,
        code_block: StyleFn,
        code_block_border: StyleFn,
        quote: StyleFn,
        quote_border: StyleFn,
        hr: StyleFn,
        list_bullet: StyleFn,
        bold: StyleFn,
        italic: StyleFn,
        strikethrough: StyleFn,
        underline: StyleFn,
    ) -> Self {
        Self {
            heading,
            link,
            link_url,
            code,
            code_block,
            code_block_border,
            quote,
            quote_border,
            hr,
            list_bullet,
            bold,
            italic,
            strikethrough,
            underline,
            highlight_code: None,
            code_block_indent: "  ".to_string(),
        }
    }
}

// ── DefaultTextStyle ─────────────────────────────────────────────

/// Default text styling for markdown content.
/// Applied to all text unless overridden by markdown formatting.
pub struct DefaultTextStyle {
    /// Optional foreground color function.
    pub color: Option<StyleFn>,
    pub bold: bool,
    pub italic: bool,
    pub strikethrough: bool,
    pub underline: bool,
}

// ── Internal helpers ─────────────────────────────────────────────

/// Context for inline rendering, carrying the parent-style functions
/// and the ANSI prefix to restore after inline resets.
struct InlineCtx {
    /// Apply the current text style (color + decorations).
    apply_text: Arc<dyn Fn(&str) -> String>,
    /// ANSI prefix to emit after closing an inline element,
    /// restoring this context's styling.
    style_prefix: String,
}

impl InlineCtx {
    fn new(apply_text: Arc<dyn Fn(&str) -> String>) -> Self {
        let prefix = get_style_prefix(&*apply_text);
        Self {
            apply_text,
            style_prefix: prefix,
        }
    }
}

/// Extract the ANSI prefix from a style function.
fn get_style_prefix(style_fn: &dyn Fn(&str) -> String) -> String {
    const SENTINEL: char = '\0';
    let styled = style_fn(&SENTINEL.to_string());
    styled
        .find(SENTINEL)
        .map(|i| styled[..i].to_string())
        .unwrap_or_default()
}

/// Check whether hyperlinks (OSC 8) are supported.
pub(crate) fn hyperlinks_supported() -> bool {
    if let Ok(prog) = std::env::var("TERM_PROGRAM")
        && (prog == "iTerm.app" || prog == "kitty" || prog == "WezTerm" || prog == "vscode")
    {
        return true;
    }
    if let Ok(term) = std::env::var("TERM")
        && term.contains("kitty")
    {
        return true;
    }
    #[cfg(windows)]
    {
        if let Ok(prog) = std::env::var("WT_SESSION") {
            let _ = prog;
            return true;
        }
    }
    false
}

/// Wrap text in an OSC 8 hyperlink.
pub(crate) fn hyperlink(text: &str, url: &str) -> String {
    format!("\x1b]8;;{}\x07{}\x1b]8;;\x07", url, text)
}

// ── Image Display Support (Kitty Protocol) ───────────────────────

/// Check whether the terminal supports the Kitty image protocol.
pub(crate) fn kitty_images_supported() -> bool {
    // Kitty, iTerm2, and WezTerm all support the Kitty image protocol.
    if let Ok(prog) = std::env::var("TERM_PROGRAM")
        && (prog == "iTerm.app" || prog == "kitty" || prog == "WezTerm")
    {
        return true;
    }
    if let Ok(term) = std::env::var("TERM")
        && term.contains("kitty")
    {
        return true;
    }
    false
}

/// Generate a Kitty image protocol sequence for inline display.
///
/// The image is displayed inline at the cursor position. After the sequence,
/// the cursor moves to the end of the image (which occupies one line in the
/// terminal, with height calculated from aspect ratio).
///
/// Format: `\x1b_Ga=T,f=<format>,m=0;<base64>\x1b\\`
pub(crate) fn kitty_image_sequence(data: &[u8], mime_type: &str) -> String {
    use base64::Engine as _;
    let format = match mime_type {
        "image/png" => 100,
        "image/jpeg" | "image/jpg" => 101,
        "image/gif" => 102,
        "image/webp" => 103,
        _ => 100, // default to PNG
    };
    let b64 = base64::engine::general_purpose::STANDARD.encode(data);
    format!("\x1b_Ga=T,f={},m=0;{}\x1b\\", format, b64)
}

// ── Markdown Component ───────────────────────────────────────────

/// Markdown rendering component.
///
/// Parses markdown with comrak (tree-based CommonMark parser),
/// restructures the AST to fix LLM-induced nesting artifacts,
/// then renders to styled ANSI output.
pub struct Markdown {
    text: String,
    padding_x: usize,
    padding_y: usize,
    theme: MarkdownTheme,
    default_text_style: Option<DefaultTextStyle>,

    // Cache
    cached_text: Option<String>,
    cached_width: Option<usize>,
    cached_lines: Vec<String>,
}

impl Markdown {
    pub fn new(
        text: impl Into<String>,
        padding_x: usize,
        padding_y: usize,
        theme: MarkdownTheme,
        default_text_style: Option<DefaultTextStyle>,
    ) -> Self {
        Self {
            text: text.into(),
            padding_x,
            padding_y,
            theme,
            default_text_style,
            cached_text: None,
            cached_width: None,
            cached_lines: Vec::new(),
        }
    }

    pub fn set_text(&mut self, text: impl Into<String>) {
        self.text = text.into();
        self.invalidate();
    }

    pub fn cached_text_matches(&self, other: &str) -> bool {
        self.cached_text.as_deref() == Some(&self.text) && self.text == other
    }

    pub fn get_text(&self) -> &str {
        &self.text
    }

    // ── Style helpers ────────────────────────────────────────────

    fn build_default_ctx(&self) -> InlineCtx {
        InlineCtx::new(self.build_default_apply_fn())
    }

    fn build_default_apply_fn(&self) -> Arc<dyn Fn(&str) -> String> {
        let style = &self.default_text_style;
        let theme = &self.theme;

        let color: Option<StyleFn> = style.as_ref().and_then(|s| s.color.clone());
        let bold = style.as_ref().map(|s| s.bold).unwrap_or(false);
        let italic = style.as_ref().map(|s| s.italic).unwrap_or(false);
        let strikethrough = style.as_ref().map(|s| s.strikethrough).unwrap_or(false);
        let underline = style.as_ref().map(|s| s.underline).unwrap_or(false);
        let theme_bold = theme.bold.clone();
        let theme_italic = theme.italic.clone();
        let theme_strikethrough = theme.strikethrough.clone();
        let theme_underline = theme.underline.clone();

        Arc::new(move |text: &str| {
            let mut styled = text.to_string();
            if let Some(ref color_fn) = color {
                styled = color_fn(&styled);
            }
            if bold {
                styled = theme_bold(&styled);
            }
            if italic {
                styled = theme_italic(&styled);
            }
            if strikethrough {
                styled = theme_strikethrough(&styled);
            }
            if underline {
                styled = theme_underline(&styled);
            }
            styled
        })
    }

    fn heading_ctx(&self, level: u8) -> InlineCtx {
        let theme_heading = self.theme.heading.clone();
        let theme_bold = self.theme.bold.clone();
        let theme_underline = self.theme.underline.clone();

        let style_fn: Arc<dyn Fn(&str) -> String> = match level {
            1 => Arc::new(move |text: &str| theme_heading(&theme_bold(&theme_underline(text)))),
            _ => Arc::new(move |text: &str| theme_heading(&theme_bold(text))),
        };
        InlineCtx::new(style_fn)
    }

    fn quote_ctx(&self) -> InlineCtx {
        let theme_quote = self.theme.quote.clone();
        let theme_italic = self.theme.italic.clone();
        let style_fn: Arc<dyn Fn(&str) -> String> =
            Arc::new(move |text: &str| theme_quote(&theme_italic(text)));
        InlineCtx::new(style_fn)
    }

    // ── Flattening: float "LLM artifact" nodes out of lists ─────
    //
    // LLM markdown output often indents headings, code blocks, and
    // blockquotes inside list items, e.g.:
    //
    //   - Step 1
    //     ### Notes
    //     ```python
    //     ...
    //     ```
    //
    // CommonMark parsers nest these inside the list item. This pass
    // detects such nodes and detaches/reparents them just after the
    // nearest enclosing List, so they render at list-sibling depth.
    //
    // We collect nodes first, then reparent, to avoid issues with
    // tree mutation during iteration.

    /// Collect nodes that should be floated out of their enclosing list.
    fn collect_float_candidates<'a>(&self, root: &'a AstNode<'a>) -> Vec<&'a AstNode<'a>> {
        let mut candidates: Vec<&'a AstNode<'a>> = Vec::new();

        for node in root.descendants() {
            let val = node.data.borrow();
            let is_floatable = matches!(
                val.value,
                NodeValue::Heading(_) | NodeValue::CodeBlock(_) | NodeValue::BlockQuote
            );
            if !is_floatable {
                continue;
            }
            // Check if any ancestor is a List or Item (but not reaching root)
            let mut ancestor = node.parent();
            let mut inside_list = false;
            while let Some(anc) = ancestor {
                let av = anc.data.borrow();
                match av.value {
                    NodeValue::List(_) | NodeValue::Item { .. } => {
                        inside_list = true;
                        break;
                    }
                    NodeValue::Document => break,
                    _ => {}
                }
                ancestor = anc.parent();
            }
            if inside_list {
                candidates.push(node);
            }
        }
        candidates
    }

    /// Find the nearest enclosing List ancestor of a node.
    fn find_enclosing_list<'a>(&self, node: &'a AstNode<'a>) -> Option<&'a AstNode<'a>> {
        let mut ancestor = node.parent();
        while let Some(anc) = ancestor {
            let av = anc.data.borrow();
            if matches!(av.value, NodeValue::List(_)) {
                return Some(anc);
            }
            ancestor = anc.parent();
        }
        None
    }

    /// Float collected candidates out of their enclosing lists.
    fn float_block_nodes<'a>(&self, root: &'a AstNode<'a>) {
        let candidates = self.collect_float_candidates(root);
        for node in candidates {
            // If already detached by a previous reparenting, skip
            if node.parent().is_none() {
                continue;
            }
            let Some(list_node) = self.find_enclosing_list(node) else {
                continue;
            };

            // Detach the candidate from its current parent
            node.detach();

            // Insert it after the list node (at the list's sibling level)
            list_node.insert_after(node);
        }
    }

    // ── Comrak options ───────────────────────────────────────────

    fn comrak_options() -> Options<'static> {
        use comrak::options::Extension;
        Options {
            extension: Extension {
                strikethrough: true,
                table: true,
                autolink: true,
                tasklist: true,
                tagfilter: false,
                ..Extension::default()
            },
            ..Options::default()
        }
    }
}

impl Component for Markdown {
    fn render(&mut self, width: usize) -> Vec<String> {
        // Check cache
        if self.cached_text.as_deref() == Some(&self.text) && self.cached_width == Some(width) {
            return self.cached_lines.clone();
        }

        // Don't render anything if there's no actual text
        if self.text.is_empty() || self.text.trim().is_empty() {
            self.cached_text = Some(self.text.clone());
            self.cached_width = Some(width);
            self.cached_lines = Vec::new();
            return Vec::new();
        }

        let content_width = width.saturating_sub(2 * self.padding_x).max(1);

        // Parse with comrak
        let arena = Arena::new();
        let normalized = self.text.replace('\t', "   ");
        let opts = Self::comrak_options();
        let root = parse_document(&arena, &normalized, &opts);

        // AST manipulation: float headings/code/blockquotes out of lists
        self.float_block_nodes(root);

        // Render tree to styled ANSI lines
        let rendered = self.render_node_lines(root, content_width, 0);

        // Wrap lines
        let mut wrapped: Vec<String> = Vec::new();
        for line in &rendered {
            for wl in wrap_text_with_ansi(line, content_width) {
                wrapped.push(wl);
            }
        }

        // Add padding
        let left_margin = " ".repeat(self.padding_x);
        let right_margin = " ".repeat(self.padding_x);
        let mut content_lines: Vec<String> = Vec::new();
        for line in &wrapped {
            let line_with_margins = format!("{}{}{}", left_margin, line, right_margin);
            let visible = visible_width(&line_with_margins);
            let padded = if visible < width {
                format!("{}{}", line_with_margins, " ".repeat(width - visible))
            } else {
                line_with_margins
            };
            content_lines.push(padded);
        }

        let empty_line = " ".repeat(width);
        let mut result = Vec::new();
        for _ in 0..self.padding_y {
            result.push(empty_line.clone());
        }
        result.extend(content_lines);
        for _ in 0..self.padding_y {
            result.push(empty_line.clone());
        }

        // Update cache
        self.cached_text = Some(self.text.clone());
        self.cached_width = Some(width);
        self.cached_lines = result.clone();

        if result.is_empty() {
            vec![String::new()]
        } else {
            result
        }
    }

    fn invalidate(&mut self) {
        self.cached_text = None;
        self.cached_width = None;
        self.cached_lines.clear();
    }
}

// ── Tree Rendering ──────────────────────────────────────────────

impl Markdown {
    /// Render a node's children as lines, collecting non-inline children.
    /// `list_depth` tracks list nesting for indentation (the float pass
    /// removes most artifical nesting, but genuine nested lists remain).
    /// Determine whether to add a blank line between two consecutive block-level siblings.
    /// Determine whether to add a blank line between two consecutive block-level siblings.
    /// Matches pi's per-block-type behavior:
    ///   - Paragraph: add blank unless next is List
    ///   - List: never add trailing blank
    ///   - Heading, CodeBlock, BlockQuote, Table, ThematicBreak: always add blank
    ///   - HtmlBlock, FrontMatter, other: never add blank
    fn should_add_block_spacing(current: &NodeValue, next: &NodeValue) -> bool {
        match current {
            NodeValue::Paragraph => !matches!(next, NodeValue::List(_)),
            NodeValue::List(_) => false,
            NodeValue::Heading(_)
            | NodeValue::CodeBlock(_)
            | NodeValue::BlockQuote
            | NodeValue::Table(_)
            | NodeValue::ThematicBreak => true,
            _ => false,
        }
    }

    fn render_node_lines<'a>(
        &self,
        node: &'a AstNode<'a>,
        width: usize,
        list_depth: usize,
    ) -> Vec<String> {
        let val = node.data.borrow();
        let mut lines: Vec<String> = Vec::new();
        let children: Vec<_> = node.children().collect();

        match &val.value {
            NodeValue::Document => {
                for (i, child) in children.iter().enumerate() {
                    let child_lines = self.render_node_lines(child, width, 0);
                    let is_last = i + 1 == children.len();
                    if child_lines.is_empty() && is_last {
                        continue;
                    }
                    lines.extend(child_lines);
                    if !is_last {
                        let current_val = child.data.borrow();
                        let next_val = children[i + 1].data.borrow();
                        if Self::should_add_block_spacing(&current_val.value, &next_val.value) {
                            lines.push(String::new());
                        }
                    }
                }
            }

            NodeValue::Paragraph => {
                let ctx = self.build_default_ctx();
                let text = self.render_inline_children(&children, &ctx);
                if !text.is_empty() {
                    lines.push(text);
                }
            }

            NodeValue::Heading(h) => {
                let ctx = self.heading_ctx(h.level);
                let content = self.render_inline_children(&children, &ctx);
                let styled = if h.level >= 3 {
                    let prefix = format!("{} ", "#".repeat(h.level as usize));
                    format!("{}{}", (ctx.apply_text)(&prefix), content)
                } else {
                    content
                };
                lines.push(styled);
            }

            NodeValue::CodeBlock(cb) => {
                self.render_code_block(cb, &mut lines);
            }

            NodeValue::List(_lst) => {
                let list_lines = self.render_list(node, children.clone(), width, list_depth);
                lines.extend(list_lines);
            }

            NodeValue::Item(_) => {
                // Items are handled by render_list; render children directly
                for child in &children {
                    lines.extend(self.render_node_lines(child, width, list_depth));
                }
            }

            NodeValue::BlockQuote => {
                lines.extend(self.render_blockquote(&children, width));
            }

            NodeValue::Table(tbl) => {
                lines.extend(self.render_table(node, tbl, &children, width));
            }

            NodeValue::ThematicBreak => {
                lines.push((self.theme.hr)(&"".repeat(width.min(80))));
            }

            NodeValue::HtmlBlock(hb) => {
                let ctx = self.build_default_ctx();
                for line in hb.literal.lines() {
                    let trimmed = line.trim();
                    if !trimmed.is_empty() {
                        lines.push((ctx.apply_text)(trimmed));
                    }
                }
            }

            NodeValue::FrontMatter(_) => {
                // Skip front matter
            }

            _ => {
                // Fallback: try to render as inline text if there's any
                let ctx = self.build_default_ctx();
                let text = self.render_inline_children(&children, &ctx);
                if !text.is_empty() {
                    lines.push(text);
                }
            }
        }

        lines
    }

    // ── Code Block ───────────────────────────────────────────────

    fn render_code_block(&self, cb: &NodeCodeBlock, lines: &mut Vec<String>) {
        let border = self.theme.code_block_border.clone();
        let code_fn = self.theme.code_block.clone();
        let indent = &self.theme.code_block_indent;

        let lang = if cb.info.is_empty() {
            None
        } else {
            Some(cb.info.as_str())
        };

        // Opening fence
        lines.push(border(&format!("```{}", lang.unwrap_or(""))));

        // Syntax highlighting or plain
        if let Some(ref highlight) = self.theme.highlight_code {
            let hl_lines = highlight(&cb.literal, lang);
            for hl in hl_lines {
                lines.push(format!("{}{}", indent, hl));
            }
        } else {
            for code_line in cb.literal.split('\n') {
                lines.push(format!("{}{}", indent, code_fn(code_line)));
            }
        }

        // Closing fence
        lines.push(border("```"));
    }

    // ── List ─────────────────────────────────────────────────────

    fn render_list<'a>(
        &self,
        node: &'a AstNode<'a>,
        children: Vec<&'a AstNode<'a>>,
        width: usize,
        depth: usize,
    ) -> Vec<String> {
        let mut result: Vec<String> = Vec::new();
        let val = node.data.borrow();
        let NodeValue::List(lst) = &val.value else {
            return result;
        };

        let indent_str = "    ".repeat(depth.min(8));
        let start_number = lst.start.max(1);
        let mut item_index: u64 = 0;

        for child in &children {
            let cv = child.data.borrow();
            let is_item = matches!(cv.value, NodeValue::Item(_) | NodeValue::TaskItem(_));
            if !is_item {
                continue;
            }
            item_index += 1;

            // Check for task list marker
            let mut task_marker = String::new();
            if let NodeValue::TaskItem(ti) = &cv.value {
                task_marker = if ti.symbol.is_some() {
                    "[x] ".to_string()
                } else {
                    "[ ] ".to_string()
                };
            } else {
                // Also check children for TaskItem (some comrak versions nest it)
                for ic in child.children() {
                    if let NodeValue::TaskItem(ti) = &ic.data.borrow().value {
                        task_marker = if ti.symbol.is_some() {
                            "[x] ".to_string()
                        } else {
                            "[ ] ".to_string()
                        };
                        break;
                    }
                }
            }

            let raw_marker = if lst.list_type == ListType::Ordered {
                format!("{}. ", start_number + item_index as usize - 1)
            } else {
                "- ".to_string()
            };
            let marker = format!("{}{}", raw_marker, task_marker);

            let bullet_prefix = indent_str.clone() + &(self.theme.list_bullet)(&marker);
            let continuation_prefix = indent_str.clone() + &" ".repeat(visible_width(&marker));
            let item_width = width.saturating_sub(visible_width(&bullet_prefix)).max(1);
            let mut rendered_any = false;

            // Gather item's block-level children
            let item_children: Vec<_> = child.children().collect();
            for item_child in &item_children {
                let ic_val = item_child.data.borrow();
                match &ic_val.value {
                    NodeValue::List(_) => {
                        // Nested list: fold into rendering by recursing
                        let nested = self.render_list(
                            item_child,
                            item_child.children().collect(),
                            width,
                            depth + 1,
                        );
                        result.extend(nested);
                        rendered_any = true;
                    }
                    NodeValue::Paragraph => {
                        let ctx = self.build_default_ctx();
                        let text = self.render_inline_children(
                            &item_child.children().collect::<Vec<_>>(),
                            &ctx,
                        );
                        for wl in wrap_text_with_ansi(&text, item_width) {
                            let prefix = if rendered_any {
                                &continuation_prefix
                            } else {
                                &bullet_prefix
                            };
                            result.push(format!("{}{}", prefix, wl));
                            rendered_any = true;
                        }
                    }
                    _ => {
                        // Other block (already floated, but handle eg nested quotes)
                        let block_lines = self.render_node_lines(item_child, item_width, depth);
                        for bl in &block_lines {
                            for wl in wrap_text_with_ansi(bl, item_width) {
                                let prefix = if rendered_any {
                                    &continuation_prefix
                                } else {
                                    &bullet_prefix
                                };
                                result.push(format!("{}{}", prefix, wl));
                                rendered_any = true;
                            }
                        }
                    }
                }
            }

            if !rendered_any {
                result.push(bullet_prefix);
            }
        }

        result
    }

    // ── Blockquote ───────────────────────────────────────────────

    fn render_blockquote<'a>(&self, children: &[&'a AstNode<'a>], width: usize) -> Vec<String> {
        let quote_content_width = width.saturating_sub(2).max(1);
        let quote_ctx = self.quote_ctx();
        let quote_style_prefix = get_style_prefix(&|s: &str| (quote_ctx.apply_text)(s));
        let qborder = self.theme.quote_border.clone();

        let mut inner_lines: Vec<String> = Vec::new();
        for (i, child) in children.iter().enumerate() {
            let child_lines = self.render_node_lines(child, quote_content_width, 0);
            let is_last = i + 1 == children.len();
            inner_lines.extend(child_lines);
            if !is_last {
                let current_val = child.data.borrow();
                let next_val = children[i + 1].data.borrow();
                if Self::should_add_block_spacing(&current_val.value, &next_val.value) {
                    inner_lines.push(String::new());
                }
            }
        }

        // Remove trailing blank lines
        while inner_lines.last().is_some_and(|l| l.is_empty()) {
            inner_lines.pop();
        }

        let mut result: Vec<String> = Vec::new();
        for line in &inner_lines {
            let restyled = if !quote_style_prefix.is_empty() {
                line.replace("\x1b[0m", &format!("\x1b[0m{}", quote_style_prefix))
            } else {
                line.clone()
            };
            let styled = (quote_ctx.apply_text)(&restyled);
            let wrapped = wrap_text_with_ansi(&styled, quote_content_width);
            for wl in wrapped {
                result.push(format!("{} {}", qborder(""), wl));
            }
        }

        result
    }

    // ── Table ────────────────────────────────────────────────────

    fn render_table<'a>(
        &self,
        _node: &'a AstNode<'a>,
        tbl: &NodeTable,
        children: &[&'a AstNode<'a>],
        width: usize,
    ) -> Vec<String> {
        let ctx = self.build_default_ctx();
        let num_cols = tbl.num_columns;
        if num_cols == 0 {
            return Vec::new();
        }

        let border_overhead = 3 * num_cols + 1;
        let available_for_cells = width.saturating_sub(border_overhead);
        if available_for_cells < num_cols {
            return Vec::new();
        }

        // Separate rows into header and body
        let mut header_cells: Vec<Vec<String>> = Vec::new();
        let mut body_rows: Vec<Vec<Vec<String>>> = Vec::new();

        for child in children {
            let cv = child.data.borrow();
            if let NodeValue::TableRow(is_header) = &cv.value {
                let row_cells: Vec<Vec<String>> = child
                    .children()
                    .filter_map(|cell_node| {
                        let cell_val = cell_node.data.borrow();
                        if matches!(cell_val.value, NodeValue::TableCell) {
                            let cell_children: Vec<_> = cell_node.children().collect();
                            let text = self.render_inline_children(&cell_children, &ctx);
                            Some(text.split('\n').map(|s| s.to_string()).collect::<Vec<_>>())
                        } else {
                            None
                        }
                    })
                    .collect();

                if *is_header {
                    header_cells = row_cells;
                } else {
                    body_rows.push(row_cells);
                }
            }
        }

        if header_cells.is_empty() {
            return Vec::new();
        }

        // Calculate column widths (same algorithm as current)
        let max_unbroken_word_width = 30;
        let mut natural_widths = vec![0usize; num_cols];
        let mut min_word_widths = vec![1usize; num_cols];

        let update_widths =
            |cells: &[Vec<String>], natural: &mut [usize], min_word: &mut [usize]| {
                for (i, cell_lines) in cells.iter().enumerate() {
                    if i >= num_cols {
                        break;
                    }
                    for cl in cell_lines {
                        let vw = visible_width(cl);
                        natural[i] = natural[i].max(vw);
                        let longest = cl
                            .split_whitespace()
                            .map(visible_width)
                            .max()
                            .unwrap_or(0)
                            .min(max_unbroken_word_width);
                        min_word[i] = min_word[i].max(longest.max(1));
                    }
                }
            };

        update_widths(&header_cells, &mut natural_widths, &mut min_word_widths);
        for row_cells in &body_rows {
            update_widths(row_cells, &mut natural_widths, &mut min_word_widths);
        }

        let total_natural: usize = natural_widths.iter().sum();
        let mut column_widths = vec![0usize; num_cols];

        if total_natural + border_overhead <= width {
            for i in 0..num_cols {
                column_widths[i] = natural_widths[i].max(min_word_widths[i]);
            }
        } else {
            let min_total: usize = min_word_widths.iter().sum();
            let extra = available_for_cells.saturating_sub(min_total);
            let grow_potential: usize = natural_widths
                .iter()
                .zip(min_word_widths.iter())
                .map(|(n, m)| n.saturating_sub(*m))
                .sum();

            if min_total <= available_for_cells {
                for i in 0..num_cols {
                    let n = natural_widths[i];
                    let m = min_word_widths[i];
                    let potential = n.saturating_sub(m);
                    let grow = if grow_potential > 0 {
                        extra
                            .checked_mul(potential)
                            .map(|p| p / grow_potential)
                            .unwrap_or(0)
                    } else {
                        0
                    };
                    column_widths[i] = m + grow;
                }
                let allocated: usize = column_widths.iter().sum();
                let mut remaining = available_for_cells.saturating_sub(allocated);
                for i in 0..num_cols {
                    if remaining == 0 {
                        break;
                    }
                    if column_widths[i] < natural_widths[i] {
                        column_widths[i] += 1;
                        remaining -= 1;
                    }
                }
            } else {
                let base = available_for_cells / num_cols;
                let rem = available_for_cells % num_cols;
                for (i, cw) in column_widths.iter_mut().enumerate() {
                    *cw = base + if i < rem { 1 } else { 0 };
                }
            }
        }

        // Render
        let mut result: Vec<String> = Vec::new();

        // Top border
        let top_cells: Vec<String> = column_widths.iter().map(|w| "".repeat(*w)).collect();
        result.push(format!("┌─{}─┐", top_cells.join("─┬─")));

        // Header row
        let header_lines = self.render_table_row(&header_cells, &column_widths, num_cols, true);
        result.extend(header_lines);

        // Separator
        let sep_cells: Vec<String> = column_widths.iter().map(|w| "".repeat(*w)).collect();
        result.push(format!("├─{}─┤", sep_cells.join("─┼─")));

        // Body rows
        for (ri, row_cells) in body_rows.iter().enumerate() {
            let row_lines = self.render_table_row(row_cells, &column_widths, num_cols, false);
            result.extend(row_lines);
            if ri < body_rows.len() - 1 {
                result.push(format!("├─{}─┤", sep_cells.join("─┼─")));
            }
        }

        // Bottom border
        let bottom_cells: Vec<String> = column_widths.iter().map(|w| "".repeat(*w)).collect();
        result.push(format!("└─{}─┘", bottom_cells.join("─┴─")));

        result
    }

    fn render_table_row(
        &self,
        cells: &[Vec<String>],
        column_widths: &[usize],
        num_cols: usize,
        is_header: bool,
    ) -> Vec<String> {
        if cells.is_empty() {
            return Vec::new();
        }

        let mut wrapped_cells: Vec<Vec<String>> = Vec::new();
        for (i, cell_lines) in cells.iter().enumerate() {
            if i >= num_cols {
                break;
            }
            let col_width = column_widths[i];
            let mut wrapped: Vec<String> = Vec::new();
            for cl in cell_lines {
                for wl in wrap_text_with_ansi(cl, col_width) {
                    wrapped.push(wl);
                }
            }
            if wrapped.is_empty() {
                wrapped.push(String::new());
            }
            wrapped_cells.push(wrapped);
        }

        let max_lines = wrapped_cells.iter().map(|c| c.len()).max().unwrap_or(1);
        for cell in &mut wrapped_cells {
            while cell.len() < max_lines {
                cell.push(String::new());
            }
        }

        let mut result: Vec<String> = Vec::new();
        for line_idx in 0..max_lines {
            let mut row_parts: Vec<String> = Vec::new();
            for (col_idx, cell) in wrapped_cells.iter().enumerate() {
                let text = cell.get(line_idx).map(|s| s.as_str()).unwrap_or("");
                let vw = visible_width(text);
                let padding = column_widths[col_idx].saturating_sub(vw);
                let padded = if is_header {
                    (self.theme.bold)(&format!("{}{}", text, " ".repeat(padding)))
                } else {
                    format!("{}{}", text, " ".repeat(padding))
                };
                row_parts.push(padded);
            }
            result.push(format!("{}", row_parts.join("")));
        }

        result
    }

    // ── Inline Rendering ─────────────────────────────────────────

    /// Render inline children into a single styled string.
    fn render_inline_children<'a>(&self, children: &[&'a AstNode<'a>], ctx: &InlineCtx) -> String {
        let mut result = String::new();

        for node in children {
            let val = node.data.borrow();
            match &val.value {
                NodeValue::Text(t) => {
                    result.push_str(&split_newline_apply(t, &*ctx.apply_text));
                }
                NodeValue::Code(c) => {
                    result.push_str(&(self.theme.code)(&c.literal));
                    result.push_str(&ctx.style_prefix);
                }
                NodeValue::Emph => {
                    let inner =
                        self.render_inline_children(&node.children().collect::<Vec<_>>(), ctx);
                    result.push_str(&(self.theme.italic)(&inner));
                    result.push_str(&ctx.style_prefix);
                }
                NodeValue::Strong => {
                    let inner =
                        self.render_inline_children(&node.children().collect::<Vec<_>>(), ctx);
                    result.push_str(&(self.theme.bold)(&inner));
                    result.push_str(&ctx.style_prefix);
                }
                NodeValue::Strikethrough => {
                    let inner =
                        self.render_inline_children(&node.children().collect::<Vec<_>>(), ctx);
                    result.push_str(&(self.theme.strikethrough)(&inner));
                    result.push_str(&ctx.style_prefix);
                }
                NodeValue::Link(link) => {
                    let inner =
                        self.render_inline_children(&node.children().collect::<Vec<_>>(), ctx);
                    let styled_link = (self.theme.link)(&(self.theme.underline)(&inner));
                    if hyperlinks_supported() {
                        result.push_str(&hyperlink(&styled_link, &link.url));
                    } else {
                        let href_clean = if let Some(mailto) = link.url.strip_prefix("mailto:") {
                            mailto
                        } else {
                            &link.url
                        };
                        if inner.trim() == href_clean || inner.trim() == link.url {
                            result.push_str(&styled_link);
                        } else {
                            result.push_str(&styled_link);
                            result.push_str(&(self.theme.link_url)(&format!(" ({})", link.url)));
                        }
                    }
                    result.push_str(&ctx.style_prefix);
                }
                NodeValue::Image(_) => {
                    // Skip image content
                }
                NodeValue::SoftBreak | NodeValue::LineBreak => {
                    result.push('\n');
                }
                NodeValue::HtmlInline(h) => {
                    result.push_str(&(ctx.apply_text)(h.trim()));
                }

                _ => {
                    // Skip unknown inline nodes
                }
            }
        }

        // Trim trailing style prefix
        while result.ends_with(&ctx.style_prefix) && !ctx.style_prefix.is_empty() {
            result = result[..result.len() - ctx.style_prefix.len()].to_string();
        }

        result
    }
}

// ── Helper functions ─────────────────────────────────────────────

/// Split text by newlines and apply style to each segment.
fn split_newline_apply(text: &str, apply: &dyn Fn(&str) -> String) -> String {
    let segments: Vec<&str> = text.split('\n').collect();
    segments
        .iter()
        .enumerate()
        .map(|(i, s)| {
            if i > 0 {
                format!("\n{}", apply(s))
            } else {
                apply(s)
            }
        })
        .collect()
}

// ── Syntax Highlighting (feature-gated) ─────────────────────────

/// Create a syntax highlighting function.
pub fn create_highlight_fn() -> Option<HighlightFn> {
    #[cfg(feature = "syntect")]
    {
        Some(Arc::new(highlight_code))
    }
    #[cfg(not(feature = "syntect"))]
    {
        None
    }
}

#[cfg(feature = "syntect")]
pub fn highlight_code(code: &str, lang: Option<&str>) -> Vec<String> {
    use std::sync::LazyLock;

    use syntect::{
        easy::HighlightLines,
        highlighting::ThemeSet,
        parsing::SyntaxSet,
        util::{LinesWithEndings, as_24_bit_terminal_escaped},
    };

    static SYNTAX_SET: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);

    static THEME_SET: LazyLock<ThemeSet> = LazyLock::new(ThemeSet::load_defaults);

    let ss = &SYNTAX_SET;
    let ts = &THEME_SET;

    let syntax = lang
        .and_then(|l| ss.find_syntax_by_token(l))
        .unwrap_or_else(|| ss.find_syntax_plain_text());

    let theme = ts
        .themes
        .get("base16-ocean.dark")
        .or_else(|| ts.themes.iter().next().map(|(_, t)| t));

    let Some(theme) = theme else {
        return code.split('\n').map(|s| s.to_string()).collect();
    };

    let mut highlighter = HighlightLines::new(syntax, theme);
    let mut result = Vec::new();

    for line in LinesWithEndings::from(code) {
        match highlighter.highlight_line(line, ss) {
            Ok(ranges) => {
                let escaped = as_24_bit_terminal_escaped(&ranges, false);
                let trimmed = escaped.trim_end_matches('\n');
                if trimmed.is_empty() {
                    result.push(String::new());
                } else {
                    result.push(format!("{}\x1b[0m", trimmed));
                }
            }
            Err(_) => {
                result.push(line.trim_end_matches('\n').to_string());
            }
        }
    }

    result
}

/// Map a file path to a language identifier for syntax highlighting.
pub fn path_to_language(path: &str) -> Option<&'static str> {
    let ext = path.rsplit('.').next()?.to_lowercase();
    let lang = match ext.as_str() {
        "ts" | "tsx" => "typescript",
        "js" | "jsx" | "mjs" | "cjs" => "javascript",
        "py" => "python",
        "rb" => "ruby",
        "rs" => "rust",
        "go" => "go",
        "java" => "java",
        "kt" => "kotlin",
        "swift" => "swift",
        "c" | "h" => "c",
        "cpp" | "cc" | "cxx" | "hpp" => "cpp",
        "cs" => "csharp",
        "php" => "php",
        "sh" | "bash" | "zsh" => "bash",
        "ps1" => "powershell",
        "sql" => "sql",
        "html" | "htm" => "html",
        "css" | "scss" | "sass" | "less" => "css",
        "json" => "json",
        "yaml" | "yml" => "yaml",
        "toml" => "toml",
        "xml" => "xml",
        "md" | "markdown" => "markdown",
        "clj" | "cljs" | "cljc" => "clojure",
        "ex" | "exs" => "elixir",
        "hs" => "haskell",
        "lua" => "lua",
        _ => return None,
    };
    Some(lang)
}

// ── Tests ────────────────────────────────────────────────────────

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

    fn test_theme() -> MarkdownTheme {
        MarkdownTheme::new(
            Arc::new(|s| format!("\x1b[33m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[34m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[90m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[36m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[32m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[90m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[90m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[90m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[90m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[33m{}\x1b[39m", s)),
            Arc::new(|s| format!("\x1b[1m{}\x1b[22m", s)),
            Arc::new(|s| format!("\x1b[3m{}\x1b[23m", s)),
            Arc::new(|s| format!("\x1b[9m{}\x1b[29m", s)),
            Arc::new(|s| format!("\x1b[4m{}\x1b[24m", s)),
        )
    }

    #[test]
    fn test_basic_paragraph() {
        let theme = test_theme();
        let mut md = Markdown::new("hello world", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("hello world"));
        assert!(!all.contains("\x1b["));
    }

    #[test]
    fn test_heading_h1() {
        let theme = test_theme();
        let mut md = Markdown::new("# Heading 1", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("Heading 1"));
        assert!(all.contains("\x1b[1m"));
        assert!(all.contains("\x1b[33m"));
    }

    #[test]
    fn test_heading_h3_marker() {
        let theme = test_theme();
        let mut md = Markdown::new("### Heading 3", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("###") || all.contains("Heading 3"));
    }

    #[test]
    fn test_bold_italic() {
        let theme = test_theme();
        let mut md = Markdown::new("**bold** and *italic*", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("bold"));
        assert!(all.contains("italic"));
        assert!(all.contains("\x1b[1m"));
        assert!(all.contains("\x1b[3m"));
    }

    #[test]
    fn test_codespan() {
        let theme = test_theme();
        let mut md = Markdown::new("use `code` here", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("code"));
        assert!(all.contains("\x1b[36m"));
    }

    #[test]
    fn test_inline_code_style_restore() {
        let theme = test_theme();
        let mut md = Markdown::new("**bold `code` end**", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("bold"));
        assert!(all.contains("code"));
        assert!(all.contains("end"));
    }

    #[test]
    fn test_code_block() {
        let theme = test_theme();
        let mut md = Markdown::new("```\nlet x = 1;\n```", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("let x = 1;"));
        assert!(all.contains("\x1b[32m"));
        assert!(all.contains("```"));
    }

    #[test]
    fn test_fenced_code_with_language() {
        let theme = test_theme();
        let mut md = Markdown::new("```rust\nfn main() {}\n```", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("```rust"));
        assert!(all.contains("fn main() {}"));
    }

    #[test]
    fn test_unordered_list() {
        let theme = test_theme();
        let mut md = Markdown::new("- item 1\n- item 2\n- item 3", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("item 1"));
        assert!(all.contains("item 2"));
        assert!(all.contains("item 3"));
    }

    #[test]
    fn test_strikethrough() {
        let theme = test_theme();
        let mut md = Markdown::new("~~struck~~", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("struck"));
        assert!(all.contains("\x1b[9m"));
    }

    #[test]
    fn test_link_inline() {
        let theme = test_theme();
        let mut md = Markdown::new("[text](https://example.com)", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("text"));
        assert!(all.contains("https://example.com"));
    }

    #[test]
    fn test_empty_text() {
        let theme = test_theme();
        let mut md = Markdown::new("", 0, 0, theme, None);
        let lines = md.render(80);
        assert!(lines.is_empty() || (lines.len() == 1 && lines[0].is_empty()));
    }

    #[test]
    fn test_whitespace_only() {
        let theme = test_theme();
        let mut md = Markdown::new("   ", 0, 0, theme, None);
        let lines = md.render(80);
        assert!(lines.is_empty() || (lines.len() == 1 && lines[0].is_empty()));
    }

    #[test]
    fn test_horizontal_rule() {
        let theme = test_theme();
        let mut md = Markdown::new("---", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains(''));
    }

    #[test]
    fn test_padding_x() {
        let theme = test_theme();
        let mut md = Markdown::new("hello", 2, 0, theme, None);
        let lines = md.render(20);
        assert_eq!(visible_width(&lines[0]), 20);
        assert!(lines[0].starts_with("  "));
    }

    #[test]
    fn test_padding_y() {
        let theme = test_theme();
        let mut md = Markdown::new("hello", 0, 1, theme, None);
        let lines = md.render(20);
        assert_eq!(lines.len(), 3);
    }

    #[test]
    fn test_cache_hit() {
        let theme = test_theme();
        let mut md = Markdown::new("hello", 1, 0, theme, None);
        let a = md.render(20);
        let b = md.render(20);
        assert_eq!(a, b);
    }

    #[test]
    fn test_cache_invalidation() {
        let theme = test_theme();
        let mut md = Markdown::new("hello", 1, 0, theme, None);
        let a = md.render(20);
        md.set_text("world");
        let b = md.render(20);
        assert_ne!(a, b);
    }

    #[test]
    fn test_blockquote() {
        let theme = test_theme();
        let mut md = Markdown::new("> quoted text", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("quoted text"));
        assert!(all.contains(""));
    }

    #[test]
    fn test_task_list() {
        let theme = test_theme();
        let mut md = Markdown::new("- [x] done\n- [ ] todo", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("[x]") || all.contains("done"));
        assert!(all.contains("[ ]") || all.contains("todo"));
    }

    #[test]
    fn test_paragraph_spacing() {
        let theme = test_theme();
        let mut md = Markdown::new("para one\n\npara two", 0, 0, theme, None);
        let lines = md.render(80);
        // Two paragraphs should produce three lines: para one, blank, para two
        assert!(lines.len() >= 2, "should have at least 2 lines");
        // Lines are padded to width; check trimmed versions
        assert!(
            lines[0].trim_end().ends_with("para one"),
            "first line should contain 'para one', got {:?}",
            lines[0]
        );
        assert!(
            lines[1].trim().is_empty(),
            "line between paragraphs should be empty, got {:?}",
            lines[1]
        );
        assert!(
            lines[2].trim_end().ends_with("para two"),
            "third line should contain 'para two', got {:?}",
            lines[2]
        );
    }

    #[test]
    fn test_tabs_replaced() {
        let theme = test_theme();
        let mut md = Markdown::new("\tindented", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("indented"));
    }

    #[test]
    fn test_default_text_style() {
        let theme = test_theme();
        let default_style = DefaultTextStyle {
            color: Some(Arc::new(|s| format!("\x1b[33m{}\x1b[39m", s))),
            bold: true,
            italic: false,
            strikethrough: false,
            underline: false,
        };
        let mut md = Markdown::new("styled text", 0, 0, theme, Some(default_style));
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("styled text"));
        assert!(all.contains("\x1b[1m"));
        assert!(all.contains("\x1b[33m"));
    }

    #[test]
    fn test_table_basic() {
        let theme = test_theme();
        let mut md = Markdown::new(
            "| H1 | H2 |\n| --- | --- |\n| A1 | B1 |\n| A2 | B2 |",
            0,
            0,
            theme,
            None,
        );
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("H1"));
        assert!(all.contains("H2"));
        assert!(all.contains("A1"));
        assert!(all.contains(""));
        assert!(all.contains(""));
        assert!(all.contains(""));
    }

    #[test]
    fn test_table_narrow_fallback() {
        let theme = test_theme();
        let mut md = Markdown::new("| A | B |\n| --- | --- |\n| 1 | 2 |", 0, 0, theme, None);
        let lines = md.render(10);
        assert!(!lines.is_empty());
    }

    #[test]
    fn test_ordered_list() {
        let theme = test_theme();
        let mut md = Markdown::new("1. first\n2. second\n3. third", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("first"));
        assert!(all.contains("second"));
        assert!(all.contains("third"));
    }

    #[test]
    fn test_nested_list() {
        let theme = test_theme();
        let mut md = Markdown::new("- outer\n  - inner\n- more", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("outer"));
        assert!(all.contains("inner"));
        assert!(all.contains("more"));
    }

    #[test]
    fn test_blockquote_nested() {
        let theme = test_theme();
        let mut md = Markdown::new("> outer\n> > nested\n> back", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("outer"));
        assert!(all.contains("nested"));
        assert!(all.contains("back"));
        assert!(all.contains(""));
    }

    #[test]
    fn test_link_with_dest() {
        let theme = test_theme();
        let mut md = Markdown::new("[example](https://example.com/page)", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("example"));
        assert!(all.contains("example.com/page"));
    }

    #[test]
    fn test_autolink() {
        let theme = test_theme();
        let mut md = Markdown::new("<https://example.com>", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("example.com"));
    }

    #[test]
    fn test_wrap_long_text() {
        let theme = test_theme();
        let long = "this is a very long line that should definitely wrap to multiple lines when rendered in a narrow terminal column";
        let mut md = Markdown::new(long, 0, 0, theme, None);
        let lines = md.render(30);
        assert!(lines.len() > 1);
        for line in &lines {
            assert!(visible_width(line) <= 30);
        }
    }

    #[test]
    fn test_cache_different_width() {
        let theme = test_theme();
        let mut md = Markdown::new("hello world", 1, 0, theme, None);
        let a = md.render(30);
        let b = md.render(50);
        assert_ne!(a, b);
    }

    #[test]
    fn test_html_block_plain() {
        let theme = test_theme();
        let mut md = Markdown::new("<div>plain html</div>", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("plain html"));
    }

    #[test]
    fn test_bold_italic_style_restore() {
        let theme = test_theme();
        let mut md = Markdown::new("**bold `code` more bold**", 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("bold"));
        assert!(all.contains("code"));
        assert!(all.contains("more"));
    }

    // ── Heading-in-list float test ───────────────────────────────

    #[test]
    fn test_heading_inside_list_is_floated() {
        let theme = test_theme();
        let md_text = "- item\n  ### heading\n  - nested\n- more";
        let mut md = Markdown::new(md_text, 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        // heading should NOT be indented with list prefix — it was floated
        // Check it appears near the left margin, not 4+ spaces in
        assert!(all.contains("heading"), "Should contain heading text");
        // The nested list item should still be indented
        assert!(all.contains("nested"), "Should contain nested item");
        assert!(all.contains("more"), "Should contain more item");
    }

    // ── Code block inside list float test ────────────────────────

    #[test]
    fn test_code_block_inside_list_is_floated() {
        let theme = test_theme();
        let md_text = "- item\n  ```python\n  print('hi')\n  ```\n- more";
        let mut md = Markdown::new(md_text, 0, 0, theme, None);
        let lines = md.render(80);
        let all = lines.join("\n");
        assert!(all.contains("print('hi')"), "Should contain code content");
        assert!(all.contains("```"), "Should have fence markers");
        assert!(all.contains("item"), "Should contain item text");
        assert!(all.contains("more"), "Should contain more item");
    }
}