mindfork 0.19.0

A terminal AI chat written in Rust: local models via llama.cpp, or OpenAI, Anthropic, Gemini, Grok and OpenRouter in the cloud, with persistent memory, notes, RAG and tools.
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
//! Markdown — pulldown-cmark event walker → lines (Writer). Part of module
//! [`super`]; split out of the markdown.rs monolith (see
//! docs/history/refactoring-god-objects.md, stage 6).

use super::*;

/// Line accumulator: unrolls the pulldown-cmark event stream into `Vec<Line>`.
pub(super) struct Writer {
    palette: Palette,
    /// Panel width in columns (table layout).
    width: usize,
    pub(super) lines: Vec<Line<'static>>,
    /// Inline-style stack (top — current).
    inline_styles: Vec<Style>,
    /// Line prefixes (for quotes: `>`), applied in [`Writer::push_line`].
    line_prefixes: Vec<Span<'static>>,
    /// Line-style stack (quotes/code block).
    line_styles: Vec<Style>,
    /// List-index stack (`None` — bulleted, `Some` — numbered).
    list_indices: Vec<Option<u64>>,
    /// Accumulated link URL (appended when the tag closes).
    link: Option<String>,
    /// Accumulated image URL (separate from `link` — an image can sit inside
    /// a link).
    image: Option<String>,
    /// Highlighter for the active code block.
    code_highlighter: Option<HighlightLines<'static>>,
    /// Active table collection (`None` outside a table).
    table: Option<TableBuilder>,
    /// Raw source of the HTML block being collected (`None` outside one).
    /// Block-level HTML arrives as opaque `Html` chunks split by line, and a
    /// tag can straddle two of them — so the block is accumulated whole and
    /// converted once, at [`Writer::end_html_block`]. See [`super::html`].
    html: Option<String>,
    /// Whether a blank separator is needed before the next block.
    needs_newline: bool,
    /// A list item was just opened (the marker line `1. `/`- ` is already
    /// added), and this item's first paragraph should continue **on the
    /// marker's line**, not start a new one. In "loose" lists pulldown-cmark
    /// wraps the item's content in a `Paragraph`; without this flag the
    /// number would stay on one line and the text would slide to the next.
    /// Reset at the start of any `Start(tag)` and at `End(Item)` — otherwise
    /// in a **tight** list, which has no `Paragraph` wrapper, nothing would
    /// consume the flag and it would "leak" onto the next block.
    item_marker_open: bool,
    /// Treat a "soft" break (a single `\n`) as a real line break (GFM style).
    /// For user messages — `true`. See [`RenderOpts`].
    pub(super) soft_break_as_newline: bool,
    /// Horizontal separators between table body rows. See [`RenderOpts`].
    pub(super) table_row_separators: bool,
    /// Render ```mermaid blocks as a diagram. See [`RenderOpts`] and the
    /// [`super::mermaid`] submodule.
    pub(super) render_mermaid: bool,
    /// The background of an unhighlighted code block. See [`RenderOpts`].
    pub(super) code_block_background: CodeBlockBackground,
    /// Active collection of a ```mermaid block: `(fence info string, source)`.
    /// While `Some`, `Text` events accumulate here (modeled on
    /// [`TableBuilder`]), and [`Writer::end_codeblock`] decides "diagram or
    /// fallback source". The info string is stored whole
    /// (` ```mermaid title=x `) — the fallback prints it into the fence
    /// byte-for-byte, like the old path.
    mermaid: Option<(String, String)>,
    /// Whether the fence of the code block currently being opened is closed
    /// (set in [`Writer::run`] before every `Start(CodeBlock)`, from the
    /// source, see [`fenced_block_is_closed`]). Needed only by the mermaid
    /// path: pulldown-cmark itself closes an unclosed fence at the end of the
    /// document, so a stream-truncated block is indistinguishable from a
    /// complete one by events alone — and a diagram can't be rendered from a
    /// stub (flicker "partial diagram ↔ source" as chunks arrive). An
    /// unclosed block goes the source path; once the closing fence arrives,
    /// the feed's cache recomputes the message and swaps the source for the
    /// diagram.
    codeblock_closed: bool,
    /// Index in [`Writer::lines`] of the opening fence of the code block being
    /// collected, for the **unhighlighted** path on the inverted background
    /// only (`None` otherwise). The
    /// block's background is squared off into a rectangle once its width is
    /// known, i.e. at [`Writer::end_codeblock`] — see [`pad_code_block`].
    code_start: Option<usize>,
    /// The monochrome mode only: the lines that carry line prefixes, as
    /// `(index in [`Writer::lines`], how many prefix spans lead it)` —
    /// [`Writer::finish`] wraps them with the prefix on every row. An index
    /// stays valid because in that mode nothing re-lays the lines out
    /// ([`pad_code_block`], the one thing that does, is not called).
    hanging: Vec<(usize, usize)>,
}

impl Writer {
    pub(super) fn new(palette: Palette, width: usize) -> Self {
        Self {
            palette,
            width,
            lines: Vec::new(),
            inline_styles: Vec::new(),
            line_prefixes: Vec::new(),
            line_styles: Vec::new(),
            list_indices: Vec::new(),
            link: None,
            image: None,
            html: None,
            code_highlighter: None,
            table: None,
            needs_newline: false,
            item_marker_open: false,
            soft_break_as_newline: false,
            table_row_separators: false,
            render_mermaid: false,
            code_block_background: CodeBlockBackground::default(),
            mermaid: None,
            codeblock_closed: true,
            code_start: None,
            hanging: Vec::new(),
        }
    }

