adocers-html 0.3.2

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
//! The HTML5 back end for AsciiDoc.
//!
//! `asciidoc-parser` renders *inline* content — bold, links, cross-references,
//! passthroughs — but deliberately stops there: turning the block tree into a
//! page is the back end's job, and this crate is that back end. The markup it
//! emits follows Asciidoctor's HTML5 converter (the same wrapper `div`s and
//! class names), so stylesheets written for Asciidoctor apply unchanged.
//!
//! # A back end we could adopt instead
//!
//! [`asciidoc-html5`](https://github.com/asciidoc-rs/asciidoc-html5) is the
//! parser author's own HTML5 back end, and it covers what this crate covers:
//! rendered against `resources/showcase.adoc` the two agree on every wrapper
//! and class name, and on constructs the showcase leaves out — video, audio,
//! bibliographies, roles, hard breaks, passthroughs — they agree byte for byte.
//! Both are bounded by the same parser, so neither is ahead on coverage.
//!
//! Adopting it would mean giving up what this crate does *beyond* Asciidoctor,
//! with no supported way to add it back:
//!
//! - source blocks highlighted here rather than in the browser, which that
//!   crate rules out ("client-side syntax highlighters only");
//! - mermaid blocks turned into diagrams, which it renders as listings;
//! - admonitions marked with an icon rather than a label;
//! - the labelled document header.
//!
//! Its README also rules out an extension mechanism before 1.0, so hooking
//! those back in would mean rewriting its output rather than configuring it.
//!
//! It is worth revisiting if that changes — or if the long tail of Asciidoctor
//! fidelity becomes more work than it is worth. That tail is now measured
//! rather than guessed at: the workspace's `tests/doctest.rs` renders
//! Asciidoctor's own test corpus through this back end and compares the result
//! against Asciidoctor's, and `KNOWN_FAILURES` there is the whole of what does
//! not match yet.

#![warn(clippy::print_stderr, clippy::print_stdout)]

mod block;
mod callout;
mod copy;
mod css;
mod html;
mod reading;

#[cfg_attr(not(feature = "highlight"), path = "highlight_off.rs")]
mod highlight;
mod list;
#[cfg(feature = "math")]
mod math;
mod media;
mod table;
mod toc;

use asciidoc_parser::{
    Document,
    blocks::FindBlocks,
    document::{
        InterpretedValue,
        TocMode,
    },
};

use adocers_render_core::{
    metadata::{
        displayed_as,
        is_list,
        label_for,
    },
    numbering::Numbering,
};

use crate::html::Buffer;
pub use crate::html::{
    escape_attr,
    escape_text,
};

/// How the rendered body should be wrapped.
#[derive(Clone, Debug, Default)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "these mirror command line flags, and one field per flag is what reads clearly"
)]
pub struct Options {
    /// Emit only the body content, with no surrounding HTML page.
    pub fragment: bool,

    /// CSS to embed in the page, or `None` for an unstyled page.
    ///
    /// Ignored when [`fragment`](Self::fragment) is set, since a fragment has
    /// no `<head>` to put it in.
    pub stylesheet: Option<String>,

    /// Markup appended just before `</body>`, for scripts and the like.
    ///
    /// Ignored when [`fragment`](Self::fragment) is set, for the same reason.
    pub body_suffix: String,

    /// Whether an admonition is marked with an icon rather than its label.
    pub icons: bool,

    /// Whether a source block is syntax highlighted.
    ///
    /// A block still carries its `language-…` class either way, so a page can
    /// be highlighted in the browser instead.
    pub highlight: bool,

    /// Whether a mermaid block is drawn as a diagram, or left as the listing
    /// block it was written as.
    pub mermaid: bool,

    /// Whether an equation is converted to `MathML`, or left as the notation it
    /// was written in.
    pub math: bool,

