mq-markdown 0.10.0

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

use super::*;
use std::cell::Cell;

thread_local! {
    /// Set while the output is read again as Markdown to make HTML of it, not as MDX.
    static HTML_TARGET: Cell<bool> = const { Cell::new(false) };
}

/// Runs `render` with the JSX elements written so that their children are Markdown in HTML.
pub(crate) fn for_html<R>(render: impl FnOnce() -> R) -> R {
    struct Reset(bool);
    impl Drop for Reset {
        fn drop(&mut self) {
            HTML_TARGET.set(self.0);
        }
    }
    let _reset = Reset(HTML_TARGET.replace(true));
    render()
}

impl Node {
    /// Writes the node as Markdown with the given options.
    pub fn to_string_with(&self, options: &RenderOptions) -> String {
        self.render_with_theme(options, &ColorTheme::PLAIN)
    }

    /// Returns a colored string representation of this node using ANSI escape codes.
    #[cfg(feature = "color")]
    pub fn to_colored_string_with(&self, options: &RenderOptions) -> String {
        self.render_with_theme(options, &ColorTheme::COLORED)
    }

    pub(crate) fn render_with_theme(&self, options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
        match self {
            Self::List(List {
                level,
                checked,
                values,
                ordered,
                index,
                start,
                marker,
                ..
            }) => {
                let marker = if *ordered {
                    let delimiter = if *marker == Some(ListMarker::Paren) { ')' } else { '.' };
                    format!("{}{}", start.unwrap_or(1) as usize + *index, delimiter)
                } else if let Some(style) = &options.list_style {
                    style.to_string()
                } else {
                    marker.and_then(ListMarker::style).unwrap_or_default().to_string()
                };
                let checkbox = (*checked).map(|it| if it { "[x] " } else { "[ ] " }).unwrap_or("");
                let prefix_width = *level as usize * 2 + list_own_prefix_width(*ordered, *index, *start);
                // Lines after the first are indented to the content of the item, whatever column they
                // had in the source, which is not reliable after an escape.
                let content = render_values_block(values, options, theme);
                let content = indent_continuation(&content, prefix_width);
                let (ms, me) = &theme.list_marker;
                format!(
                    "{}{}{}{} {}{}",
                    "  ".repeat(*level as usize),
                    ms,
                    marker,
                    me,
                    checkbox,
                    content
                )
            }
            Self::TableRow(TableRow { values, .. }) => {
                let (ts, te) = &theme.table_separator;
                let cells = values
                    .iter()
                    .map(|cell| cell.render_with_theme(options, theme))
                    .collect::<Vec<_>>()
                    .join("|");
                format!("{}|{}{}|", ts, te, cells)
            }
            Self::TableCell(TableCell { values, .. }) => render_cell_values(values, options, theme),
            Self::TableAlign(TableAlign { align, .. }) => {
                let (ts, te) = &theme.table_separator;
                format!("{}|{}|{}", ts, align.iter().map(|a| a.to_string()).join("|"), te)
            }
            Self::Blockquote(Blockquote { values, .. }) => {
                let (bs, be) = &theme.blockquote_marker;
                render_values_block(values, options, theme)
                    .split('\n')
                    .map(|line| format!("{}> {}{}", bs, be, line))
                    .join("\n")
            }
            #[cfg(feature = "callout")]
            Self::Callout(Callout {
                kind,
                fold,
                title,
                values,
                ..
            }) => {
                let (bs, be) = &theme.blockquote_marker;
                let fold = fold.map(String::from).unwrap_or_default();
                let header = match title.as_deref() {
                    Some(t) if !t.is_empty() => format!("[!{}]{} {}", kind, fold, t),
                    _ => format!("[!{}]{}", kind, fold),
                };
                let header_line = format!("{}> {}{}", bs, be, header);
                if values.is_empty() {
                    return header_line;
                }
                let body = render_values_block(values, options, theme);
                if body.trim().is_empty() {
                    header_line
                } else {
                    let body_lines = body
                        .split('\n')
                        .map(|line| format!("{}> {}{}", bs, be, line))
                        .join("\n");
                    format!("{}\n{}", header_line, body_lines)
                }
            }
            #[cfg(feature = "embed")]
            Self::Embed(Embed { target, display, .. }) => match display.as_deref() {
                Some(d) if !d.is_empty() => format!("![[{}|{}]]", target, d),
                _ => format!("![[{}]]", target),
            },
            Self::Code(Code {
                value,
                lang,
                fence,
                meta,
                position,
            }) => {
                let (cs, ce) = &theme.code;
                if lang.is_some() || *fence {
                    let meta = meta.as_deref().map(|meta| format!(" {}", meta)).unwrap_or_default();
                    let info = format!("{}{}", lang.as_deref().unwrap_or(""), meta);
                    // Empty body skips the content line so it doesn't gain a blank one.
                    let fence_str = code_fence(value, &info);
                    if value.is_empty() {
                        // Blank lines are not in the value, but the lines of the block tell of them.
                        let blank = position
                            .as_ref()
                            .map_or(0, |p| p.end.line.saturating_sub(p.start.line).saturating_sub(1));
                        format!(
                            "{}{}{}\n{}{}{}",
                            cs,
                            fence_str,
                            info,
                            "\n".repeat(blank as usize),
                            fence_str,
                            ce
                        )
                    } else {
                        format!("{}{}{}\n{}\n{}{}", cs, fence_str, info, value, fence_str, ce)
                    }
                } else {
                    value.lines().map(|line| format!("{}    {}{}", cs, line, ce)).join("\n")
                }
            }
            Self::Definition(Definition {
                ident,
                label,
                url,
                title,
                ..
            }) => {
                let (us, ue) = &theme.link_url;
                format!(
                    "[{}]: {}{}{}{}",
                    definition_label(label.as_deref(), ident),
                    us,
                    url.to_string_with(options),
                    ue,
                    title
                        .as_ref()
                        .map(|title| format!(" {}", title.to_string_with(options)))
                        .unwrap_or_default()
                )
            }
            Self::Delete(Delete { values, .. }) => {
                let (ds, de) = &theme.delete;
                format!("{}~~{}~~{}", ds, render_values(values, options, theme), de)
            }
            Self::Emphasis(Emphasis { values, .. }) => {
                render_emphasis(values, emphasis_delimiter(values), options, theme)
            }
            Self::Footnote(Footnote { values, ident, .. }) => {
                format!(
                    "[^{}]: {}",
                    escape_brackets(ident),
                    render_values(values, options, theme)
                )
            }
            Self::FootnoteRef(FootnoteRef { label, ident, .. }) => {
                format!("[^{}]", reference_label(label.as_deref(), ident))
            }
            Self::Heading(Heading { depth, values, .. }) => {
                let (hs, he) = &theme.heading;
                let text = render_values(values, options, theme);
                // A line ending at either end is not part of the heading text, so it is written as a
                // character reference.
                let text = {
                    let inner = text.trim_matches('\n');
                    let leading = text.len() - text.trim_start_matches('\n').len();
                    let trailing = text.len() - text.trim_end_matches('\n').len();
                    if inner.is_empty() || (leading == 0 && trailing == 0) {
                        text.clone()
                    } else {
                        format!("{}{}{}", "&#10;".repeat(leading), inner, "&#10;".repeat(trailing))
                    }
                };
                // Multi-line content must stay setext for depths 1-2; ATX has no setext form.
                if text.contains('\n') && *depth <= HeadingDepth::H2 {
                    let underline = if *depth == HeadingDepth::H1 { "===" } else { "---" };
                    format!("{}{}\n{}{}", hs, text, underline, he)
                } else {
                    // A trailing `#` run reads back as an ATX closing sequence and gets
                    // stripped as syntax rather than kept as heading text.
                    let text = text.replace('\n', " ");
                    let text = match text.rfind(|c: char| c != '#') {
                        Some(i) => {
                            let hash_start = i + text[i..].chars().next().map_or(1, char::len_utf8);
                            if hash_start < text.len() {
                                format!("{}\\{}", &text[..hash_start], &text[hash_start..])
                            } else {
                                text
                            }
                        }
                        None if !text.is_empty() => format!("\\{text}"),
                        _ => text,
                    };
                    format!("{}{} {}{}", hs, "#".repeat(usize::from(depth.get())), text, he)
                }
            }
            Self::Html(Html { value, .. }) => {
                let (hs, he) = &theme.html;
                format!("{}{}{}", hs, value, he)
            }
            Self::Image(Image { alt, url, title, .. }) => {
                let (is, ie) = &theme.image;
                format!(
                    "{}![{}]({}{}){}",
                    is,
                    escape_label(alt),
                    render_link_destination(url, &options.link_url_style),
                    title
                        .as_deref()
                        .map(|it| format!(" {}", render_link_title(it, &options.link_title_style)))
                        .unwrap_or_default(),
                    ie
                )
            }
            // Shortcut is safe only if `alt` normalizes back to `ident`; `ident` is raw
            // (already correctly escaped), so escape_label would double it up.
            Self::ImageRef(ImageRef { alt, ident, label, .. }) => {
                let (is, ie) = &theme.image;
                let mismatched = crate::parser::normalize(alt) != ident.as_str();
                if mismatched || needs_broad_escaping(alt) {
                    format!(
                        "{}![{}][{}]{}",
                        is,
                        escape_label(alt),
                        reference_label(label.as_deref(), ident),
                        ie
                    )
                } else {
                    format!("{}![{}]{}", is, escape_label(alt), ie)
                }
            }
            Self::CodeInline(CodeInline { value, .. }) => {
                let (cs, ce) = &theme.code_inline;
                let fence = code_span_fence(value);
                // Padding avoids fusing with an edge backtick and protects a genuine
                // leading+trailing space from the parser's own space-stripping rule.
                let all_spaces = value.chars().all(|c| c == ' ');
                if value.starts_with('`')
                    || value.ends_with('`')
                    || (!all_spaces && value.starts_with(' ') && value.ends_with(' '))
                {
                    format!("{}{} {} {}{}", cs, fence, value, fence, ce)
                } else {
                    format!("{}{}{}{}{}", cs, fence, value, fence, ce)
                }
            }
            Self::MathInline(MathInline { value, .. }) => {
                let (ms, me) = &theme.math;
                let fence = math_span_fence(value);
                // Padding keeps a dollar sign at an end from fusing with the fence, and a genuine space at
                // both ends from being removed when it is read.
                let all_spaces = value.chars().all(|c| c == ' ');
                if value.starts_with('$')
                    || value.ends_with('$')
                    || (!all_spaces && value.starts_with(' ') && value.ends_with(' '))
                {
                    format!("{}{} {} {}{}", ms, fence, value, fence, me)
                } else {
                    format!("{}{}{}{}{}", ms, fence, value, fence, me)
                }
            }
            Self::Link(Link { url, title, values, .. }) => {
                let (ls, le) = &theme.link;
                if title.is_none()
                    && let Some(target) = autolink_target(url.as_str(), values)
                {
                    return format!("{ls}<{target}>{le}");
                }
                format!(
                    "{}[{}]({}{}){}",
                    ls,
                    render_values(values, options, theme),
                    url.to_string_with(options),
                    title
                        .as_ref()
                        .map(|title| format!(" {}", title.to_string_with(options)))
                        .unwrap_or_default(),
                    le
                )
            }
            #[cfg(feature = "wikilink")]
            Self::WikiLink(WikiLink { target, text, .. }) => {
                let (ls, le) = &theme.link;
                match text.as_deref() {
                    Some(t) if t != target.as_str() => format!("{}[[{}|{}]]{}", ls, target, t, le),
                    _ => format!("{}[[{}]]{}", ls, target, le),
                }
            }
            // Same reasoning as ImageRef, plus the same broad-escaping fallback.
            Self::LinkRef(LinkRef {
                values, ident, label, ..
            }) => {
                let (ls, le) = &theme.link;
                let rendered = render_values(values, options, theme);
                let plain = values_to_value(values);
                // The label of a shortcut reference is its text as written, markup included.
                let written = render_values(values, options, &ColorTheme::PLAIN);
                let mismatched = crate::parser::normalize(&written) != ident.as_str();

                if mismatched || needs_broad_escaping(&plain) {
                    format!(
                        "{}[{}][{}]{}",
                        ls,
                        rendered,
                        reference_label(label.as_deref(), ident),
                        le
                    )
                } else {
                    format!("{}[{}]{}", ls, rendered, le)
                }
            }
            Self::Math(Math { value, .. }) => {
                let (ms, me) = &theme.math;
                let fence = "$".repeat((longest_run(value, '$') + 1).max(2));
                if value.is_empty() {
                    format!("{}{}\n{}{}", ms, fence, fence, me)
                } else {
                    format!("{}{}\n{}\n{}{}", ms, fence, value, fence, me)
                }
            }
            // Only escape text parsed from real markdown (has a position); programmatic
            // values like JSON output or attr lookups must stay untouched.
            Self::Text(Text { value, position }) => {
                if position.is_some() {
                    escape_text_with(value.clone(), options.mdx)
                } else {
                    value.clone()
                }
            }
            Self::MdxFlowExpression(mdx_flow_expression) => {
                format!("{{{}}}", indent_expression(&mdx_flow_expression.value))
            }
            Self::MdxJsxFlowElement(mdx_jsx_flow_element) => {
                let name = mdx_jsx_flow_element.name.as_deref().unwrap_or_default();
                let attributes = if mdx_jsx_flow_element.attributes.is_empty() {
                    "".to_string()
                } else {
                    format!(
                        " {}",
                        mdx_jsx_flow_element
                            .attributes
                            .iter()
                            .map(Self::mdx_attribute_content_to_string)
                            .join(" ")
                    )
                };

                if mdx_jsx_flow_element.children.is_empty() {
                    // A fragment has no self-closing form.
                    if name.is_empty() {
                        format!("<{}></>", attributes)
                    } else {
                        format!("<{}{} />", name, attributes,)
                    }
                } else {
                    // Each tag and the children sit on their own lines, or the children would read as
                    // inline content of the tag.
                    let children = render_values_block(&mdx_jsx_flow_element.children, options, theme);
                    // The lines of an expression are indented as they are written, which indenting them
                    // again would add to each time they are read.
                    if HTML_TARGET.get() {
                        // Blank lines end the tags as HTML blocks, so the children are Markdown.
                        return format!("<{}{}>\n\n{}\n\n</{}>", name, attributes, children, name);
                    }
                    let children = if mdx_jsx_flow_element.children.iter().any(has_multiline_expression) {
                        children
                    } else {
                        indent_continuation(&format!("  {}", children), 2)
                    };
                    format!("<{}{}>\n{}\n</{}>", name, attributes, children, name)
                }
            }
            Self::MdxJsxTextElement(mdx_jsx_text_element) => {
                let name = mdx_jsx_text_element.name.as_deref().unwrap_or_default();
                let attributes = if mdx_jsx_text_element.attributes.is_empty() {
                    "".to_string()
                } else {
                    format!(
                        " {}",
                        mdx_jsx_text_element
                            .attributes
                            .iter()
                            .map(Self::mdx_attribute_content_to_string)
                            .join(" ")
                    )
                };

                if mdx_jsx_text_element.children.is_empty() {
                    // A fragment has no self-closing form.
                    if name.is_empty() {
                        format!("<{}></>", attributes)
                    } else {
                        format!("<{}{} />", name, attributes,)
                    }
                } else {
                    format!(
                        "<{}{}>{}</{}>",
                        name,
                        attributes,
                        render_values(&mdx_jsx_text_element.children, options, theme),
                        name
                    )
                }
            }
            Self::MdxTextExpression(mdx_text_expression) => {
                format!("{{{}}}", indent_expression(&mdx_text_expression.value))
            }
            Self::MdxJsEsm(mdxjs_esm) => mdxjs_esm.value.to_string(),
            Self::Strong(Strong { values, .. }) => render_strong(values, "**", options, theme),
            Self::Yaml(Yaml { value, .. }) => {
                let (fs, fe) = &theme.frontmatter;
                format!("{}---\n{}\n---{}", fs, value, fe)
            }
            Self::Toml(Toml { value, .. }) => {
                let (fs, fe) = &theme.frontmatter;
                format!("{}+++\n{}\n+++{}", fs, value, fe)
            }
            Self::Break(_) => "\\\n".to_string(),
            Self::HorizontalRule(HorizontalRule { marker, .. }) => {
                let (hs, he) = &theme.horizontal_rule;
                let marker = match marker {
                    Some(HorizontalRuleMarker::Dash) => '-',
                    Some(HorizontalRuleMarker::Underscore) => '_',
                    _ => '*',
                };
                format!("{hs}{marker}{marker}{marker}{he}")
            }
            Self::Fragment(Fragment { values }) => values
                .iter()
                .filter(|value| !value.is_empty() && !value.is_empty_fragment())
                .map(|value| value.render_with_theme(options, theme))
                .join("\n"),
            Self::Empty => String::new(),
        }
    }