    /// The rendered lines. In the monochrome mode the quoted ones are wrapped
    /// here, to the panel width, with their `> ` on every row: a quote's
    /// wrapped rows are told from the prose around it by dim italic, and
    /// where that is stripped from the frame the prefix is all there is
    /// (spec §11.6). In every other mode the lines leave as they are and the
    /// feed wraps them.
    pub(super) fn finish(mut self) -> Vec<Line<'static>> {
        // Last to first, so the indexes ahead stay where they were recorded.
        for (at, prefixes) in std::mem::take(&mut self.hanging).into_iter().rev() {
            let mut line = self.lines.remove(at);
            let content = line.spans.split_off(prefixes.min(line.spans.len()));
            let prefix = std::mem::replace(&mut line.spans, content);
            let rows = wrap::wrap_hanging(&prefix, &line, self.width);
            self.lines.splice(at..at, rows);
        }
        self.lines
    }

    /// Runs the event stream with byte ranges (`Parser::into_offset_iter`
    /// over `src`). The ranges are needed by only one check — is the fence of
    /// the code block being opened closed (a `Start(Tag)` range covers the
    /// whole element); the check itself only runs with mermaid rendering
    /// enabled.
    pub(super) fn run<'a, I: Iterator<Item = (Event<'a>, std::ops::Range<usize>)>>(
        &mut self,
        src: &str,
        iter: I,
    ) {
        for (event, range) in iter {
            if self.render_mermaid && matches!(event, Event::Start(Tag::CodeBlock(_))) {
                self.codeblock_closed = fenced_block_is_closed(src, &range);
            }
            self.handle_event(event);
        }
    }

    pub(super) fn handle_event(&mut self, event: Event<'_>) {
        match event {
            Event::Start(tag) => self.start_tag(tag),
            Event::End(tag) => self.end_tag(tag),
            Event::Text(text) => self.text(text),
            Event::Code(code) => self.code(code),
            // A single line break: in the user's feed keep it as a real break
            // (like HardBreak), otherwise — the standard soft break (a
            // space). In a table cell it's always a space (the table does
            // its own row layout).
            Event::SoftBreak if self.soft_break_as_newline && !self.in_table_cell() => {
                self.push_line(Line::default())
            }
            Event::SoftBreak => self.push_span(Span::raw(" ")),
            // No line break inside a cell — continue with a space.
            Event::HardBreak if self.in_table_cell() => self.push_span(Span::raw(" ")),
            Event::HardBreak => self.push_line(Line::default()),
            // A block of raw HTML: collect it verbatim, and let
            // `end_html_block` extract its text. This arm comes **before**
            // `is_br` on purpose — a `<br>` line inside a larger block belongs
            // in the buffer, in order, not pushed out ahead of it.
            Event::Html(html) if self.html.is_some() => {
                if let Some(buf) = &mut self.html {
                    buf.push_str(&html);
                }
            }
            // `<br>` (frequent in models' table cells) — like HardBreak. Inline
            // HTML needs nothing else: its inner text arrives as `Text`, which
            // is exactly what block HTML does *not* do.
            Event::InlineHtml(html) if is_br(&html) => {
                if self.in_table_cell() {
                    self.push_span(Span::raw(" "));
                } else {
                    self.push_line(Line::default());
                }
            }
            Event::Rule => self.rule(),
            Event::TaskListMarker(checked) => self.task_list_marker(checked),
            Event::InlineMath(content) => {
                let style = self.current_style();
                if looks_like_price_fragment(&content) {
                    // A false math match on a price range "$5-$10": pulldown
                    // hands us content="5-". Print it literally with dollar
                    // signs, not as a formula (otherwise the dollars would
                    // vanish and "5-10" would be torn into "5-" and "10").
                    self.push_span(Span::styled(format!("${content}$"), style));
                } else {
                    self.push_span(Span::styled(latex_to_unicode(&content), style));
                }
            }
            Event::DisplayMath(content) => self.display_math(&content),
            // HTML, footnotes — ignored.
            _ => {}
        }
    }

    pub(super) fn start_tag(&mut self, tag: Tag<'_>) {
        // Any block `Start` "closes" the wait for a list item's content;
        // save the value for the first paragraph (it continues the marker's
        // line).
        let marker_open = std::mem::take(&mut self.item_marker_open);
        match tag {
            Tag::Paragraph => self.start_paragraph(marker_open),
            Tag::Heading { level, .. } => self.start_heading(level),
            Tag::BlockQuote(_) => self.start_blockquote(),
            Tag::CodeBlock(kind) => self.start_codeblock(kind),
            Tag::List(start_index) => self.start_list(start_index),
            Tag::Item => self.start_item(),
            Tag::Emphasis => self.open_inline(Style::new().italic(), EMPHASIS),
            Tag::Strong => self.open_inline(Style::new().bold(), STRONG),
            Tag::Strikethrough => self.open_inline(Style::new().crossed_out(), STRIKETHROUGH),
            Tag::Link {
                link_type,
                dest_url,
                ..
            } => {
                // An autolink (`<url>`) and email print the URL as text
                // themselves — a ` (url)` suffix would duplicate it. Don't
                // remember the link for them.
                if !matches!(link_type, LinkType::Autolink | LinkType::Email) {
                    self.link = Some(dest_url.into_string());
                }
            }
            Tag::Image { dest_url, .. } => self.image = Some(dest_url.into_string()),
            Tag::HtmlBlock => self.html = Some(String::new()),
            Tag::Table(alignments) => self.start_table(alignments),
            Tag::TableHead => {
                if let Some(tb) = &mut self.table {
                    tb.current_row.clear();
                }
            }
            Tag::TableRow => {
                if let Some(tb) = &mut self.table {
                    tb.current_row.clear();
                }
            }
            Tag::TableCell => {
                if let Some(tb) = &mut self.table {
                    tb.current_cell = Some(Vec::new());
                }
            }
            _ => {}
        }
    }

    pub(super) fn end_tag(&mut self, tag: TagEnd) {
        match tag {
            TagEnd::Paragraph => self.needs_newline = true,
            TagEnd::Heading(_) => self.needs_newline = true,
            TagEnd::BlockQuote(_) => self.end_blockquote(),
            TagEnd::CodeBlock => self.end_codeblock(),
            TagEnd::HtmlBlock => self.end_html_block(),
            TagEnd::List(_) => self.end_list(),
            TagEnd::Emphasis => self.close_inline(EMPHASIS),
            TagEnd::Strong => self.close_inline(STRONG),
            TagEnd::Strikethrough => self.close_inline(STRIKETHROUGH),
            TagEnd::Link => self.end_link(),
            TagEnd::Image => self.end_image(),
            // Reset "marker open": in a TIGHT list, an item's content is
            // inline with no `Paragraph` wrapper, so nothing consumes the
            // flag, and it would "leak" onto the next block (gluing it to
            // the marker line and swallowing a blank line).
            TagEnd::Item => self.item_marker_open = false,
            TagEnd::TableCell => {
                if let Some(tb) = &mut self.table {
                    let cell = tb.current_cell.take().unwrap_or_default();
                    tb.current_row.push(cell);
                }
            }
            TagEnd::TableHead => {
                if let Some(tb) = &mut self.table {
                    tb.head = std::mem::take(&mut tb.current_row);
                }
            }
            TagEnd::TableRow => {
                if let Some(tb) = &mut self.table {
                    let row = std::mem::take(&mut tb.current_row);
                    tb.rows.push(row);
                }
            }
            TagEnd::Table => self.end_table(),
            _ => {}
        }
    }

    pub(super) fn start_paragraph(&mut self, marker_open: bool) {
        // The first paragraph of a "loose" list item continues on the marker
        // line (`1. `/`- `) rather than starting a new one — otherwise the
        // number would separate from the text.
        if marker_open {
            self.needs_newline = false;
            return;
        }
        if self.needs_newline {
            self.push_line(Line::default());
        }
        self.push_line(Line::default());
        self.needs_newline = false;
    }

    pub(super) fn start_heading(&mut self, level: HeadingLevel) {
        if self.needs_newline {
            self.push_line(Line::default());
        }
        let lvl = heading_number(level);
        let style = heading_style(lvl, &self.palette);
        let prefix = format!("{} ", "#".repeat(lvl as usize));
        self.push_line(Line::styled(prefix, style));
        self.needs_newline = false;
    }

    pub(super) fn start_blockquote(&mut self) {
        if self.needs_newline {
            self.push_line(Line::default());
            self.needs_newline = false;
        }
        self.line_prefixes.push(Span::from("> "));
        self.line_styles.push(blockquote_style());
    }

    pub(super) fn end_blockquote(&mut self) {
        self.line_prefixes.pop();
        self.line_styles.pop();
        self.needs_newline = true;
    }

    pub(super) fn start_list(&mut self, index: Option<u64>) {
        if self.list_indices.is_empty() && self.needs_newline {
            self.push_line(Line::default());
        }
        self.list_indices.push(index);
    }

    pub(super) fn end_list(&mut self) {
        self.list_indices.pop();
        self.needs_newline = true;
    }

    pub(super) fn start_item(&mut self) {
        self.push_line(Line::default());
        let width = self.list_indices.len() * 4 - 3;
        if let Some(last_index) = self.list_indices.last_mut() {
            let span = match last_index {
                None => Span::from(" ".repeat(width - 1) + "- "),
                Some(index) => {
                    *index += 1;
                    Span::styled(
                        format!("{:width$}. ", *index - 1),
                        Style::new().fg(self.palette.accent),
                    )
                }
            };
            self.push_span(span);
        }
        self.needs_newline = false;
        // This item's first paragraph should continue on the marker's line.
        self.item_marker_open = true;
    }

    pub(super) fn task_list_marker(&mut self, checked: bool) {
        let marker = if checked { 'x' } else { ' ' };
        if let Some(line) = self.lines.last_mut() {
            if let Some(first) = line.spans.first_mut() {
                let content = first.content.to_mut();
                if content.ends_with("- ") {
                    let len = content.len();
                    content.truncate(len - 2);
                    content.push_str(&format!("- [{marker}] "));
                    return;
                }
            }
            line.spans.insert(1, Span::from(format!("[{marker}] ")));
        }
    }

    pub(super) fn rule(&mut self) {
        if self.needs_newline {
            self.push_line(Line::default());
        }
        // Stretch the line to the panel width (self.width — already the
        // inner width under the rail), so `---` doesn't look like a stub
        // next to full-width tables. Line ≤ width → the re-wrap in
        // `message_feed` is a no-op.
        let rule = "─".repeat(self.width.max(3));
        self.push_line(Line::from(rule).add_modifier(Modifier::DIM));
        self.needs_newline = true;
    }

    pub(super) fn start_codeblock(&mut self, kind: CodeBlockKind<'_>) {
        if !self.lines.is_empty() {
            self.push_line(Line::default());
        }
        let info = match kind {
            CodeBlockKind::Fenced(ref lang) => lang.as_ref(),
            CodeBlockKind::Indented => "",
        };
        // The info string can carry more than the language: ` ```rust,no_run `,
        // ` ```py title=x `. Resolve the syntax from the first token, but
        // print the whole label into the fence.
        let lang = info.split([',', ' ', '\t']).next().unwrap_or("");
        // A ```mermaid block, when diagram rendering is enabled, is NOT
        // printed right away: content accumulates in a buffer (like table
        // cells in TableBuilder), and the fence/highlighting are left alone —
        // end_codeblock decides "diagram or source" once the whole block is
        // visible. A block with an unclosed fence (a streaming tail of the
        // reply) is NOT taken into the buffer — it goes the regular source
        // path until the server finishes the closing fence (otherwise a
        // partial diagram would flicker). See super::mermaid and spec §11.4.
        if self.render_mermaid
            && self.codeblock_closed
            && lang.eq_ignore_ascii_case("mermaid")
            && self.table.is_none()
        {
            self.mermaid = Some((info.to_string(), String::new()));
            return;
        }
        if let Some(syntax) = resolve_syntax(lang) {
            let theme = code_theme(&self.palette);
            self.code_highlighter = Some(HighlightLines::new(syntax, theme));
        } else {
            self.line_styles.push(self.plain_code_style());
            // From here on the lines belong to the block's background
            // rectangle (squared off in `end_codeblock`, once its width is
            // known) — the fences included, they are its top and bottom edge.
            // The normal background and the monochrome mode have none to
            // square off.
            self.code_start = self.plain_code_has_background().then_some(self.lines.len());
        }
        self.push_line(fence_line(format!("```{info}")));
        // The block's content must start on a new line under the opening
        // `​```​`, not glue onto it. In the unhighlighted path (`text`) the
        // first line would otherwise append to the fence line (`i==0`,
        // `needs_newline==false`); the highlighted path ignores this flag
        // (lays out lines itself).
        self.needs_newline = true;
    }

    pub(super) fn end_codeblock(&mut self) {
        // A buffered ```mermaid block: try the diagram, on any failure (type
        // outside the whitelist / the parser / width) — the source as a code
        // block, as with rendering disabled. The fence/highlighting of this
        // path were never opened, so the regular closing below doesn't run.
        if let Some((info, src)) = self.mermaid.take() {
            match render_mermaid_block(&src, self.width, &self.palette) {
                Some(lines) => {
                    for line in lines {
                        self.push_line(line);
                    }
                }
                None => self.emit_fenced_source(&info, &src),
            }
            self.needs_newline = true;
            return;
        }
        self.push_line(fence_line("```".to_string()));
        self.needs_newline = true;
        if self.code_highlighter.take().is_none() {
            self.line_styles.pop();
            if let Some(start) = self.code_start.take() {
                pad_code_block(&mut self.lines, start, self.width);
            }
        }
    }

    /// Prints a code block's source in the "unhighlighted" look (the chosen
    /// background, DIM fences with the info string) — the ```mermaid block's
    /// fallback. The look repeats the old path byte-for-byte
    /// (`start_codeblock` with no syntax + `text` + `end_codeblock`), see the
    /// golden test `mermaid_fallback_matches_disabled_render`.
    fn emit_fenced_source(&mut self, info: &str, src: &str) {
        let start = self.lines.len();
        self.line_styles.push(self.plain_code_style());
        self.push_line(fence_line(format!("```{info}")));
        for line in src.lines() {
            self.push_line(Line::default());
            self.push_span(Span::styled(line.to_string(), Style::default()));
        }
        self.push_line(fence_line("```".to_string()));
        self.line_styles.pop();
        if self.plain_code_has_background() {
            pad_code_block(&mut self.lines, start, self.width);
        }
    }

    /// Whether an unhighlighted code block is drawn on a background — the
    /// inverted one, outside the monochrome mode. Only then is there a
    /// rectangle to square off ([`pad_code_block`]).
    fn plain_code_has_background(&self) -> bool {
        !self.palette.mono && self.code_block_background == CodeBlockBackground::Inverted
    }

    /// The line style of an unhighlighted code block: the reversed rectangle
    /// for the inverted background, the code colour for the normal one, and
    /// nothing in the monochrome mode — reverse video is kept there for a
    /// selection and a search match, and the block has its fences.
    fn plain_code_style(&self) -> Style {
        if self.palette.mono {
            Style::default()
        } else {
            match self.code_block_background {
                CodeBlockBackground::Inverted => code_style(),
                CodeBlockBackground::Normal => code_text_style(&self.palette),
            }
        }
    }

    pub(super) fn text(&mut self, text: CowStr<'_>) {
        // Collecting a ```mermaid block: accumulate the source as-is (with
        // line breaks — resilient to the parser splitting the text into
        // events however it likes).
        if let Some((_, buf)) = &mut self.mermaid {
            buf.push_str(&text);
            return;
        }
        if let Some(highlighter) = &mut self.code_highlighter {
            // On a syntect/ansi error, don't drop the line — show it flat
            // (`highlight_line_or_plain`) — otherwise a line of code would
            // silently disappear.
            let mut rendered: Vec<Line<'static>> = Vec::new();
            for line in LinesWithEndings::from(&text) {
                rendered.extend(highlight_line_or_plain(highlighter, line));
            }
            self.lines.extend(rendered);
            self.needs_newline = false;
            return;
        }
        let style = self.current_style();
        // No line breaks inside a table cell — put it as one span (line
        // breaks collapse into a space; the layout does the real width-based
        // wrapping).
        if self.in_table_cell() {
            self.push_span(Span::styled(text.replace('\n', " "), style));
            return;
        }
        for (i, line) in text.lines().enumerate() {
            if self.needs_newline {
                self.push_line(Line::default());
                self.needs_newline = false;
            }
            if i > 0 {
                self.push_line(Line::default());
            }
            self.push_span(Span::styled(line.to_string(), style));
        }
    }

    pub(super) fn code(&mut self, code: CowStr<'_>) {
        // The chip is a colour pair; without colours the backticks the parser
        // took off are what says "code" (the monochrome mode).
        let text = if self.palette.mono {
            format!("{INLINE_CODE}{code}{INLINE_CODE}")
        } else {
            code.into_string()
        };
        self.push_span(Span::styled(text, inline_code_style(&self.palette)));
    }

    /// Block formula `$$…$$`: each line of the converted content — on its own
    /// feed line. The first line is put **into the current (empty) paragraph
    /// line** via `push_span` — otherwise there would be a double gap between
    /// the prose and the formula (`start_paragraph` already opened an empty
    /// line, and the old code put content on a new one). In a table cell the
    /// formula stays **in the cell** (lines are joined with "; "), otherwise
    /// `push_line` would send its lines into the feed above the table.
    pub(super) fn display_math(&mut self, content: &str) {
        let converted = latex_to_unicode_display(content);
        if self.in_table_cell() {
            let joined = converted.split('\n').collect::<Vec<_>>().join("; ");
            self.push_span(Span::raw(joined));
            return;
        }
        for (i, line) in converted.split('\n').enumerate() {
            if self.needs_newline {
                self.push_line(Line::default());
                self.needs_newline = false;
            }
            if i > 0 {
                self.push_line(Line::default());
            }
            self.push_span(Span::raw(line.to_string()));
        }
        self.needs_newline = true;
    }

    pub(super) fn end_link(&mut self) {
        if let Some(url) = self.link.take() {
            self.push_span(Span::from(" ("));
            self.push_span(Span::styled(url, link_style(&self.palette)));
            self.push_span(Span::from(")"));
        }
    }

    /// Closing an image `![alt](url)`: the alt text has already been printed
    /// by `Text` events, append the URL in parens (like a link). A separate
    /// `image` field — an image can be nested in a link, `self.link` must
    /// not be overwritten.
    pub(super) fn end_image(&mut self) {
        if let Some(url) = self.image.take() {
            self.push_span(Span::from(" ("));
            self.push_span(Span::styled(url, link_style(&self.palette)));
            self.push_span(Span::from(")"));
        }
    }

    /// Closing a raw HTML block: show its **text**.
    ///
    /// Before this the block was dropped whole, so a pasted `<table>` — prose
    /// and all — rendered as nothing at all (see [`super::html`] for the
    /// measurement and for why text, rather than the markup or a rebuilt
    /// table). Laid out like a paragraph: logical lines, wrapped later by the
    /// feed.
    pub(super) fn end_html_block(&mut self) {
        let Some(raw) = self.html.take() else { return };
        let lines = html_block_to_lines(&raw);
        if lines.is_empty() {
            // A block that is only a forced break (`<br>` on its own line) kept
            // its blank line before this change, and keeps it now.
            if is_break_only(&raw) {
                self.push_line(Line::default());
                self.needs_newline = false;
            }
            return;
        }
        if self.needs_newline {
            self.push_line(Line::default());
        }
        let style = self.current_style();
        for text in lines {
            self.push_line(Line::default());
            self.push_span(Span::styled(text, style));
        }
        self.needs_newline = true;
    }

    pub(super) fn start_table(&mut self, alignments: Vec<Alignment>) {
        if self.needs_newline {
            self.push_line(Line::default());
        }
        self.table = Some(TableBuilder {
            alignments,
            head: Vec::new(),
            rows: Vec::new(),
            current_row: Vec::new(),
            current_cell: None,
        });
        self.needs_newline = false;
    }

    pub(super) fn end_table(&mut self) {
        if let Some(tb) = self.table.take() {
            for line in render_table(&tb, self.width, &self.palette, self.table_row_separators) {
                self.lines.push(line);
            }
        }
        self.needs_newline = true;
    }

    /// Is a table cell's content currently being collected.
    pub(super) fn in_table_cell(&self) -> bool {
        self.table
            .as_ref()
            .is_some_and(|tb| tb.current_cell.is_some())
    }

    pub(super) fn current_style(&self) -> Style {
        self.inline_styles.last().copied().unwrap_or_default()
    }

    pub(super) fn push_inline_style(&mut self, style: Style) {
        let merged = self.current_style().patch(style);
        self.inline_styles.push(merged);
    }

    /// Opens an inline style — emphasis, strong, strikethrough. `marker` is
    /// what the source wrapped the text in, which the parser took off: in the
    /// monochrome mode it goes back in, because the style is all that said
    /// the text was struck out, and is stripped from the frame.
    fn open_inline(&mut self, style: Style, marker: &'static str) {
        self.push_inline_style(style);
        self.push_marker(marker);
    }

    /// Closes what [`Writer::open_inline`] opened.
    fn close_inline(&mut self, marker: &'static str) {
        self.push_marker(marker);
        self.inline_styles.pop();
    }

    fn push_marker(&mut self, marker: &'static str) {
        if !self.palette.mono {
            return;
        }
        // An opening marker is the first thing of its text, and starts the
        // line the text would have started (see `text`).
        if self.needs_newline && !self.in_table_cell() {
            self.push_line(Line::default());
            self.needs_newline = false;
        }
        self.push_span(Span::styled(marker, self.current_style()));
    }

    pub(super) fn push_line(&mut self, line: Line<'static>) {
        let style = self.line_styles.last().copied().unwrap_or_default();
        let mut line = line.patch_style(style);
        // Line prefixes (quotes) go at the front, in reverse stack order.
        for prefix in self.line_prefixes.iter().rev().cloned() {
            line.spans.insert(0, prefix);
        }
        if self.palette.mono && !self.line_prefixes.is_empty() {
            self.hanging
                .push((self.lines.len(), self.line_prefixes.len()));
        }
        self.lines.push(line);
    }

    pub(super) fn push_span(&mut self, span: Span<'static>) {
        // Inside a table cell, spans accumulate into the cell, not the feed.
        if let Some(tb) = &mut self.table
            && let Some(cell) = &mut tb.current_cell
        {
            cell.push(span);
            return;
        }
        if let Some(line) = self.lines.last_mut() {
            line.spans.push(span);
        } else {
            self.push_line(Line::from(vec![span]));
        }
    }
}

