html-to-markdown-rs 3.16.0

High-performance HTML to Markdown converter using the astral-tl parser. Part of the Xberg ecosystem.
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
//! Text-escaping helpers for Markdown link/label rendering.
//!
//! Split out of `content.rs` to stay under the 1000-line quality gate; these
//! functions evolve independently of the extraction helpers that remain there.

use std::borrow::Cow;

/// Escape a link label or image alt text so it cannot break out of the `[...]` / `![...]`
/// it is about to be wrapped in.
///
/// Two independent escapes, in order:
///
/// 1. [`escape_label_brackets`] -- a `]` with no local opener, or a matched pair that is
///    itself link- or reference-link-shaped.
/// 2. [`escape_block_openers_on_continuation_lines`] -- a `CommonMark` block-structure
///    marker opening a line after the first (issue #496).
///
/// Both are unconditional, unlike the `escape_misc`/`escape_asterisks` family: those decide
/// whether text that merely *looks* like Markdown is emitted verbatim, whereas these two
/// decide whether the link or image survives at all.
pub fn escape_link_label(text: &str) -> Cow<'_, str> {
    match escape_label_brackets(text) {
        Cow::Borrowed(bracketed) => escape_block_openers_on_continuation_lines(bracketed),
        Cow::Owned(bracketed) => Cow::Owned(escape_block_openers_on_continuation_lines(&bracketed).into_owned()),
    }
}

/// Escape the brackets in a link label or image alt text that would otherwise terminate it.
///
/// One of the two halves of [`escape_link_label`]; see there for the other.
/// Tracks matched bracket pairs and escapes a closing bracket that has no local opener
/// (it would otherwise close the caller's own wrapping `[`/`![` early), an opening
/// bracket that is never matched by a later closer (it would otherwise open a
/// link/image span that swallows the caller's own closing `]`/`)` on reparse), and
/// escapes a matched pair outright when it is itself link- or reference-link-shaped.
///
/// # Examples
/// ```text
/// Input:  "]"
/// Output: "\\]"
///
/// Input:  "[A;B)"
/// Output: "\\[A;B)"
///
/// Input:  "[outer [inner]]"
/// Output: "[outer [inner]]"
///
/// Input:  "[foo](uri2)"
/// Output: "\\[foo\\](uri2)"
/// ```
///
/// Scan `text` for `[`/`]` bytes that must be escaped and return a per-byte marker vector
/// (`true` at a byte offset that needs a preceding `\`). Split out of
/// [`escape_label_brackets`] to keep that function under the line-count quality gate.
fn mark_bracket_escapes(text: &str) -> Vec<bool> {
    let mut escape_at = vec![false; text.len()];
    // ~keep Byte offsets (into `text`) of unescaped `[` openers not yet matched by a `]`,
    // ~keep innermost last. A bare depth counter cannot tell "is there a local opener"
    // ~keep from "which one", and the `](`/`][` check below needs the specific opener.
    let mut open_positions: Vec<usize> = Vec::new();
    let mut backslash_count = 0usize;
    let mut chars = text.char_indices().peekable();

    while let Some((byte_pos, ch)) = chars.next() {
        if ch == '\\' {
            backslash_count += 1;
            continue;
        }

        let is_escaped = backslash_count % 2 == 1;
        backslash_count = 0;

        match ch {
            '[' if !is_escaped => open_positions.push(byte_pos),
            ']' if !is_escaped => match open_positions.pop() {
                None => {
                    // ~keep No local opener: left alone, this `]` closes the caller's own
                    // ~keep wrapping `[`/`![` early, truncating the label.
                    escape_at[byte_pos] = true;
                }
                Some(open_pos) => {
                    // ~keep A `]` immediately followed by `(` or `[` completes an inline
                    // ~keep link/image (`](dest)`) or a reference link (`][ref]`) on
                    // ~keep reparse: `CommonMark` parses link/image label content as full
                    // ~keep inline markdown, so a literal `[foo](uri2)` inside it silently
                    // ~keep becomes a real nested link and the destination is lost --
                    // ~keep escaping only this closer is not enough and is actively worse:
                    // ~keep the still-open outer `[`/`![` is then free to be captured by a
                    // ~keep *later* unescaped `]` instead (verified against comrak), so the
                    // ~keep image/link fails to form at all. Escaping both ends of the
                    // ~keep matched pair together is the only shape that round-trips.
                    //
                    // ~keep Exempted when the opener is itself preceded by `!`: that is a
                    // ~keep real, intentional `![alt](src)` this converter already emitted
                    // ~keep while walking a nested `<img>` inside link text (CommonMark
                    // ~keep permits images, just not links, inside link text), not literal
                    // ~keep text that merely looks link-shaped -- escaping it would corrupt
                    // ~keep the nested image instead of protecting the label (caught by
                    // ~keep `test_commonmark_compliance`'s `[![moon](moon.jpg)](/uri)`).
                    let is_link_shaped = matches!(chars.peek(), Some((_, '(' | '[')));
                    let is_nested_image = open_pos > 0 && text.as_bytes()[open_pos - 1] == b'!';
                    if is_link_shaped && !is_nested_image {
                        escape_at[open_pos] = true;
                        escape_at[byte_pos] = true;
                    }
                }
            },
            _ => {}
        }
    }

    // ~keep Whatever is left in `open_positions` once the scan ends is a `[` with no
    // ~keep matching `]` anywhere in the label. Left alone, it starts a link/image span
    // ~keep that CommonMark's inline parser will happily extend into the *caller's own*
    // ~keep closing `]`/`)` on reparse -- the exact failure in issue #499, where
    // ~keep `![[A;B)](S)` reparses as dangling `!` text followed by a real
    // ~keep `[A;B)](S)` link, silently dropping the image. Escaping every such opener
    // ~keep is the mirror of the unmatched-`]` case above.
    for open_pos in open_positions {
        escape_at[open_pos] = true;
    }

    escape_at
}

