adocers-html 0.2.0

Render an AsciiDoc document to HTML, following Asciidoctor's HTML5 converter
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
//! Block-level rendering: the dispatch from a parsed [`Block`] to its markup.

use std::fmt::Write as _;

use asciidoc_parser::{
    blocks::{
        AdmonitionBlock,
        Block,
        Break,
        BreakType,
        CompoundDelimitedBlock,
        CompoundDelimitedContext,
        IsBlock,
        Preamble,
        QuoteBlock,
        QuoteType,
        RawDelimitedBlock,
        SectionBlock,
        SectionType,
        SimpleBlock,
        SimpleBlockStyle,
    },
    content::Content,
};

use adocers_render_core::icons;

use crate::{
    Renderer,
    TocMode,
    callout,
    highlight,
    html::{
        escape_attr,
        escape_text,
        open_tag_with,
    },
};

impl<'src> Renderer<'src> {
    /// Render one block and everything beneath it.
    #[expect(
        clippy::match_same_arms,
        reason = "the arms that produce nothing do so for different reasons, and saying which is \
                  the point of listing them separately"
    )]
    pub(super) fn block(&mut self, block: &'src Block<'src>) {
        match block {
            Block::Simple(simple) => self.simple_block(block, simple),
            Block::Section(section) => self.section_block(block, section),
            Block::List(list) => self.list_block(block, list),
            Block::RawDelimited(raw) => self.raw_delimited_block(block, raw),
            Block::CompoundDelimited(compound) => self.compound_delimited_block(block, compound),
            Block::Admonition(admonition) => self.admonition_block(block, admonition),
            Block::Quote(quote) => self.quote_block(block, quote),
            Block::Media(media) => self.media_block(block, media),
            Block::Table(table) => self.table_block(block, table),
            Block::Preamble(preamble) => self.preamble_block(preamble),
            Block::Break(r#break) => self.break_block(r#break),
            Block::Toc(toc) => self.toc_macro(toc),

            // A list item never appears on its own: its list renders it, along
            // with the marker that gives it meaning.
            Block::ListItem(_) => {}

            // An attribute entry in the body sets a value for the blocks that
            // follow it; the parser has already applied it and it has no
            // rendering of its own.
            Block::DocumentAttribute(_) => {}

            _ => {}
        }
    }

    /// Render a sequence of blocks in document order.
    pub(super) fn blocks(&mut self, blocks: impl Iterator<Item = &'src Block<'src>>) {
        for block in blocks {
            self.block(block);
        }
    }

    /// Emit a block's `<div class="title">`, including any caption prefix
    /// ("Example 1. ", "Figure 2. ") the parser assigned.
    pub(super) fn block_title(&mut self, block: &'src Block<'src>) {
        let caption = block.caption().unwrap_or_default().to_string();

        self.titled(block, &caption);
    }

    /// The same, with a caption worked out here rather than by the parser.
    ///
    /// A drawn diagram is a figure and is numbered with the pictures, which the
    /// parser cannot know: to it the block is a listing.
    pub(super) fn titled(&mut self, block: &'src Block<'src>, caption: &str) {
        let Some(title) = block.title() else {
            return;
        };

        // Both halves are already inline-rendered; escaping here would show the
        // reader the markup instead of applying it.
        self.out
            .line(&format!("<div class=\"title\">{caption}{title}</div>"));
    }

    /// The caption for the next figure, and the number that goes in it.
    ///
    /// Only a figure that carries a title is numbered — an untitled picture
    /// shows no caption and takes no number — and `:figure-caption!:` leaves
    /// the title to stand on its own. Both are the rules the parser follows for
    /// a picture, followed here so that a diagram joins the same sequence.
    pub(super) fn figure_caption(&mut self, block: &'src Block<'src>) -> String {
        if block.title().is_none() {
            return String::new();
        }

        let Some(label) = self
            .attribute("figure-caption")
            .filter(|label| !label.is_empty())
        else {
            return String::new();
        };

        self.figures += 1;

        format!("{label} {}. ", self.figures)
    }

    /// Open a block wrapper `<div>` with the block's id and class list.
    pub(super) fn open_wrapper(&mut self, block: &'src Block<'src>, context: &str) {
        let classes = wrapper_classes(block, &[context]);
        let classes: Vec<&str> = classes.iter().map(String::as_str).collect();

        self.out.open("div", block.id(), &classes);
    }

    /// A paragraph, or a listing/literal block written without delimiters.
    fn simple_block(&mut self, block: &'src Block<'src>, simple: &'src SimpleBlock<'src>) {
        let content = simple.content().rendered_html();

        match simple.style() {
            SimpleBlockStyle::Paragraph => {
                // A line comment reaches the back end as a paragraph with
                // nothing in it. So does anything else that substitutes away to
                // nothing, and none of it should leave an empty `<p>` behind.
                if content.trim().is_empty() {
                    return;
                }

                // A style can make one paragraph into a block of another kind,
                // saving its author the delimiters. The content then sits bare
                // inside that block rather than in a `<p>` of its own, which is
                // what the delimited form would have given it.
                match block.declared_style() {
                    Some("sidebar") => {
                        self.open_wrapper(block, "sidebarblock");
                        self.out.open("div", None, &["content"]);
                        self.block_title(block);
                        self.out.line(content);
                        self.out.close("div");
                        self.out.close("div");
                    }

                    Some("example") => {
                        self.open_wrapper(block, "exampleblock");
                        self.block_title(block);
                        self.out.open("div", None, &["content"]);
                        self.out.line(content);
                        self.out.close("div");
                        self.out.close("div");
                    }

                    // A part's introduction, which Asciidoctor makes an open
                    // block of. The paragraph keeps its own wrapper inside,
                    // unlike the three styles below, because the delimited form
                    // holds whole blocks and this is one of them.
                    //
                    // Asciidoctor drops the content when this is not inside a
                    // book part. It is rendered here wherever it is written:
                    // throwing away what an author wrote because of where they
                    // put it is the worse of the two answers.
                    Some("partintro") => {
                        let classes = wrapper_classes(block, &["openblock", "partintro"]);
                        let classes: Vec<&str> = classes.iter().map(String::as_str).collect();

                        self.out.open("div", block.id(), &classes);
                        self.block_title(block);
                        self.out.open("div", None, &["content"]);
                        self.out.open("div", None, &["paragraph"]);
                        self.out.line(&format!("<p>{content}</p>"));
                        self.out.close("div");
                        self.out.close("div");
                        self.out.close("div");
                    }

                    Some("abstract") => {
                        let classes = wrapper_classes(block, &["quoteblock", "abstract"]);
                        let classes: Vec<&str> = classes.iter().map(String::as_str).collect();

                        self.out.open("div", block.id(), &classes);
                        self.block_title(block);
                        self.out.line("<blockquote>");
                        self.out.line(content);
                        self.out.line("</blockquote>");
                        self.out.close("div");
                    }

                    _ => {
                        self.open_wrapper(block, "paragraph");
                        self.block_title(block);
                        self.out.line(&format!("<p>{content}</p>"));
                        self.out.close("div");
                    }
                }
            }

            SimpleBlockStyle::Literal => self.literal(block, content),
            SimpleBlockStyle::Listing | SimpleBlockStyle::Source => {
                self.listing(block, simple.content());
            }
        }
    }

    /// A `----` listing, `....` literal, `++++` passthrough, `////` comment or
    /// stem block. Their content is verbatim, already substituted to the degree
    /// the block's substitution group calls for.
    fn raw_delimited_block(
        &mut self,
        block: &'src Block<'src>,
        raw: &'src RawDelimitedBlock<'src>,
    ) {
        let content = raw.content().rendered_html();

        match raw.raw_context().as_ref() {
            "listing" => self.listing(block, raw.content()),
            "literal" => self.literal(block, content),

            "stem" => {
                // The source is escaped for the page; the converter needs it
                // back as the author wrote it.
                let source = unescape(content);

                // An equation the converter cannot read stays as its source,
                // which is more use to a reader than a gap.
                let body = self
                    .equation(&source, block)
                    .unwrap_or_else(|| content.to_string());

                self.open_wrapper(block, "stemblock");
                self.block_title(block);

                // An equation cannot be broken across lines, so a wide one
                // scrolls rather than running off the page — and something that
                // scrolls has to be reachable from the keyboard, or a reader
                // who does not use a mouse cannot see the rest of it.
                self.out.line(&format!("<div class=\"content\"{SCROLLS}>"));
                self.out.line(&body);
                self.out.close("div");
                self.out.close("div");
            }

            // A passthrough block is the author asking for their bytes to reach
            // the page untouched.
            "pass" => self.out.line(content),

            // A comment block is not part of the output at all.
            "comment" => {}

            other => {
                self.open_wrapper(block, other);
                self.block_title(block);
                self.out.line(content);
                self.out.close("div");
            }
        }
    }

    /// `<div class="listingblock">`, syntax highlighted when the block declares
    /// a language a compiled-in grammar covers.
    fn listing(&mut self, block: &'src Block<'src>, content: &'src Content<'src>) {
        let rendered = content.rendered_html();

        if self.options.mermaid && self.is_mermaid(block) && self.mermaid_block(block, rendered) {
            return;
        }

        self.open_wrapper(block, "listingblock");
        self.block_title(block);
        self.out.open("div", None, &["content"]);

        // A `[source]` block is wrapped in `<code>` whether or not it named a
        // language: the style alone is what says this is source.
        if block.declared_style() == Some("source") {
            let language = self.source_language(block);

            let body = language
                .as_deref()
                .and_then(|language| self.highlighted(language, content))
                .unwrap_or_else(|| rendered.to_string());

            let body = self.marked(&body);

            let language = language
                .as_deref()
                .map(escape_attr)
                .map_or_else(String::new, |language| {
                    format!(" class=\"language-{language}\" data-lang=\"{language}\"")
                });

            self.out.line(&format!(
                "<pre class=\"highlight{}\"><code{language}>{body}</code></pre>",
                nowrap(block)
            ));
        } else {
            let body = self.marked(rendered);

            self.out
                .line(&format!("<pre{}>{body}</pre>", pre_class(block)));
        }

        self.out.close("div");
        self.out.close("div");
    }

    /// Draw a listing's callout markers, if this run draws marks at all.
    ///
    /// `--no-icons` is one switch for both kinds: an admonition falls back to
    /// its label and a callout to the `(1)` the parser rendered.
    fn marked(&self, body: &str) -> String {
        if self.options.icons {
            callout::iconize(body)
        } else {
            body.to_string()
        }
    }

    /// The heading text, with whatever `:sectanchors:` and `:sectlinks:` ask to
    /// be wrapped around it.
    ///
    /// An anchor is an empty link before the text, there for a stylesheet to
    /// hang a mark on so a reader can grab the section's address. A section
    /// link makes the text itself that link. Both need somewhere to point, so a
    /// section without an id gets neither.
    fn linked_title(&self, section: &'src SectionBlock<'src>, title: &str) -> String {
        let anchors = self.document.is_attribute_set("sectanchors");
        let links = self.document.is_attribute_set("sectlinks");

        if !anchors && !links {
            return title.to_string();
        }

        let Some(id) = section.id().map(escape_attr) else {
            return title.to_string();
        };

        let mut out = String::new();

        if anchors {
            let _ = write!(out, "<a class=\"anchor\" href=\"#{id}\"></a>");
        }

        if links {
            let _ = write!(out, "<a class=\"link\" href=\"#{id}\">{title}</a>");
        } else {
            out.push_str(title);
        }

        out
    }

    /// The language a source block should be highlighted and labelled as.
    ///
    /// `[source,rust]` names it outright. A bare `[source]` takes the
    /// document's `:source-language:`, which is how a document whose listings
    /// are all one language says so once instead of on every block.
    fn source_language(&self, block: &'src Block<'src>) -> Option<String> {
        if block.declared_style() != Some("source") {
            return None;
        }

        let declared = block.attrlist().and_then(|attrlist| {
            attrlist
                .named_attribute("language")
                .or_else(|| attrlist.nth_attribute(2))
                .map(asciidoc_parser::attributes::ElementAttribute::value)
                .filter(|language| !language.is_empty())
                .map(str::to_string)
        });

        declared.or_else(|| {
            self.attribute("source-language")
                .filter(|language| !language.is_empty())
        })
    }

    /// Whether a block was written as a mermaid diagram.
    ///
    /// Both spellings count: `[mermaid]`, which `asciidoctor-diagram` uses, and
    /// `[source,mermaid]`, which renders as a diagram on GitHub. A document
    /// that has to serve both usually picks between them with an attribute, so
    /// a renderer that took only one would show the other as a wall of arrows.
    fn is_mermaid(&self, block: &'src Block<'src>) -> bool {
        let declared = block
            .declared_style()
            .is_some_and(|style| style.to_lowercase() == "mermaid");

        declared
            || self
                .source_language(block)
                .is_some_and(|language| language.to_lowercase() == "mermaid")
    }

    /// Draw a diagram here, if this build can and `merman` reads it.
    ///
    /// `content` is the diagram's source escaped for the page, which is the
    /// form the browser would have read out of the element; it is turned back
    /// into source first, exactly as the browser does.
    ///
    /// Each diagram gets a name of its own, because the markup carries an id
    /// and two elements on a page may not share one.
    #[cfg(feature = "mermaid")]
    fn drawn(&mut self, content: &str) -> Option<String> {
        self.drawings += 1;

        adocers_render_core::mermaid::svg(&unescape(content), &format!("diagram-{}", self.drawings))
    }

    /// Never draws: `merman` is not compiled in.
    #[cfg(not(feature = "mermaid"))]
    #[expect(
        clippy::unused_self,
        reason = "the other half of this pair keeps a counter, and both are called the same way"
    )]
    fn drawn(&mut self, _content: &str) -> Option<String> {
        None
    }

    /// Convert a stem block to `MathML`, if this build can and it reads.
    #[cfg(feature = "math")]
    fn equation(&self, source: &str, block: &'src Block<'src>) -> Option<String> {
        crate::math::mathml(source, self.notation(block))
    }

    /// Never converts: no converter is compiled in.
    #[cfg(not(feature = "math"))]
    #[expect(
        clippy::unused_self,
        reason = "the other half of this pair reads the document, and both are called the same way"
    )]
    fn equation(&self, _source: &str, _block: &'src Block<'src>) -> Option<String> {
        None
    }

    /// Which notation a stem block is written in.
    ///
    /// `[latexmath]` and `[asciimath]` say so outright; a plain `[stem]` takes
    /// whatever `:stem:` was set to, which is `AsciiMath` unless it says
    /// otherwise.
    #[cfg(feature = "math")]
    fn notation(&self, block: &'src Block<'src>) -> crate::math::Notation {
        use crate::math::Notation;

        match block.declared_style() {
            Some("latexmath") => return Notation::Latex,
            Some("asciimath") => return Notation::AsciiMath,
            _ => {}
        }

        if self
            .attribute("stem")
            .is_some_and(|stem| stem == "latexmath")
        {
            Notation::Latex
        } else {
            Notation::AsciiMath
        }
    }

    /// Highlight a listing's source, if this build can and the block asked for
    /// a language it knows.
    ///
    /// The highlighter is given the block's original text, not the parser's
    /// rendering of it: the rendering is already escaped, and a highlighter
    /// needs the code as the author wrote it. Escaping is then the
    /// highlighter's job, which it does as it emits.
    fn highlighted(&self, language: &str, content: &'src Content<'src>) -> Option<String> {
        if !self.options.highlight {
            return None;
        }

        let source = content.original().data();

        // Callout markers are the parser's rendering, not the author's code, so
        // they come out before the highlighter sees them and go back after.
        // When the two readings of the source disagree, the block is left to
        // the parser entirely rather than highlighted with its callouts lost.
        let callouts = callout::locate(source, content.rendered_html())?;
        let stripped = callout::strip(source, &callouts);
        let highlighted = highlight::highlight(language, &stripped)?;

        Some(callout::reapply(&highlighted, &callouts))
    }

    /// `<div class="literalblock">`.
    fn literal(&mut self, block: &'src Block<'src>, content: &str) {
        if self.options.mermaid && self.is_mermaid(block) && self.mermaid_block(block, content) {
            return;
        }

        self.open_wrapper(block, "literalblock");
        self.block_title(block);
        self.out.open("div", None, &["content"]);
        self.out
            .line(&format!("<pre{}>{content}</pre>", pre_class(block)));
        self.out.close("div");
        self.out.close("div");
    }

    /// A mermaid diagram, handed to the browser as its own source to draw.
    ///
    /// The wrapper carries `imageblock` so that a stylesheet written for
    /// Asciidoctor centres the diagram and puts its caption underneath, the way
    /// it would for a diagram that had been rendered to an image.
    /// Returns whether the diagram was drawn. One this build cannot read is
    /// left to the caller, which renders it as the listing block it was written
    /// as — the source of a diagram being more use to a reader than a gap.
    fn mermaid_block(&mut self, block: &'src Block<'src>, content: &str) -> bool {
        let Some(svg) = self.drawn(content) else {
            return false;
        };

        let classes = wrapper_classes(block, &["imageblock", "diagram"]);
        let classes: Vec<&str> = classes.iter().map(String::as_str).collect();

        self.out.open("div", block.id(), &classes);
        self.out.line(&format!("<div class=\"content\"{SCROLLS}>"));
        self.out.line(&svg);
        self.out.close("div");

        // A diagram's caption sits below it, as an image's does, and is
        // numbered in the same sequence: both are figures once drawn.
        let caption = self.figure_caption(block);

        self.titled(block, &caption);
        self.out.close("div");

        true
    }

    /// A section heading and its body.
    ///
    /// Asciidoctor gives a level-1 section an extra `sectionbody` wrapper and
    /// deeper sections none, so this reproduces that asymmetry rather than
    /// inventing a uniform structure a stylesheet would not expect.
    fn section_block(&mut self, block: &'src Block<'src>, section: &'src SectionBlock<'src>) {
        // A level-0 heading that declares a style — `[colophon]`, `[preface]`,
        // `[appendix]` and the rest — is a section of the book rather than a
        // part of it, and is set at the level below. A discrete heading is the
        // exception: it is not a section at all.
        let level = section.level();
        let level = if level == 0
            && section.section_type() != SectionType::Discrete
            && block.declared_style().is_some()
        {
            1
        } else {
            level
        };

        let heading = format!("h{}", (level + 1).min(6));
        let title = format!(
            "{}{}",
            self.numbering.prefix(section),
            section.section_title()
        );

        if section.section_type() == SectionType::Discrete {
            // A discrete heading is a heading and nothing else: it owns no body
            // and never enters the table of contents.
            let mut classes = vec!["discrete".to_string()];
            classes.extend(block.roles().into_iter().map(str::to_string));
            let classes: Vec<&str> = classes.iter().map(String::as_str).collect();

            self.out.element(&heading, section.id(), &classes, &title);
            return;
        }

        let title = self.linked_title(section, &title);

        if level == 0 {
            // A level-0 heading in the body is not a section wrapper of its
            // own.
            self.out.element("h1", section.id(), &["sect0"], &title);
            self.blocks(section.child_blocks());
            return;
        }

        // The id goes on the heading, which is what a link to the section
        // should scroll to; putting it on the wrapper as well would make the
        // document contain the same id twice.
        let classes = wrapper_classes(block, &[&format!("sect{level}")]);
        let classes: Vec<&str> = classes.iter().map(String::as_str).collect();

        self.out.open("div", None, &classes);
        self.out.element(&heading, section.id(), &[], &title);

        if level == 1 {
            self.out.open("div", None, &["sectionbody"]);
            self.blocks(section.child_blocks());
            self.out.close("div");
        } else {
            self.blocks(section.child_blocks());
        }

        self.out.close("div");
    }

    /// The preamble: everything between the document header and the first
    /// section.
    fn preamble_block(&mut self, preamble: &'src Preamble<'src>) {
        // Rendered aside first, because a preamble holding nothing that reaches
        // the page — a lone comment, say — is not a preamble, and an empty one
        // would draw its own margins around nothing.
        let body = self.aside(|renderer| renderer.blocks(preamble.child_blocks()));

        if body.trim().is_empty() && self.document.toc_mode() != TocMode::Preamble {
            return;
        }

        self.out.open("div", Some("preamble"), &[]);
        self.out.open("div", None, &["sectionbody"]);
        self.out.raw(&body);
        self.out.close("div");

        // `:toc: preamble` places the outline below the preamble's body but
        // still inside it: the preamble introduces the document, and the
        // outline is the last thing that introduction says.
        if self.document.toc_mode() == TocMode::Preamble {
            self.toc();
        }

        self.out.close("div");
    }

    /// `'''` and `<<<`.
    fn break_block(&mut self, r#break: &'src Break<'src>) {
        match r#break.type_() {
            BreakType::Thematic => self.out.line("<hr>"),

            // There is no page break in HTML, only a hint for print styles.
            BreakType::Page => self
                .out
                .line("<div style=\"page-break-after: always;\"></div>"),
        }
    }

    /// `NOTE:`, `TIP:`, `IMPORTANT:`, `CAUTION:` and `WARNING:`, in both their
    /// paragraph and delimited forms.
    fn admonition_block(
        &mut self,
        block: &'src Block<'src>,
        admonition: &'src AdmonitionBlock<'src>,
    ) {
        let name = admonition.name();
        let label = admonition.label().to_string();

        let mut classes = vec!["admonitionblock".to_string(), name.to_string()];
        classes.extend(block.roles().into_iter().map(str::to_string));
        let classes: Vec<&str> = classes.iter().map(String::as_str).collect();

        self.out.open("div", block.id(), &classes);
        self.out.line("<table>");
        self.out.line("<tr>");
        self.out.line("<td class=\"icon\">");

        // The icon carries the label as its accessible name, so nothing is lost
        // by drawing one instead of writing the other. A variant with no icon
        // of its own falls back to the label rather than to an empty column.
        //
        // Asciidoctor's `icons=font` markup is not emitted: it names Font
        // Awesome classes, and a page this tool produced has no way to pull in
        // that webfont, so the column came out blank.
        let icon = self
            .options
            .icons
            .then(|| icons::admonition(name, &label))
            .flatten();

        match icon {
            Some(icon) => self.out.line(&icon),

            None => self.out.line(&format!(
                "<div class=\"title\">{}</div>",
                escape_text(&label)
            )),
        }

        self.out.line("</td>");
        self.out.line("<td class=\"content\">");

        self.block_title(block);

        match admonition.content() {
            Some(content) => self.out.line(content.rendered_html()),
            None => self.blocks(admonition.child_blocks()),
        }

        self.out.line("</td>");
        self.out.line("</tr>");
        self.out.line("</table>");
        self.out.close("div");
    }

    /// `[quote]` and `[verse]`, delimited or not.
    fn quote_block(&mut self, block: &'src Block<'src>, quote: &'src QuoteBlock<'src>) {
        let is_verse = quote.type_() == QuoteType::Verse;
        let wrapper = if is_verse { "verseblock" } else { "quoteblock" };

        self.open_wrapper(block, wrapper);
        self.block_title(block);

        if is_verse {
            // A verse keeps the author's line breaks, so its content is
            // preformatted rather than flowed.
            let content = quote
                .content()
                .map(Content::rendered_html)
                .unwrap_or_default();
            self.out
                .line(&format!("<pre class=\"content\">{content}</pre>"));
        } else {
            self.out.line("<blockquote>");

            match quote.content() {
                Some(content) => self.out.line(content.rendered_html()),
                None => self.blocks(quote.child_blocks()),
            }

            self.out.line("</blockquote>");
        }

        self.attribution(quote);
        self.out.close("div");
    }

    /// The `— Author, Work` line beneath a quote or verse.
    fn attribution(&mut self, quote: &'src QuoteBlock<'src>) {
        let attribution = quote.attribution();
        let citetitle = quote.citetitle();

        if attribution.is_none() && citetitle.is_none() {
            return;
        }

        self.out.open("div", None, &["attribution"]);

        match (attribution, citetitle) {
            (Some(who), Some(what)) => {
                self.out.line(&format!("&#8212; {who}<br>"));
                self.out.line(&format!("<cite>{what}</cite>"));
            }

            (Some(who), None) => self.out.line(&format!("&#8212; {who}")),
            (None, Some(what)) => self.out.line(&format!("<cite>{what}</cite>")),
            (None, None) => unreachable!("guarded above"),
        }

        self.out.close("div");
    }

    /// `====` example, `****` sidebar and `--` open blocks — the three
    /// delimited forms whose content is itself a sequence of blocks.
    fn compound_delimited_block(
        &mut self,
        block: &'src Block<'src>,
        compound: &'src CompoundDelimitedBlock<'src>,
    ) {
        // A `--` block can be told to take another block's shape. The parser
        // routes most of those masquerades itself; the ones that arrive here
        // still wearing `Open` are handled below.
        let masquerade = match compound.context_kind() {
            CompoundDelimitedContext::Open => block.declared_style(),
            _ => None,
        };

        match (compound.context_kind(), masquerade) {
            (_, Some("sidebar")) | (CompoundDelimitedContext::Sidebar, _) => {
                self.sidebar_block(block, compound);
            }

            (_, Some("abstract")) => {
                // An abstract is set like a quotation rather than like an open
                // block, which is the one masquerade that reaches for a shape
                // no other style has.
                let classes = wrapper_classes(block, &["quoteblock", "abstract"]);
                let classes: Vec<&str> = classes.iter().map(String::as_str).collect();

                self.out.open("div", block.id(), &classes);
                self.block_title(block);
                self.out.line("<blockquote>");
                self.blocks(compound.child_blocks());
                self.out.line("</blockquote>");
                self.out.close("div");
            }

            (_, Some("example")) | (CompoundDelimitedContext::Example, _) => {
                // `%collapsible` turns an example into a disclosure widget, and
                // its title becomes the summary rather than a heading above it.
                if block.has_option("collapsible") {
                    // The `<details>` stands on its own: no `exampleblock`
                    // wrapper, so the block's id and roles land on it directly.
                    let open = if block.has_option("open") {
                        " open"
                    } else {
                        ""
                    };
                    let summary = block.title().unwrap_or("Details");
                    let roles = block.roles();

                    self.out
                        .line(&open_tag_with("details", block.id(), &roles, open));
                    self.out
                        .line(&format!("<summary class=\"title\">{summary}</summary>"));
                    self.out.open("div", None, &["content"]);
                    self.blocks(compound.child_blocks());
                    self.out.close("div");
                    self.out.line("</details>");
                    return;
                }

                self.open_wrapper(block, "exampleblock");
                self.block_title(block);
                self.out.open("div", None, &["content"]);
                self.blocks(compound.child_blocks());
                self.out.close("div");
                self.out.close("div");
            }

            _ => {
                // Any other style is a name the author gave this block, which
                // becomes a class on it: `[partintro]` and `[normal]` are the
                // ones AsciiDoc defines, and a stylesheet may know others.
                let classes =
                    wrapper_classes(block, &["openblock", masquerade.unwrap_or_default()]);
                let classes: Vec<&str> = classes.iter().map(String::as_str).collect();

                self.out.open("div", block.id(), &classes);
                self.block_title(block);
                self.out.open("div", None, &["content"]);
                self.blocks(compound.child_blocks());
                self.out.close("div");
                self.out.close("div");
            }
        }
    }

    /// `<div class="sidebarblock">`, whose title lives inside its content box
    /// rather than above it.
    fn sidebar_block(
        &mut self,
        block: &'src Block<'src>,
        compound: &'src CompoundDelimitedBlock<'src>,
    ) {
        self.open_wrapper(block, "sidebarblock");
        self.out.open("div", None, &["content"]);
        self.block_title(block);
        self.blocks(compound.child_blocks());
        self.out.close("div");
        self.out.close("div");
    }
}