/// The markers of the inline styles, as the monochrome mode puts them back
/// ([`Writer::open_inline`], [`Writer::code`]) — the ones CommonMark and GFM
/// write them with.
const EMPHASIS: &str = "*";
const STRONG: &str = "**";
const STRIKETHROUGH: &str = "~~";
const INLINE_CODE: &str = "`";

/// A code block's fence line (` ```lang ` / ` ``` `). `DIM` sits on the
/// **span**, not on the line: the line style carries the block's background
/// ([`code_style`]), and the padding [`pad_code_block`] appends must take that
/// background *without* the dimming — otherwise the rectangle's top and bottom
/// edges would come out a different shade from its body. Visually identical to
/// the previous line-level `DIM` for the fence text itself (the line style is
/// folded into the spans on render).
pub(super) fn fence_line(text: String) -> Line<'static> {
    Line::from(Span::styled(text, Style::new().add_modifier(Modifier::DIM)))
}

/// Whether a fenced code block is closed in the source. `range` — the byte
/// range of the **whole** block from pulldown-cmark's `OffsetIter` (a
/// `Start(CodeBlock)`'s range covers the whole element). CommonMark stretches
/// an unclosed fence to the end of the document, so a stream cutoff is
/// indistinguishable from a complete block by parser events alone — look at
/// the source instead: for a closed block, the range's last line is the
/// closing fence (the same character, no shorter than the opener); for a
/// truncated one, it's a content line.
///
/// The check is deliberately simple (CommonMark precision isn't needed): a
/// block followed by more text in the document is closed by construction; a
/// false "closed" on an edge case (a content line indistinguishable from a
/// fence) only leads to an attempted render, which fails in the diagram
/// parser → the standard fallback to the source.
pub(super) fn fenced_block_is_closed(src: &str, range: &std::ops::Range<usize>) -> bool {
    if range.end < src.len() {
        return true; // there's text after the block — the fence is closed (a cutoff would stretch to the end)
    }
    let block = &src[range.clone()];
    let mut lines = block.lines();
    let Some(open) = lines.next() else {
        return false;
    };
    // A container prefix (a `> ` quote) and fence indent (≤3 spaces) don't
    // interfere.
    let open = open.trim_start_matches(['>', ' ', '\t']);
    let Some(fence @ ('`' | '~')) = open.chars().next() else {
        return true; // an indented block with no fence — nothing to "close"
    };
    let open_len = open.chars().take_while(|&c| c == fence).count();
    let Some(last) = lines.last() else {
        return false; // one line — only the opening fence
    };
    let last = last.trim_start_matches(['>', ' ', '\t']);
    let close_len = last.chars().take_while(|&c| c == fence).count();
    // Fence characters are ASCII — a slice by character count is safe.
    close_len >= open_len && last[close_len..].trim().is_empty()
}

