asciidoc-parser 0.29.5

Parser for AsciiDoc format
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
use std::sync::Arc;

use self_cell::self_cell;

use crate::{
    HasSpan, Parser, Span,
    attributes::Attrlist,
    blocks::{
        Block, ChildBlocks, CompoundDelimitedBlock, ContentModel, IsBlock, ListItemMarker,
        RawDelimitedBlock, SimpleBlock, TableBlock, metadata::BlockMetadata,
        parse_utils::parse_blocks_until,
    },
    content::{Content, SubstitutionGroup},
    internal::debug::DebugSliceReference,
    parser::{InlineSubstitutionRenderer, ReferenceResolver, ReferenceWarnings},
    span::MatchedItem,
    strings::CowStr,
    warnings::{MatchAndWarnings, Warning, WarningType},
};

self_cell! {
    /// A Markdown-style blockquote's nested blocks, which borrow the owned
    /// (`>`-stripped) source the block carries.
    pub struct OwnedQuoteBlocks {
        owner: String,

        #[covariant]
        dependent: OwnedQuoteBlocksInner,
    }

    impl {Debug, Eq, Hash, PartialEq}
}

/// The parsed blocks of an [`OwnedQuoteBlocks`], borrowing its owned source.
#[derive(Debug, Eq, PartialEq)]
struct OwnedQuoteBlocksInner<'src> {
    blocks: Vec<Block<'src>>,
}

/// Distinguishes the two block types that share the blockquote syntax.
///
/// Prose excerpts and quotes use the [`Quote`](Self::Quote) type, which does
/// not preserve line breaks. Verses (e.g., poems or song lyrics) use the
/// [`Verse`](Self::Verse) type, which preserves line breaks in the output.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum QuoteType {
    /// A prose excerpt or quote. Line breaks are not preserved.
    Quote,

    /// A verse (e.g., a poem or song lyric). Line breaks are preserved.
    Verse,
}

impl QuoteType {
    /// Returns the lowercase name for this type (e.g., `quote`).
    ///
    /// This is the block's context and the basis for its CSS class
    /// (`quoteblock` or `verseblock`).
    pub fn name(self) -> &'static str {
        match self {
            Self::Quote => "quote",
            Self::Verse => "verse",
        }
    }
}

impl std::fmt::Debug for QuoteType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Quote => write!(f, "QuoteType::Quote"),
            Self::Verse => write!(f, "QuoteType::Verse"),
        }
    }
}

/// A blockquote: a quote, prose excerpt, or verse, optionally attributed to a
/// person and a source citation.
///
/// A blockquote can be written in several ways, all of which produce this
/// block:
///
/// * A **delimited block** bounded by lines of four underscores (`____`),
///   optionally with a `[quote,…]` or `[verse,…]` attribute list. A `quote`
///   block has the [`Compound`](ContentModel::Compound) content model (it
///   contains other blocks); a `verse` block has the
///   [`Simple`](ContentModel::Simple) content model and preserves its line
///   breaks.
/// * A **styled paragraph** introduced by a `[quote,…]` or `[verse,…]`
///   attribute list. This produces the [`Simple`](ContentModel::Simple) content
///   model.
/// * A **quoted paragraph**: a paragraph wrapped in double quotes and followed
///   by an attribution line introduced by two hyphens (`-- …`). This produces a
///   `quote` block with the [`Simple`](ContentModel::Simple) content model.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct QuoteBlock<'src> {
    type_: QuoteType,
    content_model: ContentModel,
    content: Option<Content<'src>>,
    blocks: Vec<Block<'src>>,
    markdown_blocks: Option<Arc<OwnedQuoteBlocks>>,
    attribution: Option<String>,
    citetitle: Option<String>,
    source: Span<'src>,
    title_source: Option<Span<'src>>,
    title: Option<Content<'src>>,
    anchor: Option<Span<'src>>,
    anchor_reftext: Option<Span<'src>>,
    attrlist: Option<Attrlist<'src>>,
}

impl<'src> QuoteBlock<'src> {
    /// Returns a document-order iterator over this block's direct child blocks.
    ///
    /// This reaches the children of a Markdown-style blockquote (which borrow
    /// the block's own owned source), matching [`blocks()`](Self::blocks). For
    /// the full subtree, or to search from a [`Block`] or [`Document`], use
    /// [`FindBlocks`](crate::blocks::FindBlocks).
    ///
    /// [`Document`]: crate::Document
    pub fn child_blocks(&'src self) -> ChildBlocks<'src> {
        ChildBlocks::from_slice(self.blocks())
    }

    /// Returns the block's title as a mutable [`Content`], if the block has
    /// one.
    ///
    /// This narrow seam exists for the document-order title resolution pass
    /// (see `document::title_refs`), which installs the re-rendered title
    /// after resolving any cross-references embedded in it. All other access
    /// goes through the read-only [`IsBlock::title`] accessor.
    pub(crate) fn title_content_mut(&mut self) -> Option<&mut Content<'src>> {
        self.title.as_mut()
    }