/// Returns `Cow::Borrowed` when `text` contains neither `[` nor `]` (escaping is then
/// necessarily a no-op), or `Cow::Owned` with the escaped text otherwise.
fn escape_label_brackets(text: &str) -> Cow<'_, str> {
    if text.is_empty() {
        return Cow::Borrowed("");
    }

    // ~keep Escapes are only ever inserted at `[`/`]` byte positions (see the match below),
    // ~keep so when neither appears the two-pass logic further down is guaranteed to be a
    // ~keep no-op -- skip both its allocations (the `escape_at` vec and the output String).
    if memchr::memchr2(b'[', b']', text.as_bytes()).is_none() {
        return Cow::Borrowed(text);
    }

    // ~keep Two linear passes rather than one pass that mutates the output string as it
    // ~keep goes: escaping a matched bracket pair needs to touch the *opener*, which by
    // ~keep the time its `]` is found has already been written. Retroactively
    // ~keep `String::insert`-ing it back in is O(remaining length) per escape, so a label
    // ~keep built of many link-shaped pairs (`[a](b)[a](b)...`) would make the whole
    // ~keep function O(n^2) -- the same denial-of-service shape `bare_lt_complexity.rs`
    // ~keep exists to catch elsewhere in this crate. Precomputing which byte offsets need
    // ~keep an escape first keeps the second pass a single linear append.
    let escape_at = mark_bracket_escapes(text);

    let mut result = String::with_capacity(text.len() + 2);
    for (byte_pos, ch) in text.char_indices() {
        if escape_at[byte_pos] {
            result.push('\\');
        }
        result.push(ch);
    }

    Cow::Owned(result)
}

/// `CommonMark` HTML-block start conditions of type 1: raw-text elements, whose *opening*
/// tag alone on a line starts a block. Their closing tags do not.
const HTML_BLOCK_RAW_TEXT_TAGS: [&str; 4] = ["pre", "script", "style", "textarea"];

/// `CommonMark` HTML-block start conditions of type 6 (spec 0.31.2): either an opening or a
/// closing tag with one of these names starts a block, and type 6 -- unlike type 7 -- may
/// interrupt a paragraph.
const HTML_BLOCK_TAGS: [&str; 62] = [
    "address",
    "article",
    "aside",
    "base",
    "basefont",
    "blockquote",
    "body",
    "caption",
    "center",
    "col",
    "colgroup",
    "dd",
    "details",
    "dialog",
    "dir",
    "div",
    "dl",
    "dt",
    "fieldset",
    "figcaption",
    "figure",
    "footer",
    "form",
    "frame",
    "frameset",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "head",
    "header",
    "hr",
    "html",
    "iframe",
    "legend",
    "li",
    "link",
    "main",
    "menu",
    "menuitem",
    "nav",
    "noframes",
    "ol",
    "optgroup",
    "option",
    "p",
    "param",
    "search",
    "section",
    "summary",
    "table",
    "tbody",
    "td",
    "tfoot",
    "th",
    "thead",
    "title",
    "tr",
    "track",
    "ul",
];

/// Escape a `CommonMark` block-structure marker that opens a *continuation* line of a link
/// label or image alt text.
///
/// Block structure is parsed before inline structure (spec appendix A), so a line inside a
/// multi-line label that reads as a block opener terminates the paragraph the label lives in
/// and the `[` / `![` never pairs with its `]`. `![A\n-\n](S)` therefore produces no image at
/// all -- it produces `<h2>![A</h2><p>](S)</p>`, with the image simply gone (issue #496).
/// A hard line break does not protect the next line either: hard breaks are inline, and block
/// parsing has already finished by the time they are looked at.
///
/// Only continuation lines are examined. A label's first line is preceded on that same line by
/// the caller's `[` / `![`, so it cannot start a block however it begins.
///
/// Returns `Cow::Borrowed` when `text` is single-line or no continuation line opens a block.
fn escape_block_openers_on_continuation_lines(text: &str) -> Cow<'_, str> {
    if !text.contains('\n') {
        return Cow::Borrowed(text);
    }

    let mut escape_at: Vec<usize> = Vec::new();
    let mut line_start = 0usize;
    for (index, line) in text.split('\n').enumerate() {
        if index > 0 {
            if let Some(offset) = block_opener_escape_offset(line) {
                escape_at.push(line_start + offset);
            }
        }
        line_start += line.len() + 1;
    }

    if escape_at.is_empty() {
        return Cow::Borrowed(text);
    }

    let mut result = String::with_capacity(text.len() + escape_at.len());
    let mut copied = 0usize;
    for position in escape_at {
        result.push_str(&text[copied..position]);
        result.push('\\');
        copied = position;
    }
    result.push_str(&text[copied..]);
    Cow::Owned(result)
}

/// Byte offset within `line` of the character to backslash-escape so the line stops opening a
/// block, or `None` when the line opens no block that can interrupt a paragraph.
fn block_opener_escape_offset(line: &str) -> Option<usize> {
    let (indent, column) = leading_indent(line);
    // ~keep Four columns of indent is an indented code block, and an indented code block
    // ~keep cannot interrupt a paragraph -- such a line is already inert.
    if column >= 4 {
        return None;
    }
    let rest = line.get(indent..)?;
    block_opener_offset(rest).map(|offset| indent + offset)
}

/// Escape the character that makes `rest`, the first line of a paragraph without its
/// indentation, start a block, when the next line is a setext underline of `underline` (`=` or `-`).
///
/// ~keep At the start of a paragraph more lines start a block than can interrupt one: an empty
/// ~keep list item (`-`, `*`, `1.`), an ordered list at any number (spec section 5.2) and a link
/// ~keep reference definition (spec section 4.7). An underlined heading writes its text as such a
/// ~keep line (issues #653, #661).
pub fn escape_paragraph_start(rest: &str, underline: u8) -> Cow<'_, str> {
    block_opener_offset(rest)
        .or_else(|| list_marker_offset(rest))
        .or_else(|| starts_link_reference_definition(rest, underline).then_some(0))
        .map_or(Cow::Borrowed(rest), |at| {
            Cow::Owned(format!("{}\\{}", &rest[..at], &rest[at..]))
        })
}

