tuika 0.4.0

A composable terminal UI toolkit — flexbox layout, overlays, focus, and safe ratatui interoperability.
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
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
//! Streaming Markdown rendering.
//!
//! [`MarkdownState`] renders CommonMark (via `pulldown-cmark`) to styled
//! [`Line`]s, incrementally: as a message streams in, only the **in-flight tail**
//! is re-parsed each frame. Everything before the last *stable block boundary*
//! (a blank line outside an open code fence) is parsed and highlighted once and
//! cached — so a long transcript does not re-tokenize, and tree-sitter does not
//! re-highlight settled code blocks, on every delta. This mirrors the split
//! Hermes' TUI uses for its streaming markdown.
//!
//! Output is width-aware and correct for prose, code, and tables: prose is
//! word-wrapped (via [`wrap_lines`]); code is emitted verbatim, because its
//! indentation is meaningful; and GFM tables are re-laid-out to the width each
//! frame, with per-column fitting and styled cells (bold headers, links, inline
//! code, emoji). Callers draw the returned lines **without** further wrapping
//! (e.g. ratatui's `Paragraph` with no `.wrap`, or tuika's
//! [`Text`](crate::components::Text)).
//!
//! For one-shot (non-streaming) text, [`markdown_to_lines`] renders a whole
//! string in one call. The [`Markdown`] view wraps either for direct placement
//! in a layout.

use pulldown_cmark::{Alignment, CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd};
use ratatui_core::layout::Rect;
use ratatui_core::style::{Modifier, Style};
use ratatui_core::text::{Line, Span};
use unicode_segmentation::UnicodeSegmentation;

use crate::components::code_block::code_block_lines;
use crate::components::line_width;
use crate::geometry::Size;
use crate::highlight::{CodeHighlighter, Highlighter};
use crate::hyperlink::{BufferLink, LinkPolicy, apply_buffer_links};
use crate::image::{Image, ImageData, ImageLayer, ImageSupport};
use crate::style::{StyleBundle, StyleSheet, Theme};
use crate::surface::Surface;
use crate::view::{RenderCtx, View};
use crate::width::grapheme_cols;

/// Columns of indentation added per level of list / block-quote nesting.
const INDENT: u16 = 2;

/// Widest a block image is drawn, in cells, regardless of the available width —
/// so a resolved `![alt](url)` stays a reasonable inline size rather than filling
/// the whole transcript.
const MAX_IMAGE_COLS: u16 = 60;

/// Resolves a markdown image URL to decoded pixels.
///
/// Markdown carries only the URL, never pixels, so — exactly like
/// [`Highlighter`] does for fenced code — the host supplies the decode. A
/// resolved `![alt](url)` is rendered as a block image (real pixels via the
/// terminal graphics protocol, or the alt fallback); returning `None` leaves it
/// as the inline text placeholder. Wire one up with [`Markdown::images`].
pub trait ImageResolver {
    /// Resolve `url` to image data, or `None` to keep the text placeholder.
    fn resolve(&self, url: &str) -> Option<ImageData>;
}

/// A block image in a rendered markdown document: the row it reserved (0-based,
/// within the returned lines), its cell footprint, the alt text, and the pixels.
///
/// The [`Markdown`] view overlays these itself. A host that draws
/// [`MarkdownState::lines`] manually reads [`MarkdownState::images`] and paints
/// each one — build an [`Image`] from `data`/`cols`/`rows`/`alt` and render it at
/// [`rect`](Self::rect) against the area the lines were drawn into.
#[derive(Clone, Debug)]
pub struct MarkdownImage {
    /// Row the image reserved, 0-based within the rendered lines.
    pub row: u16,
    /// Left indent in cells (list / block-quote nesting).
    pub indent: u16,
    /// Width in cells.
    pub cols: u16,
    /// Height in cells.
    pub rows: u16,
    /// Decoded pixels to paint.
    pub data: ImageData,
    /// Alt text, shown as the fallback where graphics aren't supported.
    pub alt: String,
}

impl MarkdownImage {
    /// The absolute screen rect for this image, given the `area` the markdown
    /// lines were drawn into — clamped so it never exceeds `area`.
    pub fn rect(&self, area: Rect) -> Rect {
        let x = area.x.saturating_add(self.indent).min(area.right());
        let y = area.y.saturating_add(self.row).min(area.bottom());
        Rect {
            x,
            y,
            width: self.cols.min(area.right().saturating_sub(x)),
            height: self.rows.min(area.bottom().saturating_sub(y)),
        }
    }
}

/// Cell footprint for a block image at `avail` columns: capped at
/// [`MAX_IMAGE_COLS`], with the row count derived from the pixel aspect ratio
/// (terminal cells are about twice as tall as wide, so the height is halved).
fn image_cell_size(data: &ImageData, avail: u16) -> (u16, u16) {
    let cols = avail.clamp(1, MAX_IMAGE_COLS);
    let rows = (cols as u32 * data.pixel_height() / (data.pixel_width().max(1) * 2)).clamp(1, 30);
    (cols, rows as u16)
}

/// A parsed, width-independent markdown block. Wrapping and table layout happen
/// later, at [`flatten`] time, against a concrete width.
enum MdItem {
    /// Word-wrappable prose (a paragraph line, heading, list item, quote line).
    Prose { spans: Vec<RichSpan>, indent: u16 },
    /// A verbatim line (code) drawn as-is at `indent`, never reflowed.
    Verbatim { line: Line<'static>, indent: u16 },
    /// A GFM table, laid out to the available width when flattened.
    Table { table: TableData, indent: u16 },
    /// A resolved block image: reserves rows at flatten time and is painted by an
    /// [`Image`] overlay in the view (see [`ImageResolver`]).
    Image {
        data: ImageData,
        alt: String,
        indent: u16,
    },
    /// A blank spacer row separating blocks.
    Blank,
}

/// An inline run that may carry an OSC 8 hyperlink target.
///
/// ratatui's [`Span`] has no href field, so markdown keeps the destination here
/// through wrapping; [`flatten_linked`] turns contiguous href runs into
/// [`BufferLink`]s the host (or [`Markdown`] view) applies with
/// [`apply_buffer_links`].
#[derive(Clone, Debug)]
struct RichSpan {
    content: String,
    style: Style,
    /// When set, this run is a hyperlink to `href` (the visible label may differ).
    href: Option<String>,
}

impl RichSpan {
    fn styled(content: impl Into<String>, style: Style, href: Option<String>) -> Self {
        Self {
            content: content.into(),
            style,
            href,
        }
    }

    fn to_span(&self) -> Span<'static> {
        Span::styled(self.content.clone(), self.style)
    }
}

/// Table contents captured during parsing: each cell is a run of pre-styled
/// inline spans (bold, links, inline code, emoji), boxed and width-fitted at
/// render time by [`render_table`].
struct TableData {
    aligns: Vec<Alignment>,
    header: Vec<Cell>,
    rows: Vec<Vec<Cell>>,
}

/// One table cell's inline content, already styled by the shared inline
/// machinery so cells carry the same markup as prose.
type Cell = Vec<RichSpan>;

/// Parse `source` into width-independent [`MdItem`]s. Fenced code blocks are
/// highlighted here (once), via `highlighter`, using `theme`'s code palette;
/// prose roles (headings, links, emphasis, …) are styled from `sheet`.
fn parse(
    source: &str,
    theme: &Theme,
    sheet: &StyleSheet,
    highlighter: CodeHighlighter,
) -> Vec<MdItem> {
    parse_with(source, theme, sheet, highlighter, None)
}

/// [`parse`] with an optional [`ImageResolver`]: a resolved `![alt](url)` becomes
/// a block [`MdItem::Image`] instead of the inline text placeholder.
fn parse_with(
    source: &str,
    theme: &Theme,
    sheet: &StyleSheet,
    highlighter: CodeHighlighter,
    resolver: Option<&dyn ImageResolver>,
) -> Vec<MdItem> {
    let mut b = Builder::new(theme, sheet, highlighter, resolver);
    let mut opts = Options::empty();
    opts.insert(Options::ENABLE_TABLES);
    opts.insert(Options::ENABLE_STRIKETHROUGH);
    for event in Parser::new_ext(source, opts) {
        b.event(event);
    }
    b.finish();
    b.items
}

/// Walks the pulldown-cmark event stream, accumulating [`MdItem`]s.
struct Builder<'a> {
    theme: &'a Theme,
    sheet: &'a StyleSheet,
    highlighter: CodeHighlighter<'a>,
    items: Vec<MdItem>,

    // Inline accumulation for the current prose block.
    inline: Vec<RichSpan>,
    style_stack: Vec<Style>,
    /// Destinations for open `[label](url)` tags (usually depth 1). Text pushed
    /// while this is non-empty inherits the innermost href.
    link_stack: Vec<String>,

    // Block nesting.
    lists: Vec<Option<u64>>, // ordered start counter per open list, `None` = bullet
    quote_depth: u16,
    pending_marker: Option<Vec<RichSpan>>,

    // Fenced/indented code block being collected.
    code: Option<(String, String)>, // (language tag, body)

    // Table being collected. Cells reuse the shared `inline` accumulator, so
    // they pick up the same styling as prose; each cell drains `inline` on its
    // `TableCell` end. Header vs body rows are routed by which End event
    // (`TableHead` / `TableRow`) closes the accumulated cells.
    table: Option<TableData>,
    cur_row: Vec<Cell>,

    // Inline image being collected: (dest URL, alt-text accumulator). Set on
    // `Tag::Image`, drained on `TagEnd::Image` into a placeholder or, when the
    // resolver yields pixels, a block `MdItem::Image`.
    image: Option<(String, String)>,

    // Host hook resolving image URLs to pixels; `None` keeps the text placeholder.
    resolver: Option<&'a dyn ImageResolver>,
}

