Skip to main content

flm_core/stdlib/features/xnotes/
mod.rs

1//! The `xnotes` feature: footnotes, and the other kinds of note set apart
2//! from the running text, written `\footnote{…}` by default.
3//!
4//! The guide to the language describes these notes for authors
5//! ([xnotes](crate::guide::language_syntax#xnotes)).
6//!
7//! # Xnotes and xnote kinds
8//!
9//! An **xnote** is a piece of text set apart from the running text, marked
10//! where it belongs and shown elsewhere or in place (a footnote, an endnote,
11//! a side note); an **xnote kind** is one way of being an xnote, declared by
12//! the feature's configuration. (The word is made up: "note" alone says too
13//! little, and "footnote" or "endnote" each describe one place where the note
14//! is shown; the *x* stands for *foot*, *end*, *side*.) The footnotes written
15//! `\footnote{…}` are one xnote kind; a host adds others, such as endnotes or
16//! side notes, through the configuration, and another feature may contribute
17//! an xnote kind for the notes its own elements carry. The configuration,
18//! [`XnotesConfig`], lists the xnote kinds an author writes, each an
19//! [`XnoteKind`]; the default configuration lists one, `footnote`.
20//!
21//! # What an author writes
22//!
23//! ```text
24//! The claim holds in every case.\footnote{Except the empty one, which we
25//! exclude by convention.} The next sentence goes on.
26//!
27//! A note holding paragraphs.\footnote{The first paragraph of the note.
28//!
29//!   The second paragraph.}
30//!
31//! A labeled note.\footnote[\label{fn:appendix}]{See the appendix.}
32//! See \ref{fn:appendix}, or \ref[noprefix]{fn:appendix}.
33//! ```
34//!
35//! An xnote is written `\<command>[<labels>]{<content>}`, where `<command>`
36//! is one of the commands of its xnote kind ([`XnoteKind::commands`]). The
37//! content is inline content when it is written as one run of text, and
38//! paragraphs when it holds a blank line or a block such as a list; the xnote
39//! kind's [`layout`](XnoteKind::layout) may fix one of the two.
40//!
41//! The optional argument holds the xnote's labels, `\label{fn:…}`, as many
42//! as the author wants, and nothing else. A
43//! [label](crate::guide::concepts_overview#reference-points-labels-and-anchors)
44//! is the text an author writes as `\label{type:label}` to refer to a place
45//! from elsewhere. Anything else written in the optional argument is reported
46//! ([`BadLabelArgument`]; [`labels_of`] reads the argument), and the labels
47//! written beside it still label the xnote. `\label` can be written in that
48//! argument because the argument's declaration refers to the references
49//! feature's scoped package
50//! [`flm.refs.label`](crate::stdlib::features::refs::LABEL_PACKAGE): a
51//! scoped package ([`ScopedPackageDef`](crate::lang::mint::ScopedPackageDef))
52//! is a set of element declarations that can be written only inside the
53//! environment bodies and arguments whose declarations refer to it. A
54//! `\label` written after the xnote, as in `\footnote{…}\label{fn:x}`, is
55//! therefore an unknown command, as it is in running text. The label type
56//! (the part before the colon) must be the xnote kind's
57//! [`label_type`](XnoteKind::label_type), `fn` for footnotes; the references
58//! feature reports any other label type (`flm.refs.label-type-not-accepted`).
59//!
60//! An xnote may be written wherever inline content may be written: in a
61//! paragraph, a heading's title, a list item, a `\text{…}` inside a formula,
62//! the template of a user definition. Its commands are available in text
63//! mode only, so a `\footnote` written directly in a formula is not an xnote:
64//! it is passed to the formula renderer with the rest of the formula. An
65//! xnote may be written inside another xnote's content, of its own xnote kind
66//! or of another. It is then an xnote like any other: numbered, labeled and
67//! listed in its xnote kind's list in document order, its mark placed where
68//! it is written, inside the outer xnote's content. The `xnotes` feature
69//! refuses no position; a feature that contributes an xnote kind and does not
70//! accept its xnotes in some positions (inside another xnote, for instance)
71//! reports them itself.
72//!
73//! # Where an xnote is shown
74//!
75//! The [`placement`](XnoteKind::placement) of an xnote kind
76//! ([`XnotePlacement`]) says where its xnotes are shown:
77//!
78//! - A **listed** xnote leaves its **xnote mark** where it is written: a
79//!   superscript (the xnote's number, for a numbered xnote kind) linked to the
80//!   xnote. Its content is shown in the xnote kind's **list**, placed after
81//!   the document's content. A listed xnote is inline content attached to the
82//!   word before it: a space written before `\footnote` is removed.
83//! - An **in-place** xnote is shown where it is written, in brackets, with its
84//!   mark at the head: as inline content where its content is inline, and as
85//!   a block of its own where its content holds paragraphs. Such a block ends
86//!   the paragraph it is written in, as a list does, and the text after it is
87//!   a new paragraph.
88//!
89//! The block-structure pass ([`crate::lang::rewrites::blocks`]) decides
90//! whether an in-place xnote is a block, from the xnote kind and the node
91//! ([`argument_holds_blocks`]), before the document's trees are frozen (no
92//! longer changed; see [frozen
93//! trees](crate::guide::concepts_overview#frozen-trees-and-computed-data)). The
94//! placement is therefore part of the configuration, fixed when the registry
95//! is built, and no render request can change it.
96//!
97//! The first xnote of the example above prints, on the plain-text output:
98//!
99//! ```text
100//! The claim holds in every case.¹ The next sentence goes on.
101//!
102//! Footnotes
103//! ---------
104//!
105//! ¹ Except the empty one, which we exclude by convention.
106//! ```
107//!
108//! The general rules ([`XnoteRule`], [`ListRule`]) state the shapes that the
109//! plain-text output receives and that the HTML rules build on; [`html`] and [`latex`] state what the HTML page and the
110//! recomposed LaTeX write; the rendering guide shows the printed results
111//! ([Xnotes](crate::guide::rendering#xnotes)).
112//!
113//! # What the feature registers
114//!
115//! The `xnotes` feature ([`XnotesFeature`], an
116//! [`FlmFeature`]) registers, from its
117//! configuration:
118//!
119//! - **The elements.** One element value of [`XNOTE`] (`flm.xnotes.xnote`)
120//!   per configured xnote kind that has commands, carrying an
121//!   [`XnoteElement`]; and four synthesized elements, which no document can
122//!   write: the list of each xnote kind ([`list_element_name`],
123//!   `flm.xnotes.<kind>.list`), an entry of a list ([`ENTRY`]), the content
124//!   pointer an entry holds ([`CONTENT_POINTER`]), and the node that
125//!   represents an xnote in content shown again ([`MARK_OF`]).
126//! - **The service slot of xnote kinds**, [`KINDS_SLOT`] (`flm.xnotes.kinds`,
127//!   declared with
128//!   [`service_slot`](crate::core::registry::FeatureBuilder::service_slot)),
129//!   which holds every xnote kind of the registry, in order. A service slot
130//!   is the declaration, by the feature that owns an interaction, of a dotted
131//!   name, the type of the values the slot takes and its arity; any feature
132//!   may contribute a value to it ([`crate::core::services`]). The feature
133//!   contributes its configured xnote kinds; another feature contributes an
134//!   xnote kind of its own through [`contribute_kind`], the function that
135//!   makes every declaration an xnote kind needs.
136//! - **The table of xnotes**, [`XNOTES`] (`flm.xnotes`, an [`Xnotes`]): every
137//!   xnote of the document, by xnote kind, in document order. The **collect
138//!   stage**, [`COLLECT`] (`flm.xnotes.collect`), writes it from the table of
139//!   reference points. It finds xnotes by the reference kind of their points,
140//!   never by element, so the xnotes of a kind another feature contributes are
141//!   collected like `\footnote` (see [`XnoteSource`]).
142//! - **The list of each xnote kind.** A *piece*, a document-level
143//!   [synthesized value](crate::guide::concepts_overview#synthesized-values)
144//!   that a backend places beside the document's content
145//!   ([`Piece`]), held in the table
146//!   `flm.xnotes.list.<kind>` ([`piece_table`]) and built by the stage
147//!   `flm.xnotes.build-list.<kind>` ([`ListBuilder`]); it is declared to the
148//!   `pieces` feature as placed after the content and on by default.
149//!   The documentation of [`contribute_kind`] lists every declaration made
150//!   for a list.
151//! - **For a numbered xnote kind, a counter and two counter styles**, declared
152//!   to the numbering feature (see [Numbers, references and
153//!   anchors](#numbers-references-and-anchors) below).
154//! - **The lowering rules.** A lowering rule
155//!   ([`LoweringRule`]) is written for
156//!   one element and stages (builds into the lowered tree; see
157//!   [`Lowerer`](crate::core::lowering::Lowerer)) its presentation for the
158//!   backend being rendered; its default mark says on which backends it is
159//!   chosen. The general rules are marked default on every backend; a
160//!   backend with a rule of its own marked default there uses that rule
161//!   instead ([`SelectedRules`](crate::core::plan::SelectedRules) states the
162//!   rule selection order). The general rules, which a backend uses for
163//!   every element that has no rule of its own there:
164//!   - [`XNOTE_RULE`] ([`XnoteRule`]): an xnote becomes its mark for a listed
165//!     xnote kind, and the bracketed xnote for an in-place one;
166//!   - `flm.xnotes.<kind>.list.lower.default` ([`ListRule`], one per xnote
167//!     kind): the list becomes a block holding the title as a heading and a
168//!     labeled list, one entry per xnote, labeled with its mark;
169//!   - [`POINTER_RULE`] ([`PointerRule`]): a content pointer becomes the
170//!     content it refers to;
171//!   - [`MARK_OF_RULE`] ([`MarkOfRule`]): the node representing an xnote in
172//!     content shown again becomes the xnote's mark;
173//!   - [`ENTRY_RULE`] ([`EntryRule`]): an entry outside its list becomes
174//!     nothing and is reported.
175//!
176//!   The plain-text backend uses the general rules only. The `html` backend
177//!   has rules of its own for the xnote and the list ([`html`]), which write
178//!   the same shapes with no bracket text and with a link back from each
179//!   entry to its mark. The `latex-recomposed` backend has rules of its own
180//!   for every element but the entry ([`latex`]): an xnote becomes the
181//!   command `\flmXN<kind>`, and the list, the content pointer and the node
182//!   representing an xnote in content shown again become nothing.
183//! - **The stylesheet** [`STYLE`] (`flm.xnotes.style`) of the HTML page
184//!   ([`html::stylesheet`]).
185//! - **The settings**: the fields of [`XnotesConfig`] written as data, one
186//!   entry per xnote kind under the settings key `kinds`, keyed by the xnote
187//!   kind's name ([`crate::core::settings`]).
188//!
189//! The [standard features](crate::stdlib::add_features) include the feature,
190//! with the configuration
191//! [`StdlibConfig::xnotes`](crate::stdlib::StdlibConfig::xnotes).
192//!
193//! # Numbers, references and anchors
194//!
195//! Each xnote has two reference points
196//! ([`RefPoint`]): places in the document
197//! that can be referred to, numbered, or given an anchor, the identifier a
198//! link points at (see [reference points, labels and
199//! anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)).
200//! [`ref_points`] returns the two:
201//!
202//! - **The xnote's own point**, whose reference kind is the xnote kind's name
203//!   (`footnote`), carrying the xnote's labels. The xnote of a numbered xnote
204//!   kind counts in the kind's counter, `flm.xnotes.<kind>`, which the
205//!   [`numbering`](crate::stdlib::features::numbering) feature counts; its
206//!   anchor is built from its number (`fn-1`, or `fn-2-1` for a kind numbered
207//!   within sections), a `\ref` to it prints the kind's word and the number
208//!   (`Footnote 1`), and `\ref[noprefix]` prints the number alone (`1`). The
209//!   xnote of an unnumbered xnote kind takes its first label as its anchor,
210//!   or else an anchor built from its position (`sn--1kzmq`); a `\ref` to it
211//!   prints its content where the content is inline, and otherwise prints the
212//!   label and is reported
213//!   ([`NothingToShow`](crate::stdlib::features::refs::NothingToShow)).
214//! - **The mark's point**, of the reference kind `<kind>-mark`
215//!   (`footnote-mark`), which accepts no label and always takes an anchor
216//!   built from its position (`fnref--1kzmq`): the place in the running text
217//!   that the entry of a listed xnote links back to.
218//!
219//! The references feature's anchors stage computes the anchors (the table
220//! [`ANCHORS`](crate::stdlib::features::refs::ANCHORS)), and the numbering
221//! feature the numbers (the counter table
222//! [`COUNTERS`]), as for every
223//! reference point; the `xnotes` feature computes neither and stores nothing
224//! derived from them.
225//!
226//! A counter is a dotted name under which things are counted in document
227//! order, and a counter style says how a counter value is shown (see
228//! [counters and counter
229//! styles](crate::guide::concepts_overview#counters-and-counter-styles)). A
230//! numbered xnote kind declares its counter ([`counter_name`]) and two counter
231//! styles to the numbering feature, as peer contributions to that feature's
232//! service slots (a peer contribution is dropped, with one Note, when the
233//! feature that owns the slot is not registered): the reference style
234//! `flm.xnotes.style.<kind>` ([`style_name`]: the xnote kind's words and
235//! number format), and the mark style `flm.xnotes.style.<kind>.mark`
236//! ([`mark_style_name`]: the xnote kind's mark template), which a host
237//! replaces like any declared counter style. In a registry without the
238//! numbering feature, the xnotes of a numbered kind have no number: a
239//! reference prints the label, and the collect stage reports [`NoNumbering`]
240//! once per xnote kind. An unnumbered xnote kind declares nothing to the
241//! numbering feature.
242//!
243//! # Xnotes in content shown again
244//!
245//! Content that is shown a second time, away from where it is written (a
246//! heading's title that a reference prints, an unnumbered float's caption, a
247//! defined term, a list item's tag), holds no xnote. When such content is
248//! copied to be shown again, the xnote's element replaces the xnote in the
249//! copy, through its [`InCopy`] aspect, by a
250//! node of the element [`MARK_OF`] ([`MarkOf`], [`copied_as`]), which
251//! [`MarkOfRule`] writes as the xnote's mark, linked to the xnote and with no
252//! anchor of its own (and as the marks of every xnote of a node that carries
253//! several). The xnote itself is shown, listed and reported only where it is
254//! written.
255//!
256//! # Xnotes carried by another feature's element
257//!
258//! An element of another feature can carry xnotes (for instance an element
259//! one of whose arguments is a note). Four things make a node an xnote, and
260//! the author's `\footnote` goes through the same four:
261//!
262//! 1. its xnote kind, contributed through [`contribute_kind`] (a kind with no
263//!    command, since only the `xnotes` feature declares commands);
264//! 2. the element's [`Referenceable`]
265//!    aspect, returning the two points of [`ref_points`] per xnote;
266//! 3. the element's [`XnoteSource`] aspect, returning per xnote the region of
267//!    the node that holds its content;
268//! 4. the element's [`ApartFromText`]
269//!    aspect, including those regions ([`regions_apart_from_text`]).
270//!
271//! The element's lowering rules write each xnote with the public staging
272//! helpers, so that it is written as `\footnote` is: [`stage_mark`] for a
273//! listed xnote kind, [`stage_in_place`] for an in-place one, [`stage_latex`]
274//! on the recomposed LaTeX. Each helper reads the table of xnotes by the
275//! node's address and writes one xnote, identified by its position among the
276//! node's xnotes of its kind; [`XnoteSource`] states how a node's xnotes are
277//! paired with their contents. The element's [`InCopy`]
278//! aspect returns [`copied_as`], so that its xnotes are shown in a copy as
279//! `\footnote`'s are.
280//!
281//! # Interactions with other features
282//!
283//! - **`numbering`** numbers the xnotes of numbered kinds. Without it, those
284//!   xnotes have no number, and [`NoNumbering`] is reported.
285//! - **`refs`** declares `\label` and computes the anchors. Without it, the
286//!   optional argument accepts no `\label`: every `\label` written there is
287//!   refused like any other content (the first refused item of each xnote is
288//!   reported as [`BadLabelArgument`]), and the marks carry no link and the
289//!   entries no link back.
290//! - **`refpoints`** writes the table of reference points
291//!   ([`REFPOINTS`](crate::stdlib::features::refpoints::REFPOINTS)) from
292//!   which the collect stage finds the xnotes.
293//! - **`pieces`** declares the service slot the lists are declared to.
294//!   Without it, no backend places a list. A render leaves one xnote kind's
295//!   list out through the render options
296//!   [`PiecesRenderOptions`](crate::stdlib::backends::pieces::PiecesRenderOptions),
297//!   with the piece's name `flm.xnotes.list.<kind>`.
298//! - **`lowering`, `html`, `latex` and `latex-recomposed`** own the
299//!   presentation elements, the backends and the LaTeX constructs the rules
300//!   use, and `numbering` and `refs` own the tables the rules read. The
301//!   feature declares each name it uses with a peer declaration
302//!   ([`PeerName`](crate::core::registry::PeerName)), so that it builds in a
303//!   registry without those features: a rule that produces a presentation
304//!   element or is the default on a backend that nobody declares is set
305//!   aside (excluded from rule selection; see
306//!   [`PeerName`](crate::core::registry::PeerName)), and a rule that reads a
307//!   table optionally runs and finds the table absent.
308//!
309//! # Diagnostics
310//!
311//! Every condition is reported under `flm.xnotes.*`, and the documentation
312//! of each states what the feature does after reporting it:
313//! [`BadLabelArgument`], [`NoNumbering`], [`Empty`], [`PointerRefused`],
314//! [`EntryOutsideList`], [`Unpaired`], and [`StageFailed`] (a stage of the
315//! feature could not read or write a table it declared).
316//!
317//! # Map of the items
318//!
319//! - Configuration: [`XnotesConfig`], [`XnoteKind`], [`XnotePlacement`];
320//!   [`XnotesFeature`] and [`feature`].
321//! - Names: [`FEATURE`], [`XNOTE`], [`LABELS_ARG`], [`XNOTE_ARG`],
322//!   [`ENTRY`], [`CONTENT_POINTER`], [`MARK_OF`], [`KINDS_SLOT`],
323//!   [`COLLECT`], [`STYLE`], the rule names [`XNOTE_RULE`], [`ENTRY_RULE`],
324//!   [`POINTER_RULE`], [`MARK_OF_RULE`], the roles and kind tokens
325//!   [`MARK_ROLE`], [`INPLACE_ROLE`], [`ENTRY_MARK_ROLE`], [`KIND_XNOTES`],
326//!   [`LINK_KIND`], [`BACKLINK_KIND`]; the heading name [`TITLE_HEADING`];
327//!   the names per xnote
328//!   kind [`list_element_name`], [`piece_name`], [`piece_table`],
329//!   [`builder_name`], [`counter_name`], [`style_name`],
330//!   [`mark_style_name`], [`list_rule_name`].
331//! - The element and its aspects: [`XnoteElement`], [`XnotesListElement`],
332//!   [`XnoteSource`], [`XnoteOf`], [`ref_points`],
333//!   [`regions_apart_from_text`], [`labels_of`] and [`Rejected`],
334//!   [`MarkOf`] and [`copied_as`].
335//! - Declaring an xnote kind: [`contribute_kind`].
336//! - The table and the stages: [`XNOTES`], [`Xnotes`], [`XnoteRecord`],
337//!   [`ListBuilder`].
338//! - Lowering: the rules [`XnoteRule`], [`ListRule`], [`PointerRule`],
339//!   [`MarkOfRule`], [`EntryRule`]; the staging helpers [`stage_mark`],
340//!   [`stage_in_place`], [`stage_mark_text`], [`append_to_last_paragraph`],
341//!   [`Brackets`]; the backends' rules in [`html`], [`latex`]
342//!   ([`stage_latex`]) and [`latex_rendered`], which also holds the
343//!   definition piece of the rendered LaTeX.
344//! - Diagnostics: [`BadLabelArgument`], [`NoNumbering`], [`Empty`],
345//!   [`PointerRefused`], [`EntryOutsideList`], [`Unpaired`],
346//!   [`StageFailed`].
347
348mod config;
349mod diagnostics;
350mod kinds;
351mod labels;
352mod list;
353mod lower;
354mod mark_of;
355mod marks;
356mod pointer;
357mod stages;
358pub mod html;
359pub mod latex;
360pub mod latex_rendered;
361
362use std::sync::Arc;
363
364use techy::core::node::NodeRef;
365
366use crate::core::settings::SettingsDecl;
367use crate::core::data::table::TableHandle;
368use crate::core::lowering::{DefaultMark, LoweringDecl, LoweringRule, NodeRegion};
369use crate::core::piece::Piece;
370use crate::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature};
371use crate::lang::mint::{ArgDef, ElementDef, SyntaxDef};
372use crate::lang::rewrites::blocks::argument_holds_blocks;
373use crate::lang::Flm;
374use crate::model::aspects::{
375    AcceptedRefTypes, AnchorPolicy, ApartFromText, BlockRole, BlockRoleAspect, ContentRef, FixedBlockRole,
376    InCopy, InlineSpacing, NumberSource, RefPoint, Referenceable,
377};
378use crate::model::element::ElementSpec;
379use crate::model::names::{ElementName, Name, RefKind, StageName};
380use crate::stdlib::backends::pres;
381use crate::stdlib::features::numbering::COUNTERS;
382use crate::stdlib::features::refs::{self, LabelUse};
383
384pub use config::{XnoteKind, XnotePlacement, XnotesConfig};
385pub use diagnostics::{
386    BadLabelArgument, Empty, EntryOutsideList, NoNumbering, PointerRefused, Unpaired,
387};
388pub use kinds::contribute_kind;
389pub use labels::{labels_of, Rejected};
390pub use list::{list_rule_name, ListRule, TITLE_HEADING};
391pub use lower::{
392    append_to_last_paragraph, stage_in_place, stage_mark, stage_mark_text, Brackets, EntryRule,
393    XnoteRule,
394};
395pub use mark_of::{copied_as, MarkOf, MarkOfRule};
396pub use pointer::PointerRule;
397pub use stages::{ListBuilder, StageFailed, XnoteRecord, Xnotes, XNOTES};
398pub use latex::stage_latex;
399
400/// The feature's registered name, `xnotes`.
401pub const FEATURE: &str = "xnotes";
402
403/// The declaration of the feature's settings: the fields of [`XnotesConfig`]
404/// are its settings keys, and each xnote kind is one entry of the map `kinds`,
405/// keyed by its name. See [`crate::core::settings`].
406fn settings() -> SettingsDecl {
407    SettingsDecl::new(FEATURE)
408        .config::<XnotesConfig>(
409            "The kinds of xnote (notes set apart from the running text, such as footnotes): \
410            for each kind, its commands, the words a reference writes, its label type, whether \
411            it is numbered, its number and mark templates, where its notes are shown, how its \
412            content is laid out, the title of its list, the text of the link back to the mark \
413            and the LaTeX command it is handed to. Fixed when the registry is built: it cannot \
414            vary per document or per render.",
415        )
416        .merge_entries("kinds", || crate::core::settings::named::to_data(&XnotesConfig::default().kinds, "name"))
417        .remove_false("kinds")
418        .markup("kinds.*.words")
419        .markup("kinds.*.title")
420        .markup("kinds.*.backlink")
421        .markup("kinds.*.number_format")
422        .markup("kinds.*.mark")
423        .markup("kinds.*.within.joiner.joined")
424        .markup("kinds.*.within.joiner.template")
425}
426
427/// The name of the element of an xnote an author writes, `flm.xnotes.xnote`:
428/// one element value per configured xnote kind that has commands, each
429/// carrying an [`XnoteElement`].
430pub const XNOTE: &str = "flm.xnotes.xnote";
431
432/// The name of an xnote's optional argument, `labels`, which holds the
433/// `\label{…}` commands that label the xnote ([`labels_of`] reads them).
434pub const LABELS_ARG: &str = "labels";
435
436/// The name of an xnote's mandatory argument, `xnote`, which holds the
437/// xnote's content.
438pub const XNOTE_ARG: &str = "xnote";
439
440/// The name of the element of one entry of a list of xnotes,
441/// `flm.xnotes.entry`: a synthesized element, which no document can write,
442/// with one element value. [`ListBuilder`] creates one entry per xnote.
443pub const ENTRY: &str = "flm.xnotes.entry";
444
445/// The name of the element of a content pointer, `flm.xnotes.content-pointer`:
446/// a synthesized element, which no document can write, with one element
447/// value.
448///
449/// A node of this element is placed in an entry of a list of xnotes, in the
450/// place of the xnote's content. It carries a
451/// [`ContentPointer`](crate::stdlib::backends::lowering::ContentPointer): the
452/// payload of a synthesized node that shows, where the node is placed,
453/// content written elsewhere in the tree without copying it, here the address
454/// of the node carrying the xnote and the region of that node that holds the
455/// content. The list shows the content by lowering that region where the
456/// pointer is placed ([`PointerRule`], [`ListRule`]).
457pub const CONTENT_POINTER: &str = "flm.xnotes.content-pointer";
458
459/// The name of the element of the node that represents an xnote in content
460/// shown again, `flm.xnotes.mark-of`: a synthesized element, which no
461/// document can write, with one element value.
462///
463/// When content is copied to be shown again (a heading's title that a
464/// reference prints), the copy holds a node of this element in the place of
465/// each node carrying xnotes: the [`InCopy`] aspect of [`XnoteElement`], and
466/// of any element that implements it with [`copied_as`], returns it. The node
467/// has no children and carries a [`MarkOf`], which identifies the xnotes it
468/// represents; [`MarkOfRule`] writes it as their marks.
469pub const MARK_OF: &str = "flm.xnotes.mark-of";
470
471/// The name of the general lowering rule of the element [`MARK_OF`],
472/// `flm.xnotes.mark-of.lower.default` ([`MarkOfRule`]): the node becomes the
473/// mark of each xnote it represents, linked to the xnote, with no anchor.
474pub const MARK_OF_RULE: &str = "flm.xnotes.mark-of.lower.default";
475
476/// The name of the general lowering rule of the element [`CONTENT_POINTER`],
477/// `flm.xnotes.content-pointer.lower.default` ([`PointerRule`]): the pointer
478/// becomes the content it refers to, lowered where the pointer is placed.
479pub const POINTER_RULE: &str = "flm.xnotes.content-pointer.lower.default";
480
481/// The name of the service slot of xnote kinds, `flm.xnotes.kinds`: it holds
482/// every xnote kind of the registry, in order, each an [`XnoteKind`].
483///
484/// The `xnotes` feature declares the slot (any number of values, in
485/// contribution order) and contributes its configured kinds;
486/// [`contribute_kind`] contributes any other ([`crate::core::services`]
487/// describes service slots). The collect stage reads it, and so does a build
488/// hook of the feature that compiles, once the registry is built, the mark of
489/// every unnumbered xnote kind (its [`mark`](XnoteKind::mark) template, which
490/// holds no number and so writes the same text beside every xnote).
491pub const KINDS_SLOT: &str = "flm.xnotes.kinds";
492
493/// The name of the collect stage, `flm.xnotes.collect`, which writes the table
494/// [`XNOTES`] (see [`Xnotes`] for what it records).
495pub const COLLECT: &str = "flm.xnotes.collect";
496
497/// The role of the superscript span around an xnote's mark in the running
498/// text, `flm.xnotes.xnote.mark`.
499pub const MARK_ROLE: &str = "flm.xnotes.xnote.mark";
500
501/// The role of the span or the block holding an in-place xnote,
502/// `flm.xnotes.xnote.inplace`.
503pub const INPLACE_ROLE: &str = "flm.xnotes.xnote.inplace";
504
505/// The role of the mark beside an entry of a list of xnotes,
506/// `flm.xnotes.entry.mark`.
507pub const ENTRY_MARK_ROLE: &str = "flm.xnotes.entry.mark";
508
509/// The kind token `xnotes`, carried by the block holding a list of xnotes, by
510/// the presentation list inside it and by an in-place xnote; the xnote kind's
511/// name is the kind token after it. (A kind token is a feature-owned name on a
512/// presentation payload that a stylesheet or a lowering rule selects on; see
513/// [`pres::payload`].)
514pub const KIND_XNOTES: &str = "xnotes";
515
516/// The kind token of the link from a mark to its xnote, `xnote`.
517pub const LINK_KIND: &str = "xnote";
518
519/// The kind token of the link from the entry of a listed xnote back to its
520/// mark, `xnote-back` (written on the HTML page only; see [`html`]).
521pub const BACKLINK_KIND: &str = "xnote-back";
522
523/// The feature's style identifier, `flm.xnotes.style`, which the lowering of
524/// an xnote and of a list of xnotes requires on every backend but the
525/// recomposed LaTeX: the stylesheet [`html::stylesheet`] on the HTML page.
526pub const STYLE: &str = "flm.xnotes.style";
527
528/// The name of the general lowering rule of the element [`XNOTE`],
529/// `flm.xnotes.xnote.lower.default` ([`XnoteRule`]): an xnote becomes its
530/// mark for a listed xnote kind, and the xnote in place for an in-place one.
531pub const XNOTE_RULE: &str = "flm.xnotes.xnote.lower.default";
532
533/// The name of the lowering rule of the element [`ENTRY`],
534/// `flm.xnotes.entry.lower.default` ([`EntryRule`]): an entry lowered outside
535/// its list becomes nothing and is reported.
536pub const ENTRY_RULE: &str = "flm.xnotes.entry.lower.default";
537
538/// The name of the list element of the xnote kind `kind`,
539/// `flm.xnotes.<kind>.list`: a synthesized element, which no document can
540/// write, with one element value per xnote kind, carrying an
541/// [`XnotesListElement`].
542pub fn list_element_name(kind: &str) -> ElementName {
543    ElementName::from(format!("flm.xnotes.{kind}.list"))
544}
545
546/// The name of the piece holding the list of the xnote kind `kind`, which is
547/// also the name of the table holding it: `flm.xnotes.list.<kind>`.
548pub fn piece_name(kind: &str) -> Name {
549    Name::from(format!("flm.xnotes.list.{kind}"))
550}
551
552/// The table of the list of the xnote kind `kind`, `flm.xnotes.list.<kind>`
553/// ([`piece_name`]): the table that the kind's builder ([`ListBuilder`])
554/// writes, and from which the backends place the list after the content.
555///
556/// The rest of the pipeline reads the list from this table only, so the
557/// stage that writes the table decides the list. To build one xnote kind's
558/// list differently, register a document-scope stage of your own that writes
559/// this table (from the table [`XNOTES`], the document's trees, or any other
560/// table it declares that it reads), and prefer it in a plan request
561/// ([`Overrides::prefer`](crate::core::plan::Overrides::prefer)) or in a
562/// workflow of your own
563/// ([`WorkflowDef::prefer`](crate::core::registry::WorkflowDef::prefer)).
564/// Without a preference, the plan refuses to choose between the two stages
565/// and reports [`PlanError::Contested`](crate::core::plan::PlanError::Contested),
566/// which lists both. The lists of the other xnote kinds are not affected.
567pub fn piece_table(kind: &str) -> TableHandle<Piece> {
568    TableHandle::new(piece_name(kind))
569}
570
571/// The name of the stage that builds the list of the xnote kind `kind`,
572/// `flm.xnotes.build-list.<kind>` ([`ListBuilder`]).
573pub fn builder_name(kind: &str) -> StageName {
574    StageName::from(format!("flm.xnotes.build-list.{kind}"))
575}
576
577/// The name of the counter in which the xnotes of the numbered xnote kind
578/// `kind` are counted, `flm.xnotes.<kind>` (see
579/// [`CounterDecl`](crate::stdlib::features::numbering::CounterDecl)).
580pub fn counter_name(kind: &str) -> Name {
581    Name::from(format!("flm.xnotes.{kind}"))
582}
583
584/// The name of the reference style of the numbered xnote kind `kind`,
585/// `flm.xnotes.style.<kind>`: the counter style
586/// ([`CounterStyleDecl`](crate::stdlib::features::numbering::CounterStyleDecl))
587/// in which a `\ref` writes an xnote's number, with the kind's words
588/// (`Footnote~1`).
589pub fn style_name(kind: &str) -> Name {
590    Name::from(format!("flm.xnotes.style.{kind}"))
591}
592
593/// The name of the mark style of the numbered xnote kind `kind`,
594/// `flm.xnotes.style.<kind>.mark`: the counter style in which an xnote's mark
595/// writes its number (`1`), made from the kind's
596/// [`mark`](XnoteKind::mark) template.
597pub fn mark_style_name(kind: &str) -> Name {
598    Name::from(format!("flm.xnotes.style.{kind}.mark"))
599}
600
601/// The reference kind of the mark's point of an xnote of the xnote kind
602/// `kind`, `<kind>-mark`.
603fn mark_point_kind(kind: &str) -> RefKind {
604    RefKind::from(format!("{kind}-mark"))
605}
606
607/// The per-value data of the [`XNOTE`] element: the xnote kind that a command
608/// writes.
609///
610/// The value also implements the element's five aspects: its block role
611/// ([`BlockRoleAspect`]: inline content for a listed xnote kind; inline or a
612/// block of its own for an in-place one), its reference points
613/// ([`Referenceable`], through [`ref_points`]), the content of its xnote
614/// ([`XnoteSource`]: the argument [`XNOTE_ARG`]), the content it sets apart
615/// from the text around it ([`ApartFromText`]), and what replaces it in
616/// content shown again ([`InCopy`]: a node of the element [`MARK_OF`]).
617#[derive(Debug, Clone)]
618pub struct XnoteElement {
619    /// The xnote kind.
620    pub kind: Arc<XnoteKind>,
621}
622
623impl PartialEq for XnoteElement {
624    /// Two values are equal when their xnote kinds are equal.
625    fn eq(&self, other: &XnoteElement) -> bool {
626        self.kind == other.kind
627    }
628}
629
630impl Eq for XnoteElement {}
631
632/// The per-value data of the list element of an xnote kind
633/// ([`list_element_name`]): the xnote kind whose xnotes the list holds.
634#[derive(Debug, Clone, PartialEq, Eq)]
635pub struct XnotesListElement {
636    /// The xnote kind.
637    pub kind: Arc<XnoteKind>,
638}
639
640/// The aspect an element implements when its nodes carry xnotes: for one
641/// node, which xnote kinds it carries and which region of the node holds the
642/// content of each.
643///
644/// The content of an xnote is always a region of the node itself, one of its
645/// arguments or one of its bodies (a slot of the node; [`NodeRegion`]), in
646/// whichever tree the node
647/// is placed. The list of the xnote kind shows the content by lowering that
648/// region where the entry is placed ([`CONTENT_POINTER`]); nothing of it is
649/// copied. The [`XNOTE`] element returns one xnote, whose content is its
650/// argument [`XNOTE_ARG`]. An element of another feature returns the regions
651/// of its own node that hold the contents of its xnotes; the collect stage
652/// records the node where it is placed in the document.
653///
654/// This aspect is one of the four things that make a node an xnote; the
655/// others are the xnote kind in the service slot [`KINDS_SLOT`]
656/// ([`contribute_kind`]), the two reference points of each xnote
657/// ([`ref_points`], returned through [`Referenceable`]), and the element's
658/// [`ApartFromText`] aspect, which includes the regions the xnotes are made
659/// from ([`regions_apart_from_text`]) so that their words are not read as
660/// part of the text around them (for instance by the anchor a heading builds
661/// from its title). The author's `\footnote` goes through the same four.
662///
663/// The content of an xnote must be a region of a node of the document. An
664/// xnote whose content a feature builds itself, as a synthesized value rather
665/// than as a region of a node, is not implemented: the list can point only
666/// into the document's trees and into the synthesized values that the
667/// lowering of the list holds.
668///
669/// # Several xnotes on one node
670///
671/// A node may carry several xnotes, of one xnote kind or of several. Its
672/// element returns one [`XnoteOf`] per xnote here, and one pair of points per
673/// xnote through its [`Referenceable`] aspect, calling [`ref_points`] once
674/// per xnote. **The two lists are paired by order, xnote kind by xnote
675/// kind**: the node's n-th pair of points of a kind (the n-th record of that
676/// kind that the table [`XNOTES`] holds for the node,
677/// [`Xnotes::records_at`]) is the xnote whose content is the n-th [`XnoteOf`]
678/// of that kind returned here. Every reader of a node's xnotes follows this
679/// pairing: the collect stage records the region of each xnote's content with
680/// it
681/// ([`XnoteRecord::content`]); the staging helpers take the position of the
682/// xnote they write among the node's xnotes of its kind ([`stage_mark`],
683/// [`stage_in_place`], [`stage_latex`]); and the node that represents the
684/// node in content shown again represents every one of its xnotes
685/// ([`MarkOf`]). A node whose two lists hold different numbers of xnotes of
686/// a kind is reported ([`Unpaired`]). Each [`XnoteOf`] of a node must refer
687/// to a region of its own: the list of an xnote kind finds an entry's xnote
688/// by the node and the region that the entry's content pointer refers to
689/// ([`ContentPointer`](crate::stdlib::backends::lowering::ContentPointer)).
690///
691/// The element decides which labels label which xnote, through the labels it
692/// passes to each [`ref_points`] call: the labels of
693/// `\footnote[\label{…}]{…}` label the single xnote of its node.
694pub trait XnoteSource: Send + Sync {
695    /// The xnotes that `node` carries, in order: for each, its xnote kind
696    /// and the region of `node` that holds its content.
697    fn xnotes(&self, node: &NodeRef<'_, Flm>) -> Vec<XnoteOf>;
698}
699
700/// The regions holding the contents of the xnotes of the xnote kind `kind`
701/// that `node` carries, in the order the node's [`XnoteSource`] returns them:
702/// the n-th is the content of the node's n-th xnote of that kind, under the
703/// pairing that aspect states. Empty for a node whose element does not
704/// implement the aspect.
705fn contents_of_kind(node: &NodeRef<'_, Flm>, kind: &str) -> Vec<NodeRegion> {
706    let Some(source) = node.ext().element.aspect::<dyn XnoteSource>() else { return Vec::new() };
707    source.xnotes(node).into_iter().filter(|xnote| xnote.kind.as_str() == kind).map(|xnote| xnote.content).collect()
708}
709
710/// One xnote that a node carries, as [`XnoteSource`] returns it.
711#[derive(Debug, Clone, PartialEq, Eq)]
712pub struct XnoteOf {
713    /// The name of the xnote kind.
714    pub kind: Name,
715    /// The region of the node that holds the xnote's content: the argument
716    /// `xnote` for `\footnote` ([`NodeRegion::argument_named`] finds an
717    /// argument's position from its name).
718    pub content: NodeRegion,
719}
720
721/// The two reference points of one xnote of the xnote kind `kind`, labeled
722/// by `labels` and showing `content` where a reference shows content.
723///
724/// Every element that carries xnotes implements its [`Referenceable`] aspect
725/// with this function, called once per xnote, so that the collect stage finds
726/// its xnotes: the stage recognizes an xnote by these two points. `labels`
727/// are the labels the author wrote for the xnote, as [`labels_of`] or the
728/// references feature's readers
729/// ([`label_uses_in`](crate::stdlib::features::refs::label_uses_in)) read
730/// them.
731///
732/// The function returns the two points in this order:
733///
734/// 1. **The xnote's own point**, whose reference kind is the xnote kind's
735///    name. It carries the labels and accepts the kind's
736///    [`label_type`](XnoteKind::label_type) alone. For a numbered xnote kind,
737///    the point counts in the kind's counter ([`counter_name`]), advancing it
738///    by one, and is shown in the reference style ([`style_name`]); its anchor
739///    is built from its number, `fn-1` (from its first label where it has no
740///    number), and it shows no content. For an unnumbered xnote kind, the
741///    point counts in no counter, its anchor is its first label or else is
742///    built from its position (`fn--3kzmq`), and a reference to it shows
743///    `content`.
744/// 2. **The mark's point**, of the reference kind `<kind>-mark`: no label,
745///    accepting none, no number, no content; its anchor is built from its
746///    position, with the prefix `<label type>ref` (`fnref--1kzmq`).
747///
748/// `content` is the xnote's content where a reference can show it: inline
749/// content only, since a reference is itself inline. Pass `None` for content
750/// that holds blocks; a reference to such an unnumbered xnote then shows the
751/// label it was written with.
752///
753/// The points are returned wherever the node is placed, inside another
754/// xnote's content too: an xnote inside an xnote is an xnote like any other.
755pub fn ref_points(
756    kind: &XnoteKind,
757    labels: &[LabelUse],
758    content: Option<ContentRef>,
759) -> Vec<RefPoint> {
760    let name = kind.name.as_str();
761    let (labels, malformed) = refs::point_labels(labels);
762    let xnote = RefPoint {
763        kind: RefKind::from(name),
764        labels,
765        malformed,
766        computed: 0,
767        anchor: if kind.numbered {
768            AnchorPolicy::FromValue { prefix: kind.label_type.clone() }
769        } else {
770            AnchorPolicy::Auto { prefix: kind.label_type.clone() }
771        },
772        number: kind.numbered.then(|| NumberSource {
773            counter: counter_name(name),
774            instances: Vec::new(),
775            style: style_name(name),
776            advance: vec![0],
777            number_format: None,
778        }),
779        content: if kind.numbered { None } else { content },
780        accepts: AcceptedRefTypes::these([kind.label_type.as_str()]),
781    };
782    let mark = RefPoint {
783        kind: mark_point_kind(name),
784        labels: Vec::new(),
785        malformed: Vec::new(),
786        computed: 0,
787        anchor: AnchorPolicy::Auto { prefix: format!("{}ref", kind.label_type) },
788        number: None,
789        content: None,
790        accepts: AcceptedRefTypes::these(Vec::<String>::new()),
791    };
792    vec![xnote, mark]
793}
794
795/// Whether the content argument of the xnote `node` holds blocks, as the
796/// block-structure pass laid it out.
797fn holds_blocks(node: &NodeRef<'_, Flm>) -> bool {
798    matches!(
799        NodeRegion::argument_named(node, XNOTE_ARG),
800        Some(NodeRegion::Argument(index)) if argument_holds_blocks(node, index)
801    )
802}
803
804/// A listed xnote is inline content that attaches to the word before it (a
805/// space before it is removed); an in-place xnote is inline content where its
806/// content is inline, and a block where the block-structure pass laid its
807/// content out as blocks.
808impl BlockRoleAspect for XnoteElement {
809    fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
810        match self.kind.placement {
811            XnotePlacement::List => {
812                BlockRole::Inline(InlineSpacing { absorb_before: true, absorb_after: false })
813            }
814            XnotePlacement::InPlace if holds_blocks(node) => BlockRole::Block,
815            XnotePlacement::InPlace => BlockRole::Inline(InlineSpacing::CONTENT),
816        }
817    }
818}
819
820/// The two points of [`ref_points`], labeled by the `\label` commands of the
821/// optional argument ([`labels_of`]; anything else the argument holds is
822/// ignored here and reported by the xnote's lowering rule), and showing the
823/// content argument where it is inline.
824impl Referenceable for XnoteElement {
825    fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
826        let (labels, _) = labels_of(node);
827        let content = (!holds_blocks(node)).then(|| ContentRef::ArgumentNamed(XNOTE_ARG.to_string()));
828        ref_points(&self.kind, &labels, content)
829    }
830}
831
832/// One xnote of the element's xnote kind, whose content is the argument
833/// [`XNOTE_ARG`].
834impl XnoteSource for XnoteElement {
835    fn xnotes(&self, node: &NodeRef<'_, Flm>) -> Vec<XnoteOf> {
836        NodeRegion::argument_named(node, XNOTE_ARG)
837            .map(|content| XnoteOf { kind: self.kind.name.clone(), content })
838            .into_iter()
839            .collect()
840    }
841}
842
843/// The regions that `node`'s xnotes are made from, as the node's
844/// [`XnoteSource`] returns them, written as [content references](ContentRef).
845///
846/// An element that carries xnotes returns these from its [`ApartFromText`]
847/// aspect, together with anything else of its own that is apart from the
848/// text (such as the labels of `\footnote`). The element thus states its
849/// xnotes' regions once, in its [`XnoteSource`] implementation, and the two
850/// aspects cannot disagree.
851///
852/// An argument region becomes [`ContentRef::Argument`] at the same position;
853/// a slot region becomes each of the slot's content nodes, as
854/// [`ContentRef::Node`]. The result is empty for a node whose element does
855/// not implement [`XnoteSource`].
856pub fn regions_apart_from_text(node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
857    let Some(source) = node.ext().element.aspect::<dyn XnoteSource>() else { return Vec::new() };
858    let mut apart = Vec::new();
859    for xnote in source.xnotes(node) {
860        match xnote.content {
861            NodeRegion::Argument(index) => apart.push(ContentRef::Argument(index)),
862            NodeRegion::Slot(_) => apart.extend(
863                xnote.content.content_nodes(node).unwrap_or_default().iter().map(|n| ContentRef::Node(n.id())),
864            ),
865        }
866    }
867    apart
868}
869
870/// Nothing of an xnote is part of the text around it: its content, the
871/// argument [`XNOTE_ARG`], is shown apart from the words it is attached to (at
872/// the foot of the page, in a list, beside them), and its labels, the
873/// argument [`LABELS_ARG`], identify it. A heading whose title holds an xnote
874/// therefore builds its anchor from the title's own words. The content
875/// regions are the ones the element's [`XnoteSource`] implementation returns
876/// ([`regions_apart_from_text`]).
877impl ApartFromText for XnoteElement {
878    fn apart_from_text(&self, node: &NodeRef<'_, Flm>) -> Vec<ContentRef> {
879        let mut apart = vec![ContentRef::ArgumentNamed(LABELS_ARG.to_string())];
880        apart.extend(regions_apart_from_text(node));
881        apart
882    }
883}
884
885/// What every rule of the element [`XNOTE`] reads and produces, except the
886/// recomposition rule: the table of xnotes, the counter and anchors tables
887/// optionally, and the presentation elements that [`stage_mark`] and
888/// [`stage_in_place`] stage.
889fn xnote_decl() -> LoweringDecl {
890    LoweringDecl::new()
891        .reads(XNOTES)
892        .reads_opt(COUNTERS)
893        .reads_opt(refs::ANCHORS)
894        .produces(pres::SPAN)
895        .produces(pres::LINK)
896        .produces(pres::BLOCK)
897        .produces(pres::PAR)
898}
899
900/// The element value of the commands of the xnote kind `kind`.
901fn xnote_element(kind: Arc<XnoteKind>) -> Arc<ElementSpec> {
902    let value = Arc::new(XnoteElement { kind });
903    Arc::new(
904        ElementSpec::new(XNOTE)
905            .docs(format!("`\\{}`: a note of the xnote kind `{}`.", value.kind.commands.join("`, `\\"), value.kind.name))
906            .with::<dyn BlockRoleAspect>(Arc::clone(&value) as Arc<dyn BlockRoleAspect>)
907            .with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
908            .with::<dyn XnoteSource>(Arc::clone(&value) as Arc<dyn XnoteSource>)
909            .with::<dyn ApartFromText>(Arc::clone(&value) as Arc<dyn ApartFromText>)
910            .with::<dyn InCopy>(Arc::clone(&value) as Arc<dyn InCopy>)
911            .with_value(value),
912    )
913}
914
915/// The element value of an entry of a list of xnotes: a block of its own.
916fn entry_element() -> Arc<ElementSpec> {
917    Arc::new(
918        ElementSpec::new(ENTRY)
919            .docs("One entry of a list of xnotes, holding a pointer to the xnote's content.")
920            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Block))),
921    )
922}
923
924/// The `xnotes` feature, an [`FlmFeature`]: footnotes and the other xnote
925/// kinds.
926///
927/// From its [`XnotesConfig`], it declares the service slot of xnote kinds
928/// [`KINDS_SLOT`], every configured xnote kind through [`contribute_kind`],
929/// one element value of [`XNOTE`] per xnote kind that has commands, the
930/// synthesized elements [`ENTRY`], [`MARK_OF`] and [`CONTENT_POINTER`], the
931/// table [`XNOTES`] and the collect stage that writes it, the lowering rules
932/// of those elements on every backend, and the stylesheet [`STYLE`]. The
933/// [module documentation](self) describes what each does.
934///
935/// Registering the feature fails with [`BuildError::Feature`] when the
936/// configuration fails [`XnotesConfig::validate`].
937#[derive(Debug, Clone, Default)]
938pub struct XnotesFeature {
939    config: XnotesConfig,
940}
941
942impl XnotesFeature {
943    /// The feature with the configuration `config`. A feature's configuration
944    /// is the plain Rust value the feature is constructed from; it is fixed
945    /// when the registry is built and cannot vary per document or per render
946    /// (see [settings, options and
947    /// configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
948    pub fn new(config: XnotesConfig) -> XnotesFeature {
949        XnotesFeature { config }
950    }
951
952    /// The configuration this feature was constructed with.
953    pub fn config(&self) -> &XnotesConfig {
954        &self.config
955    }
956}
957
958impl FlmFeature for XnotesFeature {
959    fn info(&self) -> FeatureInfo {
960        FeatureInfo::new(FEATURE, "Xnotes").docs(
961            "Footnotes and the other kinds of xnote (notes set apart from the running text): \
962             the configured kinds and their commands, the two reference points of every xnote, \
963             the service slot `flm.xnotes.kinds` of the kinds, and the table `flm.xnotes` of \
964             every xnote of a document by kind.",
965        )
966    }
967
968    fn settings(&self) -> Option<SettingsDecl> {
969        Some(settings())
970    }
971
972    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
973        let owner = b.feature().clone();
974        self.config
975            .validate()
976            .map_err(|detail| BuildError::Feature { feature: owner.clone(), detail })?;
977        b.service_slot::<XnoteKind>(
978            KINDS_SLOT,
979            crate::core::services::Arity::OrderedMany,
980            "the kinds of xnote, in order: the ones the `xnotes` feature's configuration \
981             declares and the ones other features contribute",
982        )?;
983        // The label package belongs to the references feature, which may be
984        // absent: the optional argument then accepts no `\label`. Declared
985        // once here, not per kind: a contributed kind has no command, so no
986        // argument of the contributing feature names the package.
987        b.peer_scoped_package(
988            refs::LABEL_PACKAGE,
989            "the `\\label` an xnote's optional argument accepts",
990        )?;
991        for kind in &self.config.kinds {
992            let kind = Arc::new(kind.clone());
993            contribute_kind(b, Arc::clone(&kind))?;
994            if kind.commands.is_empty() {
995                continue;
996            }
997            b.element(
998                ElementDef::new(
999                    owner.clone(),
1000                    kind.commands.iter().map(String::as_str),
1001                    SyntaxDef::Macro {
1002                        args: vec![
1003                            ArgDef::optional(LABELS_ARG)
1004                                .scoped(refs::LABEL_PACKAGE)
1005                                .docs("The xnote's labels, `\\label{…}`, and nothing else."),
1006                            ArgDef::mandatory(XNOTE_ARG)
1007                                .layout(kind.layout)
1008                                .docs("The xnote's content."),
1009                        ],
1010                    },
1011                    xnote_element(Arc::clone(&kind)),
1012                )
1013                .docs(format!(
1014                    "Writes a note of the xnote kind `{}`, set apart from the running text and \
1015                     marked where it is written. A label of the note has the label type `{}`.",
1016                    kind.name, kind.label_type
1017                )),
1018            )?;
1019        }
1020        if self.config.kinds.iter().any(|kind| !kind.commands.is_empty()) {
1021            b.element_type_text(
1022                XNOTE,
1023                "A note set apart from the running text, such as a footnote: marked where it is \
1024                 written, and shown in place or elsewhere as its xnote kind says.",
1025            )?;
1026        }
1027        b.element(
1028            ElementDef::new(owner.clone(), Vec::<&str>::new(), SyntaxDef::Synthesized, entry_element())
1029                .docs(
1030                    "One entry of a list of xnotes. It is never written in a document: a kind's \
1031                     list builder creates it.",
1032                ),
1033        )?;
1034        b.element(
1035            ElementDef::new(
1036                owner.clone(),
1037                Vec::<&str>::new(),
1038                SyntaxDef::Synthesized,
1039                Arc::clone(mark_of::mark_of_spec().element()),
1040            )
1041            .docs(
1042                "The mark of an xnote in content shown again, such as a heading's title that a \
1043                 reference prints: it refers to the xnote and is written as its mark. It is never \
1044                 written in a document: a copy of the content creates it in place of the xnote.",
1045            ),
1046        )?;
1047        b.element(
1048            ElementDef::new(
1049                owner.clone(),
1050                Vec::<&str>::new(),
1051                SyntaxDef::Synthesized,
1052                pointer::pointer_element(),
1053            )
1054            .docs(
1055                "The content of an xnote, shown where this node is placed: it refers to the node \
1056                 carrying the xnote and the region of that node that holds the content. It is \
1057                 never written in a document: a kind's list builder creates it.",
1058            ),
1059        )?;
1060        b.element_type_text(
1061            ENTRY,
1062            "One entry of a list of xnotes: the mark of one xnote and its content.",
1063        )?;
1064        b.element_type_text(
1065            MARK_OF,
1066            "The mark of an xnote in content shown a second time, such as a heading's title that \
1067             a reference prints, standing for the xnote itself.",
1068        )?;
1069        b.element_type_text(
1070            CONTENT_POINTER,
1071            "The content of an xnote, shown in a list of xnotes, away from the place where the \
1072             xnote is written.",
1073        )?;
1074        // The presentation elements belong to the lowering feature, which a
1075        // registry that renders nothing may leave out: the rules are then set
1076        // aside. The counter table belongs to the numbering feature and the
1077        // anchors table to the references feature, either of which may be
1078        // absent. `contribute_kind` declares the same names again for each
1079        // kind's list rule, which the registry merges.
1080        list::declare_peers(b)?;
1081        // The element `flm.xnotes.xnote` exists only where a kind has a
1082        // command, and a rule names a registered element.
1083        if self.config.kinds.iter().any(|kind| !kind.commands.is_empty()) {
1084            b.lowering_rule(
1085                LoweringRule::new(
1086                    XNOTE_RULE,
1087                    XNOTE,
1088                    xnote_decl(),
1089                    Arc::new(XnoteRule),
1090                    DefaultMark::Everywhere,
1091                )
1092                .docs(
1093                    "an xnote lowers to its mark, a superscript `flm.pres.span` holding a link to \
1094                     the xnote, for a listed xnote kind; to a `flm.pres.span` or a \
1095                     `flm.pres.block` holding the mark and the content, bracketed, for an in-place \
1096                     xnote kind",
1097                ),
1098            )?;
1099        }
1100        b.lowering_rule(
1101            LoweringRule::new(ENTRY_RULE, ENTRY, LoweringDecl::new(), Arc::new(EntryRule), DefaultMark::Everywhere)
1102                .docs("an entry of a list of xnotes outside its list lowers to nothing and is reported"),
1103        )?;
1104        b.lowering_rule(pointer::pointer_rule())?;
1105        b.lowering_rule(mark_of::mark_of_rule())?;
1106        b.table(
1107            XNOTES,
1108            "Every xnote of the document, by xnote kind, in document order: its reference point \
1109             and the reference point of its mark.",
1110        )?;
1111        // An unnumbered kind's fixed mark is compiled once the kinds slot is
1112        // assembled and the language built, and carried by the collect stage
1113        // into the table.
1114        let fixed_marks = Arc::new(marks::FixedMarks::default());
1115        b.finalizer(Arc::new(marks::DeclareFixedMarks { marks: Arc::clone(&fixed_marks) }))?;
1116        b.stage(Arc::new(stages::Collect { marks: fixed_marks }))?;
1117        let with_element = self.config.kinds.iter().any(|kind| !kind.commands.is_empty());
1118        html::register(b, with_element)?;
1119        latex_rendered::register(b, with_element)?;
1120        latex::register(b, with_element)?;
1121        b.digest_input(&self.config.digest_bytes())?;
1122        Ok(())
1123    }
1124}
1125
1126/// The [`XnotesFeature`] with the default configuration (the single xnote kind
1127/// `footnote`), ready to be listed in a package entry.
1128///
1129/// Use `Arc::new(XnotesFeature::new(config))` to list the feature under an
1130/// [`XnotesConfig`] of your own.
1131pub fn feature() -> Arc<dyn FlmFeature> {
1132    Arc::new(XnotesFeature::default())
1133}