/// Whether `rest`, the first line of a paragraph without its indentation, starts a link reference
/// definition when a setext underline of `underline` follows it: a label, a colon, then a
/// destination with an optional title and nothing after it, or nothing at all.
///
/// ~keep With nothing after the colon the destination is read from the next line. markdown-it
/// ~keep takes an `=` underline as that destination (`CommonMark` renderers keep the heading); a
/// ~keep `-` underline as long as a label and a colon is a thematic break, which ends the
/// ~keep definition first in both.
fn starts_link_reference_definition(rest: &str, underline: u8) -> bool {
    let Some(after_label) = link_label_len(rest).and_then(|len| rest[len..].strip_prefix(':')) else {
        return false;
    };
    let destination = after_label.trim_matches([' ', '\t']);
    if destination.is_empty() {
        return underline == b'=';
    }
    let Some(len) = link_destination_len(destination) else {
        return false;
    };
    let after_destination = &destination[len..];
    let title = after_destination.trim_start_matches([' ', '\t']);
    title.is_empty() || (title.len() < after_destination.len() && is_link_title(title))
}

/// Byte length of the link label, `[` to the first unescaped `]`, that starts `text`: at most 999
/// characters inside, no unescaped `[`, and not only spaces and tabs (spec section 4.7).
fn link_label_len(text: &str) -> Option<usize> {
    let bytes = text.as_bytes();
    if bytes.first() != Some(&b'[') {
        return None;
    }
    let mut at = 1;
    while at < bytes.len() {
        match bytes[at] {
            b'\\' => at += 2,
            b'[' => return None,
            b']' => {
                let label = &text[1..at];
                let valid = !label.trim_matches([' ', '\t']).is_empty() && label.chars().count() <= 999;
                return valid.then_some(at + 1);
            }
            _ => at += 1,
        }
    }
    None
}

/// Byte length of the link destination that starts `text`: `<` to an unescaped `>` without a `<`
/// in between, or a run of characters other than spaces and controls with balanced parentheses.
fn link_destination_len(text: &str) -> Option<usize> {
    let bytes = text.as_bytes();
    if bytes.first() == Some(&b'<') {
        let mut at = 1;
        while at < bytes.len() {
            match bytes[at] {
                b'\\' => at += 2,
                b'>' => return Some(at + 1),
                b'<' => return None,
                _ => at += 1,
            }
        }
        return None;
    }
    let mut depth = 0usize;
    let mut at = 0;
    while at < bytes.len() {
        match bytes[at] {
            b'\\' if bytes.get(at + 1).is_some_and(u8::is_ascii_punctuation) => at += 1,
            b'(' => depth += 1,
            b')' if depth == 0 => break,
            b')' => depth -= 1,
            byte if byte <= b' ' || byte == 0x7f => break,
            _ => {}
        }
        at += 1;
    }
    (at > 0 && depth == 0).then_some(at)
}

/// Whether `text` is exactly one link title: `"..."`, `'...'` or `(...)`, with no unescaped
/// closing character before its end (and no unescaped `(` in a parenthesized title).
fn is_link_title(text: &str) -> bool {
    let bytes = text.as_bytes();
    let close = match bytes.first() {
        Some(b'"') => b'"',
        Some(b'\'') => b'\'',
        Some(b'(') => b')',
        _ => return false,
    };
    let mut at = 1;
    while at < bytes.len() {
        match bytes[at] {
            b'\\' => at += 2,
            byte if byte == close => return at + 1 == bytes.len(),
            b'(' if close == b')' => return false,
            _ => at += 1,
        }
    }
    false
}

/// Byte offset within `text`, the trimmed text of an ATX heading, of the `#` run at its end when a parser
/// reads that run as the heading's closing sequence: the run is all of the text, or follows a
/// space or tab (spec section 4.2).
///
/// ~keep Escaping the run's first `#` keeps it as text: the run then follows a backslash
/// ~keep (issue #661).
pub fn atx_closing_sequence_offset(text: &str) -> Option<usize> {
    let run_start = text.trim_end_matches('#').len();
    let closes = run_start < text.len() && (run_start == 0 || matches!(text.as_bytes()[run_start - 1], b' ' | b'\t'));
    closes.then_some(run_start)
}

/// Byte offset of the delimiter of the list marker that starts `rest`, a line without its
/// indentation: a bullet, or one to nine digits then `.` or `)`, followed by a space, a tab or
/// the end of the line.
fn list_marker_offset(rest: &str) -> Option<usize> {
    let bytes = rest.as_bytes();
    let delimiter = match bytes.first()? {
        b'-' | b'*' | b'+' => 0,
        b'0'..=b'9' => {
            let digits = bytes.iter().take_while(|byte| byte.is_ascii_digit()).count();
            if digits > 9 || !matches!(bytes.get(digits), Some(b'.' | b')')) {
                return None;
            }
            digits
        }
        _ => return None,
    };
    matches!(bytes.get(delimiter + 1), None | Some(b' ' | b'\t')).then_some(delimiter)
}

/// Whether `line`, with its indentation, opens a block that can interrupt a paragraph.
pub fn line_opens_block(line: &str) -> bool {
    block_opener_escape_offset(line).is_some()
}

/// Escape the block opener at the start of `buffer[from..]`, text just written, when that text
/// starts a line that continues the paragraph above it.
///
/// ~keep A line after a hard break continues its paragraph only if it cannot interrupt it, the
/// ~keep rule a link label's continuation lines follow (issue #651). The text starts such a line
/// ~keep when only its container's indent is before it on the line and the line above holds text;
/// ~keep after a blank line it starts a paragraph of its own. The indent scan stops at the first
/// ~keep other byte, and the line above is read once per line, so the check stays linear.
pub fn escape_continuation_line_start(buffer: &mut String, from: usize) {
    let before = &buffer[..from];
    let Some(line_end) = before.trim_end_matches([' ', '\t']).strip_suffix('\n') else {
        return;
    };
    let line_above = &line_end[line_end.rfind('\n').map_or(0, |pos| pos + 1)..];
    if line_above.trim().is_empty() {
        return;
    }
    let text = &buffer[from..];
    let line = &text[..text.find('\n').unwrap_or(text.len())];
    if let Some(offset) = block_opener_escape_offset(line) {
        buffer.insert(from + offset, '\\');
    }
}

/// Whether `rest`, a line without its indentation, opens a block that can interrupt a paragraph.
pub fn opens_block(rest: &str) -> bool {
    block_opener_offset(rest).is_some()
}

/// Whether `rest`, a line without its indentation, is a setext heading underline: nothing but `=`
/// or nothing but `-`.
pub fn is_heading_underline(rest: &str) -> bool {
    is_setext_underline(rest, b'=') || is_setext_underline(rest, b'-')
}