impl<'a> Builder<'a> {
    fn new(
        theme: &'a Theme,
        sheet: &'a StyleSheet,
        highlighter: CodeHighlighter<'a>,
        resolver: Option<&'a dyn ImageResolver>,
    ) -> Self {
        Self {
            theme,
            sheet,
            highlighter,
            items: Vec::new(),
            inline: Vec::new(),
            style_stack: vec![Style::default().fg(theme.text)],
            link_stack: Vec::new(),
            lists: Vec::new(),
            quote_depth: 0,
            pending_marker: None,
            code: None,
            table: None,
            cur_row: Vec::new(),
            image: None,
            resolver,
        }
    }

    fn cur_style(&self) -> Style {
        *self.style_stack.last().unwrap()
    }

    fn cur_href(&self) -> Option<String> {
        self.link_stack.last().cloned()
    }

    /// Indentation for the current block, from list + quote nesting.
    fn indent(&self) -> u16 {
        (self.lists.len().saturating_sub(1) as u16 + self.quote_depth) * INDENT
    }

    /// True when we are inside a list or block quote (nested, not top level).
    fn nested(&self) -> bool {
        !self.lists.is_empty() || self.quote_depth > 0
    }

    /// Insert a blank spacer before a new top-level block (never inside a list
    /// or quote, and never doubling blanks).
    fn separate(&mut self) {
        if self.nested() {
            return;
        }
        if matches!(self.items.last(), None | Some(MdItem::Blank)) {
            return;
        }
        self.items.push(MdItem::Blank);
    }

    /// Flush the current inline run as one prose line, attaching a pending list
    /// marker to the item's first line.
    fn flush(&mut self) {
        if self.inline.is_empty() && self.pending_marker.is_none() {
            return;
        }
        let indent = self.indent();
        let mut spans = self.pending_marker.take().unwrap_or_default();
        spans.append(&mut self.inline);
        self.items.push(MdItem::Prose { spans, indent });
    }

    fn push_text(&mut self, text: &str) {
        if let Some((_, body)) = self.code.as_mut() {
            body.push_str(text);
            return;
        }
        // Inside an image, text is the alt description — collect it for the
        // placeholder rather than emitting it as prose.
        if let Some((_, alt)) = self.image.as_mut() {
            alt.push_str(text);
            return;
        }
        let style = self.cur_style();
        let href = self.cur_href();
        // Only linkify bare URLs in plain body text, not inside links/headings.
        // Inside an explicit link the destination is already on `href`.
        if href.is_some() || style.add_modifier.contains(Modifier::UNDERLINED) {
            self.inline
                .push(RichSpan::styled(text.to_string(), style, href));
        } else {
            for span in linkify(text, style, self.sheet.link) {
                self.inline.push(span);
            }
        }
    }

    /// Render an inline image as a visible placeholder: a small marker glyph plus
    /// the alt text — or the URL when there is no alt — link-styled, so an image
    /// is never silently dropped. Actually painting the pixels in markdown
    /// (resolving the URL to [`ImageData`](crate::image::ImageData) and emitting
    /// through an [`ImageLayer`](crate::image::ImageLayer)) is a later phase; see
    /// `knowledge/specs/tuika-images.md`.
    fn push_image_placeholder(&mut self, url: &str, alt: &str) {
        let label = if alt.trim().is_empty() { url } else { alt };
        self.inline.push(RichSpan::styled(
            "🖼 ",
            self.sheet.image_marker.to_style(),
            None,
        ));
        // Placeholder label points at the image URL so Ctrl+click / OSC 8 can
        // still open it when the host applies buffer links.
        self.inline.push(RichSpan::styled(
            label.to_string(),
            self.sheet.link.to_style(),
            Some(url.to_string()),
        ));
    }

    fn event(&mut self, event: Event<'a>) {
        match event {
            Event::Start(tag) => self.start(tag),
            Event::End(tag) => self.end(tag),
            Event::Text(t) => self.push_text(&t),
            Event::Code(t) => {
                self.inline.push(RichSpan::styled(
                    t.to_string(),
                    self.sheet.inline_code.to_style(),
                    self.cur_href(),
                ));
            }
            Event::SoftBreak => {
                if self.code.is_none() {
                    self.inline
                        .push(RichSpan::styled(" ", self.cur_style(), self.cur_href()));
                }
            }
            // A hard break inside a cell can't split it into another block, so
            // it collapses to a space; elsewhere it flushes the prose line.
            Event::HardBreak if self.table.is_some() => {
                self.inline
                    .push(RichSpan::styled(" ", self.cur_style(), self.cur_href()))
            }
            Event::HardBreak => self.flush(),
            Event::Rule => {
                self.separate();
                self.items.push(MdItem::Prose {
                    spans: vec![RichSpan::styled(
                        "".repeat(24),
                        self.sheet.rule.to_style(),
                        None,
                    )],
                    indent: self.indent(),
                });
            }
            Event::TaskListMarker(done) => {
                let glyph = if done { "[x] " } else { "[ ] " };
                self.inline.push(RichSpan::styled(
                    glyph.to_string(),
                    self.sheet.task_marker.to_style(),
                    None,
                ));
            }
            _ => {}
        }
    }

    fn start(&mut self, tag: Tag<'a>) {
        match tag {
            Tag::Paragraph => self.separate(),
            Tag::Heading { level, .. } => {
                self.separate();
                let mut style = self.sheet.heading.to_style();
                if level > HeadingLevel::H2 {
                    style = style.add_modifier(Modifier::ITALIC);
                }
                self.style_stack.push(style);
            }
            Tag::BlockQuote(_) => {
                self.separate();
                self.quote_depth += 1;
            }
            Tag::CodeBlock(kind) => {
                self.separate();
                let lang = match kind {
                    CodeBlockKind::Fenced(info) => {
                        info.split_whitespace().next().unwrap_or("").to_string()
                    }
                    CodeBlockKind::Indented => String::new(),
                };
                self.code = Some((lang, String::new()));
            }
            Tag::List(start) => {
                self.separate();
                self.lists.push(start);
            }
            Tag::Item => {
                let marker = match self.lists.last_mut() {
                    Some(Some(n)) => {
                        let m = format!("{n}. ");
                        *self.lists.last_mut().unwrap() = Some(n.saturating_add(1));
                        m
                    }
                    _ => "".to_string(),
                };
                self.pending_marker = Some(vec![RichSpan::styled(
                    marker,
                    self.sheet.list_marker.to_style(),
                    None,
                )]);
            }
            Tag::Emphasis => self.push_style_bundle(self.sheet.emphasis),
            Tag::Strong => self.push_style_bundle(self.sheet.strong),
            Tag::Strikethrough => self.push_style_bundle(self.sheet.strikethrough),
            Tag::Link { dest_url, .. } => {
                self.link_stack.push(dest_url.to_string());
                self.style_stack.push(self.sheet.link.to_style());
            }
            Tag::Image { dest_url, .. } => {
                // Capture the target; alt text accrues via `push_text` until the
                // matching `TagEnd::Image` renders the placeholder.
                self.image = Some((dest_url.to_string(), String::new()));
            }
            Tag::Table(aligns) => {
                self.separate();
                self.table = Some(TableData {
                    aligns,
                    header: Vec::new(),
                    rows: Vec::new(),
                });
            }
            Tag::TableHead => {
                self.cur_row.clear();
                // Header cells render in the heading style; push it as the cell
                // base so plain header text picks it up, while links and inline
                // code inside a header keep their own styling on top.
                self.style_stack.push(self.sheet.heading.to_style());
            }
            Tag::TableRow => self.cur_row.clear(),
            Tag::TableCell => self.inline.clear(),
            _ => {}
        }
    }

    fn end(&mut self, tag: TagEnd) {
        match tag {
            TagEnd::Paragraph => self.flush(),
            TagEnd::Heading(_) => {
                self.flush();
                self.style_stack.pop();
            }
            TagEnd::BlockQuote(_) => {
                self.flush();
                self.quote_depth = self.quote_depth.saturating_sub(1);
            }
            TagEnd::CodeBlock => {
                if let Some((lang, body)) = self.code.take() {
                    let body = body.strip_suffix('\n').unwrap_or(&body);
                    let lines: Vec<&str> = body.split('\n').collect();
                    let indent = self.indent();
                    for line in
                        code_block_lines(&lang, &lines, self.theme, self.highlighter, true, None)
                    {
                        self.items.push(MdItem::Verbatim { line, indent });
                    }
                }
            }
            TagEnd::List(_) => {
                self.lists.pop();
            }
            TagEnd::Item => self.flush(),
            TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough => {
                self.style_stack.pop();
            }
            TagEnd::Link => {
                self.style_stack.pop();
                self.link_stack.pop();
            }
            TagEnd::Image => {
                if let Some((url, alt)) = self.image.take() {
                    match self.resolver.and_then(|r| r.resolve(&url)) {
                        // Resolved: promote to a block image on its own rows. Any
                        // inline run so far is flushed first so the image stands
                        // apart from surrounding text.
                        Some(data) => {
                            self.flush();
                            let indent = self.indent();
                            self.items.push(MdItem::Image { data, alt, indent });
                        }
                        None => self.push_image_placeholder(&url, &alt),
                    }
                }
            }
            TagEnd::TableCell => {
                let cell = trim_spans(std::mem::take(&mut self.inline));
                self.cur_row.push(cell);
            }
            TagEnd::TableHead => {
                self.style_stack.pop();
                if let Some(t) = self.table.as_mut() {
                    t.header = std::mem::take(&mut self.cur_row);
                }
            }
            TagEnd::TableRow => {
                if let Some(t) = self.table.as_mut() {
                    t.rows.push(std::mem::take(&mut self.cur_row));
                }
            }
            TagEnd::Table => {
                if let Some(table) = self.table.take() {
                    let indent = self.indent();
                    self.items.push(MdItem::Table { table, indent });
                }
            }
            _ => {}
        }
    }