    /// Whether a verbatim block is given a button that copies it to the
    /// clipboard.
    ///
    /// The button is added by a small script the page carries, so a
    /// [`fragment`](Self::fragment) never has one: the page it is embedded in
    /// owns what it loads.
    pub copy: bool,

    /// How deep the outline goes, overriding the document's `toclevels`.
    ///
    /// `None` leaves the depth to the document, which is what a standalone
    /// render wants. A host building a site has a site-wide default and its own
    /// name for the per-page override — Antora spells it `page-toclevels` —
    /// and has already resolved the two by the time it renders, so it says the
    /// answer rather than trying to write it back into the document.
    pub toc_levels: Option<usize>,

    /// Whether the outline marks the entry for the section being read.
    ///
    /// Beside a long document a docked outline can say where the reader is as
    /// well as what there is, which is the difference between a list of links
    /// and a sense of place. Like the copy button it is applied by a script the
    /// page carries, so a [`fragment`](Self::fragment) never has it and a page
    /// with scripting switched off still gets an outline that works.
    pub mark_reading: bool,
}

/// What a render produced.
#[derive(Clone, Debug)]
pub struct Rendered {
    /// The markup.
    pub html: String,

    /// The outline, as markup, or `None` when the document has no sections.
    ///
    /// This is handed over whether or not the document asked for an outline,
    /// because where one goes is not always the document's decision: a host
    /// laying out its own page may want the outline beside the article rather
    /// than in it, which is a placement no attribute can describe.
    ///
    /// It is the *same* markup [`html`](Self::html) carries when the document
    /// does ask for one — so a host that places this itself should unset `toc`,
    /// or the reader gets two. Unsetting it is the whole of what such a host
    /// has to do: the outline is still built, and still honours `toclevels` and
    /// `toc-title`.
    pub toc: Option<String>,
}

/// The stylesheet embedded in a standalone page when the caller names no other.
pub fn default_stylesheet() -> String {
    format!(
        "{}{}{}{}",
        css::VARIABLES,
        css::PAGE,
        css::TOC,
        css::DOCUMENT
    )
}

/// The custom properties the document rules — and every drawn diagram — read.
///
/// A host rendering a [`fragment`](Options::fragment) into a page of its own
/// needs these at the top level, unscoped. A diagram drawn by this crate
/// carries theme overrides written against them, looked up from inside the
/// `<svg>`: a property declared out of their reach is a property that does not
/// exist, and `fill: var(--code-bg)` resolving to nothing leaves the diagram a
/// set of solid black boxes.
pub fn stylesheet_variables() -> &'static str {
    css::VARIABLES
}

/// The rules for a document's own content, for a host that supplies the page.
///
/// Every selector is either a class this crate emits or an element inside a
/// document, so the whole block can be nested under wherever the host puts the
/// document and will reach nothing else:
///
/// ```text
/// article.doc {
///     /* adocers_html::document_stylesheet() */
/// }
/// ```
///
/// Taken together with [`stylesheet_variables`], this is what a host uses
/// instead of writing a stylesheet of its own that looks similar — and then
/// drifts.
pub fn document_stylesheet() -> &'static str {
    css::DOCUMENT
}

/// The rules for the outline, for a host that places one itself.
///
/// These are the entries' own look and nothing about where they sit: no
/// width, no docking, no column. A host that takes [`Rendered::toc`] and puts
/// it in a layout of its own wants exactly this much — the rest is the page's
/// business, and a host that has its own page has its own answer for it.
///
/// Unlike [`document_stylesheet`] these are *not* nested under wherever the
/// document goes: an outline placed beside the document is not inside it.
pub fn toc_stylesheet() -> &'static str {
    css::TOC
}