    /// Parse a blockquote, if the given metadata and content describe one.
    ///
    /// Returns `None` (without consuming the block) when the content is not a
    /// blockquote, so that the caller can fall through to other block parsers.
    pub(crate) fn parse(
        metadata: &BlockMetadata<'src>,
        parser: &mut Parser,
    ) -> Option<MatchAndWarnings<'src, Option<MatchedItem<'src, Self>>>> {
        let style = metadata.attrlist.as_ref().and_then(|a| a.block_style());
        let styled_type = match style {
            Some("quote") => Some(QuoteType::Quote),
            Some("verse") => Some(QuoteType::Verse),
            _ => None,
        };

        let first_line = metadata.block_start.take_normalized_line().item;
        let is_quote_delimiter = is_quote_verse_delimiter(&first_line);

        // A `[quote]` or `[verse]` style masquerades over a quote-delimited
        // block, an open block, or a paragraph.
        if let Some(type_) = styled_type {
            if is_quote_delimiter {
                return Some(Self::parse_delimited(metadata, parser, type_));
            }

            // A `[quote]`/`[verse]` style also masquerades over an open block
            // (`--`): the open delimiter adopts the quote/verse context. This is
            // unique to the open block – every other structural container (below)
            // keeps its own context and ignores the style.
            if first_line.data() == "--" {
                return Some(Self::parse_delimited(metadata, parser, type_));
            }

            // The style is set on some other structural container (example,
            // sidebar, listing, literal, passthrough, table). That container
            // keeps its own context and the style is ignored, so this is not a
            // blockquote.
            if RawDelimitedBlock::is_valid_delimiter(&first_line)
                || CompoundDelimitedBlock::is_valid_delimiter(&first_line)
                || TableBlock::is_table_delimiter(&first_line)
            {
                return None;
            }

            return Self::parse_styled_paragraph(metadata, parser, type_);
        }

        // A bare quote-delimited block (no `[quote]`/`[verse]` style) is a quote
        // block. Any other style on it (e.g. an admonition label) is ignored.
        if is_quote_delimiter {
            return Some(Self::parse_delimited(metadata, parser, QuoteType::Quote));
        }

        // A Markdown-style blockquote, introduced by a `>` marker.
        if first_line.data().starts_with('>') {
            return Self::parse_markdown(metadata, parser);
        }

        // A quoted paragraph: text wrapped in double quotes followed by a `-- `
        // attribution line.
        Self::parse_quoted_paragraph(metadata, parser)
    }

    /// Parse a quote- or verse-delimited block (bounded by `____` lines).
    fn parse_delimited(
        metadata: &BlockMetadata<'src>,
        parser: &mut Parser,
        type_: QuoteType,
    ) -> MatchAndWarnings<'src, Option<MatchedItem<'src, Self>>> {
        let delimiter = metadata.block_start.take_normalized_line();

        let mut next = delimiter.after;
        let (closing_delimiter, after) = loop {
            if next.is_empty() {
                break (next, next);
            }

            let line = next.take_normalized_line();
            if line.item.data() == delimiter.item.data() {
                break (line.item, line.after);
            }
            next = line.after;
        };

        let inside_delimiters = delimiter.after.trim_remainder(closing_delimiter);

        let (attribution, citetitle) = extract_attribution(metadata.attrlist.as_ref());

        let (content_model, content, blocks, mut warnings) = match type_ {
            // A quote block contains other blocks.
            QuoteType::Quote => {
                // A `== …` line inside the quote block is literal content, not a
                // section heading; suppress section recognition for the nested
                // parse (saved and restored to compose with outer contexts).
                let previously_in_delimited_block = parser.in_delimited_block;
                parser.in_delimited_block = true;

                let maw_blocks = parse_blocks_until(inside_delimiters, |_, _| false, parser);

                parser.in_delimited_block = previously_in_delimited_block;
                (
                    ContentModel::Compound,
                    None,
                    maw_blocks.item.item,
                    maw_blocks.warnings,
                )
            }

            // A verse block preserves its content verbatim (line breaks
            // included), with normal substitutions applied.
            QuoteType::Verse => {
                let content = render_verbatim(inside_delimiters, parser);
                (ContentModel::Simple, Some(content), vec![], vec![])
            }
        };

        let source = metadata
            .source
            .trim_remainder(closing_delimiter.discard_all())
            .trim_trailing_whitespace();

        if closing_delimiter.is_empty() {
            warnings.insert(
                0,
                Warning::new(delimiter.item, WarningType::UnterminatedDelimitedBlock),
            );
        }

        MatchAndWarnings {
            item: Some(MatchedItem {
                item: Self {
                    type_,
                    content_model,
                    content,
                    blocks,
                    markdown_blocks: None,
                    attribution,
                    citetitle,
                    source,
                    title_source: metadata.title_source,
                    title: metadata.title.clone(),
                    anchor: metadata.anchor,
                    anchor_reftext: metadata.anchor_reftext,
                    attrlist: metadata.attrlist.clone(),
                },
                after,
            }),
            warnings,
        }
    }

    /// Parse a `[quote,…]` or `[verse,…]` styled paragraph.
    fn parse_styled_paragraph(
        metadata: &BlockMetadata<'src>,
        parser: &mut Parser,
        type_: QuoteType,
    ) -> Option<MatchAndWarnings<'src, Option<MatchedItem<'src, Self>>>> {
        // The paragraph text is read as a simple block. The `quote`/`verse`
        // block style is not one of the verbatim styles, so the content is
        // parsed as a normal paragraph (normal substitutions, line breaks
        // preserved in the rendered text).
        let inner = SimpleBlock::parse(metadata, parser)?;

        let (attribution, citetitle) = extract_attribution(metadata.attrlist.as_ref());

        let source = metadata
            .source
            .trim_remainder(inner.after)
            .trim_trailing_whitespace();

        Some(MatchAndWarnings {
            item: Some(MatchedItem {
                item: Self {
                    type_,
                    content_model: ContentModel::Simple,
                    content: Some(inner.item.content().clone()),
                    blocks: vec![],
                    markdown_blocks: None,
                    attribution,
                    citetitle,
                    source,
                    title_source: metadata.title_source,
                    title: metadata.title.clone(),
                    anchor: metadata.anchor,
                    anchor_reftext: metadata.anchor_reftext,
                    attrlist: metadata.attrlist.clone(),
                },
                after: inner.after,
            }),
            warnings: vec![],
        })
    }