    /// Push a style derived by overlaying `bundle` onto the current style — used
    /// for inline roles (emphasis, strong, strikethrough) that add a modifier
    /// (and possibly a color) on top of the surrounding text.
    fn push_style_bundle(&mut self, bundle: StyleBundle) {
        let s = bundle.apply(self.cur_style());
        self.style_stack.push(s);
    }

    fn finish(&mut self) {
        // A still-streaming table (open at end of input) never renders partially;
        // drop its in-progress cell rather than flushing it as stray prose.
        if self.table.is_some() {
            self.inline.clear();
        }
        // Close any dangling paragraph in truncated (still-streaming) input.
        self.flush();
        if let Some((lang, body)) = self.code.take() {
            let body = body.strip_suffix('\n').unwrap_or(&body);
            let lines: Vec<&str> = body.split('\n').collect();
            for line in code_block_lines(&lang, &lines, self.theme, self.highlighter, true, None) {
                self.items.push(MdItem::Verbatim { line, indent: 0 });
            }
        }
    }
}

/// Trim surrounding whitespace from a cell's span run: the leading edge of the
/// first span and the trailing edge of the last, dropping any span left empty.
fn trim_spans(mut spans: Vec<RichSpan>) -> Vec<RichSpan> {
    if let Some(first) = spans.first_mut() {
        first.content = first.content.trim_start().to_string();
    }
    if let Some(last) = spans.last_mut() {
        last.content = last.content.trim_end().to_string();
    }
    spans.retain(|s| !s.content.is_empty());
    spans
}

/// Display columns of a cell's span run, grapheme-aware.
fn spans_cols(spans: &[RichSpan]) -> usize {
    spans
        .iter()
        .map(|s| crate::width::str_cols(&s.content) as usize)
        .sum()
}

/// Style bare `http(s)://` URLs in `text` with the `link` role, leaving the rest
/// at `base`. The link role is overlaid onto `base`, so a URL inside otherwise
/// plain prose keeps that prose's context and gains the link color + underline.
/// Each URL span also carries `href = Some(url)` so OSC 8 / Ctrl+click can open
/// it after wrapping.
fn linkify(text: &str, base: Style, link: StyleBundle) -> Vec<RichSpan> {
    let mut spans = Vec::new();
    let mut rest = text;
    while let Some(start) = rest.find("http://").or_else(|| rest.find("https://")) {
        let (before, from) = rest.split_at(start);
        if !before.is_empty() {
            spans.push(RichSpan::styled(before.to_string(), base, None));
        }
        let raw = from.find(char::is_whitespace).unwrap_or(from.len());
        let end = from[..raw]
            .trim_end_matches(['.', ',', ';', ':', '!', '?', ')', ']'])
            .len();
        let (url, after) = from.split_at(end.max(1));
        spans.push(RichSpan::styled(
            url.to_string(),
            link.apply(base),
            Some(url.to_string()),
        ));
        rest = after;
    }
    if !rest.is_empty() {
        spans.push(RichSpan::styled(rest.to_string(), base, None));
    }
    if spans.is_empty() {
        spans.push(RichSpan::styled(text.to_string(), base, None));
    }
    spans
}

/// Flatten parsed items into lines plus [`BufferLink`]s for every hyperlink run
/// that survived wrapping — labeled markdown links included.
fn flatten_linked(
    items: &[MdItem],
    width: u16,
    theme: &Theme,
) -> (Vec<Line<'static>>, Vec<BufferLink>) {
    let mut images = Vec::new();
    flatten_linked_into(items, width, theme, &mut images)
}

/// Flatten into lines and collect the block images reserved, with the row each
/// landed on, so the [`Markdown`] view can overlay an [`Image`] at the matching
/// screen rect. A block image reserves `rows` blank lines here.
fn flatten_into(
    items: &[MdItem],
    width: u16,
    theme: &Theme,
    images: &mut Vec<MarkdownImage>,
) -> Vec<Line<'static>> {
    flatten_linked_into(items, width, theme, images).0
}

fn flatten_linked_into(
    items: &[MdItem],
    width: u16,
    theme: &Theme,
    images: &mut Vec<MarkdownImage>,
) -> (Vec<Line<'static>>, Vec<BufferLink>) {
    let mut out = Vec::new();
    let mut links = Vec::new();
    for item in items {
        match item {
            MdItem::Blank => out.push(Line::default()),
            MdItem::Prose { spans, indent } => {
                let avail = width.saturating_sub(*indent).max(1);
                for (row, row_links) in wrap_rich(spans, avail) {
                    let line_idx = out.len() as u16;
                    let line = prefix_line(*indent, row);
                    for mut bl in row_links {
                        bl.line = line_idx;
                        bl.start_col = bl.start_col.saturating_add(*indent);
                        bl.end_col = bl.end_col.saturating_add(*indent);
                        links.push(bl);
                    }
                    out.push(line);
                }
            }
            MdItem::Verbatim { line, indent } => {
                out.push(prefix_line(
                    *indent,
                    line.spans
                        .iter()
                        .map(|s| RichSpan {
                            content: s.content.to_string(),
                            style: s.style,
                            href: None,
                        })
                        .collect(),
                ));
            }
            MdItem::Table { table, indent } => {
                let avail = width.saturating_sub(*indent).max(1);
                for (row, row_links) in render_table_linked(table, avail, theme) {
                    let line_idx = out.len() as u16;
                    let line = prefix_line(*indent, row);
                    for mut bl in row_links {
                        bl.line = line_idx;
                        bl.start_col = bl.start_col.saturating_add(*indent);
                        bl.end_col = bl.end_col.saturating_add(*indent);
                        links.push(bl);
                    }
                    out.push(line);
                }
            }
            MdItem::Image { data, alt, indent } => {
                let avail = width.saturating_sub(*indent).max(1);
                let (cols, rows) = image_cell_size(data, avail);
                images.push(MarkdownImage {
                    row: out.len().min(u16::MAX as usize) as u16,
                    indent: *indent,
                    cols,
                    rows,
                    data: data.clone(),
                    alt: alt.clone(),
                });
                // Reserve the image's rows; the view paints pixels over them.
                for _ in 0..rows {
                    out.push(Line::default());
                }
            }
        }
    }
    (out, links)
}

/// Prefix `spans` with `indent` blank columns.
fn prefix_line(indent: u16, mut spans: Vec<RichSpan>) -> Line<'static> {
    if indent == 0 {
        return Line::from(spans.into_iter().map(|s| s.to_span()).collect::<Vec<_>>());
    }
    let mut line = vec![Span::raw(" ".repeat(indent as usize))];
    line.extend(spans.drain(..).map(|s| s.to_span()));
    Line::from(line)
}

/// Word-wrap rich spans to `width`, preserving style and href across the reflow.
/// Returns each output row as `(spans, link runs relative to column 0)`.
fn wrap_rich(spans: &[RichSpan], width: u16) -> Vec<(Vec<RichSpan>, Vec<BufferLink>)> {
    if width == 0 {
        let links = link_runs(spans, 0);
        return vec![(spans.to_vec(), links)];
    }
    // Grapheme cells carry style + href so a multi-scalar emoji stays intact and
    // a labeled link keeps its destination across the wrap.
    let cells: Vec<(&str, Style, Option<&str>)> = spans
        .iter()
        .flat_map(|s| {
            let href = s.href.as_deref();
            s.content.graphemes(true).map(move |g| (g, s.style, href))
        })
        .collect();
    let mut out: Vec<(Vec<RichSpan>, Vec<BufferLink>)> = Vec::new();
    let mut cur: Vec<(&str, Style, Option<&str>)> = Vec::new();
    let mut cur_w = 0u16;
    let mut i = 0;
    let n = cells.len();
    let is_break = |g: &str| g.chars().all(char::is_whitespace);
    while i < n {
        if is_break(cells[i].0) {
            i += 1;
            continue;
        }
        let start = i;
        let mut word_w = 0u16;
        while i < n && !is_break(cells[i].0) {
            word_w = word_w.saturating_add(grapheme_cols(cells[i].0));
            i += 1;
        }
        let word = &cells[start..i];
        let sep = u16::from(!cur.is_empty());
        if word_w <= width && cur_w + sep + word_w <= width {
            if sep == 1 {
                let (_, st, href) = *cur.last().expect("sep implies non-empty cur");
                cur.push((" ", st, href));
                cur_w += 1;
            }
            cur.extend_from_slice(word);
            cur_w += word_w;
        } else if word_w <= width {
            if !cur.is_empty() {
                out.push(coalesce_rich(&cur));
                cur.clear();
            }
            cur.extend_from_slice(word);
            cur_w = word_w;
        } else {
            if !cur.is_empty() {
                out.push(coalesce_rich(&cur));
                cur.clear();
                cur_w = 0;
            }
            for &cell in word {
                let w = grapheme_cols(cell.0);
                if cur_w + w > width && !cur.is_empty() {
                    out.push(coalesce_rich(&cur));
                    cur.clear();
                    cur_w = 0;
                }
                cur.push(cell);
                cur_w += w;
            }
        }
    }
    if !cur.is_empty() {
        out.push(coalesce_rich(&cur));
    }
    if out.is_empty() {
        out.push((Vec::new(), Vec::new()));
    }
    out
}

fn coalesce_rich(cells: &[(&str, Style, Option<&str>)]) -> (Vec<RichSpan>, Vec<BufferLink>) {
    let mut spans: Vec<RichSpan> = Vec::new();
    let mut buf = String::new();
    let mut run_style: Option<Style> = None;
    let mut run_href: Option<String> = None;
    let flush = |spans: &mut Vec<RichSpan>,
                 buf: &mut String,
                 style: &mut Option<Style>,
                 href: &mut Option<String>| {
        if let Some(st) = style.take() {
            spans.push(RichSpan::styled(std::mem::take(buf), st, href.take()));
        }
    };
    for &(g, st, href) in cells {
        let href = href.map(str::to_string);
        match (&run_style, &run_href) {
            (Some(s), h) if *s == st && *h == href => buf.push_str(g),
            _ => {
                flush(&mut spans, &mut buf, &mut run_style, &mut run_href);
                run_style = Some(st);
                run_href = href;
                buf.push_str(g);
            }
        }
    }
    flush(&mut spans, &mut buf, &mut run_style, &mut run_href);
    let links = link_runs(&spans, 0);
    (spans, links)
}