/// Render `document` to HTML.
pub fn render<'src>(document: &'src Document<'src>, options: &'src Options) -> Rendered {
    let mut renderer = Renderer {
        document,
        options,
        out: Buffer::new(),
        numbering: Numbering::of(document),
        figures: 0,
        toc_rendered: false,
        #[cfg(feature = "mermaid")]
        drawings: 0,
    };

    let body = renderer.body();

    // The parser marks an inline equation with the delimiters a typesetter used
    // to look for. Nothing looks for them now, so they are converted here, over
    // the whole body at once — an equation can sit in a paragraph, a heading, a
    // list item or a table cell, and this catches all of them in one place.
    let body = inline_equations(&body);

    let html = if options.fragment {
        body
    } else {
        document_page(document, options, &body)
    };

    Rendered {
        html,
        toc: renderer.outline(),
    }
}

/// Convert the inline equations in a rendered body.
#[cfg(feature = "math")]
fn inline_equations(body: &str) -> String {
    math::inline(body)
}

/// Leaves them as they are: no converter is compiled in.
#[cfg(not(feature = "math"))]
fn inline_equations(body: &str) -> String {
    body.to_string()
}

/// Walks the block tree, appending markup as it goes.
struct Renderer<'src> {
    /// The document being rendered; consulted for attributes and TOC settings.
    document: &'src Document<'src>,

    /// How the caller asked for the document to be rendered.
    options: &'src Options,

    /// Markup accumulated so far.
    out: Buffer,

    /// What each section shows in front of its title, worked out up front so
    /// the outline and the headings cannot disagree about it.
    numbering: Numbering,

    /// How many figures have been captioned, so each is numbered in turn.
    ///
    /// A picture and a drawn diagram share one sequence, which the parser
    /// cannot count for us: to it a diagram is a listing.
    figures: usize,

    /// Whether a `toc::[]` macro has already emitted the table of contents.
    ///
    /// Asciidoctor renders the macro form at most once; a second `toc::[]` is
    /// ignored rather than duplicating the whole outline.
    toc_rendered: bool,

    /// How many diagrams have been drawn, so each can be given a name of its
    /// own. Two elements on a page may not share an id.
    #[cfg(feature = "mermaid")]
    drawings: usize,
}