    /// Parse a quoted paragraph: text wrapped in double quotes followed by a
    /// `-- ` attribution line.
    ///
    /// Returns `None` if the content does not match this shape.
    fn parse_quoted_paragraph(
        metadata: &BlockMetadata<'src>,
        parser: &mut Parser,
    ) -> Option<MatchAndWarnings<'src, Option<MatchedItem<'src, Self>>>> {
        // A quoted paragraph must begin with a double quote. Test that on the
        // block's first byte *before* scanning the whole paragraph. `read_paragraph`
        // (below) walks every line up to the next blank line, so testing the first
        // byte here avoids that scan for the common non-quoted paragraph: without
        // it, a long run of non-blank lines that never forms a quoted paragraph is
        // rescanned in full for every block, making the parse O(n²) on pathological
        // input (e.g. thousands of consecutive delimiter lines with no blank line
        // between them). `read_paragraph` starts at `block_start`, so a paragraph
        // beginning with `"` shares this first byte — testing it here loses nothing.
        if !metadata.block_start.data().starts_with('"') {
            return None;
        }

        // The paragraph extends to the first blank line.
        let para = read_paragraph(metadata.block_start);
        let data = para.data();

        // Locate the attribution line: the first line that begins with `--`
        // followed by whitespace and at least one more character. Splits the
        // paragraph into the quoted text and the attribution text.
        let (quoted, attribution_text) = split_at_attribution_line(data)?;

        // The quoted text, with surrounding whitespace removed, must be wrapped
        // in double quotes.
        let inner = quoted
            .trim_end()
            .strip_prefix('"')
            .and_then(|s| s.strip_suffix('"'))
            .filter(|inner| !inner.is_empty())?;

        // The quoted text, with the surrounding quotes removed, becomes the
        // blockquote content. Build a span that points just past the opening
        // quote so source positions stay meaningful.
        let inner_span = para.slice(1..1 + inner.len());
        let mut content = Content::from(inner_span);
        SubstitutionGroup::Normal.apply(&mut content, parser, None);

        // The attribution line provides the attribution and (optional) citation.
        let (attribution, citetitle) = split_attribution_line(attribution_text.trim(), parser);

        let source = metadata
            .source
            .trim_remainder(read_paragraph_after(metadata.block_start))
            .trim_trailing_whitespace();

        Some(MatchAndWarnings {
            item: Some(MatchedItem {
                item: Self {
                    type_: QuoteType::Quote,
                    content_model: ContentModel::Simple,
                    content: Some(content),
                    blocks: vec![],
                    markdown_blocks: None,
                    attribution,
                    citetitle,
                    source,
                    title_source: metadata.title_source,
                    title: metadata.title.clone(),
                    anchor: metadata.anchor,
                    anchor_reftext: metadata.anchor_reftext,
                    attrlist: metadata.attrlist.clone(),
                },
                after: read_paragraph_after(metadata.block_start).discard_empty_lines(),
            }),
            warnings: vec![],
        })
    }

    /// Parse a Markdown-style blockquote: a run of lines introduced by a `>`
    /// marker.
    ///
    /// Returns `None` when the content is not a Markdown-style blockquote,
    /// including the case where it is a description list (which takes
    /// precedence, since the `>` marker is a valid description-list term
    /// prefix).
    fn parse_markdown(
        metadata: &BlockMetadata<'src>,
        parser: &mut Parser,
    ) -> Option<MatchAndWarnings<'src, Option<MatchedItem<'src, Self>>>> {
        let first_line = metadata.block_start.take_normalized_line().item;

        // The first line must begin the Markdown blockquote: a `>` followed by a
        // space, or a bare `>`. A `>` immediately followed by other text (e.g.
        // `>foo`) is not a blockquote.
        if !is_markdown_marker_line(first_line.data()) {
            return None;
        }

        // A description list takes precedence over a Markdown-style blockquote:
        // the `>` marker is a valid prefix for a description-list term, so a
        // line like `> term:: def` is a description list, not a blockquote.
        if let Some(MatchedItem {
            item: ListItemMarker::DefinedTerm { .. },
            ..
        }) = ListItemMarker::parse(metadata.block_start, parser)
        {
            return None;
        }

        // The blockquote spans the paragraph: every line up to the first blank
        // line. Within it, each line's `>` marker is stripped (a bare `>`
        // becomes a blank line); a line with no marker is a lazy continuation
        // and is kept as-is.
        let chunk = read_paragraph(metadata.block_start);
        let after = read_paragraph_after(metadata.block_start);

        let mut lines: Vec<String> = chunk
            .data()
            .split('\n')
            .map(|line| {
                if line == ">" {
                    String::new()
                } else if let Some(rest) = line.strip_prefix("> ") {
                    rest.to_string()
                } else {
                    line.to_string()
                }
            })
            .collect();

        // A trailing attribution line (introduced by `--`) is pulled out of the
        // content and used as the attribution and citation.
        let (attribution, citetitle) = take_trailing_attribution(&mut lines, parser);

        let body = lines.join("\n");

        // The stripped body owns its source; its blocks borrow from it. Warnings
        // from the owned parse reference spans in that owned source, so they
        // cannot be returned to the caller as `Warning<'src>`. Their
        // [`WarningType`]s (which carry no borrowed data) are collected instead
        // and re-anchored at the blockquote's own source span below: the
        // `>`-stripped body is not contiguous in the document source, so a
        // precise location is not available anyway, but the diagnostic itself
        // must not be lost.
        let mut nested_warning_types: Vec<WarningType> = vec![];
        let owned = OwnedQuoteBlocks::new(body, |source| {
            // The blocks parse from `source`, an owned copy that does not map to
            // the document. Mark that so a footnote defined inside records no
            // (misleading) document location; see `Parser::owned_subsource_depth`.
            parser.owned_subsource_depth += 1;

            // A `== …` line inside the blockquote is literal content, not a
            // section heading; suppress section recognition for the nested parse
            // (saved and restored to compose with outer contexts).
            let previously_in_delimited_block = parser.in_delimited_block;
            parser.in_delimited_block = true;

            let mut maw = parse_blocks_until(Span::new(source), |_, _| false, parser);

            parser.in_delimited_block = previously_in_delimited_block;
            parser.owned_subsource_depth -= 1;
            nested_warning_types.extend(maw.warnings.drain(..).map(|w| w.warning));
            OwnedQuoteBlocksInner {
                blocks: maw.item.item,
            }
        });

        let source = metadata
            .source
            .trim_remainder(after)
            .trim_trailing_whitespace();

        let warnings = nested_warning_types
            .into_iter()
            .map(|warning| Warning::new(source, warning))
            .collect();

        Some(MatchAndWarnings {
            item: Some(MatchedItem {
                item: Self {
                    type_: QuoteType::Quote,
                    content_model: ContentModel::Compound,
                    content: None,
                    blocks: vec![],
                    markdown_blocks: Some(Arc::new(owned)),
                    attribution,
                    citetitle,
                    source,
                    title_source: metadata.title_source,
                    title: metadata.title.clone(),
                    anchor: metadata.anchor,
                    anchor_reftext: metadata.anchor_reftext,
                    attrlist: metadata.attrlist.clone(),
                },
                after: after.discard_empty_lines(),
            }),
            warnings,
        })
    }