/// Contiguous href runs in `spans`, with columns relative to `col_offset`.
fn link_runs(spans: &[RichSpan], col_offset: u16) -> Vec<BufferLink> {
    let mut links = Vec::new();
    let mut col = col_offset;
    let mut i = 0;
    while i < spans.len() {
        let Some(url) = spans[i].href.clone() else {
            col = col.saturating_add(crate::width::str_cols(&spans[i].content));
            i += 1;
            continue;
        };
        let start = col;
        while i < spans.len() && spans[i].href.as_deref() == Some(url.as_str()) {
            col = col.saturating_add(crate::width::str_cols(&spans[i].content));
            i += 1;
        }
        if col > start {
            links.push(BufferLink {
                line: 0, // filled in by flatten
                start_col: start,
                end_col: col,
                url,
            });
        }
    }
    links
}

/// Lay a table out to `width` columns with box-drawing borders. Column widths
/// fit the content, shrinking the widest columns (and wrapping their cells)
/// until the whole table fits. Link hrefs in cells are preserved.
fn render_table_linked(
    table: &TableData,
    width: u16,
    theme: &Theme,
) -> Vec<(Vec<RichSpan>, Vec<BufferLink>)> {
    let cols = table
        .header
        .len()
        .max(table.rows.iter().map(Vec::len).max().unwrap_or(0))
        .max(1);

    if (width as usize) < 4 * cols + 1 {
        return render_table_plain_linked(table, width, cols, theme);
    }

    let mut widths = vec![0usize; cols];
    for (c, w) in widths.iter_mut().enumerate() {
        *w = spans_cols(cell_at(&table.header, c));
        for row in &table.rows {
            *w = (*w).max(spans_cols(cell_at(row, c)));
        }
        *w = (*w).max(1);
    }

    let budget = (width as usize).saturating_sub(3 * cols + 1).max(cols);
    while widths.iter().sum::<usize>() > budget {
        let (idx, _) = widths.iter().enumerate().max_by_key(|(_, w)| **w).unwrap();
        if widths[idx] <= 1 {
            break;
        }
        widths[idx] -= 1;
    }

    let border = Style::default().fg(theme.dim);
    let mut out = Vec::new();
    out.push((
        vec![RichSpan::styled(
            rule_row_text('', '', '', &widths),
            border,
            None,
        )],
        vec![],
    ));
    out.extend(cell_rows_linked(
        &table.header,
        &widths,
        &table.aligns,
        border,
        cols,
    ));
    out.push((
        vec![RichSpan::styled(
            rule_row_text('', '', '', &widths),
            border,
            None,
        )],
        vec![],
    ));
    for row in &table.rows {
        out.extend(cell_rows_linked(row, &widths, &table.aligns, border, cols));
    }
    out.push((
        vec![RichSpan::styled(
            rule_row_text('', '', '', &widths),
            border,
            None,
        )],
        vec![],
    ));
    out
}

fn render_table_plain_linked(
    table: &TableData,
    width: u16,
    cols: usize,
    theme: &Theme,
) -> Vec<(Vec<RichSpan>, Vec<BufferLink>)> {
    let sep = Style::default().fg(theme.dim);
    let join = |row: &[Cell]| -> Vec<RichSpan> {
        let mut spans = Vec::new();
        for c in 0..cols {
            if c > 0 {
                spans.push(RichSpan::styled(" | ".to_string(), sep, None));
            }
            spans.extend(cell_at(row, c).iter().cloned());
        }
        spans
    };

    let mut out = Vec::new();
    out.extend(wrap_rich(&join(&table.header), width));
    for row in &table.rows {
        out.extend(wrap_rich(&join(row), width));
    }
    out
}

/// The `c`th cell of `row`, or an empty span run when the row is short.
fn cell_at(row: &[Cell], c: usize) -> &[RichSpan] {
    row.get(c).map(Vec::as_slice).unwrap_or(&[])
}

fn rule_row_text(left: char, mid: char, right: char, widths: &[usize]) -> String {
    let mut s = String::new();
    s.push(left);
    for (i, w) in widths.iter().enumerate() {
        s.push_str(&"".repeat(w + 2));
        s.push(if i + 1 == widths.len() { right } else { mid });
    }
    s
}

fn cell_rows_linked(
    row: &[Cell],
    widths: &[usize],
    aligns: &[Alignment],
    border: Style,
    cols: usize,
) -> Vec<(Vec<RichSpan>, Vec<BufferLink>)> {
    let wrapped: Vec<Vec<(Vec<RichSpan>, Vec<BufferLink>)>> = (0..cols)
        .map(|c| {
            let cell = cell_at(row, c);
            if cell.is_empty() {
                vec![(Vec::new(), Vec::new())]
            } else {
                let lines = wrap_rich(cell, widths[c].max(1) as u16);
                if lines.is_empty() {
                    vec![(Vec::new(), Vec::new())]
                } else {
                    lines
                }
            }
        })
        .collect();
    let height = wrapped.iter().map(Vec::len).max().unwrap_or(1);
    let empty: (Vec<RichSpan>, Vec<BufferLink>) = (Vec::new(), Vec::new());
    let mut lines = Vec::new();
    for r in 0..height {
        let mut spans = vec![RichSpan::styled("".to_string(), border, None)];
        let mut links = Vec::new();
        let mut col = 1u16; // after the leading │
        for (c, width) in widths.iter().enumerate() {
            let (content, cell_links) = wrapped[c].get(r).unwrap_or(&empty);
            let content_w = spans_cols(content) as u16;
            let pad = (*width as u16).saturating_sub(content_w);
            let align = aligns.get(c).copied().unwrap_or(Alignment::None);
            let (left, right) = match align {
                Alignment::Right => (pad, 0),
                Alignment::Center => (pad / 2, pad - pad / 2),
                _ => (0, pad),
            };
            // gutter space
            spans.push(RichSpan::styled(" ".to_string(), Style::default(), None));
            col += 1;
            if left > 0 {
                spans.push(RichSpan::styled(
                    " ".repeat(left as usize),
                    Style::default(),
                    None,
                ));
                col += left;
            }
            for mut bl in cell_links.iter().cloned() {
                bl.start_col = bl.start_col.saturating_add(col);
                bl.end_col = bl.end_col.saturating_add(col);
                links.push(bl);
            }
            spans.extend(content.iter().cloned());
            col = col.saturating_add(content_w);
            if right > 0 {
                spans.push(RichSpan::styled(
                    " ".repeat(right as usize),
                    Style::default(),
                    None,
                ));
                col += right;
            }
            spans.push(RichSpan::styled(" ".to_string(), Style::default(), None));
            col += 1;
            spans.push(RichSpan::styled("".to_string(), border, None));
            col += 1;
        }
        lines.push((spans, links));
    }
    lines
}

/// Render a whole markdown string to width-fitted styled lines in one call.
///
/// For streaming input, prefer [`MarkdownState`], which caches the settled
/// prefix instead of re-parsing the whole buffer each frame.
pub fn markdown_to_lines(
    source: &str,
    width: u16,
    theme: &Theme,
    sheet: &StyleSheet,
    highlighter: CodeHighlighter,
) -> Vec<Line<'static>> {
    markdown_to_linked_lines(source, width, theme, sheet, highlighter).0
}

/// Like [`markdown_to_lines`], but also returns [`BufferLink`]s for every
/// hyperlink run (labeled `[text](url)` and bare URLs) after wrapping.
///
/// Apply them with [`apply_buffer_links`] after painting the lines so OSC 8 /
/// Ctrl+click can open the destination even when the visible label is not the
/// URL. Pass [`LinkPolicy::NONE`] to [`apply_buffer_links`] to skip emission.
pub fn markdown_to_linked_lines(
    source: &str,
    width: u16,
    theme: &Theme,
    sheet: &StyleSheet,
    highlighter: CodeHighlighter,
) -> (Vec<Line<'static>>, Vec<BufferLink>) {
    let items = parse(source, theme, sheet, highlighter);
    flatten_linked(&items, width, theme)
}

/// Byte offset of the last *stable block boundary* in `source[from..]`, in
/// absolute bytes: the position just past the last blank line that sits outside
/// an open code fence. Blocks before it are complete and safe to cache; the tail
/// after it is still in flight.
fn stable_boundary(source: &str, from: usize) -> usize {
    let mut fence_open = false;
    let mut boundary = from;
    let mut pos = from;
    for line in source[from..].split_inclusive('\n') {
        let trimmed = line.trim();
        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
            fence_open = !fence_open;
        } else if trimmed.is_empty() && !fence_open {
            boundary = pos + line.len();
        }
        pos += line.len();
    }
    boundary
}