impl Renderer<'_> {
    /// Render the document header, body and footer into a single body fragment.
    ///
    /// An embedded fragment drops the page furniture — the `#header` and
    /// `#footer` wrappers and the `#content` div — because the page it is
    /// pasted into supplies its own, and a "Last updated" line belongs to a
    /// standalone document rather than to a fragment of one. This matches what
    /// Asciidoctor emits with `--no-header-footer`.
    fn body(&mut self) -> String {
        if self.options.fragment {
            // The document title is normally the host page's job, so it appears
            // only when the document asks for it with `:showtitle:`.
            if self.document.show_title(false) {
                self.doctitle();
            }

            if toc_precedes_content(self.document.toc_mode()) {
                self.toc();
            }

            self.content();
            self.footnotes();
        } else {
            self.header();

            // `<main>`, `<header>` and `<footer>` rather than Asciidoctor's
            // three `<div>`s: these are the page's landmarks, which an
            // assistive reader uses to move between the parts of a page instead
            // of through them. The ids are Asciidoctor's, so a stylesheet
            // written for it still finds every one of them.
            //
            // The footnotes belong to the content and are inside it, rather
            // than a fourth region belonging to nothing.
            self.out.open("main", Some("content"), &[]);
            self.content();
            self.footnotes();
            self.out.close("main");

            self.footer();
        }

        std::mem::replace(&mut self.out, Buffer::new()).finish()
    }

    /// Emit the document title as an `<h1>`, with its subtitle if it has one.
    fn doctitle(&mut self) {
        let Some(title) = self.document.doctitle() else {
            return;
        };

        // `doctitle` is the whole title, subtitle included, so a title split
        // into two parts has to be rebuilt from the parts — appending the
        // subtitle to the whole would say it twice.
        let heading = match (
            self.document.header().main_title(),
            self.document.subtitle(),
        ) {
            (Some(main), Some(subtitle)) => {
                format!("{main}: <span class=\"subtitle\">{subtitle}</span>")
            }

            _ => title.to_string(),
        };

        // Every part is already inline-rendered by the parser.
        self.out.line(&format!("<h1>{heading}</h1>"));
    }

    /// Render `#header`: the document title, author line and, for most TOC
    /// placements, the table of contents.
    fn header(&mut self) {
        let show_title = self.document.show_title(true) && self.document.doctitle().is_some();
        let details = self.details();
        let toc_in_header = toc_precedes_content(self.document.toc_mode());

        if !show_title && details.is_empty() && !toc_in_header {
            return;
        }

        self.out.open("header", Some("header"), &[]);

        if show_title {
            self.doctitle();
        }

        if !details.is_empty() {
            self.out.open("div", None, &["details"]);
            self.out.raw(&details);
            self.out.close("div");
        }

        if toc_in_header {
            self.toc();
        }

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

    /// The author and revision lines shown under the document title.
    ///
    /// Each is a labelled line — `Author: …`, `Version: …` — rather than the
    /// bare stack of values Asciidoctor emits, which leaves the reader to work
    /// out what a lone date on its own line is meant to be. The ids and classes
    /// are Asciidoctor's, so a stylesheet written for it still finds them.
    fn details(&self) -> String {
        let mut details = Buffer::new();

        if let Some(line) = self.authors() {
            details.raw(&line);
        }

        details.raw(&self.revision());

        details.raw(&self.metadata());

        // The remark describes the revision rather than naming part of it, so
        // it reads as its own sentence, set apart from the labels above.
        if let Some(remark) = self.attribute("revremark") {
            details.line(&format!(
                "<div class=\"remark\"><span id=\"revremark\">{}</span></div>",
                escape_text(&remark)
            ));
        }

        details.finish()
    }

    /// The `Author:` line, or `None` when the document names nobody.
    fn authors(&self) -> Option<String> {
        let authors = self.document.authors();

        if authors.is_empty() {
            return None;
        }

        let written: Vec<String> = authors
            .iter()
            .enumerate()
            .map(|(index, author)| {
                // Asciidoctor numbers every author after the first; the first
                // is plain `author`/`email` so existing
                // stylesheets keep working.
                let suffix = if index == 0 {
                    String::new()
                } else {
                    (index + 1).to_string()
                };

                let name = format!(
                    "<span id=\"author{suffix}\" class=\"author\">{}</span>",
                    escape_text(author.name())
                );

                // The angle brackets are the convention every reader already
                // knows from a commit or a mail header.
                match author.email() {
                    Some(email) => format!(
                        "{name} <span id=\"email{suffix}\" class=\"email\">&lt;<a \
                         href=\"mailto:{}\">{}</a>&gt;</span>",
                        escape_attr(email),
                        escape_text(email)
                    ),

                    None => name,
                }
            })
            .collect();

        let label = if written.len() == 1 {
            "Author"
        } else {
            "Authors"
        };

        Some(detail(label, &written.join(", ")))
    }

    /// The `Version:` and `Date:` lines.
    ///
    /// These read the attributes rather than the revision line, because an
    /// explicit `v1.0, 2026-09-10` line sets them too — so the two ways of
    /// writing a revision, the line and `:revnumber:`/`:revdate:`, are one case
    /// here rather than two. Either may appear without the other.
    fn revision(&self) -> String {
        let mut rows = String::new();

        if let Some(number) = self.attribute("revnumber") {
            rows.push_str(&detail(
                "Version",
                &format!("<span id=\"revnumber\">{}</span>", escape_text(&number)),
            ));
        }

        if let Some(date) = self.attribute("revdate") {
            rows.push_str(&detail(
                "Date",
                &format!("<span id=\"revdate\">{}</span>", escape_text(&date)),
            ));
        }

        rows
    }

    /// The rows for whatever else the header says about the document.
    ///
    /// A header holds two sorts of attribute: facts about the document, and
    /// instructions to the renderer. `:status:` is the first sort and
    /// `:sectnums:` the second, and only the first belongs in front of a
    /// reader — so this shows a known set of metadata names plus everything in
    /// Antora's `page-` namespace, which is defined as page metadata, and
    /// leaves every other attribute alone.
    fn metadata(&self) -> String {
        let mut rows = String::new();

        for attribute in self.document.header().attributes() {
            let name = attribute.name().data();

            let Some(shown) = displayed_as(name) else {
                continue;
            };

            // An attribute set without a value — `:sectnums:` — says something
            // to the renderer and nothing to a reader.
            let InterpretedValue::Value(value) = attribute.value() else {
                continue;
            };

            if value.is_empty() {
                continue;
            }

            rows.push_str(&detail(&label_for(shown), &value_for(shown, value)));
        }

        rows
    }

    /// Render every top-level block, honouring the TOC placements that fall
    /// inside the content area.
    fn content(&mut self) {
        let toc_mode = self.document.toc_mode();

        for block in self.document.child_blocks() {
            self.block(block);
        }

        if matches!(toc_mode, TocMode::Bottom) {
            self.toc();
        }
    }

    /// Render `#footnotes`: the definitions the `footnote:[]` references in the
    /// body link down to.
    ///
    /// The parser renders each reference as a link to `#_footnotedef_N`, so
    /// without this block every footnote in the document is a dead link.
    fn footnotes(&mut self) {
        let footnotes = self.document.catalog().footnotes();

        if footnotes.is_empty() {
            return;
        }

        self.out.open("div", Some("footnotes"), &[]);
        self.out.line("<hr>");

        for footnote in footnotes {
            let index = escape_attr(&footnote.index);

            // Written out rather than opened, because Asciidoctor puts the
            // class before the id here and nowhere else.
            self.out.line(&format!(
                "<div class=\"footnote\" id=\"_footnotedef_{index}\">"
            ));
            self.out.line(&format!(
                "<a href=\"#_footnoteref_{index}\">{}</a>. {}",
                escape_text(&footnote.index),
                footnote.text
            ));
            self.out.close("div");
        }

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

    /// Render `#footer`: the document's revision, then the date it was last
    /// modified, each on a line of its own.
    ///
    /// A document with neither has no footer at all.
    fn footer(&mut self) {
        if self.document.is_attribute_set("nofooter") {
            return;
        }

        let mut lines: Vec<String> = Vec::new();

        if let Some(number) = self.attribute("revnumber") {
            let label = self
                .attribute("version-label")
                .unwrap_or_else(|| "Version".to_string());

            lines.push(format!("{} {}", escape_text(&label), escape_text(&number)));
        }

        if let Some(date) = self
            .attribute("docdatetime")
            .or_else(|| self.attribute("localdatetime"))
        {
            let label = self
                .attribute("last-update-label")
                .unwrap_or_else(|| "Last updated".to_string());

            lines.push(format!("{} {}", escape_text(&label), escape_text(&date)));
        }

        if lines.is_empty() {
            return;
        }

        self.out.open("footer", Some("footer"), &[]);
        self.out.open("div", Some("footer-text"), &[]);
        self.out.line(&lines.join("<br>\n"));
        self.out.close("div");
        self.out.close("footer");
    }

    /// Render something into a buffer of its own and hand back the markup.
    ///
    /// Used where a wrapper should only be written once its contents turn out
    /// to be worth wrapping.
    pub(crate) fn aside(&mut self, render: impl FnOnce(&mut Self)) -> String {
        let outer = std::mem::replace(&mut self.out, Buffer::new());

        render(self);

        std::mem::replace(&mut self.out, outer).finish()
    }

    /// The value of a document attribute, if it is set to one.
    fn attribute(&self, name: &str) -> Option<String> {
        match self.document.attribute_value(name) {
            InterpretedValue::Value(value) => Some(value),
            _ => None,
        }
    }
}

/// One labelled line of the document header.
fn detail(label: &str, value: &str) -> String {
    format!("<div class=\"detail\"><span class=\"label\">{label}:</span> {value}</div>\n")
}

/// The markup for an attribute's value.
///
/// A list of tags, keywords or standards is a set of separate things that
/// happens to be written with commas, so each is shown as its own mark rather
/// than run together into a sentence.
fn value_for(name: &str, value: &str) -> String {
    if !is_list(name) {
        return escape_text(value);
    }

    value
        .split(',')
        .map(str::trim)
        .filter(|tag| !tag.is_empty())
        .map(|tag| format!("<span class=\"tag\">{}</span>", escape_text(tag)))
        .collect::<Vec<_>>()
        .join(" ")
}

/// Whether a TOC placement puts the outline above the document's content.
fn toc_precedes_content(mode: TocMode) -> bool {
    matches!(
        mode,
        TocMode::Auto | TocMode::Left | TocMode::Right | TocMode::Top
    )
}

/// Everything about a standalone page that is not its body markup.
///
/// This is public so that a caller which builds its own body — the server's
/// directory listing, say — can put it in the same page as a rendered document
/// and have it look the same.
#[derive(Clone, Debug, Default)]
pub struct Page<'a> {
    /// Value of the `lang` attribute on `<html>`.
    pub lang: &'a str,

    /// Plain-text `<title>`; markup here would be shown, not applied.
    pub title: &'a str,

    /// Value of the `description` meta tag, if there is one.
    pub description: Option<&'a str>,

    /// Class list for `<body>`.
    pub body_classes: &'a str,

    /// CSS to embed, or `None` for an unstyled page.
    pub stylesheet: Option<&'a str>,

    /// Markup appended just before `</body>`, for scripts and the like.
    pub body_suffix: &'a str,
}