    /// Returns the blockquote type (quote or verse).
    pub fn type_(&self) -> QuoteType {
        self.type_
    }

    /// Returns the rendered attribution (the person the content is attributed
    /// to), if any.
    pub fn attribution(&self) -> Option<&str> {
        self.attribution.as_deref()
    }

    /// Returns the rendered citation title (the work the content is drawn
    /// from), if any.
    pub fn citetitle(&self) -> Option<&str> {
        self.citetitle.as_deref()
    }

    /// Returns the simple content of this blockquote, if it has the
    /// [`Simple`](ContentModel::Simple) content model.
    pub fn content(&self) -> Option<&Content<'src>> {
        self.content.as_ref()
    }

    /// Returns the nested blocks of a compound blockquote as a slice.
    ///
    /// This includes the blocks of a Markdown-style blockquote, which borrow
    /// the block's own owned source rather than the document source. See
    /// [`child_blocks()`](Self::child_blocks) for the iterator form.
    pub fn blocks(&self) -> &[Block<'_>] {
        match &self.markdown_blocks {
            Some(owned) => &owned.borrow_dependent().blocks,
            None => &self.blocks,
        }
    }

    /// Resolves any deferred cross-references in this blockquote's nested
    /// blocks.
    ///
    /// The blocks of a `____`-delimited quote are reached through
    /// [`child_blocks_mut()`](IsBlock::child_blocks_mut) by the generic block
    /// walker; this method handles the Markdown-style case, whose blocks borrow
    /// the block's own owned source.
    pub(crate) fn resolve_references(
        &mut self,
        resolver: &dyn ReferenceResolver,
        renderer: &dyn InlineSubstitutionRenderer,
        warnings: &mut ReferenceWarnings<'src>,
    ) {
        let source = self.source;

        // The owned store is shared behind an `Arc`, but references are resolved
        // immediately after parsing while the block is still its sole owner, so
        // `get_mut` succeeds.
        if let Some(owned) = self.markdown_blocks.as_mut()
            && let Some(owned) = Arc::get_mut(owned)
        {
            owned.with_dependent_mut(|_, dependent| {
                // These blocks borrow the quote's own owned source, so their
                // warnings are collected separately and then re-anchored to the
                // quote block's span in the document.
                let mut owned_warnings = ReferenceWarnings::default();

                for block in &mut dependent.blocks {
                    block.resolve_references(resolver, renderer, &mut owned_warnings);
                }

                owned_warnings.rehome_into(warnings, source);
            });
        }
    }
}

/// Returns `true` if `line` introduces a Markdown-style blockquote: a `>`
/// followed by a space, or a bare `>`.
fn is_markdown_marker_line(line: &str) -> bool {
    line == ">" || line.starts_with("> ")
}

/// Removes a trailing attribution line (introduced by `--`) from `lines`,
/// returning the rendered attribution and citation.
///
/// Trailing blank lines are discarded first. If the last remaining line begins
/// with `--` followed by whitespace and text, it is consumed and split into the
/// attribution and (optional) citation.
fn take_trailing_attribution(
    lines: &mut Vec<String>,
    parser: &Parser,
) -> (Option<String>, Option<String>) {
    while lines.last().is_some_and(|line| line.is_empty()) {
        lines.pop();
    }

    if let Some(last) = lines.last()
        && let Some(rest) = last.strip_prefix("--")
        && (rest.starts_with(' ') || rest.starts_with('\t'))
    {
        let result = split_attribution_line(rest.trim(), parser);
        lines.pop();
        while lines.last().is_some_and(|line| line.is_empty()) {
            lines.pop();
        }
        return result;
    }

    (None, None)
}

/// Returns `true` if `line` is a quote/verse delimiter (a line of four or more
/// underscores).
pub(crate) fn is_quote_verse_delimiter(line: &Span<'_>) -> bool {
    let data = line.data();
    data.len() >= 4 && data.starts_with("____") && data.chars().all(|c| c == '_')
}

/// Builds a verse block's verbatim content: the text between the delimiters
/// with normal substitutions applied and line breaks preserved.
fn render_verbatim<'src>(inside: Span<'src>, parser: &Parser) -> Content<'src> {
    let trimmed = inside.discard_empty_lines().trim_trailing_whitespace();
    let mut content = Content::from(trimmed);
    SubstitutionGroup::Normal.apply(&mut content, parser, None);
    content
}

/// Renders a fragment of attribution text (the attribution or citation) by
/// applying normal inline substitutions, returning the owned result.
fn render_inline(parser: &Parser, text: &str) -> String {
    let span = Span::new(text);
    let mut content = Content::from(span);
    SubstitutionGroup::Normal.apply(&mut content, parser, None);
    content.rendered_owned()
}