/// Incremental markdown renderer for streamed text — the state to hold across
/// frames for a live transcript.
///
/// Feed it deltas with [`push_str`](Self::push_str) (or replace the whole buffer
/// with [`set`](Self::set)); call [`lines`](Self::lines) each frame for the
/// current width-fitted rendering. Settled blocks — everything before the last
/// blank line outside an open code fence — are parsed, highlighted, **and
/// flattened once** and cached; each delta re-does only the in-flight tail. That
/// keeps a streamed render linear in the transcript length, instead of
/// re-tokenizing and re-laying-out the whole settled prefix on every delta.
///
/// The parse/highlight cache is width-independent. The flattened-line cache is
/// per-width: a resize re-wraps the settled prefix once (then reuses it), and a
/// [`set`](Self::set) or [`Theme`] change discards everything. [`lines`](Self::lines)
/// returns a borrow of the cached line buffer — clone it with `.to_vec()` to own it.
///
/// ```
/// use tuika::{MarkdownState, CodeHighlighter, StyleSheet, Theme};
/// let theme = Theme::default();
/// let sheet = StyleSheet::from_theme(&theme);
/// let mut md = MarkdownState::new();
/// for delta in ["# Title\n\n", "Some **bo", "ld** text.\n"] {
///     md.push_str(delta);                                  // forward each stream delta
///     let _lines = md.lines(80, &theme, &sheet, CodeHighlighter::Plain); // render this frame
/// }
/// ```
#[derive(Default)]
pub struct MarkdownState {
    source: String,
    stable_len: usize,
    stable: Vec<MdItem>,
    cached_theme: Option<Theme>,
    cached_sheet: Option<StyleSheet>,
    // Settled lines are flattened *once*, as blocks settle, and kept here across
    // frames — never re-flattened while streaming. Without this, `lines` would
    // re-flatten (re-wrap, re-lay-out, re-clone) the whole settled prefix every
    // delta, making a streamed render O(n²) in the transcript length. Returning a
    // borrow of this buffer also avoids re-materializing the prefix per frame.
    /// Flattened settled lines followed by the current in-flight tail.
    rendered: Vec<Line<'static>>,
    /// Count of leading `rendered` entries that are settled (cached) lines; the
    /// rest is the per-frame tail, dropped and rebuilt on the next call.
    settled_lines: usize,
    /// Count of `stable` items already flattened into the settled prefix.
    flattened_items: usize,
    /// Width `rendered` was flattened at; a change re-wraps the whole prefix.
    rendered_width: Option<u16>,
    /// Optional host hook turning image URLs into pixels; off ⇒ text placeholders.
    resolver: Option<Box<dyn ImageResolver>>,
    /// Block images in the settled prefix, with their absolute `rendered` rows —
    /// accumulated once as blocks settle, mirroring `settled_lines`.
    settled_images: Vec<MarkdownImage>,
    /// Settled + tail images with absolute rows, rebuilt each [`lines`](Self::lines)
    /// call; returned by [`images`](Self::images).
    frame_images: Vec<MarkdownImage>,
}

impl MarkdownState {
    /// An empty renderer.
    pub fn new() -> Self {
        Self::default()
    }

    /// Render `![alt](url)` images as real pixels, resolving each URL to
    /// [`ImageData`] via `resolver` (markdown carries only the URL — see
    /// [`ImageResolver`]). After each [`lines`](Self::lines) call, read the
    /// reserved placements from [`images`](Self::images) and paint them.
    ///
    /// The resolver may be called repeatedly for an image still in the in-flight
    /// tail (re-parsed each frame), so a host that decodes lazily should cache.
    pub fn with_image_resolver(mut self, resolver: Box<dyn ImageResolver>) -> Self {
        self.resolver = Some(resolver);
        self.reset_cache();
        self
    }

    /// The block images reserved by the last [`lines`](Self::lines) call, with
    /// rows relative to those lines. Empty unless a resolver is attached (see
    /// [`with_image_resolver`](Self::with_image_resolver)). Paint each by
    /// rendering an [`Image`] at [`MarkdownImage::rect`] against the same area.
    pub fn images(&self) -> &[MarkdownImage] {
        &self.frame_images
    }

    /// Append a streamed delta to the buffer (the settled-prefix cache is kept).
    pub fn push_str(&mut self, delta: &str) {
        self.source.push_str(delta);
    }

    /// Replace the whole buffer, discarding the cache. Use for a non-streaming
    /// re-render, or to reset between messages.
    pub fn set(&mut self, source: impl Into<String>) {
        self.source = source.into();
        self.reset_cache();
    }

    /// The accumulated source so far.
    pub fn source(&self) -> &str {
        &self.source
    }

    fn reset_cache(&mut self) {
        self.stable_len = 0;
        self.stable.clear();
        self.rendered.clear();
        self.settled_lines = 0;
        self.flattened_items = 0;
        self.rendered_width = None;
        self.settled_images.clear();
        self.frame_images.clear();
    }

    /// Render the current buffer to final, width-fitted styled lines, advancing
    /// the settled-prefix cache.
    ///
    /// `width` word-wraps prose (code and tables stay verbatim); `theme` supplies
    /// every color via [`Theme::code`](crate::CodeTheme); `highlighter` colors
    /// fenced code ([`CodeHighlighter::Plain`] for none). Draw the result
    /// **without** further wrapping (e.g. ratatui `Paragraph` with no `.wrap`).
    ///
    /// Returns a borrow of an internally-cached line buffer: settled blocks are
    /// flattened once and only the in-flight tail is recomputed per call, so a
    /// streamed render stays linear in the transcript length. The borrow is valid
    /// until the next mutation of `self`; clone with `.to_vec()` if you need to
    /// own it (e.g. to move into a ratatui `Text`).
    pub fn lines(
        &mut self,
        width: u16,
        theme: &Theme,
        sheet: &StyleSheet,
        highlighter: CodeHighlighter,
    ) -> &[Line<'static>] {
        // A theme or stylesheet change restyles everything, so every cache is
        // invalid (both feed the styles baked into the cached, parsed spans).
        if self.cached_theme != Some(*theme) || self.cached_sheet != Some(*sheet) {
            self.cached_theme = Some(*theme);
            self.cached_sheet = Some(*sheet);
            self.reset_cache();
        }
        // A width change re-wraps every settled line, but the width-independent
        // parse cache survives; drop only the flattened lines (and their images,
        // whose row offsets and sizes are width-dependent).
        if self.rendered_width != Some(width) {
            self.rendered_width = Some(width);
            self.rendered.clear();
            self.settled_lines = 0;
            self.flattened_items = 0;
            self.settled_images.clear();
        }

        let boundary = stable_boundary(&self.source, self.stable_len);
        if boundary > self.stable_len {
            let segment = &self.source[self.stable_len..boundary];
            let mut items =
                parse_with(segment, theme, sheet, highlighter, self.resolver.as_deref());
            // Each segment parses in isolation, so the blank-line separation the
            // boundary sits on is lost — restore it between committed segments.
            if !items.is_empty()
                && !self.stable.is_empty()
                && !matches!(self.stable.last(), Some(MdItem::Blank))
            {
                self.stable.push(MdItem::Blank);
            }
            self.stable.append(&mut items);
            self.stable_len = boundary;
        }

        // Drop the previous frame's tail (and settled/tail gap), then extend the
        // settled prefix with any blocks that settled since — flattened once.
        // `flatten` maps each item independently, so appending the new items'
        // lines equals re-flattening the whole prefix.
        self.rendered.truncate(self.settled_lines);
        if self.flattened_items < self.stable.len() {
            let base = self.rendered.len() as u16;
            let mut settled_imgs = Vec::new();
            let settled = flatten_into(
                &self.stable[self.flattened_items..],
                width,
                theme,
                &mut settled_imgs,
            );
            for mut img in settled_imgs {
                img.row = img.row.saturating_add(base);
                self.settled_images.push(img);
            }
            self.rendered.extend(settled);
            self.flattened_items = self.stable.len();
            self.settled_lines = self.rendered.len();
        }

        let tail = parse_with(
            &self.source[self.stable_len..],
            theme,
            sheet,
            highlighter,
            self.resolver.as_deref(),
        );
        let mut tail_imgs = Vec::new();
        let tail_lines = flatten_into(&tail, width, theme, &mut tail_imgs);
        // The tail begins just past the boundary's blank line; keep that gap.
        if !self.rendered.is_empty()
            && !tail_lines.is_empty()
            && !is_blank_line(self.rendered.last().unwrap())
            && !is_blank_line(&tail_lines[0])
        {
            self.rendered.push(Line::default());
        }
        let tail_base = self.rendered.len() as u16;
        self.rendered.extend(tail_lines);

        // Republish this frame's placements: the settled prefix (fixed) plus the
        // in-flight tail, each shifted to its absolute row in `rendered`.
        self.frame_images.clear();
        self.frame_images
            .extend(self.settled_images.iter().cloned());
        for mut img in tail_imgs {
            img.row = img.row.saturating_add(tail_base);
            self.frame_images.push(img);
        }
        &self.rendered
    }
}

/// Whether a rendered line is visually blank (no spans, or only whitespace).
fn is_blank_line(line: &Line) -> bool {
    line.spans.iter().all(|s| s.content.trim().is_empty())
}

/// A view that renders a static markdown string to its area — word-wrapping
/// prose to the width and drawing code and tables verbatim.
///
/// ![markdown demo](https://raw.githubusercontent.com/everruns/yolop/main/crates/tuika/docs/demos/markdown.gif)
///
/// For a *streaming* transcript, hold a [`MarkdownState`] and draw its
/// [`lines`](MarkdownState::lines) directly (that is what the demo above does);
/// this view is the one-shot convenience for static markdown placed in a layout.
///
/// # Options
///
/// | Builder | Default | Effect |
/// | --- | --- | --- |
/// | [`new(source)`](Self::new) | — | the markdown source to render |
/// | [`highlighter(&h)`](Self::highlighter) | plain | syntax-highlight fenced code |
/// | [`images(&r, s, &l)`](Self::images) | off | render `![alt](url)` as real pixels |
/// | [`link_policy(p)`](Self::link_policy) | [`LinkPolicy::WEB`] | OSC 8 schemes for links |
///
/// ```no_run
/// use tuika::Markdown;
/// let doc = Markdown::new("# Title\n\nSome **bold** prose.");
/// // `doc` is a `View`: render it via `tuika::paint` or embed it in a `Flex`.
/// # let _ = doc;
/// ```
pub struct Markdown<'a> {
    source: String,
    highlighter: CodeHighlighter<'a>,
    resolver: Option<&'a dyn ImageResolver>,
    image_support: ImageSupport,
    image_layer: Option<ImageLayer>,
    /// Which URL schemes become OSC 8 hyperlinks when this view paints.
    link_policy: LinkPolicy,
}