/// Whether `rest`, a line without its indentation, is a thematic break: three or more `-`, `*` or
/// `_` and nothing else but spaces/tabs.
pub fn is_rule(rest: &str) -> bool {
    rest.bytes()
        .next()
        .is_some_and(|marker| matches!(marker, b'-' | b'*' | b'_') && is_thematic_break(rest, marker))
}

/// The fence character and the length of its run when `rest`, a line without its indentation,
/// opens a fenced code block.
pub fn code_fence(rest: &str) -> Option<(u8, usize)> {
    let marker = *rest.as_bytes().first()?;
    let run = rest.bytes().take_while(|&byte| byte == marker).count();
    (matches!(marker, b'`' | b'~') && is_code_fence(rest, marker)).then_some((marker, run))
}

/// Byte offset within `rest`, a line without its indentation, of the character to backslash-escape
/// so the line stops opening a block, or `None` when it opens no block that can interrupt a
/// paragraph.
fn block_opener_offset(rest: &str) -> Option<usize> {
    let marker = *rest.as_bytes().first()?;
    let opens = match marker {
        b'>' => true,
        b'#' => is_atx_heading(rest),
        b'`' | b'~' => is_code_fence(rest, marker),
        b'=' => is_setext_underline(rest, b'='),
        b'-' => is_setext_underline(rest, b'-') || is_thematic_break(rest, b'-') || is_bullet_list_item(rest),
        b'*' => is_thematic_break(rest, b'*') || is_bullet_list_item(rest),
        b'+' => is_bullet_list_item(rest),
        b'_' => is_thematic_break(rest, b'_'),
        b'<' => is_html_block_opener(rest),
        // ~keep A digit cannot carry a backslash escape, so an ordered-list marker is
        // ~keep defused at its `.`/`)` delimiter instead of at its number.
        b'0'..=b'9' => return ordered_list_delimiter_offset(rest),
        _ => false,
    };
    opens.then_some(0)
}

/// Split `line`'s leading indentation, returning `(byte length, column width)`.
pub fn leading_indent(line: &str) -> (usize, usize) {
    let mut length = 0usize;
    let mut column = 0usize;
    for &byte in line.as_bytes() {
        match byte {
            b' ' => column += 1,
            // ~keep A tab advances to the next multiple of four (spec section 2.2), so a
            // ~keep single leading tab is already four columns of indent.
            b'\t' => column += 4 - column % 4,
            _ => break,
        }
        length += 1;
    }
    (length, column)
}

/// An ATX heading: one to six `#`, then a space/tab or the end of the line.
fn is_atx_heading(rest: &str) -> bool {
    let hashes = rest.bytes().take_while(|&byte| byte == b'#').count();
    (1..=6).contains(&hashes) && matches!(rest.as_bytes().get(hashes), None | Some(b' ' | b'\t' | b'\r'))
}

/// An opening code fence: three or more of the same fence character.
fn is_code_fence(rest: &str, fence: u8) -> bool {
    let run = rest.bytes().take_while(|&byte| byte == fence).count();
    // ~keep A backtick fence's info string may not itself contain a backtick, so such a line
    // ~keep is ordinary text and needs no escape.
    run >= 3 && (fence != b'`' || !rest[run..].contains('`'))
}

/// A setext heading underline: nothing but `marker`, plus optional trailing whitespace.
fn is_setext_underline(rest: &str, marker: u8) -> bool {
    let trimmed = rest.trim_end();
    !trimmed.is_empty() && trimmed.bytes().all(|byte| byte == marker)
}

/// A thematic break: three or more `marker` characters and nothing else but spaces/tabs.
fn is_thematic_break(rest: &str, marker: u8) -> bool {
    let mut count = 0usize;
    for byte in rest.bytes() {
        if byte == marker {
            count += 1;
        } else if !matches!(byte, b' ' | b'\t' | b'\r') {
            return false;
        }
    }
    count >= 3
}

/// A bullet list item that can interrupt a paragraph: a marker, a space/tab, then content.
fn is_bullet_list_item(rest: &str) -> bool {
    // ~keep An empty list item cannot interrupt a paragraph (spec section 5.2), so both the
    // ~keep separating space/tab and non-blank content after it are required.
    matches!(rest.as_bytes().get(1), Some(b' ' | b'\t')) && rest.get(2..).is_some_and(|tail| !tail.trim().is_empty())
}

/// Byte offset of the `.`/`)` of an ordered list marker that can interrupt a paragraph.
fn ordered_list_delimiter_offset(rest: &str) -> Option<usize> {
    let digits = first_ordered_marker_len(rest)? - 1;
    let bytes = rest.as_bytes();
    let starts_a_list = matches!(bytes.get(digits + 1), Some(b' ' | b'\t'))
        && rest.get(digits + 2..).is_some_and(|tail| !tail.trim().is_empty());
    starts_a_list.then_some(digits)
}

/// The byte length of the ordered list marker at the start of `rest` when that marker starts a
/// list at 1: one to nine digits whose value is 1 (`1.`, `01)`, `000000001.`), then `.` or `)`.
///
/// ~keep Only a list starting at 1 can interrupt a paragraph, and the start number is the
/// ~keep marker's value, so leading zeros count; ten digits are no marker (spec section 5.2).
pub fn first_ordered_marker_len(rest: &str) -> Option<usize> {
    let bytes = rest.as_bytes();
    let digits = bytes.iter().take_while(|byte| byte.is_ascii_digit()).count();
    let value_is_one =
        (1..=9).contains(&digits) && bytes[digits - 1] == b'1' && bytes[..digits - 1].iter().all(|&byte| byte == b'0');
    (value_is_one && matches!(bytes.get(digits), Some(b'.' | b')'))).then_some(digits + 1)
}