/// Heuristic for "this is a price range/fraction, not a formula": the math
/// parser hands `$5-$10` to us as `InlineMath("5-")`. Content made only of
/// digits/dots/commas/spaces/dashes/slashes AND ending in a separator
/// (`-`/`–`/`/`) is a price-range signature; a legitimate number ends in a
/// digit, while a formula contains math symbols.
pub(super) fn looks_like_price_fragment(content: &str) -> bool {
    let t = content.trim();
    if t.is_empty() {
        return false;
    }
    t.chars()
        .all(|c| c.is_ascii_digit() || matches!(c, '.' | ',' | ' ' | '-' | '–' | '/'))
        && t.ends_with(['-', '–', '/'])
}

/// Recognizes the line-break tag `<br>` in its forms (case-insensitive).
pub(super) fn is_br(html: &str) -> bool {
    matches!(
        html.trim().to_ascii_lowercase().as_str(),
        "<br>" | "<br/>" | "<br />"
    )
}

pub(super) fn heading_number(level: HeadingLevel) -> u8 {
    match level {
        HeadingLevel::H1 => 1,
        HeadingLevel::H2 => 2,
        HeadingLevel::H3 => 3,
        HeadingLevel::H4 => 4,
        HeadingLevel::H5 => 5,
        HeadingLevel::H6 => 6,
    }
}

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

    /// End to end through the renderer: the defect this fixes is that the
    /// *whole block* vanished, which only shows up past `Event::Html`.
    #[test]
    fn html_block_prose_reaches_the_render() {
        let collected = rendered_text(
            "before\n\n<table>\n<tr><td>первая ячейка</td><td>вторая</td></tr>\n\
             <tr><td>вторая строка</td></tr>\n</table>\n\nafter",
        );
        assert!(collected.contains("первая ячейка вторая"), "{collected:?}");
        assert!(collected.contains("вторая строка"), "{collected:?}");
        // The surrounding markdown is untouched and still separated.
        assert!(collected.contains("before"));
        assert!(collected.contains("after"));
    }

    /// The regression that guards the *other* half: inline HTML always worked,
    /// because its inner text arrives as `Text`. Buffering block HTML must not
    /// disturb it.
    #[test]
    fn inline_html_still_renders_its_text() {
        let collected = rendered_text("абзац с <strong>жирным</strong> словом");
        assert!(collected.contains("абзац с жирным словом"), "{collected:?}");
    }

    /// A standalone `<br>` is an HTML *block*, so it now goes through the
    /// buffer — and must still produce the blank line it always did.
    #[test]
    fn a_lone_br_block_still_breaks_the_line() {
        let collected = rendered_text("раз\n\n<br>\n\nдва");
        assert!(collected.contains("раз"));
        assert!(collected.contains("два"));
        // A `<br>` in a table cell is inline and stays a space.
        let cell = rendered_text("| a | b |\n|---|---|\n| one<br>two | x |");
        assert!(cell.contains("one two"), "{cell:?}");
    }

    /// Script and style content must not leak into the feed as prose — the one
    /// way "strip the tags" could be worse than the bug.
    #[test]
    fn html_block_does_not_leak_css_or_scripts() {
        let collected =
            rendered_text("<div>\n<style>.x { color: red; }</style>\nвидимый текст\n</div>");
        assert!(collected.contains("видимый текст"), "{collected:?}");
        assert!(!collected.contains("color"), "{collected:?}");
    }

    /// A long HTML block behaves like a **paragraph**, not like a table: the
    /// writer leaves it as one logical line and the feed wraps it, which is
    /// what `max_line_width` shows (a table would have been laid out to fit).
    /// The invariant that matters here is that no span carries a raw newline —
    /// the source is full of them, and one surviving would break the feed's
    /// row math.
    #[test]
    fn html_block_is_paragraph_like_and_free_of_raw_newlines() {
        let long = format!("<div>{}</div>", "слово ".repeat(60));
        let plain = "слово ".repeat(60);
        assert!(
            max_line_width(&long, 24) > 24 && max_line_width(&plain, 24) > 24,
            "the writer does not wrap paragraphs — the feed does"
        );
        for line in render(&long, 24, &Palette::default()).lines {
            for span in line.spans {
                assert!(
                    !span.content.contains('\n'),
                    "a raw newline survived into a span: {:?}",
                    span.content
                );
            }
        }
    }

    #[test]
    fn render_produces_owned_text() {
        let text = render("# Заголовок\n\nабзац с `кодом`.", 80, &Palette::default());
        assert!(!text.lines.is_empty());
        let collected = rendered_text("# Заголовок\n\nабзац с `кодом`.");
        assert!(collected.contains("Заголовок"));
    }

    #[test]
    fn render_headings_lists_quotes() {
        let collected = rendered_text("## Заголовок\n\n- пункт раз\n- пункт два\n\n> цитата");
        assert!(collected.contains("## Заголовок"));
        assert!(collected.contains("- пункт раз"));
        assert!(collected.contains("> цитата"));
    }

    /// A "loose" ordered list — items separated by a blank line, so
    /// pulldown-cmark wraps the content in a `Paragraph`. The number and the
    /// text must stay on **one** line (`1. text`), not split apart
    /// (regression: `start_paragraph` unconditionally added a new line after
    /// the marker).
    #[test]
    fn loose_ordered_list_keeps_number_with_text() {
        let md = "1. **Первый.** Текст первого пункта.\n\n\
                  2. **Второй.** Текст второго пункта.\n\n\
                  3. **Третий.** Текст третьего пункта.";
        let collected = rendered_text(md);
        // The number is glued to its text on one feed line.
        assert!(
            collected.contains("1. Первый."),
            "the number separated from the text:\n{collected}"
        );
        assert!(collected.contains("2. Второй."));
        assert!(collected.contains("3. Третий."));
        // There should be no blank line between the marker and its text.
        assert!(
            !collected.contains("1. \n"),
            "a line break appeared after the marker:\n{collected}"
        );
    }

    /// A multi-paragraph item of a "loose" list: the first paragraph — on the
    /// marker line, subsequent ones — on their own lines (the marker isn't
    /// duplicated).
    #[test]
    fn loose_list_item_second_paragraph_on_own_line() {
        let md = "1. Первый абзац.\n\n   Второй абзац того же пункта.\n\n2. Другой пункт.";
        let collected = rendered_text(md);
        assert!(collected.contains("1. Первый абзац."));
        assert!(collected.contains("Второй абзац того же пункта."));
        assert!(collected.contains("2. Другой пункт."));
    }

    /// Render lines as a vector of strings (to check row layout).
    fn rows(input: &str, width: usize) -> Vec<String> {
        render(input, width, &Palette::default())
            .lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect()
    }

    /// Exactly one blank line between prose and a block formula `$$…$$`
    /// (regression: there were two — `start_paragraph` opened a blank line,
    /// and `display_math` put content on a new one, leaving that one blank).
    #[test]
    fn display_math_single_blank_line_before() {
        let lines = rows("текст\n\n$$E=mc^2$$\n\nконец", 80);
        let text_idx = lines.iter().position(|l| l.contains("текст")).unwrap();
        let math_idx = lines.iter().position(|l| l.contains("E=mc")).unwrap();
        assert_eq!(
            math_idx - text_idx,
            2,
            "expected one blank line between prose and the formula:\n{lines:?}"
        );
        assert!(lines[text_idx + 1].trim().is_empty());
    }

    /// A block formula inside a quote keeps the `> ` prefix.
    #[test]
    fn display_math_in_blockquote_keeps_prefix() {
        let lines = rows("> $$x+1$$", 80);
        let math = lines.iter().find(|l| l.contains("x+1")).unwrap();
        assert!(math.starts_with("> "), "quote prefix lost: {math:?}");
    }

    /// A `$$…$$` formula inside a table cell stays **in the cell**, not
    /// leaking as a line above the table (regression: `display_math` called
    /// `push_line` without checking `in_table_cell`).
    #[test]
    fn display_math_in_table_cell_stays_in_cell() {
        let md = "| A | B |\n| :--- | :--- |\n| $$x+1$$ | y |";
        let lines = rows(md, 60);
        let first = lines
            .iter()
            .find(|l| !l.trim().is_empty())
            .expect("empty render");
        assert!(
            first.contains('┌'),
            "the first line should be the table's top border, not the formula: {first:?}"
        );
        let joined = lines.join("\n");
        assert!(joined.contains("x+1"), "formula lost: {joined}");
    }

    /// An autolink `<url>` prints the URL once (regression: `end_link`
    /// appended ` (url)` on top of the URL text → "url (url)").
    #[test]
    fn autolink_url_not_duplicated() {
        let collected = rendered_text("см. <https://example.com> тут");
        assert_eq!(
            collected.matches("example.com").count(),
            1,
            "autolink URL duplicated: {collected}"
        );
    }

    /// A regular link `[t](u)` still prints the URL in parens.
    #[test]
    fn inline_link_keeps_url_suffix() {
        let collected = rendered_text("[текст](https://example.com)");
        assert!(
            collected.contains("текст (https://example.com)"),
            "{collected}"
        );
    }

    /// `<br>` in a paragraph — a line break.
    #[test]
    fn br_tag_breaks_line_in_paragraph() {
        let lines = rows("a<br>b", 80);
        assert!(lines.iter().any(|l| l.trim() == "a"), "{lines:?}");
        assert!(lines.iter().any(|l| l.trim() == "b"), "{lines:?}");
    }

    /// `<br>` inside a table cell — a space (no line breaks in a cell).
    #[test]
    fn br_tag_in_table_cell_becomes_space() {
        let md = "| A | B |\n| :--- | :--- |\n| x<br>y | z |";
        let joined = rendered_text_w(md, 60);
        assert!(
            joined.contains("x y"),
            "<br> in a cell should become a space: {joined}"
        );
    }

    /// A language label with an info-string tail (` ```rust,no_run `) resolves
    /// by the first token — the block is highlighted (regression: the whole
    /// info string didn't match the syntax).
    #[test]
    fn code_block_info_string_resolves_language() {
        use crate::shared::config::Theme;
        let colors = fg_colors(
            "```rust,no_run\nfn main() {}\n```",
            &Palette::for_theme(Theme::Dark),
        );
        assert!(
            colors.iter().any(|c| matches!(c, Color::Rgb(..))),
            "expected highlighting by the language from the info string"
        );
    }

    /// A horizontal rule `---` stretches to the panel width (not a stub `───`).
    #[test]
    fn rule_spans_panel_width() {
        let w = 40;
        let text = render("текст\n\n---\n\nещё", w, &Palette::default());
        let rule = text
            .lines
            .iter()
            .find(|l| l.spans.iter().any(|s| s.content.contains('─')))
            .expect("no separator line");
        let width: usize = rule
            .spans
            .iter()
            .map(|s| wrap::display_width(&s.content.chars().collect::<Vec<_>>()))
            .sum();
        assert_eq!(width, w, "the line should span the panel width");
    }

    /// A tight list item doesn't "leak" onto the next block: after
    /// `3. Title` with a blank line, the following paragraph doesn't glue
    /// to the marker line, and the blank line is preserved (regression:
    /// `item_marker_open` in a tight list was never consumed — the item's
    /// content is inline, with no `Paragraph` wrapper). Scene — an album
    /// tracklist: `3. Track` + Suno tags on the following lines.
    #[test]
    fn tight_list_item_does_not_bleed_into_next_block() {
        let md = "3. Взгляд из ниоткуда\n\n[Intro - Ambient]\nЯ — тишина.";
        let lines = rows(md, 100);
        let marker = lines
            .iter()
            .find(|l| l.contains("3. Взгляд из ниоткуда"))
            .expect("no marker line");
        assert!(
            !marker.contains("[Intro"),
            "the next block glued onto the marker line: {marker:?}"
        );
        let marker_idx = lines.iter().position(|l| l.contains("3. Взгляд")).unwrap();
        let intro_idx = lines.iter().position(|l| l.contains("[Intro")).unwrap();
        assert!(
            intro_idx > marker_idx,
            "the tags aren't on their own line: {lines:?}"
        );
        // between the marker and the tags — the preserved blank line
        assert!(
            lines[marker_idx + 1..intro_idx]
                .iter()
                .any(|l| l.trim().is_empty()),
            "lost the blank line after the track title: {lines:?}"
        );
    }

    /// An ordinary tight list (several items) isn't broken: each item — on
    /// its own line, the next one doesn't glue onto the previous one.
    #[test]
    fn tight_list_items_stay_on_separate_lines() {
        let lines = rows("- один\n- два\n- три", 80);
        assert!(lines.iter().any(|l| l.trim() == "- один"), "{lines:?}");
        assert!(lines.iter().any(|l| l.trim() == "- два"), "{lines:?}");
        assert!(lines.iter().any(|l| l.trim() == "- три"), "{lines:?}");
    }

    /// An image prints the alt text and the URL in parens (like a link).
    #[test]
    fn image_prints_alt_and_url() {
        let collected = rendered_text("![схема](http://x/i.png)");
        assert!(collected.contains("схема (http://x/i.png)"), "{collected}");
    }

    /// A price range/fraction `$5-$10` isn't swallowed by the math extension
    /// (dollars remain, "5-10" isn't torn apart).
    #[test]
    fn price_range_not_treated_as_math() {
        let c = rendered_text("товар $5-$10 или $5/$7");
        assert!(c.contains("$5-$10"), "{c}");
        assert!(c.contains("$5/$7"), "{c}");
    }

    /// Render with the mermaid flag on (other flags default).
    fn render_mermaid_on(input: &str, width: usize) -> Text<'static> {
        render_with(
            input,
            width,
            &Palette::default(),
            RenderOpts {
                render_mermaid: true,
                ..Default::default()
            },
        )
    }

    /// A valid mermaid block with rendering enabled — a diagram instead of
    /// the source: box-drawing frames are present, no fences ``` or raw
    /// `-->` remain.
    #[test]
    fn mermaid_block_renders_diagram_when_enabled() {
        let md = "до\n\n```mermaid\nsequenceDiagram\n    participant A\n    participant B\n    A->>B: hi\n```\n\nпосле";
        let text = render_mermaid_on(md, 90);
        let joined: String = text
            .lines
            .iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
        assert!(joined.contains('┌'), "no diagram frames:\n{joined}");
        assert!(
            !joined.contains("```"),
            "the fence should not be printed:\n{joined}"
        );
        assert!(
            !joined.contains("->>"),
            "source leaked into the feed:\n{joined}"
        );
        assert!(
            joined.contains("до") && joined.contains("после"),
            "{joined}"
        );
    }

    /// Golden fallback: on any failure (garbage / a type outside the
    /// whitelist / doesn't fit the width) the output with the flag enabled
    /// **exactly matches** the output with it disabled — lines AND styles
    /// (Line: PartialEq). The guarantee "worst case = previous behavior".
    #[test]
    fn mermaid_fallback_matches_disabled_render() {
        let cases = [
            // garbage in the block (the LLM left the syntax unfinished/broken)
            ("```mermaid\nпросто текст без диаграммы\n```", 90),
            // a type outside the whitelist (pie)
            ("```mermaid\npie title X\n    \"A\" : 1\n```", 90),
            // valid, but doesn't fit a narrow panel
            (
                "```mermaid\nsequenceDiagram\n    participant Client\n    participant Server\n    Client->>Server: GET /api/data\n```",
                20,
            ),
            // an info string with a tail after the language is preserved in the fallback's fence
            ("```mermaid title=x\nне диаграмма\n```", 90),
        ];
        for (md, w) in cases {
            let on = render_mermaid_on(md, w);
            let off = render(md, w, &Palette::default());
            assert_eq!(
                on.lines, off.lines,
                "fallback diverged from the previous look (w={w}):\n{md}"
            );
        }
    }

    /// The flag off (Default) — the previous behavior: the source as a code
    /// block.
    #[test]
    fn mermaid_flag_off_keeps_source() {
        let md = "```mermaid\nsequenceDiagram\n    A->>B: hi\n```";
        let joined = rendered_text(md);
        assert!(joined.contains("```mermaid"), "{joined}");
        assert!(joined.contains("A->>B: hi"), "{joined}");
    }

    /// Streaming: a block with an unclosed fence (the server is still
    /// finishing the diagram) prints as the source **byte-for-byte as with
    /// rendering disabled** — no "partial diagram ↔ source" flicker as
    /// chunks arrive. Regression: pulldown-cmark stretches an unclosed fence
    /// to the end of the document, and a syntactically valid stub (the first
    /// case) used to render as a diagram.
    #[test]
    fn mermaid_unclosed_fence_streams_as_source() {
        let cases = [
            // a valid stub: without the closure check it would render as a diagram
            "текст\n\n```mermaid\nflowchart LR\n    A[Старт] --> B[Конец]",
            // the same with a trailing line break
            "```mermaid\nsequenceDiagram\n    A->>B: hi\n",
            // cut off mid-word
            "```mermaid\nsequenceDiagram\n    participant Ser",
            // only the opening fence
            "```mermaid",
            // a tilde fence
            "~~~mermaid\nflowchart LR\n    A --> B",
            // the closing fence is shorter than the opening one — the block is NOT closed
            "````mermaid\nflowchart LR\n    A --> B\n```",
        ];
        for md in cases {
            let on = render_mermaid_on(md, 90);
            let off = render(md, 90, &Palette::default());
            assert_eq!(
                on.lines, off.lines,
                "an unclosed block should go the source path:\n{md}"
            );
        }
    }

    /// The closing fence has arrived — the block renders as a diagram, even
    /// when the message keeps streaming after it (closure is a property of
    /// the block, not of the end of the message). A tilde fence is treated
    /// equally.
    #[test]
    fn mermaid_closed_fence_renders_even_while_tail_streams() {
        for md in [
            "```mermaid\nflowchart LR\n    A[Старт] --> B[Конец]\n```\n\nа дальше стримится тек",
            "~~~mermaid\nflowchart LR\n    A[Старт] --> B[Конец]\n~~~",
        ] {
            let text = render_mermaid_on(md, 90);
            let joined: String = text
                .lines
                .iter()
                .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
                .collect();
            assert!(joined.contains("Старт"), "{joined}");
            assert!(
                !joined.contains("```") && !joined.contains("~~~"),
                "the fence should not be printed: {joined}"
            );
            assert!(
                !joined.contains("-->"),
                "source leaked into the feed: {joined}"
            );
        }
    }

    /// A Cyrillic flowchart renders as a diagram (upstream regression in
    /// 0.56.0 — a panic/corrupted labels on multibyte input; our fix #29/#30).
    #[test]
    fn mermaid_cyrillic_flowchart_renders() {
        let md = "```mermaid\nflowchart LR\n    A[Старт] -->|да| B[Конец]\n```";
        let text = render_mermaid_on(md, 90);
        let joined: String = text
            .lines
            .iter()
            .flat_map(|l| l.spans.iter().map(|s| s.content.as_ref()))
            .collect();
        assert!(joined.contains("Конец"), "{joined}");
        assert!(!joined.contains("[Конец]"), "label corrupted: {joined}");
    }

    /// Real math still converts (dollar signs stripped).
    #[test]
    fn real_math_still_converts() {
        let c = rendered_text(r"значения $3.14$, $2+2$ и $x^2$");
        assert!(c.contains("3.14"), "{c}");
        assert!(
            !c.contains("$3.14$"),
            "dollars not stripped from a real formula: {c}"
        );
        assert!(c.contains("x²"), "{c}");
    }

    // ---- the monochrome mode (spec §11.6, docs/history/theme-modes.md §9) ----

    /// Render lines as strings, under a given palette.
    fn rows_in(input: &str, width: usize, palette: &Palette) -> Vec<String> {
        render(input, width, palette)
            .lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect()
    }

    /// Bold, italic, strikethrough and inline code are styling and nothing
    /// else: the parser takes their markers off. Where no styling reaches the
    /// screen the markers go back in — struck-out text that read as stated
    /// would say the opposite of what was written.
    #[test]
    fn inline_styles_are_said_by_their_markers_without_styling() {
        let md = "a **bold** and *italic* and ~~gone~~ and `code` word";
        assert_eq!(
            rows_in(md, 80, &Palette::mono()).join("\n").trim(),
            "a **bold** and *italic* and ~~gone~~ and `code` word"
        );
        assert_eq!(
            rows_in(md, 80, &Palette::default()).join("\n").trim(),
            "a bold and italic and gone and code word",
            "every other mode says them with styling, as before"
        );

        // Nested, and written the other way: what goes back in is the
        // canonical marker, inside out.
        let nested = rows_in("__bold _both_ bold__", 80, &Palette::mono()).join("");
        assert_eq!(nested.trim(), "**bold *both* bold**");
    }

    /// The markers reach every place inline text does — a heading, a list
    /// item (tight and loose), a quote, a table cell — and a table is still
    /// laid out to what its cells now hold.
    #[test]
    fn the_markers_reach_wherever_inline_text_does() {
        let mono = Palette::mono();
        let text = |md: &str| rows_in(md, 60, &mono).join("\n");

        assert!(text("# a **loud** title").contains("# a **loud** title"));
        let tight = text("- **first**\n- second");
        assert!(tight.contains("- **first**"), "{tight}");
        let loose = text("1. **first**\n\n2. second");
        assert!(loose.contains("1. **first**"), "{loose}");
        assert!(text("> quoted *softly*").contains("> quoted *softly*"));
        // The marker opens its text's line even right after a block — where
        // no paragraph opens it: next to a block formula, and in a tight list
        // item that holds a code block. Left on the line before, the marker
        // would be parted from the text it marks.
        for md in ["$$x$$**next**", "- item\n  ```\n  code\n  ```\n  **next**"] {
            let after = text(md);
            assert!(
                after.lines().any(|l| l.trim() == "**next**"),
                "the marker and its text on one line of their own: {md:?} -> {after:?}"
            );
        }

        let table = rows_in(
            "| name | note |\n|---|---|\n| `x` | **yes** |\n| longer | no |",
            60,
            &mono,
        );
        let cells: Vec<&String> = table.iter().filter(|r| r.contains('│')).collect();
        assert!(cells.iter().any(|r| r.contains("`x`")), "{table:#?}");
        assert!(cells.iter().any(|r| r.contains("**yes**")), "{table:#?}");
        let widths: Vec<usize> = table
            .iter()
            .filter(|r| !r.trim().is_empty())
            .map(|r| wrap::str_width(r))
            .collect();
        assert!(
            widths.windows(2).all(|w| w[0] == w[1]),
            "the table is a rectangle with the markers in it: {table:#?}"
        );
    }

    /// A quote's wrapped rows are told from the prose around it by dim
    /// italic. Without it the `> ` is all there is, so it is on every row —
    /// each quote level's — and the rows fit the panel.
    #[test]
    fn a_quote_keeps_its_prefix_on_every_row_without_styling() {
        let quote = "a quotation long enough that it has to be wrapped onto several rows";
        let width = 24;
        let rows = rows_in(&format!("> {quote}"), width, &Palette::mono());
        let quoted: Vec<&String> = rows.iter().filter(|r| !r.is_empty()).collect();
        assert!(quoted.len() > 2, "the premise: it wraps: {rows:#?}");
        for row in &quoted {
            assert!(row.starts_with("> "), "{row:?}");
            assert!(wrap::str_width(row) <= width, "{row:?}");
        }
        let text: Vec<&str> = quoted
            .iter()
            .flat_map(|r| r.trim_start_matches("> ").split_whitespace())
            .collect();
        assert_eq!(text, quote.split_whitespace().collect::<Vec<_>>());

        // Two paragraphs that both wrap: the second is found where it is
        // after the first has grown — the lines are wrapped last to first.
        let twice = rows_in(&format!("> {quote}\n>\n> {quote}"), width, &Palette::mono());
        let quoted: Vec<&String> = twice.iter().filter(|r| !r.is_empty()).collect();
        for row in &quoted {
            assert!(row.starts_with('>'), "{row:?}");
            assert!(wrap::str_width(row) <= width, "{row:?} in {twice:#?}");
        }
        let text: Vec<&str> = quoted
            .iter()
            .flat_map(|r| r.trim_start_matches('>').split_whitespace())
            .collect();
        let both = format!("{quote} {quote}");
        assert_eq!(text, both.split_whitespace().collect::<Vec<_>>());

        let nested = rows_in(&format!("> outer\n>\n> > {quote}"), width, &Palette::mono());
        let inner: Vec<&String> = nested.iter().filter(|r| r.contains("> > ")).collect();
        assert!(inner.len() > 2, "{nested:#?}");
        assert!(inner.iter().all(|r| r.starts_with("> > ")), "{nested:#?}");
        assert!(inner.iter().all(|r| wrap::str_width(r) <= width));

        // Every other mode leaves the wrap to the feed, as before: one line.
        let plain = rows_in(&format!("> {quote}"), width, &Palette::default());
        assert!(plain.contains(&format!("> {quote}")), "{plain:#?}");
    }

    /// An unhighlighted code block is a reversed rectangle. Reverse video is
    /// kept for a selection and a search match, so the block is left to its
    /// fences: no reverse, and no padding squaring off a background that is
    /// not there.
    #[test]
    fn a_plain_code_block_is_left_to_its_fences_without_styling() {
        let md = "```nolang\nshort\na longer line of it\n```";
        let reversed = |text: &Text<'_>| {
            text.lines.iter().any(|l| {
                l.style.add_modifier.contains(Modifier::REVERSED)
                    || l.spans
                        .iter()
                        .any(|s| s.style.add_modifier.contains(Modifier::REVERSED))
            })
        };
        let plain = render(md, 40, &Palette::default());
        assert!(reversed(&plain), "the premise: the block is reversed");

        let mono = render(md, 40, &Palette::mono());
        assert!(!reversed(&mono));
        let rows = rows_in(md, 40, &Palette::mono());
        assert_eq!(rows, ["```nolang", "short", "a longer line of it", "```"]);
    }

    /// The same block by the other road: a ```mermaid block that could not be
    /// drawn falls back to its source, through a code path of its own.
    #[test]
    fn a_mermaid_fallback_is_left_to_its_fences_without_styling() {
        let md = "```mermaid
not a diagram at all
```";
        let opts = RenderOpts {
            render_mermaid: true,
            ..Default::default()
        };
        let rows = |palette: &Palette| -> Vec<String> {
            render_with(md, 40, palette, opts)
                .lines
                .iter()
                .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
                .collect()
        };
        let mono = render_with(md, 40, &Palette::mono(), opts);
        assert!(
            mono.lines
                .iter()
                .all(|l| !l.style.add_modifier.contains(Modifier::REVERSED)),
            "{mono:?}"
        );
        assert_eq!(
            rows(&Palette::mono()),
            ["```mermaid", "not a diagram at all", "```"]
        );
        // The premise: elsewhere the fallback is the padded rectangle.
        assert!(rows(&Palette::default()).iter().any(|r| r.ends_with(' ')));
    }

    /// Whether any line, or any span on one, carries reverse video.
    fn any_reversed(text: &Text<'_>) -> bool {
        text.lines.iter().any(|l| {
            l.style.add_modifier.contains(Modifier::REVERSED)
                || l.spans
                    .iter()
                    .any(|s| s.style.add_modifier.contains(Modifier::REVERSED))
        })
    }

    fn with_background(background: CodeBlockBackground) -> RenderOpts {
        RenderOpts {
            render_mermaid: true,
            code_block_background: background,
            ..Default::default()
        }
    }

    fn rows_of(text: &Text<'_>) -> Vec<String> {
        text.lines
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect()
    }

    /// The normal background (spec §11.4): an unhighlighted block is its text
    /// in the code colour between its fences — no reverse video, and no
    /// padding squaring off a rectangle that is not drawn. The control is the
    /// default, which is both.
    #[test]
    fn a_plain_code_block_on_the_normal_background_is_its_text_between_fences() {
        let md = "```nolang\nshort\na longer line of it\n```";
        let palette = Palette::default();
        let normal = render_with(
            md,
            40,
            &palette,
            with_background(CodeBlockBackground::Normal),
        );
        assert!(!any_reversed(&normal), "{normal:?}");
        assert_eq!(
            rows_of(&normal),
            ["```nolang", "short", "a longer line of it", "```"]
        );
        let short = &normal.lines[1];
        assert_eq!(
            short.style.patch(short.spans[0].style).fg,
            Some(palette.code_text),
            "the text takes the colour a highlighted block gives unscoped text"
        );

        let inverted = render_with(md, 40, &palette, RenderOpts::default());
        assert!(
            any_reversed(&inverted),
            "the control: the default is reversed"
        );
        assert!(rows_of(&inverted).iter().any(|r| r.ends_with(' ')));
    }

    /// The case the setting exists for: a ```mermaid block still streaming is
    /// shown as its source until the closing fence arrives, and on the
    /// inverted background that source is a bright rectangle that a moment
    /// later becomes a diagram with no background at all. On the normal one it
    /// is never reversed — and the diagram it becomes is the same either way.
    #[test]
    fn a_streaming_mermaid_source_on_the_normal_background_is_not_reversed() {
        let open = "Here:\n\n```mermaid\nflowchart TD\nA --> B";
        let palette = Palette::default();
        let normal = render_with(
            open,
            60,
            &palette,
            with_background(CodeBlockBackground::Normal),
        );
        assert!(!any_reversed(&normal), "{normal:?}");
        assert!(rows_of(&normal).iter().any(|r| r == "flowchart TD"));
        let inverted = render_with(
            open,
            60,
            &palette,
            with_background(CodeBlockBackground::Inverted),
        );
        assert!(
            any_reversed(&inverted),
            "the control: the reel's loud frame"
        );

        let closed = format!("{open}\n```");
        let drawn = |b| render_with(&closed, 60, &palette, with_background(b));
        let diagram = drawn(CodeBlockBackground::Normal);
        assert!(
            !rows_of(&diagram).iter().any(|r| r.contains("```")),
            "the premise: the closed block is drawn, not printed: {diagram:?}"
        );
        assert_eq!(diagram, drawn(CodeBlockBackground::Inverted));
    }

    /// A ```mermaid block that cannot be drawn falls back to its source by a
    /// road of its own — on the normal background without a rectangle too.
    #[test]
    fn a_mermaid_fallback_on_the_normal_background_has_no_rectangle() {
        let md = "```mermaid\nnot a diagram at all\n```";
        let normal = render_with(
            md,
            40,
            &Palette::default(),
            with_background(CodeBlockBackground::Normal),
        );
        assert!(!any_reversed(&normal), "{normal:?}");
        assert_eq!(
            rows_of(&normal),
            ["```mermaid", "not a diagram at all", "```"]
        );
    }

    /// What the setting does not touch: a highlighted block (it has no
    /// background to choose), and the monochrome mode (it has none at all).
    #[test]
    fn the_background_changes_only_an_unhighlighted_block_in_colour() {
        let both = |md: &str, palette: &Palette| {
            (
                render_with(
                    md,
                    40,
                    palette,
                    with_background(CodeBlockBackground::Inverted),
                ),
                render_with(
                    md,
                    40,
                    palette,
                    with_background(CodeBlockBackground::Normal),
                ),
            )
        };
        let (inverted, normal) = both(CODE_MD, &Palette::default());
        assert_eq!(inverted, normal, "a highlighted block");
        let (inverted, normal) = both("```nolang\nx\n```", &Palette::mono());
        assert_eq!(inverted, normal, "the monochrome mode");
    }

    /// The wrap of the quoted lines is done over the finished list, by index
    /// — so nothing may have moved a line in between. A document with one of
    /// everything reads the same in both modes, markers and padding aside.
    #[test]
    fn the_monochrome_render_is_the_same_document_in_the_same_order() {
        let md = "\
# Title

Prose with **bold**.

> quoted first
>
> ```nolang
> code in a quote
> ```
>
> quoted last

- item one
- item two

| a | b |
|---|---|
| 1 | 2 |

```rust
fn main() {}
```

> a second quote

The end.";
        let normal = |palette: &Palette| -> Vec<String> {
            rows_in(md, 120, palette)
                .into_iter()
                .map(|r| r.replace("**", "").trim_end().to_string())
                .collect()
        };
        assert_eq!(normal(&Palette::mono()), normal(&Palette::default()));
    }
}