impl<'a> Markdown<'a> {
    /// A markdown view over `source`, rendering fenced code as plain text until
    /// a highlighter is attached with [`highlighter`](Self::highlighter).
    pub fn new(source: impl Into<String>) -> Self {
        Self {
            source: source.into(),
            highlighter: CodeHighlighter::Plain,
            resolver: None,
            image_support: ImageSupport::None,
            image_layer: None,
            link_policy: LinkPolicy::default(),
        }
    }

    /// Use `highlighter` to syntax-highlight fenced code blocks.
    pub fn highlighter(mut self, highlighter: &'a dyn Highlighter) -> Self {
        self.highlighter = CodeHighlighter::With(highlighter);
        self
    }

    /// Configure which URL schemes are emitted as OSC 8 hyperlinks.
    ///
    /// The default ([`LinkPolicy::WEB`]) links `http(s)` only.
    /// [`LinkPolicy::NONE`] paints styled labels but emits no OSC 8 — useful when
    /// the host handles clicks itself or wants links inert.
    pub fn link_policy(mut self, policy: LinkPolicy) -> Self {
        self.link_policy = policy;
        self
    }

    /// Render `![alt](url)` images as real pixels.
    ///
    /// `resolver` decodes each URL to [`ImageData`] (markdown has only the URL —
    /// see [`ImageResolver`]); a resolved image becomes a block reserved in the
    /// layout and painted over by an [`Image`] using `support`, recording its
    /// placement into `layer` for the host to [`emit`](ImageLayer::emit) after the
    /// frame. Unresolved images, and every image when `support` is
    /// [`ImageSupport::None`], fall back to the text placeholder / alt text.
    pub fn images(
        mut self,
        resolver: &'a dyn ImageResolver,
        support: ImageSupport,
        layer: &ImageLayer,
    ) -> Self {
        self.resolver = Some(resolver);
        self.image_support = support;
        self.image_layer = Some(layer.clone());
        self
    }

    /// Flatten the source to lines, block images, and hyperlink runs.
    fn lines_images_links(
        &self,
        width: u16,
        theme: &Theme,
        sheet: &StyleSheet,
    ) -> (Vec<Line<'static>>, Vec<MarkdownImage>, Vec<BufferLink>) {
        let items = parse_with(&self.source, theme, sheet, self.highlighter, self.resolver);
        let mut images = Vec::new();
        let (lines, links) = flatten_linked_into(&items, width, theme, &mut images);
        (lines, images, links)
    }
}