/// An HTML block of type 1 to 6 -- the types that may interrupt a paragraph.
///
/// Type 7 (any other complete open tag alone on its line) deliberately may not, so inline
/// markup such as a `<span>` opening a continuation line is left alone.
fn is_html_block_opener(rest: &str) -> bool {
    let after_bracket = &rest[1..];
    // ~keep Types 2-5: comment, processing instruction, declaration, CDATA.
    if after_bracket.starts_with("!--")
        || after_bracket.starts_with('?')
        || after_bracket.starts_with("![CDATA[")
        || (after_bracket.starts_with('!') && after_bracket.as_bytes().get(1).is_some_and(u8::is_ascii_alphabetic))
    {
        return true;
    }

    let is_closing = after_bracket.starts_with('/');
    let name_start = usize::from(is_closing);
    let name: String = after_bracket[name_start..]
        .bytes()
        .take_while(u8::is_ascii_alphanumeric)
        .map(|byte| byte.to_ascii_lowercase() as char)
        .collect();
    if name.is_empty() {
        return false;
    }

    // ~keep Both start conditions require the tag name to end at whitespace, `>`, `/>` or the
    // ~keep end of the line; anything else (`<divx`, `<div=`) is not a tag at all.
    let tail = &after_bracket[name_start + name.len()..];
    let is_terminated =
        tail.is_empty() || tail.starts_with('>') || tail.starts_with("/>") || tail.starts_with(char::is_whitespace);

    is_terminated
        && (HTML_BLOCK_TAGS.contains(&name.as_str())
            || (!is_closing && HTML_BLOCK_RAW_TEXT_TAGS.contains(&name.as_str())))
}

/// Helper for block-level element detection.
pub fn is_block_level_name(tag_name: &str, is_inline: bool) -> bool {
    !is_inline
        && matches!(
            tag_name,
            "address"
                | "article"
                | "aside"
                | "blockquote"
                | "canvas"
                | "center"
                | "dd"
                | "details"
                | "dialog"
                | "div"
                | "dl"
                | "dt"
                | "fieldset"
                | "figcaption"
                | "figure"
                | "footer"
                | "form"
                | "h1"
                | "h2"
                | "h3"
                | "h4"
                | "h5"
                | "h6"
                | "header"
                | "hgroup"
                | "hr"
                | "legend"
                | "li"
                | "main"
                | "menu"
                | "nav"
                | "ol"
                | "p"
                | "pre"
                | "search"
                | "section"
                | "summary"
                | "table"
                | "tfoot"
                | "ul"
        )
}

/// Escape every `|` in a Markdown table cell that no backslash escapes yet.
///
/// GFM splits a row on each unescaped `|` before it reads any inline syntax, so a pipe in a
/// code span, a link destination or title, an image description or a flattened nested table
/// ends the cell like a pipe in plain text does, and the row no longer matches the delimiter
/// row. `\|` is a literal pipe everywhere in a cell, code spans included. A pipe after an odd
/// run of backslashes is escaped already and stays as it is.
pub fn escape_cell_pipes(text: &str) -> Cow<'_, str> {
    if !text.contains('|') {
        return Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len() + 4);
    let mut backslashes = 0usize;
    for c in text.chars() {
        if c == '|' && backslashes.is_multiple_of(2) {
            out.push('\\');
        }
        backslashes = if c == '\\' { backslashes + 1 } else { 0 };
        out.push(c);
    }
    Cow::Owned(out)
}

/// Escape any bare pipe left in a nested table's rendered markdown: one that is neither
/// already backslash-escaped nor inside a matched backtick code span (a `CommonMark`-
/// compliant reparse does not treat either as a cell delimiter, so this must not touch
/// them either).
///
/// Scoped to a nested `<table>`'s own rendered text (see the call site in
/// [`render_cell_text`]). Markdown output then escapes the whole cell with
/// [`escape_cell_pipes`], because GFM also splits a row on a pipe in a code span.
///
/// Walks backtick runs the same way a spec-compliant parser does: a run of N backticks
/// opens a code span only if a later run of exactly N backticks closes it; otherwise the
/// backticks are literal text and any pipes among them still need escaping.
pub fn escape_bare_pipes_outside_code_spans(text: &str) -> String {
    let chars: Vec<char> = text.chars().collect();
    let mut out = String::with_capacity(text.len() + 4);
    let mut i = 0usize;
    while i < chars.len() {
        let c = chars[i];
        if c == '\\' && i + 1 < chars.len() {
            out.push(c);
            out.push(chars[i + 1]);
            i += 2;
            continue;
        }
        if c == '`' {
            let run_start = i;
            while i < chars.len() && chars[i] == '`' {
                i += 1;
            }
            let run_len = i - run_start;
            if let Some(close_start) = find_matching_backtick_run(&chars, i, run_len) {
                out.extend(&chars[run_start..close_start + run_len]);
                i = close_start + run_len;
            } else {
                out.extend(&chars[run_start..i]);
            }
            continue;
        }
        if c == '|' {
            out.push('\\');
            out.push('|');
        } else {
            out.push(c);
        }
        i += 1;
    }
    out
}

// ~keep Lives here, shared, rather than beside either caller. Both tiers must escape a
// ~keep flattened nested table identically or the output forks: unescaped, these pipes are
// ~keep read as the OUTER row's cell delimiters on reparse, and GFM truncates the row to the
// ~keep header's column count, dropping the inner cells outright. That is content loss, and a
// ~keep silently drifting second copy would reintroduce it on whichever tier fell behind.