/// Wrap body markup in a complete HTML page.
#[must_use]
pub fn page(page: &Page<'_>, body: &str) -> String {
    let mut out = Buffer::new();

    out.line("<!DOCTYPE html>");
    out.line(&format!("<html lang=\"{}\">", escape_attr(page.lang)));
    out.line("<head>");
    out.line("<meta charset=\"UTF-8\">");
    out.line("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
    out.line(&format!(
        "<meta name=\"generator\" content=\"adocers {}\">",
        env!("CARGO_PKG_VERSION")
    ));

    if let Some(description) = page.description {
        out.line(&format!(
            "<meta name=\"description\" content=\"{}\">",
            escape_attr(description)
        ));
    }

    out.line(&format!("<title>{}</title>", escape_text(page.title)));

    // A browser asks for `/favicon.ico` on every page whatever the document
    // says, and a rendered page rarely has one to give — leaving a 404 in the
    // console and a wasted request on every visit. Saying there is none is
    // quieter than letting it look for one.
    out.line("<link rel=\"icon\" href=\"data:,\">");

    if let Some(css) = page.stylesheet {
        out.line("<style>");
        out.line(css);
        out.line("</style>");
    }

    out.line("</head>");
    out.line(&format!(
        "<body class=\"{}\">",
        escape_attr(page.body_classes)
    ));
    out.raw(body);
    out.newline();

    if !page.body_suffix.is_empty() {
        out.line(page.body_suffix);
    }

    out.line("</body>");
    out.line("</html>");

    out.finish()
}

/// Wrap a rendered document's body in a page built from its own metadata.
fn document_page(document: &Document<'_>, options: &Options, body: &str) -> String {
    let lang = match document.attribute_value("lang") {
        InterpretedValue::Value(lang) => lang,
        _ => "en".to_string(),
    };

    let description = match document.attribute_value("description") {
        InterpretedValue::Value(description) => Some(description),
        _ => None,
    };

    // The `<title>` is plain text, so any markup the inline renderer produced
    // for the doctitle has to come back out.
    let title = document
        .doctitle_sanitized()
        .unwrap_or_else(|| "Untitled".to_string());

    // Diagrams are drawn here and equations are converted here, so nothing is
    // fetched by the page. The scripts it carries are its own — the copy
    // button's, and the outline's reading mark — and each only when there is
    // something for it to act on; after those comes whatever the caller asked
    // for.
    let mut body_suffix = String::new();

    if options.copy && copy::wanted(body) {
        body_suffix.push_str(copy::SCRIPT);
        body_suffix.push('\n');
    }

    if options.mark_reading && reading::wanted(body) {
        body_suffix.push_str(reading::SCRIPT);
        body_suffix.push('\n');
    }

    body_suffix.push_str(&options.body_suffix);

    page(
        &Page {
            lang: &lang,
            title: &title,
            description: description.as_deref(),
            body_classes: &body_classes(document),
            stylesheet: options.stylesheet.as_deref(),
            body_suffix: body_suffix.trim_end(),
        },
        body,
    )
}

/// The `<body>` class list, which is how Asciidoctor stylesheets learn where
/// the table of contents was placed.
fn body_classes(document: &Document<'_>) -> String {
    let mut classes = vec!["article".to_string()];

    match document.toc_mode() {
        TocMode::Left => {
            classes.push("toc2".to_string());
            classes.push("toc-left".to_string());
        }

        TocMode::Right => {
            classes.push("toc2".to_string());
            classes.push("toc-right".to_string());
        }

        _ => {}
    }

    classes.join(" ")
}

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

    #[test]
    fn a_setting_is_not_shown_to_the_reader() {
        for name in [
            "sectnums",
            "icons",
            "toc",
            "source-highlighter",
            "experimental",
            "description",
            "revnumber",
            "author",
            "page-",
        ] {
            assert_eq!(displayed_as(name), None, "`{name}` should not be shown");
        }
    }

    #[test]
    fn a_fact_about_the_document_is() {
        assert_eq!(displayed_as("status"), Some("status"));
        assert_eq!(displayed_as("keywords"), Some("keywords"));
        assert_eq!(displayed_as("page-tags"), Some("tags"));
        assert_eq!(displayed_as("page-last-reviewed"), Some("last-reviewed"));
    }

    #[test]
    fn what_a_review_and_its_findings_say_about_themselves_is() {
        for name in [
            "date",
            "fixed-point",
            "head",
            "diff",
            "spec",
            "standards",
            "findings",
            "axis",
            "severity",
            "kind",
            "where",
            "source",
        ] {
            assert_eq!(displayed_as(name), Some(name), "`{name}` should be shown");
        }
    }

    #[test]
    fn a_list_of_standards_becomes_separate_marks() {
        let markup = value_for("standards", "AGENTS.md, docs/adr/0001..0009");

        assert_eq!(markup.matches("class=\"tag\"").count(), 2);
        assert!(markup.contains(">AGENTS.md<"));
        assert!(markup.contains(">docs/adr/0001..0009<"));
    }

    #[test]
    fn a_label_reads_as_a_phrase() {
        assert_eq!(label_for("status"), "Status");
        assert_eq!(label_for("last-reviewed"), "Last reviewed");
        assert_eq!(label_for("tags"), "Tags");
    }

    #[test]
    fn a_list_of_tags_becomes_separate_marks() {
        let markup = value_for("tags", "design, flux , ci,,");

        assert_eq!(markup.matches("class=\"tag\"").count(), 3);
        assert!(markup.contains(">design<"));
        assert!(markup.contains(">flux<"));
    }

    #[test]
    fn any_other_value_is_plain_escaped_text() {
        assert_eq!(value_for("status", "in <review>"), "in &lt;review&gt;");
        assert_eq!(value_for("status", "a, b"), "a, b");
    }
}