/// Extracts the attribution and citation from a block's attribute list.
///
/// The attribution is the `attribution` named attribute or the second
/// positional attribute; the citation is the `citetitle` named attribute or the
/// third positional attribute. An empty value is treated as absent.
///
/// The values are used as-is: an attribute list value already has its
/// substitutions applied (e.g. a single-quoted value is rendered when the
/// attribute list is parsed), so they must not be re-rendered here.
fn extract_attribution(attrlist: Option<&Attrlist<'_>>) -> (Option<String>, Option<String>) {
    let Some(attrlist) = attrlist else {
        return (None, None);
    };

    let attribution = attrlist
        .named_or_positional_attribute("attribution", 2)
        .map(|a| a.value())
        .filter(|v| !v.is_empty())
        .map(str::to_string);

    let citetitle = attrlist
        .named_or_positional_attribute("citetitle", 3)
        .map(|a| a.value())
        .filter(|v| !v.is_empty())
        .map(str::to_string);

    (attribution, citetitle)
}

/// Splits an attribution line's text (everything after the leading `-- `) into
/// the attribution and the optional citation, separated by the first comma.
fn split_attribution_line(text: &str, parser: &Parser) -> (Option<String>, Option<String>) {
    match text.split_once(',') {
        Some((attribution, citetitle)) => {
            let attribution = attribution.trim();
            let citetitle = citetitle.trim();
            (
                non_empty(attribution).map(|v| render_inline(parser, v)),
                non_empty(citetitle).map(|v| render_inline(parser, v)),
            )
        }
        None => (
            non_empty(text.trim()).map(|v| render_inline(parser, v)),
            None,
        ),
    }
}

fn non_empty(s: &str) -> Option<&str> {
    if s.is_empty() { None } else { Some(s) }
}

/// Finds the attribution line in a quoted paragraph and splits it from the
/// quoted text.
///
/// The attribution line begins with `--` followed by at least one space or tab
/// and then more text. The **last** such line is used (matching Asciidoctor's
/// greedy match and the Markdown-style path), so a `-- …` that appears earlier
/// in the quoted body does not prematurely terminate the quote. Returns the
/// text before that line (the quoted text) and the attribution text (everything
/// after the `--` marker and its trailing whitespace), or `None` if no
/// attribution line is present.
fn split_at_attribution_line(data: &str) -> Option<(&str, &str)> {
    let mut line_start = 0;
    let mut attribution: Option<(usize, &str)> = None;

    for line in data.split_inclusive('\n') {
        let trimmed = line.strip_suffix('\n').unwrap_or(line);

        if let Some(rest) = trimmed.strip_prefix("--")
            && (rest.starts_with(' ') || rest.starts_with('\t'))
        {
            let attribution_text = rest.trim_start_matches([' ', '\t']);

            // `line_start > 0` ensures there is at least one line of quoted text
            // before the attribution line.
            if !attribution_text.is_empty() && line_start > 0 {
                attribution = Some((line_start, attribution_text));
            }
        }

        line_start += line.len();
    }

    // `line_start` is always a line boundary, so `split_at` never lands inside a
    // character.
    attribution.map(|(start, text)| (data.split_at(start).0, text))
}