/// Find the start index of the next backtick run of exactly `run_len` backticks at or
/// after `start`, treating a longer or shorter run as not matching (mirroring `CommonMark`
/// code span matching, which requires an exact backtick-count match).
pub fn find_matching_backtick_run(chars: &[char], start: usize, run_len: usize) -> Option<usize> {
    let mut i = start;
    while i < chars.len() {
        if chars[i] == '`' {
            let candidate_start = i;
            while i < chars.len() && chars[i] == '`' {
                i += 1;
            }
            if i - candidate_start == run_len {
                return Some(candidate_start);
            }
        } else {
            i += 1;
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::super::content::{chomp_inline, merge_adjacent_emphasis, normalize_link_label};
    use super::*;

    #[test]
    fn escape_cell_pipes_escapes_each_pipe_no_backslash_escapes() {
        assert!(matches!(escape_cell_pipes("a b"), Cow::Borrowed("a b")));
        assert_eq!(escape_cell_pipes("a|b"), r"a\|b");
        assert_eq!(escape_cell_pipes(r"a\|b"), r"a\|b");
        assert_eq!(escape_cell_pipes(r"a\\|b"), r"a\\\|b");
        assert_eq!(escape_cell_pipes("`a|b` [t](u|v)"), r"`a\|b` [t](u\|v)");
        assert_eq!(escape_cell_pipes("||"), r"\|\|");
    }

    #[test]
    fn escape_link_label_leaves_plain_text_unchanged() {
        assert_eq!(escape_link_label("plain text"), "plain text");
    }

    #[test]
    fn escape_link_label_escapes_an_unmatched_closing_bracket() {
        assert_eq!(escape_link_label("]"), "\\]");
    }

    // ~keep A `[...]` pair with a local opener and no trailing `(`/`[` is left unescaped
    // ~keep even though it superficially resembles the unmatched-bracket case above: the
    // ~keep opener/closer here match each other, so unlike a bare `]` they do not close
    // ~keep the caller's own wrapping bracket early.
    #[test]
    fn escape_link_label_leaves_a_matched_non_link_shaped_pair_unchanged() {
        assert_eq!(escape_link_label("[link]"), "[link]");
    }

    #[test]
    fn escape_link_label_leaves_balanced_nested_brackets_unchanged() {
        assert_eq!(escape_link_label("[outer [inner]]"), "[outer [inner]]");
    }

    // ~keep Regression for Cluster B (image alt text losing its nested destination):
    // ~keep `<img alt="[foo](uri2)">` must not let the alt text's own `[foo](uri2)` be
    // ~keep reparsed as a real nested link, or `uri2` is silently dropped on a second
    // ~keep conversion pass (CommonMark parses an image's alt as full inline content).
    #[test]
    fn escape_link_label_escapes_a_link_shaped_bracket_pair() {
        assert_eq!(escape_link_label("[foo](uri2)"), "\\[foo\\](uri2)");
    }

    // ~keep Same hazard, reference-link form: `[foo][ref]` is just as reparsable as
    // ~keep `[foo](uri2)`.
    #[test]
    fn escape_link_label_escapes_a_reference_link_shaped_bracket_pair() {
        assert_eq!(escape_link_label("[foo][ref]"), "\\[foo\\][ref]");
    }

    // ~keep A `[...]` NOT immediately followed by `(` or `[` cannot complete a link on
    // ~keep reparse, so it is left alone -- this is the exact shape the task's proposed
    // ~keep narrower rule ("escape `]` only before `(`") would also leave alone, but this
    // ~keep also confirms plain non-link-shaped bracket text is unaffected.
    #[test]
    fn escape_link_label_leaves_non_link_shaped_brackets_unchanged() {
        assert_eq!(escape_link_label("see [note] here"), "see [note] here");
    }

    // ~keep Regression: a link whose *label* is a real, intentionally-emitted nested
    // ~keep image (`![moon](moon.jpg)`, CommonMark permits images -- just not links --
    // ~keep inside link text) must not be escaped merely because it is link-shaped: it
    // ~keep is not literal text, it is markdown this converter already produced while
    // ~keep walking a nested `<img>`. Caught by `commonmark_compliance_test`'s example
    // ~keep 517 (`[![moon](moon.jpg)](/uri)`) before this exemption was added.
    #[test]
    fn escape_link_label_does_not_escape_a_nested_image() {
        assert_eq!(escape_link_label("![moon](moon.jpg)"), "![moon](moon.jpg)");
    }

    // ~keep A link-shaped bracket pair still nested inside an outer, non-link-shaped
    // ~keep bracket pair: only the inner (dangerous) pair is escaped, and the escape is
    // ~keep inserted at the correct byte offset for the *matching* opener, not just
    // ~keep prepended to the whole string.
    #[test]
    fn escape_link_label_escapes_only_the_link_shaped_inner_pair() {
        assert_eq!(escape_link_label("[a[b](c)]"), "[a\\[b\\](c)]");
    }

    // ~keep Regression for issue #499: an unmatched `[` is the mirror hazard of the
    // ~keep unmatched-`]` case above -- left alone, `![[A;B)](S)` reparses as dangling
    // ~keep `!` text followed by a real `[A;B)](S)` link, silently dropping the image.
    #[test]
    fn escape_link_label_escapes_an_unmatched_opening_bracket() {
        assert_eq!(escape_link_label("[A;B)"), "\\[A;B)");
    }

    #[test]
    fn escape_link_label_escapes_an_unmatched_opening_bracket_before_plain_text() {
        assert_eq!(escape_link_label("[a"), "\\[a");
    }

    // ~keep The outer `[` is unmatched and must be escaped; the inner `[a]` is a
    // ~keep matched, non-link-shaped pair and stays untouched -- the two rules apply
    // ~keep independently at their own byte offsets.
    #[test]
    fn escape_link_label_escapes_an_unmatched_outer_bracket_around_a_matched_inner_pair() {
        assert_eq!(escape_link_label("[[a]"), "\\[[a]");
    }

    #[test]
    fn escape_link_label_escapes_an_unmatched_opening_bracket_after_plain_text() {
        assert_eq!(escape_link_label("a[b"), "a\\[b");
    }

    #[test]
    fn escape_link_label_leaves_an_already_escaped_opening_bracket_unchanged() {
        assert_eq!(escape_link_label("\\[a"), "\\[a");
    }

    // ~keep Regression for CommonMark spec examples 642/643: a `<br>`-produced hard
    // ~keep line break (`"  \n"`, matching `NewlineStyle::Spaces`) mid-label must
    // ~keep survive, not collapse to a plain space.
    #[test]
    fn normalize_link_label_preserves_a_mid_label_spaces_style_hard_break() {
        assert_eq!(normalize_link_label("foo  \nbar"), "foo  \nbar");
    }

    #[test]
    fn normalize_link_label_preserves_a_mid_label_backslash_style_hard_break() {
        assert_eq!(normalize_link_label("foo\\\nbar"), "foo\\\nbar");
    }

    // ~keep Issue #497: a break at the label's edge is real content, not incidental
    // ~keep whitespace. `<a href="H">A<br></a>B` renders as A, a line break, then B, and
    // ~keep `[A  \n](H)B` re-parses to exactly that -- verified against comrak. These two
    // ~keep previously asserted the opposite (the break dropped), which is where the bug
    // ~keep lived: the whole label was `str::trim`-ed, and a flattened `"  \n"` is
    // ~keep indistinguishable from trailing source whitespace before a `</a>`.
    #[test]
    fn normalize_link_label_keeps_a_leading_hard_break() {
        assert_eq!(normalize_link_label("  \nbar"), "  \nbar");
    }

    #[test]
    fn normalize_link_label_keeps_a_trailing_hard_break() {
        assert_eq!(normalize_link_label("foo  \n"), "foo  \n");
    }

    #[test]
    fn normalize_link_label_keeps_a_boundary_hard_break_past_incidental_whitespace() {
        assert_eq!(normalize_link_label(" \u{a0}foo  \n "), "foo  \n");
    }

    // ~keep A run of breaks at one edge collapses to a single break: two adjacent markers
    // ~keep put a blank line in the label, and a blank line ends the paragraph the link
    // ~keep lives in -- destroying the link rather than preserving a second break nobody
    // ~keep can see.
    #[test]
    fn normalize_link_label_collapses_a_run_of_boundary_hard_breaks_to_one() {
        assert_eq!(normalize_link_label("  \n  \nbar"), "  \nbar");
        assert_eq!(normalize_link_label("foo  \n  \n"), "foo  \n");
    }

    // ~keep A break needs a line on both sides to mean anything, so a label of nothing but
    // ~keep breaks still collapses to empty and the caller's own href fallback takes over.
    #[test]
    fn normalize_link_label_drops_a_label_that_is_only_hard_breaks() {
        assert_eq!(normalize_link_label("  \n"), "");
        assert_eq!(normalize_link_label("  \n  \n"), "");
    }

    // ~keep An ordinary soft newline (no `<br>` behind it, e.g. wrapped source text)
    // ~keep still collapses to a single space -- only the two exact hard-break marker
    // ~keep shapes are preserved.
    #[test]
    fn normalize_link_label_still_collapses_an_incidental_newline_to_a_space() {
        assert_eq!(normalize_link_label("foo\nbar"), "foo bar");
        assert_eq!(normalize_link_label("foo \n bar"), "foo bar");
    }

    #[test]
    fn normalize_link_label_still_collapses_ordinary_whitespace_runs() {
        assert_eq!(normalize_link_label("foo   bar"), "foo bar");
        assert_eq!(normalize_link_label("  foo bar  "), "foo bar");
    }

    // ~keep Regression for a real collision in an earlier version of this function: it used
    // ~keep Private Use Area code points (U+E000/U+E001) as placeholders for the hard-break
    // ~keep markers, reasoning that no producer this crate parses assigns them. That is false
    // ~keep -- icon fonts live in the PUA (Bootstrap 3's Glyphicons start at U+E001) -- so a
    // ~keep label already containing that literal character collided with the placeholder and
    // ~keep reappeared as a spurious hard break once the placeholder was "restored". The
    // ~keep trigger needs both a literal PUA character AND a real hard-break marker in the
    // ~keep same label -- a PUA character alone never entered the placeholder-substitution
    // ~keep branch at all, which is why this was not caught by the other tests above.
    #[test]
    fn normalize_link_label_does_not_confuse_a_literal_pua_character_with_the_spaces_sentinel() {
        assert_eq!(normalize_link_label("a\u{E000}b  \nc"), "a\u{E000}b  \nc");
    }

    #[test]
    fn normalize_link_label_does_not_confuse_a_literal_pua_character_with_the_backslash_sentinel() {
        assert_eq!(normalize_link_label("a\u{E001}b\\\nc"), "a\u{E001}b\\\nc");
    }

    // ~keep The Glyphicon code point itself (U+E001) is exactly the second placeholder this
    // ~keep function used to use, so this pins the specific real-world icon-font byte, not
    // ~keep just "some" PUA character.
    #[test]
    fn normalize_link_label_preserves_a_glyphicon_code_point_alongside_a_spaces_style_hard_break() {
        assert_eq!(normalize_link_label("\u{E001} foo  \nbar"), "\u{E001} foo  \nbar");
    }

    #[test]
    fn normalize_link_label_preserves_a_glyphicon_code_point_alongside_a_backslash_style_hard_break() {
        assert_eq!(normalize_link_label("\u{E001} foo\\\nbar"), "\u{E001} foo\\\nbar");
    }

    // ~keep ── chomp_inline whitespace-only dedup (issue #481) ──────────────────────────

    #[test]
    fn chomp_inline_returns_a_single_space_prefix_for_whitespace_only_content() {
        assert_eq!(chomp_inline(" "), (" ", "", ""));
    }

    #[test]
    fn chomp_inline_returns_a_single_space_prefix_for_a_multi_char_whitespace_only_run() {
        assert_eq!(chomp_inline("   "), (" ", "", ""));
        assert_eq!(chomp_inline("\t "), (" ", "", ""));
    }

    #[test]
    fn chomp_inline_preserves_a_hard_trailing_linebreak_over_the_whitespace_only_collapse() {
        assert_eq!(chomp_inline("  \n"), (" ", "  \n", ""));
        assert_eq!(chomp_inline("\\\n"), ("", "\\\n", ""));
    }

    #[test]
    fn chomp_inline_leaves_non_whitespace_content_unaffected() {
        assert_eq!(chomp_inline(" a "), (" ", " ", "a"));
        assert_eq!(chomp_inline("a"), ("", "", "a"));
    }

    #[test]
    fn chomp_inline_returns_empty_for_empty_input() {
        assert_eq!(chomp_inline(""), ("", "", ""));
    }

    // ~keep ── merge_adjacent_emphasis (issue #483) ─────────────────────────────────────

    #[test]
    fn merge_adjacent_emphasis_pops_a_lone_matching_close_marker() {
        let mut output = String::from("*A*");
        assert!(merge_adjacent_emphasis(&mut output, '*', 1));
        assert_eq!(output, "*A");
    }

    #[test]
    fn merge_adjacent_emphasis_pops_a_double_matching_close_marker() {
        let mut output = String::from("**A**");
        assert!(merge_adjacent_emphasis(&mut output, '*', 2));
        assert_eq!(output, "**A");
    }

    #[test]
    fn merge_adjacent_emphasis_returns_false_when_output_does_not_end_with_the_marker() {
        let mut output = String::from("*A* ");
        assert!(!merge_adjacent_emphasis(&mut output, '*', 1));
        assert_eq!(output, "*A* ", "untouched on refusal");
    }

    #[test]
    fn merge_adjacent_emphasis_refuses_a_run_longer_than_count() {
        // ~keep `***x***` must not be half-eaten: a trailing run of 3 is not "exactly 2".
        let mut output = String::from("***x***");
        assert!(!merge_adjacent_emphasis(&mut output, '*', 2));
        assert_eq!(output, "***x***");
    }

    #[test]
    fn merge_adjacent_emphasis_refuses_when_the_run_is_shorter_than_count() {
        let mut output = String::from("*A*");
        assert!(!merge_adjacent_emphasis(&mut output, '*', 2));
        assert_eq!(output, "*A*");
    }

    #[test]
    fn merge_adjacent_emphasis_refuses_an_escaped_literal_asterisk() {
        // ~keep `\*` immediately before the run: the preceding character is a backslash,
        // ~keep so this is a literal escaped asterisk, not a mergeable close marker.
        let mut output = String::from(r"a\*");
        assert!(!merge_adjacent_emphasis(&mut output, '*', 1));
        assert_eq!(output, r"a\*");
    }

    #[test]
    fn merge_adjacent_emphasis_returns_false_for_zero_count() {
        let mut output = String::from("*A*");
        assert!(!merge_adjacent_emphasis(&mut output, '*', 0));
        assert_eq!(output, "*A*");
    }

    #[test]
    fn merge_adjacent_emphasis_respects_the_underscore_symbol_variant() {
        let mut output = String::from("__A__");
        assert!(merge_adjacent_emphasis(&mut output, '_', 2));
        assert_eq!(output, "__A");
    }

    #[test]
    fn opens_block_reads_an_ordered_marker_by_its_value() {
        for line in ["1. x", "1) x", "01. x", "001) x", "000000001. x", "01.\tx"] {
            assert!(opens_block(line), "{line:?} starts a list at 1");
        }
        for line in [
            "0000000001. x",
            "2. x",
            "02. x",
            "0. x",
            "00. x",
            "10. x",
            "11. x",
            "01.",
            "01. ",
            "01.x",
            "01",
        ] {
            assert!(!opens_block(line), "{line:?} cannot interrupt a paragraph");
        }
        assert_eq!(block_opener_offset("001) x"), Some(3));
        assert_eq!(block_opener_offset("1. x"), Some(1));
    }

    fn escaped_continuation(before: &str, text: &str) -> String {
        let mut buffer = format!("{before}{text}");
        escape_continuation_line_start(&mut buffer, before.len());
        buffer
    }

    #[test]
    fn escape_continuation_line_start_escapes_a_line_after_text() {
        assert_eq!(escaped_continuation("a  \n", "1) t"), "a  \n1\\) t");
        assert_eq!(escaped_continuation("x\n- a  \n  ", "- t"), "x\n- a  \n  \\- t");
        assert_eq!(escaped_continuation("a\\\n\t", "> t"), "a\\\n\t\\> t");
        assert_eq!(escaped_continuation("a  \n", "-\nx"), "a  \n\\-\nx");
    }

    #[test]
    fn escape_continuation_line_start_leaves_other_text_alone() {
        for (before, text) in [
            ("", "1) t"),
            ("a", "1) t"),
            ("a  \nb ", "1) t"),
            ("a\n\n", "1) t"),
            ("a\n  \n", "1) t"),
            ("a  \n", "2. t"),
            ("a  \n", "    1) t"),
            ("a  \n", "1)\n- t"),
        ] {
            assert_eq!(
                escaped_continuation(before, text),
                format!("{before}{text}"),
                "{before:?} {text:?}"
            );
        }
    }

    #[test]
    fn escape_paragraph_start_escapes_a_link_reference_definition() {
        for text in [
            "[a]: b",
            "[a]:",
            "[a]:b \"t\"",
            "[a]:b 't'",
            "[a]: b (t)",
            "[a]: <b c>",
            "[a]: <>",
            "[**a**]: b",
            "[a\\]]: b",
            "[a]: b(c)",
            "[a]: b\"t\"",
        ] {
            assert_eq!(escape_paragraph_start(text, b'='), format!("\\{text}"), "{text:?}");
        }
        assert_eq!(escape_paragraph_start("[a]: b", b'-'), "\\[a]: b");
    }

    #[test]
    fn escape_paragraph_start_leaves_a_line_that_starts_no_definition() {
        for text in [
            "[a]: b c",
            "[a]: b \"t\" x",
            "[a]: b\\ c",
            "[a]: b \"t",
            "[a]: b (t(u))",
            "[a]: b (t(u)",
            "[a]: <b>\"t\"",
            "[a[b]: c",
            "[a]: b(",
            "[a]: <b",
            "[a]: <b<c>",
            "[a] b",
            "[a]",
            "[ ]: b",
            "[a][b]: c",
            "[[a]]: b",
            "a [b]: c",
            "plain text",
        ] {
            assert_eq!(escape_paragraph_start(text, b'='), text, "{text:?}");
        }
        assert_eq!(escape_paragraph_start("[a]:", b'-'), "[a]:");
        let long_label = format!("[{}]: b", "é".repeat(1000));
        assert_eq!(escape_paragraph_start(&long_label, b'='), long_label);
        let longest_label = format!("[{}]: b", "é".repeat(999));
        assert_eq!(
            escape_paragraph_start(&longest_label, b'='),
            format!("\\{longest_label}")
        );
    }

    #[test]
    fn atx_closing_sequence_offset_finds_a_run_the_line_closes_on() {
        assert_eq!(atx_closing_sequence_offset("#"), Some(0));
        assert_eq!(atx_closing_sequence_offset("##"), Some(0));
        assert_eq!(atx_closing_sequence_offset("a #"), Some(2));
        assert_eq!(atx_closing_sequence_offset("a ##"), Some(2));
        assert_eq!(atx_closing_sequence_offset("a\t#"), Some(2));
        assert_eq!(atx_closing_sequence_offset("a # #"), Some(4));
        assert_eq!(atx_closing_sequence_offset("**a** #"), Some(6));
        for text in ["a#", "a \\#", "a \\\\#", "#a", "a # b", "plain text", ""] {
            assert_eq!(atx_closing_sequence_offset(text), None, "{text:?}");
        }
    }

    #[test]
    fn merge_adjacent_emphasis_returns_false_on_empty_output() {
        let mut output = String::new();
        assert!(!merge_adjacent_emphasis(&mut output, '*', 1));
        assert_eq!(output, "");
    }
}