    fn mdx_attribute_content_to_string(attr: &MdxAttributeContent) -> SmolStr {
        match attr {
            MdxAttributeContent::Expression(value) => format!("{{{}}}", indent_expression(value)).into(),
            MdxAttributeContent::Property(property) => match &property.value {
                Some(value) => match value {
                    MdxAttributeValue::Expression(value) => {
                        format!("{}={{{}}}", property.name, indent_expression(value)).into()
                    }
                    MdxAttributeValue::Literal(literal) => {
                        format!("{}={}", property.name, quote_attribute_value(literal)).into()
                    }
                },
                None => property.name.clone(),
            },
        }
    }
}

/// Whether `node` or a node in it is an expression of more than one line.
fn has_multiline_expression(node: &Node) -> bool {
    match node {
        Node::MdxFlowExpression(expression) => expression.value.contains('\n'),
        Node::MdxTextExpression(expression) => expression.value.contains('\n'),
        Node::MdxJsxTextElement(MdxJsxTextElement { attributes, .. })
        | Node::MdxJsxFlowElement(MdxJsxFlowElement { attributes, .. })
            if attributes.iter().any(|attribute| match attribute {
                MdxAttributeContent::Expression(value) => value.contains('\n'),
                MdxAttributeContent::Property(MdxJsxAttribute {
                    value: Some(MdxAttributeValue::Expression(value)),
                    ..
                }) => value.contains('\n'),
                _ => false,
            }) =>
        {
            true
        }
        other => other.children().iter().any(has_multiline_expression),
    }
}