/// The class list for a block wrapper: the context class first, then any roles
/// the author attached.
pub(super) fn wrapper_classes<'src>(block: &'src Block<'src>, shape: &[&str]) -> Vec<String> {
    let mut classes: Vec<String> = shape
        .iter()
        .filter(|class| !class.is_empty())
        .map(|class| (*class).to_string())
        .collect();

    // The author's roles come last, after every class the block's own shape
    // called for, which is the order Asciidoctor writes them in.
    classes.extend(block.roles().into_iter().map(str::to_string));
    classes
}

/// Turn escaped page text back into the source it was written as.
///
/// A converter needs what the author typed, and what reaches here has been
/// escaped for the page — which is the same thing a browser undoes when it
/// reads an element's text.
fn unescape(content: &str) -> String {
    content
        .replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&amp;", "&")
}

/// The `nowrap` class a `<pre>` carries when the block asked for it, ready to
/// be appended to a class list that already has something in it.
fn nowrap<'src>(block: &'src Block<'src>) -> &'static str {
    if block.has_option("nowrap") {
        " nowrap"
    } else {
        ""
    }
}

/// The whole `class` attribute for a `<pre>` that has no other class, or an
/// empty string when the block asked for nothing.
fn pre_class<'src>(block: &'src Block<'src>) -> &'static str {
    if block.has_option("nowrap") {
        concat!(" class=\"nowrap\"", " tabindex=\"0\"")
    } else {
        SCROLLS
    }
}

/// What a scrolling region needs to be reachable without a mouse.
///
/// A listing, a diagram and an equation all scroll sideways rather than running
/// off a narrow page, and a region that scrolls and holds nothing focusable is
/// one a keyboard cannot reach into. One tab stop is the price of the rest of
/// the line being readable.
const SCROLLS: &str = " tabindex=\"0\"";