/// Returns the span of the paragraph that begins at `source`: all lines up to
/// (but not including) the first blank line.
fn read_paragraph(source: Span<'_>) -> Span<'_> {
    source.trim_remainder(read_paragraph_after(source))
}

/// Returns the span that follows the paragraph beginning at `source` (starting
/// at the first blank line or end of input).
fn read_paragraph_after(source: Span<'_>) -> Span<'_> {
    let mut next = source;
    while let Some(line) = next.take_non_empty_line() {
        next = line.after;
    }
    next
}

impl<'src> IsBlock<'src> for QuoteBlock<'src> {
    fn content_model(&self) -> ContentModel {
        self.content_model
    }

    fn raw_context(&self) -> CowStr<'src> {
        self.type_.name().into()
    }

    fn declared_style(&'src self) -> Option<&'src str> {
        self.attrlist
            .as_ref()
            .and_then(|attrlist| attrlist.block_style())
    }

    fn rendered_content(&'src self) -> Option<&'src str> {
        self.content.as_ref().map(|content| content.rendered())
    }

    /// Returns a mutable slice of the nested blocks of a `____`-delimited
    /// quote.
    ///
    /// **Note:** a Markdown-style blockquote's nested blocks borrow the block's
    /// own owned source rather than the document source, so they are not
    /// reachable through this `'src`-bound hook and this slice is empty for
    /// them. (Rendering and reference resolution go through
    /// [`blocks()`](Self::blocks) and an explicit crate-internal
    /// `resolve_references`, so this gap is internal to the crate.)
    fn child_blocks_mut(&mut self) -> &mut [Block<'src>] {
        &mut self.blocks
    }

    fn content_mut(&mut self) -> Option<&mut Content<'src>> {
        self.content.as_mut()
    }

    fn title_source(&'src self) -> Option<Span<'src>> {
        self.title_source
    }

    fn title(&self) -> Option<&str> {
        self.title.as_ref().map(Content::rendered_str)
    }

    fn anchor(&'src self) -> Option<Span<'src>> {
        self.anchor
    }

    fn anchor_reftext(&'src self) -> Option<Span<'src>> {
        self.anchor_reftext
    }

    fn attrlist(&'src self) -> Option<&'src Attrlist<'src>> {
        self.attrlist.as_ref()
    }
}

impl<'src> HasSpan<'src> for QuoteBlock<'src> {
    fn span(&self) -> Span<'src> {
        self.source
    }
}

impl std::fmt::Debug for QuoteBlock<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("QuoteBlock")
            .field("type_", &self.type_)
            .field("content_model", &self.content_model)
            .field("content", &self.content)
            .field("blocks", &DebugSliceReference(&self.blocks))
            .field("attribution", &self.attribution)
            .field("citetitle", &self.citetitle)
            .field("source", &self.source)
            .field("title_source", &self.title_source)
            .field("title", &self.title)
            .field("anchor", &self.anchor)
            .field("anchor_reftext", &self.anchor_reftext)
            .field("attrlist", &self.attrlist)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::panic)]

    use std::ops::Deref;

    use crate::{
        blocks::{Block, ContentModel, IsBlock, QuoteType},
        tests::prelude::*,
    };

    fn parse_one(input: &'static str) -> Block<'static> {
        let mut parser = Parser::default();
        Block::parse(crate::Span::new(input), &mut parser)
            .unwrap_if_no_warnings()
            .unwrap()
            .item
    }

    fn as_quote<'a>(block: &'a Block<'a>) -> &'a crate::blocks::QuoteBlock<'a> {
        match block {
            Block::Quote(quote) => quote,

            // Only reached if a test parses an input that is not a quote block;
            // it exists to fail that test loudly, so it is uncovered while the
            // tests pass.
            other => panic!("expected a quote block, got {other:?}"),
        }
    }

    mod quote_type {
        use crate::blocks::QuoteType;

        #[test]
        fn name() {
            assert_eq!(QuoteType::Quote.name(), "quote");
            assert_eq!(QuoteType::Verse.name(), "verse");
        }

        #[test]
        fn impl_debug() {
            assert_eq!(format!("{:?}", QuoteType::Quote), "QuoteType::Quote");
            assert_eq!(format!("{:?}", QuoteType::Verse), "QuoteType::Verse");
        }

        #[test]
        fn impl_clone() {
            // Silly test to mark the #[derive(...)] line as covered.
            let v1 = QuoteType::Quote;
            let v2 = v1;
            assert_eq!(v1, v2);
        }
    }

    #[test]
    fn delimited_quote_is_compound() {
        let block = parse_one("____\nA quote.\n\nWith two paragraphs.\n____");
        let quote = as_quote(&block);

        assert_eq!(quote.type_(), QuoteType::Quote);
        assert_eq!(quote.content_model(), ContentModel::Compound);
        assert_eq!(quote.raw_context().deref(), "quote");
        assert!(quote.content().is_none());
        assert!(quote.attribution().is_none());
        assert!(quote.citetitle().is_none());
        assert_eq!(quote.blocks().len(), 2);
        assert_eq!(quote.child_blocks().count(), 2);
    }

    #[test]
    fn delimited_quote_with_attribution_and_citation() {
        let block =
            parse_one("[quote,Abraham Lincoln,Gettysburg Address]\n____\nFour score.\n____");
        let quote = as_quote(&block);

        assert_eq!(quote.attribution(), Some("Abraham Lincoln"));
        assert_eq!(quote.citetitle(), Some("Gettysburg Address"));
        assert_eq!(quote.declared_style(), Some("quote"));
    }

    #[test]
    fn styled_paragraph_quote_is_simple() {
        let block = parse_one("[quote,Albert Einstein]\nA person who never made a mistake.");
        let quote = as_quote(&block);

        assert_eq!(quote.type_(), QuoteType::Quote);
        assert_eq!(quote.content_model(), ContentModel::Simple);
        assert_eq!(
            quote.content().unwrap().rendered(),
            "A person who never made a mistake."
        );
        assert_eq!(
            quote.rendered_content(),
            Some("A person who never made a mistake.")
        );
        assert_eq!(quote.attribution(), Some("Albert Einstein"));
        assert!(quote.citetitle().is_none());
    }

    #[test]
    fn verse_paragraph_is_simple() {
        let block = parse_one("[verse,Carl Sandburg,Fog]\nThe fog comes\non little cat feet.");
        let quote = as_quote(&block);

        assert_eq!(quote.type_(), QuoteType::Verse);
        assert_eq!(quote.content_model(), ContentModel::Simple);
        assert_eq!(quote.raw_context().deref(), "verse");
        assert_eq!(
            quote.content().unwrap().rendered(),
            "The fog comes\non little cat feet."
        );
        assert_eq!(quote.attribution(), Some("Carl Sandburg"));
        assert_eq!(quote.citetitle(), Some("Fog"));
    }

    #[test]
    fn verse_delimited_preserves_line_breaks() {
        let block = parse_one("[verse]\n____\nA verse\ndelimited block\n____");
        let quote = as_quote(&block);

        assert_eq!(quote.type_(), QuoteType::Verse);
        assert_eq!(quote.content_model(), ContentModel::Simple);
        assert_eq!(
            quote.content().unwrap().rendered(),
            "A verse\ndelimited block"
        );
        assert!(quote.child_blocks().next().is_none());
    }

    #[test]
    fn quote_or_verse_style_over_other_container_is_not_a_quote() {
        // A `quote`/`verse` style over an example, sidebar, listing, literal, or
        // passthrough block keeps that container's own context.
        assert_eq!(
            parse_one("[quote]\n====\nx\n====").raw_context().deref(),
            "example"
        );
        assert_eq!(
            parse_one("[verse]\n****\nx\n****").raw_context().deref(),
            "sidebar"
        );
        assert_eq!(
            parse_one("[quote]\n----\nx\n----").raw_context().deref(),
            "listing"
        );
    }

    #[test]
    fn quoted_paragraph_with_attribution_and_citation() {
        let block = parse_one("\"A little rebellion is good.\"\n-- Thomas Jefferson, Volume 11");
        let quote = as_quote(&block);

        assert_eq!(quote.type_(), QuoteType::Quote);
        assert_eq!(quote.content_model(), ContentModel::Simple);
        assert_eq!(
            quote.content().unwrap().rendered(),
            "A little rebellion is good."
        );
        assert_eq!(quote.attribution(), Some("Thomas Jefferson"));
        assert_eq!(quote.citetitle(), Some("Volume 11"));
    }

    #[test]
    fn quoted_paragraph_without_citation() {
        let block = parse_one("\"A quote.\"\n-- Anonymous");
        let quote = as_quote(&block);

        assert_eq!(quote.attribution(), Some("Anonymous"));
        assert!(quote.citetitle().is_none());
    }

    #[test]
    fn quoted_paragraph_requires_attribution_line() {
        // Without a `-- ` attribution line, a quoted sentence is just a
        // paragraph.
        let block = parse_one("\"Just a quoted sentence.\"");
        assert_eq!(block.raw_context().deref(), "paragraph");
    }

    #[test]
    fn quoted_paragraph_requires_opening_quote() {
        // The attribution line alone, with no opening quote, is not a quoted
        // paragraph.
        let block = parse_one("Not quoted.\n-- Someone");
        assert_eq!(block.raw_context().deref(), "paragraph");
    }

    #[test]
    fn empty_quoted_paragraph_is_not_a_quote() {
        // A pair of quotes wrapping no text is not a quoted paragraph.
        let block = parse_one("\"\"\n-- Someone");
        assert_eq!(block.raw_context().deref(), "paragraph");
    }

    #[test]
    fn unclosed_quoted_paragraph_is_not_a_quote() {
        // An opening quote with no closing quote is not a quoted paragraph.
        let block = parse_one("\"no closing quote\n-- Someone");
        assert_eq!(block.raw_context().deref(), "paragraph");
    }

    #[test]
    fn dash_line_without_attribution_text_is_not_a_quote() {
        // A `-- ` line with no attribution text after it is not an attribution
        // line, so this is an ordinary paragraph.
        let block = parse_one("\"A quote.\"\n--  ");
        assert_eq!(block.raw_context().deref(), "paragraph");
    }

    #[test]
    fn quoted_paragraph_tab_separated_attribution() {
        // The `--` attribution marker may be separated from the text by a tab.
        let block = parse_one("\"A quote.\"\n--\tSomeone");
        let quote = as_quote(&block);
        assert_eq!(quote.attribution(), Some("Someone"));
    }

    #[test]
    fn quoted_paragraph_uses_last_attribution_line() {
        // A `-- …` that appears earlier in the quoted body does not terminate
        // the quote; the last attribution line wins (matching Asciidoctor).
        let block =
            parse_one("\"line one\n-- not really an attribution\nline two\"\n-- Real Attribution");
        let quote = as_quote(&block);
        assert_eq!(quote.attribution(), Some("Real Attribution"));
        let rendered = quote.content().unwrap().rendered();
        assert!(
            rendered.contains("line one") && rendered.contains("line two"),
            "content was: {rendered}"
        );
    }

    #[test]
    fn attribution_with_empty_name_keeps_citation() {
        // A `--` line of the form `-- , citation` has no attribution but still
        // yields a citation.
        let block = parse_one("\"A quote.\"\n-- , Just a citation");
        let quote = as_quote(&block);
        assert!(quote.attribution().is_none());
        assert_eq!(quote.citetitle(), Some("Just a citation"));
    }

    #[test]
    fn styled_paragraph_with_no_content_is_not_a_quote() {
        // A `[quote]` style with no following content cannot form a styled
        // paragraph; the lone attribute list is treated as an ordinary block.
        let mut parser = Parser::default();
        let maw = Block::parse(crate::Span::new("[quote]\n"), &mut parser);
        let block = maw.item.unwrap().item;
        assert_eq!(block.raw_context().deref(), "paragraph");
    }

    #[test]
    fn markdown_blockquote_tab_attribution_after_blank() {
        // A trailing blank (`>`) line before the `--` attribution is discarded,
        // and the attribution marker may be tab-separated.
        let block = parse_one("> A quote.\n>\n> --\tSomeone");
        let quote = as_quote(&block);
        assert_eq!(quote.attribution(), Some("Someone"));
        assert_eq!(quote.blocks().len(), 1);
    }

    #[test]
    fn markdown_blockquote_propagates_nested_warning() {
        // A warning produced while parsing the (owned, `>`-stripped) body – here
        // an unterminated nested delimited block – is re-anchored at the
        // blockquote's own span and surfaced to the caller, rather than being
        // dropped (or panicking a debug build).
        let mut parser = Parser::default();
        let maw = Block::parse(crate::Span::new("> ____\n> unclosed"), &mut parser);

        let block = maw.item.unwrap().item;
        assert_eq!(block.raw_context().deref(), "quote");
        assert_eq!(
            maw.warnings.first().unwrap().warning,
            WarningType::UnterminatedDelimitedBlock
        );

        // The warning is anchored at the blockquote's source span.
        assert_eq!(maw.warnings.first().unwrap().source, block.span());
    }

    #[test]
    fn markdown_blockquote_double_dash_without_space_is_content() {
        // A trailing `--` not followed by whitespace is content, not an
        // attribution.
        let block = parse_one("> A quote.\n> --nospace");
        let quote = as_quote(&block);
        assert!(quote.attribution().is_none());
    }

    #[test]
    fn markdown_blockquote_basic() {
        let block = parse_one("> A markdown quote.");
        let quote = as_quote(&block);

        assert_eq!(quote.type_(), QuoteType::Quote);
        assert_eq!(quote.content_model(), ContentModel::Compound);
        assert_eq!(quote.blocks().len(), 1);

        // A Markdown blockquote's nested blocks borrow the block's owned source,
        // but `child_blocks()` still exposes them (matching `blocks()`).
        assert_eq!(quote.child_blocks().count(), 1);
    }

    #[test]
    fn markdown_blockquote_with_attribution() {
        let block = parse_one("> A quote.\n> -- Someone");
        let quote = as_quote(&block);

        assert_eq!(quote.attribution(), Some("Someone"));
        assert_eq!(quote.blocks().len(), 1);
    }

    #[test]
    fn markdown_blockquote_lazy_continuation() {
        // A line without a `>` marker continues the current paragraph.
        let block = parse_one("> line one\nline two");
        let quote = as_quote(&block);

        assert_eq!(quote.blocks().len(), 1);
        let inner = quote.blocks().first().unwrap();
        assert_eq!(inner.rendered_content(), Some("line one\nline two"));
    }

    #[test]
    fn markdown_marker_requires_space() {
        // A `>` immediately followed by other text is not a blockquote.
        let block = parse_one(">foo bar");
        assert_eq!(block.raw_context().deref(), "paragraph");
    }

    #[test]
    fn markdown_yields_to_description_list() {
        // A `>`-prefixed description-list term is a description list, not a
        // Markdown-style blockquote.
        let block = parse_one("> term:: definition");
        assert_eq!(block.raw_context().deref(), "list");
    }

    #[test]
    fn unterminated_delimited_quote_warns() {
        let mut parser = Parser::default();
        let maw = Block::parse(crate::Span::new("____\nunclosed"), &mut parser);

        let block = maw.item.unwrap().item;
        assert_eq!(block.raw_context().deref(), "quote");
        assert_eq!(maw.warnings.len(), 1);
        assert_eq!(
            maw.warnings.first().unwrap().warning,
            WarningType::UnterminatedDelimitedBlock
        );
    }

    #[test]
    fn citation_receives_inline_substitutions() {
        // A link in the citation is rendered to an anchor.
        let block = parse_one(
            "[quote,Lewis Carroll,'See https://example.com/lc[the bio]']\n____\nAny road.\n____",
        );
        let quote = as_quote(&block);
        let citetitle = quote.citetitle().unwrap();
        assert!(
            citetitle.contains("<a href=\"https://example.com/lc\">the bio</a>"),
            "citation was: {citetitle}"
        );
    }

    #[test]
    fn block_enum_delegates_to_quote() {
        // Exercise the `Block`-level `IsBlock`/`Debug` arms for a quote block.
        let compound = parse_one("____\nx\n____");
        assert_eq!(compound.content_model(), ContentModel::Compound);
        assert_eq!(compound.raw_context().deref(), "quote");
        assert!(compound.title_source().is_none());
        assert!(compound.anchor().is_none());
        assert!(compound.anchor_reftext().is_none());
        assert!(compound.attrlist().is_none());
        assert_eq!(compound.substitution_group(), SubstitutionGroup::Normal);
        assert_eq!(compound.child_blocks().count(), 1);
        assert!(compound.title().is_none());
        assert!(compound.declared_style().is_none());
        assert!(format!("{compound:?}").starts_with("Block::Quote"));

        let simple = parse_one("[verse]\nverse text");
        assert_eq!(simple.rendered_content(), Some("verse text"));
        assert_eq!(simple.content_model(), ContentModel::Simple);
    }

    #[test]
    fn impl_debug() {
        let block = parse_one("____\nx\n____");
        let quote = as_quote(&block);
        let debug = format!("{quote:?}");
        assert!(debug.starts_with("QuoteBlock {"));
        assert!(debug.contains("type_: QuoteType::Quote"));
    }

    #[test]
    fn impl_clone() {
        // Silly test to mark the #[derive(...)] line as covered.
        let block = parse_one("____\nclone me\n____");
        let quote = as_quote(&block).clone();
        assert_eq!(quote.type_(), QuoteType::Quote);
    }

    #[test]
    fn title_renders_inside_quote_block() {
        let doc = Parser::default()
            .parse(".A title\n[quote,Captain Kirk]\nEverybody remember where we parked.");
        let block = doc.child_blocks().next().unwrap();
        let quote = as_quote(block);
        assert_eq!(quote.title(), Some("A title"));
    }

    /// The quoted-paragraph parser must reject a non-quote paragraph on its
    /// first byte, before scanning the paragraph to the next blank line. A
    /// document of many consecutive delimiter lines with no blank line between
    /// them otherwise makes every block rescan the entire remaining input,
    /// giving quadratic (O(n²)) parse time and a practical denial of service on
    /// modestly-sized input. This guards that the parse stays roughly linear.
    ///
    /// The bound is deliberately loose (seconds, versus a handful of
    /// milliseconds when linear) so the test is not flaky on a slow or loaded
    /// machine, while still failing decisively if the quadratic behavior
    /// returns — the quadratic parse of this input takes tens of seconds.
    #[test]
    fn many_consecutive_delimiters_parse_in_roughly_linear_time() {
        use std::time::{Duration, Instant};

        // Each of these patterns previously exercised the quadratic path: none
        // contains a blank line, so the quoted-paragraph scan ran to end of
        // input on every block.
        let example_run = "====\n".repeat(20_000);

        let mut example_run_with_text = "====\n".repeat(10_000);
        example_run_with_text.push_str("text\n");
        example_run_with_text.push_str(&"====\n".repeat(10_000));

        let open_run = "--\n".repeat(20_000);

        let budget = Duration::from_secs(10);

        for source in [&example_run, &example_run_with_text, &open_run] {
            let start = Instant::now();
            let _ = Parser::default().parse(source);
            let elapsed = start.elapsed();

            assert!(
                elapsed < budget,
                "parsing {} delimiter lines took {elapsed:?}, exceeding the {budget:?} budget \
                 (a sign the quadratic quoted-paragraph rescan has returned)",
                source.lines().count(),
            );
        }
    }

    mod section_heading_suppressed {
        //! A `== …` line inside a quote block or a Markdown-style blockquote is
        //! literal content – a paragraph – not a section heading (matching
        //! Asciidoctor, which only creates sections at the document level or
        //! within a section body).

        use crate::tests::prelude::*;

        fn assert_literal_heading(input: &str) {
            let doc = Parser::default().parse(input);

            // No section heading was recognized, so nothing renders as an `<h2>`.
            assert_xpath(&doc, "//h2", 0);

            // The line survives as ordinary paragraph content.
            assert!(rendered_paragraphs(&doc).contains(&"== not a heading".to_string()));
        }

        #[test]
        fn quote_block() {
            assert_literal_heading("____\n== not a heading\n____\n");
        }

        #[test]
        fn markdown_blockquote() {
            assert_literal_heading("> == not a heading\n");
        }
    }
}