/// Quotes the value of a JSX attribute with the quote it does not contain. Character references that the
/// value holds as text are written with their `&` as a reference.
fn quote_attribute_value(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for (index, c) in value.char_indices() {
        if c == '&' && starts_reference(&value[index + 1..]) {
            escaped.push_str("&amp;");
        } else {
            escaped.push(c);
        }
    }
    if !escaped.contains('"') {
        format!("\"{escaped}\"")
    } else if !escaped.contains('\'') {
        format!("'{escaped}'")
    } else {
        format!("\"{}\"", escaped.replace('"', "&quot;"))
    }
}

/// The content of an expression as it is written: the lines after the first are indented, as the
/// indentation of up to two characters is removed from them when they are read.
fn indent_expression(value: &str) -> String {
    value
        .split('\n')
        .enumerate()
        .map(|(index, line)| {
            if index == 0 || line.is_empty() || line == "\r" {
                line.to_string()
            } else {
                format!("  {line}")
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

pub(crate) fn values_to_string(values: &[Node], options: &RenderOptions) -> String {
    render_values(values, options, &ColorTheme::PLAIN)
}

/// Indents every line, the first included, by `width` spaces, except empty ones.
pub(crate) fn indent_lines(content: &str, width: usize) -> String {
    let pad = " ".repeat(width);
    content
        .split('\n')
        .map(|line| {
            if line.is_empty() {
                line.to_string()
            } else {
                format!("{pad}{line}")
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Indents every line after the first by `width` spaces, except empty ones.
fn indent_continuation(content: &str, width: usize) -> String {
    let Some((first, rest)) = content.split_once('\n') else {
        return content.to_string();
    };
    let pad = " ".repeat(width);
    let mut result = String::with_capacity(content.len() + width * 2);
    result.push_str(first);
    for line in rest.split('\n') {
        result.push('\n');
        if !line.is_empty() {
            result.push_str(&pad);
            result.push_str(line);
        }
    }
    result
}

/// The delimiter of emphasis around `values`. Emphasis nested at an edge takes the other one, or the
/// two runs fuse into `**` and read back as strong emphasis.
fn emphasis_delimiter(values: &[Node]) -> &'static str {
    let edge = [values.first(), values.last()]
        .into_iter()
        .flatten()
        .find_map(|node| match node {
            Node::Emphasis(Emphasis { values, .. }) => Some(values),
            _ => None,
        });
    match edge.map(|inner| emphasis_delimiter(inner)) {
        Some("_") => "*",
        Some(_) => "_",
        None => "*",
    }
}

/// Renders strong emphasis around `values` with the delimiter `delim`.
fn render_strong(values: &[Node], delim: &str, options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
    let (ss, se) = &theme.strong;
    let last = values.len().saturating_sub(1);
    let content = values
        .iter()
        .enumerate()
        .map(|(index, value)| match value {
            // Emphasis at an end uses the other delimiter, or `*` and `**` fuse into `***`.
            // An underscore does not open or close next to a letter or digit, so those keep `*`.
            Node::Emphasis(Emphasis { values: inner, .. })
                if (index == 0 || index == last)
                    && !index
                        .checked_sub(1)
                        .is_some_and(|before| ends_with_word_char(&values[before]))
                    && !values.get(index + 1).is_some_and(starts_with_word_char) =>
            {
                render_emphasis(inner, "_", options, theme)
            }
            value => value.render_with_theme(options, theme),
        })
        .collect::<String>();
    format!("{ss}{delim}{content}{delim}{se}")
}

fn render_emphasis(values: &[Node], delim: &str, options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
    let (es, ee) = &theme.emphasis;
    format!("{es}{delim}{}{delim}{ee}", render_values(values, options, theme))
}

/// Renders the content of a table cell. A pipe that is not escaped yet, as in code, would end the cell.
pub(crate) fn render_cell_values(values: &[Node], options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
    let rendered = render_values(values, options, theme);
    if !rendered.contains('|') {
        return rendered;
    }
    let mut result = String::with_capacity(rendered.len() + 4);
    let mut escaped = false;
    for c in rendered.chars() {
        if c == '|' && !escaped {
            result.push('\\');
        }
        escaped = c == '\\' && !escaped;
        result.push(c);
    }
    result
}

fn ends_with_word_char(node: &Node) -> bool {
    matches!(node, Node::Text(Text { value, .. }) if value.ends_with(|c: char| c.is_alphanumeric()))
}

fn starts_with_word_char(node: &Node) -> bool {
    matches!(node, Node::Text(Text { value, .. }) if value.starts_with(|c: char| c.is_alphanumeric()))
}

/// Whether `second` starts where `first` ends, so the two are written next to each other.
/// Nodes without positions are taken to touch.
fn touches(first: &Node, second: &Node) -> bool {
    match (first.position(), second.position()) {
        (Some(first), Some(second)) => first.end == second.start,
        _ => true,
    }
}

/// Renders `value`, escaping a `!` that ends its text when `next` starts a link, which would make an image.
///
/// `previous` is what this function returned for the last of `before`, with `value` as `next`.
pub(crate) fn render_before(
    value: &Node,
    before: &[Node],
    previous: Option<&str>,
    next: Option<&Node>,
    options: &RenderOptions,
    theme: &ColorTheme<'_>,
) -> String {
    // Emphasis right after other emphasis takes the other delimiter, or the two fuse into one run.
    if let Node::Emphasis(Emphasis { values, .. }) = value
        && matches!(before.last(), Some(Node::Emphasis(_) | Node::Strong(_)))
        && before.last().is_some_and(|last| touches(last, value))
        && !matches!(values.first(), Some(Node::Emphasis(_)))
        && !matches!(values.last(), Some(Node::Emphasis(_)))
        && !next.is_some_and(|next| touches(value, next) && starts_with_word_char(next))
    {
        let delim = if previous.is_some_and(|previous| previous.ends_with('_')) {
            "*"
        } else {
            "_"
        };
        return render_emphasis(values, delim, options, theme);
    }
    // Strong right after emphasis that ends in `*` takes `__`, or the runs of `*` fuse.
    if let Node::Strong(Strong { values, .. }) = value
        && matches!(before.last(), Some(Node::Emphasis(_) | Node::Strong(_)))
        && before.last().is_some_and(|last| touches(last, value))
        && !next.is_some_and(|next| touches(value, next) && starts_with_word_char(next))
        && previous.is_some_and(|previous| previous.ends_with('*'))
    {
        return render_strong(values, "__", options, theme);
    }
    // A reference followed by a colon at the start of a line would read back as a definition.
    let after_reference = matches!(before.last(), Some(Node::LinkRef(_) | Node::FootnoteRef(_)))
        && before.last().is_some_and(|last| touches(last, value));
    let mut rendered = value.render_with_theme(options, theme);
    let starts_link = next.is_some_and(|next| touches(value, next))
        && match next {
            Some(Node::Link(_) | Node::LinkRef(_)) => true,
            #[cfg(feature = "wikilink")]
            Some(Node::WikiLink(_)) => true,
            _ => false,
        };
    if after_reference && matches!(value, Node::Text(_)) && rendered.starts_with(':') {
        rendered.insert(0, '\\');
    }
    if starts_link && matches!(value, Node::Text(Text { position: Some(_), .. })) && rendered.ends_with('!') {
        rendered.insert(rendered.len() - 1, '\\');
    }
    rendered
}

pub(crate) fn render_values(values: &[Node], options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
    let mut pre_position: Option<Position> = None;
    let mut previous: Option<String> = None;
    values
        .iter()
        .enumerate()
        .map(|(index, value)| {
            let raw = render_before(
                value,
                &values[..index],
                previous.as_deref(),
                values.get(index + 1),
                options,
                theme,
            );
            let rendered = || raw.as_str();
            if let Some(pos) = value.position() {
                let new_line_count = pre_position
                    .as_ref()
                    .map(|p: &Position| pos.start.line.saturating_sub(p.end.line))
                    .unwrap_or_default();

                let space = if new_line_count > 0
                    && pre_position
                        .as_ref()
                        .map(|p| pos.start.line > p.end.line)
                        .unwrap_or_default()
                {
                    " ".repeat(pos.start.column.saturating_sub(1) as usize)
                } else {
                    "".to_string()
                };

                pre_position = Some(pos);

                let piece = if space.is_empty() {
                    format!("{}{}", "\n".repeat(new_line_count as usize), rendered())
                } else {
                    format!(
                        "{}{}",
                        "\n".repeat(new_line_count as usize),
                        rendered().lines().map(|line| format!("{}{}", space, line)).join("\n")
                    )
                };
                previous = Some(raw);
                piece
            } else {
                pre_position = None;
                let piece = raw.clone();
                previous = Some(raw);
                piece
            }
        })
        .collect::<String>()
}

/// The number of line endings to write before `node` after `previous`, raised to a blank line where
/// the node would otherwise read back as part of `previous`.
pub(crate) fn separated_from(count: u32, previous: Option<&Node>, node: &Node, rendered: &str) -> u32 {
    if count >= 2 {
        return count;
    }
    // A single line ending after a block quote reads back as lazy continuation, unless the node
    // opens with a fence, which ends the quote.
    let fenced = matches!(node, Node::Code(Code { lang, fence, .. }) if lang.is_some() || *fence);
    let lazy = previous.is_some_and(Node::is_blockquote_like) && !fenced;
    // A line of dashes right under paragraph text reads back as a setext heading.
    let setext = matches!(node, Node::HorizontalRule(_))
        && rendered.starts_with("---")
        && previous.is_some_and(Node::is_paragraph_text);
    // A footnote ends where the next line starts, so a block after it needs a blank line.
    let footnote = matches!(previous, Some(Node::Footnote(_))) && !matches!(node, Node::Footnote(_));
    if lazy || setext || footnote { 2 } else { count }
}

/// Writes an item, or the rest of one that follows the items nested in it, inside a container.
///
/// `indents` holds the column of the content of each open item. It is kept out of the container loop
/// so that the frame of that recursion stays small.
#[inline(never)]
fn render_list_item(
    node: &Node,
    item: &List,
    rest: bool,
    indents: &mut Vec<usize>,
    options: &RenderOptions,
    theme: &ColorTheme<'_>,
) -> String {
    if rest {
        // Indented to the content of the item and written without a marker.
        indents.truncate(item.level as usize + 1);
        let indent = indents.last().copied().unwrap_or(0);
        return indent_lines(&render_values_block(&item.values, options, theme), indent);
    }
    // Nested items are indented to the content of the item that holds them.
    indents.truncate(item.level as usize);
    let own_indent = indents.last().copied().unwrap_or(0);
    let delta = own_indent as isize - item.level as isize * 2;
    indents.push(own_indent + list_own_prefix_width(item.ordered, item.index, item.start));
    reindent_all_lines(&node.render_with_theme(options, theme), delta)
}

/// Writes what separates `node` from the one written before it, and trims `rendered` when it follows
/// the marker that holds it. Not inlined, to keep the frame of the container loop small.
#[inline(never)]
fn separate(
    result: &mut String,
    rendered: &mut String,
    pre_position: &mut Option<Position>,
    position: Option<Position>,
    previous: Option<&Node>,
    node: &Node,
) {
    if let Some(pos) = position {
        let new_line_count = pre_position
            .as_ref()
            .map(|p: &Position| pos.start.line.saturating_sub(p.end.line))
            .unwrap_or_default();
        let new_line_count = separated_from(new_line_count, previous, node, rendered);
        *pre_position = Some(pos);
        result.push_str(&"\n".repeat(new_line_count as usize));
        // An item that starts on the line of the marker that holds it follows it directly.
        if new_line_count == 0 && matches!((previous, node), (Some(Node::List(_)), Node::List(_))) {
            *rendered = rendered.trim_start().to_string();
        }
    } else {
        // Text never follows text inside one paragraph, so without positions that is a new one.
        if pre_position.is_none() && matches!((previous, node), (Some(Node::Text(_)), Node::Text(_))) {
            result.push_str("\n\n");
        }
        *pre_position = None;
    }
}

/// Like `render_values` but without column-offset–based indentation.
///
/// Inside blockquotes and callouts, node positions include the `> ` prefix offset,
/// so applying column-based spacing causes double-indentation. This variant preserves
/// blank lines between values (via newline counting) but ignores the column position.
pub(crate) fn render_values_block(values: &[Node], options: &RenderOptions, theme: &ColorTheme<'_>) -> String {
    // The children of an item that come after the items nested in it, as at the top level.
    let reordered = crate::markdown::list_order::reorder(values);
    let (values, continuation) = match &reordered {
        Some(reordered) => (reordered.nodes.as_slice(), reordered.continuation.as_slice()),
        None => (values, [].as_slice()),
    };
    let mut result = String::new();
    let mut pre_position: Option<Position> = None;
    let mut index = 0;
    // The column of the content of the open items, one for each level.
    let mut list_indent_stack: Vec<usize> = Vec::new();
    // The last node written, to tell paragraphs from the inline nodes of one when there are no positions.
    let mut previous: Option<&Node> = None;
    // What `render_before` returned for `previous`, or `None` when it is part of a table.
    let mut previous_rendered: Option<String> = None;

    while index < values.len() {
        let first = &values[index];
        // The cells of a table are laid out together, as at the top level.
        let (mut rendered, position, next) = if is_table_part(first) {
            list_indent_stack.clear();
            render_table_run(values, index, options, theme)
        } else if let Node::List(item) = first {
            let rest = continuation.get(index) == Some(&true);
            (
                render_list_item(first, item, rest, &mut list_indent_stack, options, theme),
                first.position(),
                index + 1,
            )
        } else {
            list_indent_stack.clear();
            (
                render_before(
                    first,
                    &values[..index],
                    previous_rendered.as_deref(),
                    values.get(index + 1),
                    options,
                    theme,
                ),
                first.position(),
                index + 1,
            )
        };
        index = next;

        separate(&mut result, &mut rendered, &mut pre_position, position, previous, first);
        previous = Some(&values[index - 1]);
        result.push_str(&rendered);
        previous_rendered = (!is_table_part(first)).then_some(rendered);
    }
    result
}

fn is_table_part(node: &Node) -> bool {
    matches!(node, Node::TableCell(_) | Node::TableAlign(_))
}

/// Renders the cells and the delimiter row from `values[index]` on as one table, with its position and
/// the index after it. Apart from the recursion, so that nesting does not pay for its locals.
#[inline(never)]
fn render_table_run(
    values: &[Node],
    index: usize,
    options: &RenderOptions,
    theme: &ColorTheme<'_>,
) -> (String, Option<Position>, usize) {
    let end = values[index..]
        .iter()
        .position(|node| !is_table_part(node))
        .map_or(values.len(), |offset| index + offset);
    let run = &values[index..end];
    let table = crate::Markdown {
        nodes: run.to_vec(),
        options: options.clone(),
    };
    let position = match (run[0].position(), run[run.len() - 1].position()) {
        (Some(first), Some(last)) => Some(Position {
            start: first.start,
            end: last.end,
        }),
        _ => None,
    };
    (
        table.render_with_theme(theme).trim_end_matches('\n').to_string(),
        position,
        end,
    )
}

/// Renders a link/image destination, auto-upgrading to `<...>` (escaping `\ < >`)
/// when the bare form would be unsafe (empty, or contains whitespace/control/`< >`);
/// otherwise bare, escaping `\ ( )` since unescaped parens must balance.
pub(super) fn render_link_destination(url: &str, style: &UrlSurroundStyle) -> String {
    let needs_angle = url.is_empty()
        || url
            .chars()
            .any(|c| c.is_whitespace() || c.is_control() || c == '<' || c == '>');

    if matches!(style, UrlSurroundStyle::Angle) || needs_angle {
        let mut result = String::with_capacity(url.len() + 2);
        result.push('<');
        for c in url.chars() {
            if matches!(c, '\\' | '<' | '>') {
                result.push('\\');
            }
            result.push(c);
        }
        result.push('>');
        result
    } else {
        let mut result = String::with_capacity(url.len());
        for c in url.chars() {
            if matches!(c, '\\' | '(' | ')') {
                result.push('\\');
            }
            result.push(c);
        }
        result
    }
}

/// Renders a link/image title, escaping `\` and the style's delimiter(s) so the
/// title's own quote/paren characters can't end it early.
pub(super) fn render_link_title(title: &str, style: &TitleSurroundStyle) -> String {
    let (open, close, delims): (char, char, &[char]) = match style {
        TitleSurroundStyle::Double => ('"', '"', &['"']),
        TitleSurroundStyle::Single => ('\'', '\'', &['\'']),
        TitleSurroundStyle::Paren => ('(', ')', &['(', ')']),
    };
    let mut result = String::with_capacity(title.len() + 2);
    result.push(open);
    for c in title.chars() {
        if c == '\\' || delims.contains(&c) {
            result.push('\\');
        }
        result.push(c);
    }
    result.push(close);
    result
}

/// Escapes `\ [ ]` in reference labels/idents and image alt text: plain strings
/// (not walked as inline nodes) that still sit inside `[...]` syntax.
/// True if `s` needs escaping beyond `escape_label`'s narrow `\ [ ]` set: unsafe
/// for a reference's implicit shortcut form, since the definition's label won't match.
fn needs_broad_escaping(s: &str) -> bool {
    s.bytes().any(|b| {
        matches!(
            b,
            b'`' | b'*' | b'_' | b'|' | b'~' | b'$' | b'#' | b'-' | b'+' | b'>' | b'=' | b'.' | b')' | b'!'
        )
    })
}

/// Shifts every line's leading indentation by `delta` spaces (never below zero),
/// leaving each line's own content untouched.
pub(crate) fn reindent_all_lines(content: &str, delta: isize) -> String {
    if delta == 0 {
        return content.to_string();
    }
    content
        .split('\n')
        .map(|line| {
            if line.is_empty() {
                line.to_string()
            } else {
                let leading = line.bytes().take_while(|&b| b == b' ').count();
                let new_leading = (leading as isize + delta).max(0) as usize;
                format!("{}{}", " ".repeat(new_leading), &line[leading..])
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// The width of a list item's own marker and trailing space (not including ancestor indentation),
/// e.g. 2 for `"- "`, 3 for `"1. "`, 4 for `"10. "`. A checkbox is not part of it, as the content of
/// the item starts at the checkbox, so children are indented to the marker alone.
pub(crate) fn list_own_prefix_width(ordered: bool, index: usize, start: Option<u32>) -> usize {
    let marker_len = if ordered {
        (start.unwrap_or(1) as usize + index).to_string().chars().count() + 1
    } else {
        1
    };
    marker_len + 1
}

/// The length of the longest run of `ch` in `s`.
fn longest_run(s: &str, ch: char) -> usize {
    s.split('\n')
        .flat_map(|line| line.split(|c| c != ch).map(str::len))
        .max()
        .unwrap_or(0)
}

/// Longest fence-char run in `value` + 1 (min 3); switches to tilde when `info`
/// has a backtick, since a backtick-fenced info string can't contain one.
fn code_fence(value: &str, info: &str) -> String {
    if info.contains('`') {
        let len = (longest_run(value, '~') + 1).max(3);
        "~".repeat(len)
    } else {
        let len = (longest_run(value, '`') + 1).max(3);
        "`".repeat(len)
    }
}

/// The label to write in a definition: the identifier as it was written when the label is only that
/// without its escapes and character references, which would not read back as the same identifier.
fn definition_label(label: Option<&str>, ident: &str) -> String {
    match label {
        Some(label) if crate::parser::normalize(label) == ident => escape_label(label),
        Some(label) if crate::parser::normalize(label) == crate::parser::normalize(&crate::parser::unescape(ident)) => {
            ident.to_string()
        }
        Some(label) => escape_label(label),
        None => ident.to_string(),
    }
}

/// The label to write in the second brackets of a full reference. The label as written is kept when it
/// still resolves to `ident`.
fn reference_label(label: Option<&str>, ident: &str) -> String {
    match label {
        Some(label) if crate::parser::normalize(label) == ident => escape_label(label),
        _ => ident.to_string(),
    }
}

/// Picks an inline code span delimiter one backtick longer than the longest
/// backtick run in `value`, so no run inside it can be mistaken for the closing.
fn code_span_fence(value: &str) -> String {
    let mut max_run = 0;
    let mut cur = 0;
    for c in value.chars() {
        if c == '`' {
            cur += 1;
            max_run = max_run.max(cur);
        } else {
            cur = 0;
        }
    }
    "`".repeat(max_run + 1)
}

/// The shortest run of dollar signs, from one, that is not the length of a run in `value`, so that no
/// run inside a math span can be mistaken for the closing.
fn math_span_fence(value: &str) -> String {
    let mut lengths = std::collections::HashSet::new();
    let mut current = 0;
    for c in value.chars() {
        if c == '$' {
            current += 1;
        } else if current > 0 {
            lengths.insert(current);
            current = 0;
        }
    }
    if current > 0 {
        lengths.insert(current);
    }
    "$".repeat((1..).find(|length| !lengths.contains(length)).unwrap_or(1))
}

/// Escapes the brackets that are not escaped yet, for an identifier that keeps the escapes it was written with.
fn escape_brackets(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '\\' if chars.peek().is_some_and(char::is_ascii_punctuation) => {
                result.push(c);
                result.extend(chars.next());
            }
            '[' | ']' => {
                result.push('\\');
                result.push(c);
            }
            _ => result.push(c),
        }
    }
    result
}

fn escape_label(s: &str) -> String {
    if !s.bytes().any(|b| matches!(b, b'\\' | b'[' | b']')) {
        return s.to_string();
    }
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        if matches!(c, '\\' | '[' | ']') {
            result.push('\\');
        }
        result.push(c);
    }
    result
}

/// The text of an autolink for a link whose only content is its own destination, when writing that
/// text as a link label would need escapes. A URL in a label is read as it is, so `\_` would stay.
fn autolink_target(url: &str, values: &[Node]) -> Option<String> {
    let [Node::Text(Text { value, .. })] = values else {
        return None;
    };
    let target = if value == url {
        url
    } else if url.strip_prefix("mailto:") == Some(value.as_str()) && crate::parser::is_autolink_email(value) {
        value.as_str()
    } else {
        return None;
    };
    let plain = !target
        .chars()
        .any(|c| c.is_whitespace() || c.is_control() || matches!(c, '<' | '>'));
    let scheme = target.split_once(':').is_some_and(|(scheme, _)| {
        (2..=32).contains(&scheme.len())
            && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
            && scheme
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'))
    });
    let email = value != url;
    (plain && (scheme || email) && escape_text(target.to_string()) != target).then(|| target.to_string())
}

/// Whether `rest`, the text after an `&`, reads as the rest of a character reference.
fn starts_reference(rest: &str) -> bool {
    let name = match rest.strip_prefix('#') {
        Some(number) => match number.strip_prefix(['x', 'X']) {
            Some(hex) => hex
                .split_once(';')
                .map(|(digits, _)| (digits, char::is_ascii_hexdigit as fn(&char) -> bool)),
            None => number
                .split_once(';')
                .map(|(digits, _)| (digits, char::is_ascii_digit as fn(&char) -> bool)),
        },
        None => rest
            .split_once(';')
            .map(|(name, _)| (name, char::is_ascii_alphanumeric as fn(&char) -> bool)),
    };
    name.is_some_and(|(name, is_valid)| !name.is_empty() && name.chars().all(|c| is_valid(&c)))
}

fn is_email_local(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '+')
}

/// Whether `rest`, the text after an `@`, starts with a domain that makes an email address of the text
/// before it.
fn is_email_domain(rest: &str) -> bool {
    let domain = rest
        .split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')))
        .next()
        .unwrap_or_default();
    domain
        .split_once('.')
        .is_some_and(|(label, after)| !label.is_empty() && after.starts_with(|c: char| c.is_ascii_alphanumeric()))
}

/// Re-escapes markdown-significant characters so plain text can't be reinterpreted as
/// syntax on re-parse. `# - + > =` only unsafe at line start, `. )` only after leading digits;
/// a leading `\t` and runs of 2+ `\n` (only possible via decoded entities) use `&#N;` instead.
fn escape_text(value: String) -> String {
    escape_text_with(value, false)
}

/// Whether `text` starts with the `import ` or `export ` that makes a block ESM in MDX.
fn starts_esm(text: &str) -> bool {
    text.starts_with("import ") || text.starts_with("export ")
}

/// `escape_text`, and for MDX also the braces and the `import` or `export` that starts a line.
fn escape_text_with(value: String, mdx: bool) -> String {
    // Skip the copy when nothing needs escaping; byte scan avoids UTF-8 decoding.
    let needs_escaping = value.bytes().any(|b| {
        matches!(
            b,
            b'\\'
                | b'`'
                | b'*'
                | b'_'
                | b'['
                | b']'
                | b'|'
                | b'~'
                | b'$'
                | b'#'
                | b'-'
                | b'+'
                | b'>'
                | b'<'
                | b'='
                | b'.'
                | b')'
                | b'\n'
                | b'\t'
                | b'&'
                | b'@'
        )
    });
    let mdx_special = mdx && (value.contains('{') || value.contains("import ") || value.contains("export "));
    if !needs_escaping && !mdx_special {
        return value;
    }

    let mut result = String::with_capacity(value.len());
    let mut at_line_start = true;
    // True while in an unbroken digit run since line start (ordered-list marker number).
    let mut leading_digits = false;
    let mut chars = value
        .char_indices()
        .map(|(index, c)| (c, &value[index + c.len_utf8()..]))
        .peekable();
    let mut previous = None;

    while let Some((c, rest)) = chars.next() {
        match c {
            '\n' if chars.peek().is_some_and(|(next, _)| *next == '\n') => {
                result.push_str("&#10;");
                at_line_start = true;
                leading_digits = false;
                continue;
            }
            '\t' if at_line_start => {
                result.push_str("&#9;");
                at_line_start = false;
                leading_digits = false;
                continue;
            }
            '\\' | '`' | '*' | '_' | '[' | ']' | '|' | '~' | '$' | '<' => result.push('\\'),
            '{' if mdx => result.push('\\'),
            // The first letter as a character reference keeps the line from starting an ESM block.
            'i' | 'e' if mdx && at_line_start && starts_esm(&value[value.len() - rest.len() - 1..]) => {
                result.push_str(if c == 'i' { "&#105;" } else { "&#101;" });
                at_line_start = false;
                leading_digits = false;
                previous = Some(c);
                continue;
            }
            '#' | '-' | '+' | '>' | '=' if at_line_start => result.push('\\'),
            '.' | ')' if leading_digits => result.push('\\'),
            '&' if starts_reference(rest) => result.push('\\'),
            '@' if previous.is_some_and(is_email_local) && is_email_domain(rest) => result.push('\\'),
            _ => {}
        }
        result.push(c);
        previous = Some(c);

        let is_digit = c.is_ascii_digit();
        leading_digits = if at_line_start {
            is_digit
        } else {
            leading_digits && is_digit
        };
        at_line_start = c == '\n';
    }

    result
}

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

    #[rstest]
    #[case::heading_marker("## not a heading", "\\## not a heading")]
    #[case::heading_seven_hashes_still_escaped("####### x", "\\####### x")]
    #[case::emphasis_star("*not emphasis*", "\\*not emphasis\\*")]
    #[case::emphasis_underscore("_not emphasis_", "\\_not emphasis\\_")]
    #[case::code_span("`not code`", "\\`not code\\`")]
    #[case::link_brackets("[not a link](x)", "\\[not a link\\](x)")]
    #[case::list_marker("- not a list item", "\\- not a list item")]
    #[case::blockquote_marker("> not a quote", "\\> not a quote")]
    #[case::table_pipe("| not a table |", "\\| not a table \\|")]
    #[case::strikethrough("~not strikethrough~", "\\~not strikethrough\\~")]
    #[case::math("$not math$", "\\$not math\\$")]
    #[case::plus_list_marker("+ not a list item", "\\+ not a list item")]
    #[case::ordered_list_dot("5. not a list", "5\\. not a list")]
    #[case::ordered_list_paren("5) not a list", "5\\) not a list")]
    #[case::setext_h1_underline("Foo\n===", "Foo\n\\===")]
    #[case::hash_not_at_line_start("a#b", "a#b")]
    #[case::dash_not_at_line_start("a-b", "a-b")]
    #[case::plus_not_at_line_start("a+b", "a+b")]
    #[case::gt_not_at_line_start("a>b", "a>b")]
    #[case::eq_not_at_line_start("a=b", "a=b")]
    #[case::dot_not_after_leading_digits("a5. b", "a5. b")]
    #[case::dot_after_broken_digit_run("5x3. b", "5x3. b")]
    #[case::escapes_after_embedded_newline("a\n# b", "a\n\\# b")]
    #[case::plain_text_unchanged("plain text", "plain text")]
    #[case::literal_backslash_is_doubled("a\\b", "a\\\\b")]
    #[case::empty_string("", "")]
    #[case::bang_before_bracket_only_bracket_escaped("![bar]", "!\\[bar\\]")]
    #[case::bang_at_value_end_not_escaped("foo!", "foo!")]
    #[case::consecutive_newlines_become_entity("foo\n\nbar", "foo&#10;\nbar")]
    #[case::three_consecutive_newlines("foo\n\n\nbar", "foo&#10;&#10;\nbar")]
    #[case::single_newline_unchanged("foo\nbar", "foo\nbar")]
    #[case::leading_tab_becomes_entity("\tfoo", "&#9;foo")]
    #[case::tab_not_at_line_start_unchanged("foo\tbar", "foo\tbar")]
    #[case::angle_bracket_escaped("<br/> not a tag", "\\<br/> not a tag")]
    // `&` is deliberately left unescaped: see KNOWN_FAILURES in gfm_roundtrip_fidelity.rs (#591).
    #[case::ampersand_not_escaped("a&b", "a&b")]
    fn test_escape_text(#[case] input: &str, #[case] expected: &str) {
        assert_eq!(escape_text(input.to_string()), expected);
    }

    #[rstest]
    #[case::plain("plain", "plain")]
    #[case::brackets("[a][b]", "\\[a\\]\\[b\\]")]
    #[case::backslash("a\\b", "a\\\\b")]
    fn test_escape_label(#[case] input: &str, #[case] expected: &str) {
        assert_eq!(escape_label(input), expected);
    }

    #[rstest]
    #[case::no_newline_unchanged("abc", 2, "abc")]
    #[case::continuation_indented("a\nb", 2, "a\n  b")]
    #[case::empty_lines_untouched("a\n\nb", 2, "a\n\n  b")]
    #[case::first_line_never_indented("  a\nb", 3, "  a\n   b")]
    fn test_indent_continuation(#[case] content: &str, #[case] width: usize, #[case] expected: &str) {
        assert_eq!(indent_continuation(content, width), expected);
    }

    #[rstest]
    #[case::no_backticks("", 1)]
    #[case::single_run("foo`bar", 2)]
    #[case::longer_run("foo``bar", 3)]
    fn test_code_span_fence(#[case] value: &str, #[case] expected_len: usize) {
        assert_eq!(code_span_fence(value), "`".repeat(expected_len));
    }

    #[rstest]
    #[case::no_backticks_minimum_three("plain", "", 3)]
    #[case::body_run_escalates("aaa\n```", "", 4)]
    fn test_code_fence(#[case] value: &str, #[case] info: &str, #[case] expected_len: usize) {
        assert_eq!(code_fence(value, info), "`".repeat(expected_len));
    }

    #[rstest]
    #[case::info_backtick_switches_to_tilde("plain", "a`b", 3)]
    #[case::info_backtick_run_switches_to_tilde("plain", "a``b", 3)]
    #[case::body_tilde_run_escalates_within_tilde_fence("aaa\n~~~", "a`b", 4)]
    fn test_code_fence_tilde(#[case] value: &str, #[case] info: &str, #[case] expected_len: usize) {
        assert_eq!(code_fence(value, info), "~".repeat(expected_len));
    }

    proptest! {
        // Every backslash escape_text inserts precedes exactly the character it
        // protects, and pre-existing backslashes are doubled, so blindly dropping
        // each backslash and keeping the character after it must recover the
        // original string, for any input. Tabs and repeated newlines go through a
        // separate entity-based path (see test_escape_text), excluded here.
        #[test]
        fn escape_text_is_losslessly_invertible(
            s in prop::collection::vec(any::<char>(), 0..60)
                .prop_map(|cs| cs.into_iter().collect::<String>())
                .prop_filter("excludes entity-escaped tab/newline-run cases", |s| {
                    !s.contains('\t') && !s.contains("\n\n")
                })
        ) {
            let escaped = escape_text(s.clone());
            prop_assert_eq!(naive_unescape(&escaped), s);
        }

        // Rendering must never panic, whatever the heading text (arbitrary Unicode,
        // possibly ending in a run of `#`): this is a UTF-8 char-boundary regression
        // guard for the trailing-`#` escape logic.
        #[test]
        fn heading_render_never_panics_on_unicode_text(
            body in prop::collection::vec(any::<char>(), 0..20).prop_map(|cs| cs.into_iter().collect::<String>()),
            hashes in 0usize..5,
            depth in 1u8..=6,
        ) {
            let value = format!("{}{}", body, "#".repeat(hashes));
            let node = Node::Heading(Heading { depth: HeadingDepth::saturating(i64::from(depth)), values: vec![value.into()], position: None });
            let _ = node.to_string_with(&RenderOptions::default());
        }

        #[test]
        fn escape_label_is_losslessly_invertible(
            s in prop::collection::vec(any::<char>(), 0..40).prop_map(|cs| cs.into_iter().collect::<String>())
        ) {
            let escaped = escape_label(&s);
            prop_assert_eq!(naive_unescape(&escaped), s);
        }

        // A Link's destination, rendered through the real writer and re-parsed by the
        // real markdown parser, must recover the original URL string: the concrete
        // bug class from the GFM spec-suite fidelity check (spaces/parens/angle
        // brackets silently corrupting or breaking the link on round-trip).
        #[test]
        fn link_url_round_trips_through_parser(
            url in prop::collection::vec(
                prop::sample::select(vec!['a', 'b', '1', ' ', '(', ')', '<', '>', '\\']),
                1..12,
            ).prop_map(|cs| cs.into_iter().collect::<String>())
        ) {
            let doc = format!("[text]({})\n", render_link_destination(&url, &UrlSurroundStyle::None));
            let parsed = crate::Markdown::from_markdown_str(&doc).unwrap();
            let link = parsed.nodes.iter().find_map(|n| match n {
                Node::Link(l) => Some(l.url.as_str().to_string()),
                _ => None,
            });
            prop_assert_eq!(link, Some(url));
        }

    }

    fn naive_unescape(s: &str) -> String {
        let mut result = String::with_capacity(s.len());
        let mut chars = s.chars();
        while let Some(c) = chars.next() {
            if c == '\\'
                && let Some(next) = chars.next()
            {
                result.push(next);
                continue;
            }
            result.push(c);
        }
        result
    }
}