impl View for Markdown<'_> {
    fn measure(&self, available: Size) -> Size {
        let (lines, _, _) =
            self.lines_images_links(available.width, &Theme::default(), &StyleSheet::default());
        let width = lines.iter().map(line_width).max().unwrap_or(0);
        Size::new(width.min(available.width), lines.len() as u16)
    }

    fn render(&self, area: Rect, surface: &mut Surface, ctx: &RenderCtx) {
        let (lines, images, links) = self.lines_images_links(area.width, ctx.theme, &ctx.sheet);
        for (row, line) in lines.iter().enumerate() {
            let y = area.y.saturating_add(row as u16);
            if y >= area.bottom() {
                break;
            }
            let mut x = area.x;
            for span in &line.spans {
                if x >= area.right() {
                    break;
                }
                x = surface.set_string(x, y, span.content.as_ref(), span.style);
            }
        }
        // Embed OSC 8 for labeled links (and bare URLs) so Ctrl+click / Ghostty
        // open the destination even when the visible text is not the URL.
        apply_buffer_links(
            surface.buffer_mut(),
            ratatui_core::layout::Position {
                x: area.x,
                y: area.y,
            },
            &links,
            self.link_policy,
        );
        // Overlay each block image on the rows it reserved, reusing the standalone
        // `Image` component for pixel emission and the alt fallback alike.
        for img in images {
            let y = area.y.saturating_add(img.row);
            let x = area.x.saturating_add(img.indent);
            if y >= area.bottom() || x >= area.right() {
                continue;
            }
            let rect = Rect {
                x,
                y,
                width: img.cols.min(area.right() - x),
                height: img.rows.min(area.bottom() - y),
            };
            let mut image = Image::new(img.data, img.cols, img.rows)
                .support(self.image_support)
                .alt(img.alt);
            if let Some(layer) = &self.image_layer {
                image = image.in_layer(layer);
            }
            image.render(rect, surface, ctx);
        }
    }
}

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

    /// Plain text of a rendered line (spans concatenated).
    fn text(line: &Line) -> String {
        line.spans.iter().map(|s| s.content.as_ref()).collect()
    }

    /// The whole render as plain lines, for content assertions.
    fn plain(source: &str, width: u16) -> Vec<String> {
        markdown_to_lines(
            source,
            width,
            &Theme::default(),
            &StyleSheet::default(),
            CodeHighlighter::Plain,
        )
        .iter()
        .map(text)
        .collect()
    }

    #[test]
    fn heading_is_bold_and_themed() {
        let theme = Theme::default();
        let lines = markdown_to_lines(
            "# Title",
            40,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        let span = &lines[0].spans[0];
        assert_eq!(span.content.as_ref(), "Title");
        assert!(span.style.add_modifier.contains(Modifier::BOLD));
        assert_eq!(span.style.fg, Some(theme.code.heading));
    }

    #[test]
    fn emphasis_and_strong_carry_modifiers() {
        let theme = Theme::default();
        let lines = markdown_to_lines(
            "plain *em* and **bold**",
            60,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        let em = lines[0]
            .spans
            .iter()
            .find(|s| s.content.contains("em"))
            .expect("emphasis span");
        assert!(em.style.add_modifier.contains(Modifier::ITALIC));
        let bold = lines[0]
            .spans
            .iter()
            .find(|s| s.content.contains("bold"))
            .expect("strong span");
        assert!(bold.style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn inline_code_gets_code_background() {
        let theme = Theme::default();
        let lines = markdown_to_lines(
            "use `cargo test` now",
            60,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        let code = lines[0]
            .spans
            .iter()
            .find(|s| s.content.contains("cargo test"))
            .expect("inline code span");
        assert_eq!(code.style.bg, Some(theme.code.background));
    }

    #[test]
    fn bullet_list_renders_markers() {
        let out = plain("- one\n- two", 40);
        assert!(out.iter().any(|l| l.contains("• one")), "{out:?}");
        assert!(out.iter().any(|l| l.contains("• two")), "{out:?}");
    }

    #[test]
    fn ordered_list_numbers_increment() {
        let out = plain("1. first\n2. second", 40);
        assert!(out.iter().any(|l| l.contains("1. first")), "{out:?}");
        assert!(out.iter().any(|l| l.contains("2. second")), "{out:?}");
    }

    #[test]
    fn nested_list_is_indented() {
        let out = plain("- outer\n  - inner", 40);
        let inner = out.iter().find(|l| l.contains("inner")).unwrap();
        assert!(
            inner.starts_with("  "),
            "nested item should be indented: {inner:?}"
        );
    }

    #[test]
    fn fenced_code_preserves_indentation_verbatim() {
        // A line-oriented wrapper would eat the leading spaces; code must not.
        let src = "```\n    indented\n```";
        let out = plain(src, 40);
        assert!(
            out.iter().any(|l| l.contains("    indented")),
            "code indentation must survive: {out:?}"
        );
    }

    #[test]
    fn fenced_code_shows_language_label() {
        let out = plain("```rust\nfn main() {}\n```", 40);
        assert!(out.iter().any(|l| l.contains("rust")), "{out:?}");
    }

    #[test]
    fn code_fence_is_not_word_wrapped() {
        // A long code line exceeds width but is emitted as a single (clipped)
        // row, never reflowed into multiple lines.
        let long = "x".repeat(60);
        let src = format!("```\n{long}\n```");
        let lines = markdown_to_lines(
            &src,
            20,
            &Theme::default(),
            &StyleSheet::default(),
            CodeHighlighter::Plain,
        );
        let code_rows = lines.iter().filter(|l| text(l).contains("xxxx")).count();
        assert_eq!(code_rows, 1, "code line must not wrap");
    }

    #[test]
    fn prose_word_wraps_to_width() {
        let out = plain("one two three four five six seven eight", 12);
        assert!(out.len() > 1, "long prose should wrap: {out:?}");
        for line in &out {
            assert!(line.chars().count() <= 12, "line over width: {line:?}");
        }
    }

    #[test]
    fn table_renders_boxed_with_headers() {
        let src = "| A | B |\n| - | - |\n| 1 | 2 |";
        let out = plain(src, 40);
        assert!(out.iter().any(|l| l.contains('')), "top border: {out:?}");
        assert!(
            out.iter().any(|l| l.contains('A') && l.contains('B')),
            "header: {out:?}"
        );
        assert!(
            out.iter().any(|l| l.contains('1') && l.contains('2')),
            "row: {out:?}"
        );
    }

    #[test]
    fn table_header_cells_are_bold_and_themed() {
        let theme = Theme::default();
        let src = "| Name | Kind |\n| --- | --- |\n| a | b |";
        let lines = markdown_to_lines(
            src,
            40,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        let head = lines
            .iter()
            .flat_map(|l| &l.spans)
            .find(|s| s.content.contains("Name"))
            .expect("header cell span");
        assert!(head.style.add_modifier.contains(Modifier::BOLD));
        assert_eq!(head.style.fg, Some(theme.code.heading));
    }

    #[test]
    fn table_cell_link_is_styled() {
        let theme = Theme::default();
        let src = "| Site |\n| --- |\n| [yolop](https://everruns.dev) |";
        let lines = markdown_to_lines(
            src,
            40,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        let link = lines
            .iter()
            .flat_map(|l| &l.spans)
            .find(|s| s.content.contains("yolop"))
            .expect("link cell span");
        assert_eq!(link.style.fg, Some(theme.code.link));
        assert!(link.style.add_modifier.contains(Modifier::UNDERLINED));
    }

    #[test]
    fn table_cell_bold_and_inline_code_survive() {
        let theme = Theme::default();
        let src = "| Col |\n| --- |\n| **hi** and `cargo` |";
        let lines = markdown_to_lines(
            src,
            40,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        let spans: Vec<&Span> = lines.iter().flat_map(|l| &l.spans).collect();
        let bold = spans
            .iter()
            .find(|s| s.content.contains("hi"))
            .expect("bold span");
        assert!(bold.style.add_modifier.contains(Modifier::BOLD));
        let code = spans
            .iter()
            .find(|s| s.content.contains("cargo"))
            .expect("code span");
        assert_eq!(code.style.bg, Some(theme.code.background));
    }

    #[test]
    fn table_cell_emoji_keeps_borders_aligned() {
        // A wide emoji is measured grapheme-aware, so every boxed row stays the
        // same rendered width and the borders line up.
        let src = "| Status |\n| --- |\n| ok ✅ |\n| bad |";
        let lines = markdown_to_lines(
            src,
            40,
            &Theme::default(),
            &StyleSheet::default(),
            CodeHighlighter::Plain,
        );
        let box_rows: Vec<u16> = lines
            .iter()
            .filter(|l| text(l).contains(''))
            .map(line_width)
            .collect();
        assert!(box_rows.len() >= 2, "expected boxed rows: {box_rows:?}");
        assert!(
            box_rows.windows(2).all(|w| w[0] == w[1]),
            "boxed rows must share one width: {box_rows:?}"
        );
    }

    #[test]
    fn table_falls_back_to_plain_when_too_narrow_and_always_fits() {
        let src = "| Col A | Col B |\n| --- | --- |\n| alpha | beta |";
        for width in [4u16, 8, 12, 20, 48] {
            let lines = markdown_to_lines(
                src,
                width,
                &Theme::default(),
                &StyleSheet::default(),
                CodeHighlighter::Plain,
            );
            for line in &lines {
                assert!(
                    line_width(line) <= width,
                    "table line exceeded width {width}: {:?}",
                    text(line)
                );
            }
            let body: String = lines.iter().map(text).collect::<Vec<_>>().join("\n");
            // "Col" (3 cols) survives intact even at the narrowest width; wider
            // cells may wrap across rows below the boxing threshold.
            assert!(body.contains("Col"), "content survives at width {width}");
        }
    }

    #[test]
    fn bare_url_is_linkified() {
        let theme = Theme::default();
        let lines = markdown_to_lines(
            "see https://example.com now",
            60,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        let url = lines[0]
            .spans
            .iter()
            .find(|s| s.content.as_ref().contains("example.com"))
            .expect("url span");
        assert_eq!(url.style.fg, Some(theme.code.link));
        assert!(url.style.add_modifier.contains(Modifier::UNDERLINED));
    }

    #[test]
    fn labeled_markdown_link_preserves_destination_for_ctrl_click() {
        // Reproduction of the Ghostty Ctrl+click failure: `[label](url)` was
        // only styled — the destination was dropped — so OSC 8 / ctrl_click had
        // nothing to open under the pointer.
        use crate::{Mouse, MouseButton, MouseKind, apply_buffer_links, ctrl_click_url};
        use ratatui_core::buffer::Buffer;
        use ratatui_core::layout::Position;

        let theme = Theme::default();
        let (lines, links) = markdown_to_linked_lines(
            "See the [docs](https://example.com/api) please.",
            60,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        assert!(
            links.iter().any(|l| l.url == "https://example.com/api"),
            "labeled link must yield a BufferLink: {links:?}"
        );
        let link = links
            .iter()
            .find(|l| l.url == "https://example.com/api")
            .unwrap();
        // Visible text is the label, not the URL.
        let plain: String = lines[link.line as usize]
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(plain.contains("docs"), "label visible: {plain:?}");
        assert!(
            !plain.contains("example.com"),
            "URL must not replace the label: {plain:?}"
        );

        let area = Rect::new(0, 0, 60, 3);
        let mut buffer = Buffer::empty(area);
        for (row, line) in lines.iter().enumerate() {
            let mut x = 0u16;
            for span in &line.spans {
                x = buffer.set_span(x, row as u16, span, area.width).0;
            }
        }
        apply_buffer_links(
            &mut buffer,
            Position { x: 0, y: 0 },
            &links,
            LinkPolicy::WEB,
        );
        let click_col = link.start_col + 1; // inside "docs"
        let mut event = Mouse::at(MouseKind::Up(MouseButton::Left), click_col, link.line);
        event.ctrl = true;
        assert_eq!(
            ctrl_click_url(&event, &buffer, area).as_deref(),
            Some("https://example.com/api"),
            "Ctrl+click on the label must resolve the markdown destination"
        );
    }

    #[test]
    fn custom_sheet_restyles_both_links_and_bare_urls() {
        use ratatui_core::style::Color;
        let theme = Theme::default();
        // One central rule remaps the link role: green + bold, no underline.
        let sheet = StyleSheet {
            link: StyleBundle::new().fg(Color::Green).bold(),
            ..StyleSheet::from_theme(&theme)
        };
        // A markdown link and a bare URL — both resolve the same `link` role.
        let lines = markdown_to_lines(
            "[docs](https://ex.com) and https://bare.example.com here",
            80,
            &theme,
            &sheet,
            CodeHighlighter::Plain,
        );
        let spans: Vec<&Span> = lines.iter().flat_map(|l| &l.spans).collect();
        for needle in ["docs", "bare.example.com"] {
            let span = spans
                .iter()
                .find(|s| s.content.contains(needle))
                .unwrap_or_else(|| panic!("missing {needle:?} span"));
            assert_eq!(span.style.fg, Some(Color::Green), "{needle}: recolored");
            assert!(
                span.style.add_modifier.contains(Modifier::BOLD),
                "{needle}: bold"
            );
            assert!(
                !span.style.add_modifier.contains(Modifier::UNDERLINED),
                "{needle}: underline dropped by the custom rule"
            );
        }
    }

    #[test]
    fn custom_sheet_restyles_headings() {
        use ratatui_core::style::Color;
        let theme = Theme::default();
        let sheet = StyleSheet {
            heading: StyleBundle::new().fg(Color::Magenta).italic(),
            ..StyleSheet::from_theme(&theme)
        };
        let lines = markdown_to_lines("# Title", 40, &theme, &sheet, CodeHighlighter::Plain);
        let span = &lines[0].spans[0];
        assert_eq!(span.content.as_ref(), "Title");
        assert_eq!(span.style.fg, Some(Color::Magenta));
        assert!(span.style.add_modifier.contains(Modifier::ITALIC));
        // The default heading was bold; this rule doesn't set bold, so it's gone.
        assert!(!span.style.add_modifier.contains(Modifier::BOLD));
    }

    #[test]
    fn sheet_change_invalidates_stream_cache() {
        use ratatui_core::style::Color;
        let theme = Theme::default();
        let mut state = MarkdownState::new();
        state.set("A [link](https://ex.com) in prose.");

        let default_sheet = StyleSheet::from_theme(&theme);
        let link_fg = |lines: &[Line<'static>]| {
            lines
                .iter()
                .flat_map(|l| &l.spans)
                .find(|s| s.content.contains("link"))
                .expect("link span")
                .style
                .fg
        };
        assert_eq!(
            link_fg(state.lines(60, &theme, &default_sheet, CodeHighlighter::Plain)),
            Some(theme.code.link)
        );

        // Same theme, different stylesheet: the cached spans must be rebuilt.
        let recolored = StyleSheet {
            link: StyleBundle::new().fg(Color::Green),
            ..default_sheet
        };
        assert_eq!(
            link_fg(state.lines(60, &theme, &recolored, CodeHighlighter::Plain)),
            Some(Color::Green),
            "a stylesheet change must invalidate the stream cache"
        );
    }

    #[test]
    fn streaming_matches_one_shot_render() {
        let full = "# Heading\n\nA paragraph of text.\n\n```rust\nfn main() {}\n```\n\nDone.";
        let theme = Theme::default();
        let one_shot: Vec<String> = markdown_to_lines(
            full,
            40,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        )
        .iter()
        .map(text)
        .collect();

        // Feed the same content in awkward chunks.
        let mut state = MarkdownState::new();
        let mut streamed = Vec::new();
        for chunk in [
            "# Head",
            "ing\n\nA para",
            "graph of text.\n\n```rus",
            "t\nfn main() {}\n```\n\nDone.",
        ] {
            state.push_str(chunk);
            streamed = state
                .lines(
                    40,
                    &theme,
                    &StyleSheet::from_theme(&theme),
                    CodeHighlighter::Plain,
                )
                .iter()
                .map(text)
                .collect();
        }
        assert_eq!(streamed, one_shot);
    }

    #[test]
    fn streaming_then_resize_matches_one_shot_at_new_width() {
        // The settled-prefix line cache is width-specific: a width change must
        // re-wrap the whole prefix, not serve stale lines flattened at the old
        // width. Settle several blocks at a wide width, then render narrower.
        let theme = Theme::default();
        let chunks = [
            "# A wide head",
            "ing that wraps when narrow\n\nA para",
            "graph long enough to wrap differently at 24 columns than at 60.\n\n",
            "- a bullet that also wraps\n\nDone.",
        ];
        let full: String = chunks.concat();

        let mut state = MarkdownState::new();
        for chunk in chunks {
            state.push_str(chunk);
            let _ = state.lines(
                60,
                &theme,
                &StyleSheet::from_theme(&theme),
                CodeHighlighter::Plain,
            );
        }
        let resized: Vec<String> = state
            .lines(
                24,
                &theme,
                &StyleSheet::from_theme(&theme),
                CodeHighlighter::Plain,
            )
            .iter()
            .map(text)
            .collect();
        let one_shot: Vec<String> = markdown_to_lines(
            &full,
            24,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        )
        .iter()
        .map(text)
        .collect();
        assert_eq!(
            resized, one_shot,
            "resized stream must equal a one-shot render at the new width"
        );
    }

    #[test]
    fn streaming_commits_a_stable_prefix() {
        let theme = Theme::default();
        let mut state = MarkdownState::new();
        state.push_str("First paragraph.\n\nSecond a");
        let _ = state.lines(
            40,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        // The blank line after the first paragraph is a stable boundary, so its
        // bytes are committed to the cache and won't be re-parsed.
        assert!(state.stable_len > 0, "expected a committed prefix");
        assert!(!state.stable.is_empty());
    }

    #[test]
    fn stable_boundary_never_splits_open_code_fence() {
        // A blank line *inside* an unterminated fence is not a boundary.
        let src = "```\ncode\n\nmore code";
        assert_eq!(stable_boundary(src, 0), 0);
        // Once the fence closes, the trailing blank becomes a boundary.
        let closed = "```\ncode\n```\n\nafter";
        assert!(stable_boundary(closed, 0) > 0);
    }

    #[test]
    fn partial_emphasis_degrades_gracefully() {
        // An unterminated `**` should not panic and should still render text.
        let out = plain("this is **unfinished", 40);
        assert!(out.iter().any(|l| l.contains("unfinished")), "{out:?}");
    }

    #[test]
    fn theme_change_invalidates_cache() {
        let mut state = MarkdownState::new();
        state.push_str("Para one.\n\nPara two.\n\ntail");
        let a = Theme::default();
        let _ = state.lines(40, &a, &StyleSheet::from_theme(&a), CodeHighlighter::Plain);
        assert!(state.stable_len > 0);

        let mut b = Theme::default();
        b.code.heading = ratatui_core::style::Color::Indexed(200);
        let _ = state.lines(40, &b, &StyleSheet::from_theme(&b), CodeHighlighter::Plain);
        // Cache was rebuilt under the new theme; still consistent, no stale panic.
        assert_eq!(state.cached_theme, Some(b));
    }

    #[test]
    fn image_renders_alt_as_a_marked_placeholder() {
        let theme = Theme::default();
        let lines = markdown_to_lines(
            "look: ![a cat](https://ex.com/cat.png) ok",
            60,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        let whole: String = lines.iter().map(text).collect::<Vec<_>>().join("\n");
        // The alt text shows behind an image marker; the surrounding prose stays.
        assert!(whole.contains("🖼 a cat"), "expected marked alt: {whole:?}");
        assert!(whole.contains("look:") && whole.contains("ok"));
        // The alt label is link-styled, not plain body text.
        let label = lines
            .iter()
            .flat_map(|l| &l.spans)
            .find(|s| s.content.contains("a cat"))
            .expect("alt span");
        assert_eq!(label.style.fg, Some(theme.code.link));
        assert!(label.style.add_modifier.contains(Modifier::UNDERLINED));
    }

    #[test]
    fn image_without_alt_shows_the_url_so_it_is_never_dropped() {
        // Before Tag::Image handling, an alt-less image vanished entirely — URL
        // and all. Now the URL itself is the visible, link-styled label.
        let out = plain("![](https://ex.com/x.png)", 60).join("\n");
        assert!(out.contains("🖼 "), "marker present: {out:?}");
        assert!(out.contains("https://ex.com/x.png"), "url shown: {out:?}");
    }

    /// A resolver that returns a fixed image for any URL containing "ok".
    struct StubResolver;
    impl ImageResolver for StubResolver {
        fn resolve(&self, url: &str) -> Option<ImageData> {
            url.contains("ok")
                .then(|| ImageData::from_rgba(4, 2, vec![0u8; 4 * 2 * 4]).unwrap())
        }
    }

    #[test]
    fn resolved_block_image_reserves_rows_and_records_a_placement() {
        use crate::testing::render;
        let theme = Theme::default();
        let layer = ImageLayer::new();
        let resolver = StubResolver;
        let view = Markdown::new("text before\n\n![a cat](ok.png)\n\nafter").images(
            &resolver,
            ImageSupport::Kitty,
            &layer,
        );
        // Render into a wide/tall buffer; the block image reserves rows and
        // records exactly one placement into the layer.
        let _buf = render(&view, 40, 12, &theme);
        assert_eq!(layer.len(), 1, "one block image recorded");
    }

    #[test]
    fn unresolved_image_stays_an_inline_placeholder_even_with_images_enabled() {
        use crate::testing::render;
        let theme = Theme::default();
        let layer = ImageLayer::new();
        let resolver = StubResolver;
        // URL lacks "ok", so the resolver declines → inline placeholder, no pixels.
        let view =
            Markdown::new("![a dog](nope.png)").images(&resolver, ImageSupport::Kitty, &layer);
        let buf = render(&view, 40, 4, &theme);
        let mut whole = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                whole.push_str(buf[(x, y)].symbol());
            }
        }
        assert!(whole.contains("🖼 "), "placeholder marker shown: {whole:?}");
        assert!(layer.is_empty(), "declined image records no placement");
    }

    #[test]
    fn block_image_without_graphics_support_shows_alt_fallback() {
        use crate::testing::render;
        let theme = Theme::default();
        let layer = ImageLayer::new();
        let resolver = StubResolver;
        // Resolver yields pixels, but the terminal has no graphics support.
        let view = Markdown::new("![a cat](ok.png)").images(&resolver, ImageSupport::None, &layer);
        let buf = render(&view, 40, 6, &theme);
        let mut whole = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                whole.push_str(buf[(x, y)].symbol());
            }
        }
        assert!(
            whole.contains("[image: a cat]"),
            "alt fallback painted: {whole:?}"
        );
        assert!(layer.is_empty(), "no placement without graphics support");
    }

    #[test]
    fn block_image_reserves_height_proportional_to_aspect() {
        // A 40x2 image (wide) reserves few rows; a 4x40 image (tall) reserves more.
        let wide = ImageData::from_rgba(40, 2, vec![0u8; 40 * 2 * 4]).unwrap();
        let tall = ImageData::from_rgba(4, 40, vec![0u8; 4 * 40 * 4]).unwrap();
        let (_, wr) = image_cell_size(&wide, 40);
        let (_, tr) = image_cell_size(&tall, 40);
        assert!(wr < tr, "tall image reserves more rows: {wr} vs {tr}");
        assert!(wr >= 1 && tr <= 30, "rows are clamped: {wr}, {tr}");
    }

    #[test]
    fn streaming_state_reports_a_block_image_placement() {
        let theme = Theme::default();
        let mut md = MarkdownState::new().with_image_resolver(Box::new(StubResolver));
        md.set("intro line\n\n![a cat](ok.png)\n\ntail line");
        let lines = md
            .lines(
                40,
                &theme,
                &StyleSheet::from_theme(&theme),
                CodeHighlighter::Plain,
            )
            .to_vec();
        let imgs = md.images();
        assert_eq!(imgs.len(), 1, "one block image reported");
        let img = &imgs[0];
        assert_eq!(img.alt, "a cat");
        // The reported row is inside the rendered lines and is a reserved blank.
        assert!((img.row as usize) < lines.len(), "row within lines");
        assert!(
            is_blank_line(&lines[img.row as usize]),
            "reserved row is blank"
        );
        // "intro line" is above the image, "tail line" below it.
        assert!(text(&lines[0]).contains("intro"));
    }

    #[test]
    fn streaming_image_row_matches_one_shot() {
        // Feeding the same document incrementally lands the image on the same row
        // as parsing it whole — the settled/tail offset bookkeeping is consistent.
        let theme = Theme::default();
        let doc = "# Title\n\nbefore\n\n![pic](ok.png)\n\nafter paragraph here";

        let mut whole = MarkdownState::new().with_image_resolver(Box::new(StubResolver));
        whole.set(doc);
        let _ = whole.lines(
            30,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        let whole_row = whole.images()[0].row;

        let mut streamed = MarkdownState::new().with_image_resolver(Box::new(StubResolver));
        for chunk in [
            "# Title\n\nbe",
            "fore\n\n![pic](ok",
            ".png)\n\nafter ",
            "paragraph here",
        ] {
            streamed.push_str(chunk);
            let _ = streamed.lines(
                30,
                &theme,
                &StyleSheet::from_theme(&theme),
                CodeHighlighter::Plain,
            );
        }
        assert_eq!(streamed.images().len(), 1);
        assert_eq!(
            streamed.images()[0].row,
            whole_row,
            "streamed image row matches one-shot"
        );
    }

    #[test]
    fn no_resolver_means_no_streaming_placements() {
        let theme = Theme::default();
        let mut md = MarkdownState::new();
        md.set("![a cat](ok.png)");
        let _ = md.lines(
            40,
            &theme,
            &StyleSheet::from_theme(&theme),
            CodeHighlighter::Plain,
        );
        assert!(md.images().is_empty(), "images() empty without a resolver");
    }

    #[test]
    fn markdown_image_rect_offsets_by_area_and_row() {
        let img = MarkdownImage {
            row: 3,
            indent: 2,
            cols: 10,
            rows: 4,
            data: ImageData::from_rgba(2, 2, vec![0u8; 16]).unwrap(),
            alt: String::new(),
        };
        let rect = img.rect(Rect::new(5, 1, 40, 20));
        assert_eq!((rect.x, rect.y, rect.width, rect.height), (7, 4, 10, 4));
        // Clamped to the area when it would overflow.
        let tight = img.rect(Rect::new(5, 1, 8, 5));
        assert_eq!(tight.width, 6, "clamped to area right edge");
    }
}