Skip to main content

flm_core/stdlib/features/xnotes/
config.rs

1//! The configuration of the `xnotes` feature: the xnote kinds an author
2//! writes ([`XnoteKind`], listed by [`XnotesConfig`]), each with its
3//! commands, the words a reference writes, its label type, whether it is
4//! numbered, its mark, where its xnotes are shown ([`XnotePlacement`]) and how
5//! its content is laid out.
6//!
7//! A feature's configuration is the plain Rust value the feature is
8//! constructed from; it is fixed when the registry is built and cannot vary
9//! per document or per render (see [settings, options and
10//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
11//! The same values can be written as settings, one entry per xnote kind under
12//! the settings key `kinds` ([`crate::core::settings`]).
13
14use std::hash::{Hash, Hasher};
15
16use crate::core::settings::named::{self, NamedEntry};
17use crate::lang::mint::ArgLayout;
18use crate::model::names::Name;
19use crate::stdlib::features::lists::holds_placeholder;
20use crate::stdlib::features::numbering::{NumberTemplate, PluralWords, PrefixWords, Within};
21use crate::stdlib::features::refs::CAPITAL_VARIANT;
22
23/// Where the xnotes of an xnote kind are shown: in a list after the
24/// document's content, or where each one is written.
25///
26/// The placement is part of the xnote kind's configuration, fixed when the
27/// registry is built; no render request can change it. The reason is that an
28/// in-place xnote holding paragraphs is a *block* of the document: it ends
29/// the paragraph it is written in, as a list does, and the text after it is a
30/// new paragraph.
31/// The [block-structure pass](crate::lang::rewrites::blocks) decides whether
32/// a node is a block before the document's trees are frozen (no longer
33/// changed; see [frozen
34/// trees](crate::guide::concepts_overview#frozen-trees-and-computed-data)),
35/// from the element value and the node alone, so
36/// the answer is a fact of the document, the same for every output; a listed
37/// xnote is always inline content. A document whose footnotes are listed on
38/// one output and shown in place on another is therefore rendered with two
39/// configurations, that is, with two registries.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize, serde::Serialize)]
41#[derive(schemars::JsonSchema)]
42#[serde(rename_all = "kebab-case")]
43pub enum XnotePlacement {
44    /// In a list after the document's content: the xnote's mark is placed
45    /// where the xnote was written, linked to the xnote's entry in the list.
46    /// The default.
47    #[default]
48    List,
49    /// Where the xnote is written: one inline span holding the mark and the
50    /// content, or, for content holding paragraphs, a block of its own, which
51    /// ends the paragraph it is written in.
52    InPlace,
53}
54
55/// One xnote kind: one way of being an xnote, a piece of text set apart from
56/// the running text (the footnotes written `\footnote{…}`, the side notes a
57/// configuration adds, the notes another feature's elements carry; see the
58/// [module documentation of the feature](super)).
59///
60/// An xnote kind states, field by field:
61///
62/// - [`name`](XnoteKind::name): what the kind is called, `footnote`. It is
63///   made of ASCII letters only, because other names are derived from it: the
64///   counter `flm.xnotes.<name>`, the list element, the LaTeX
65///   command `\flmXN<name>`.
66/// - [`commands`](XnoteKind::commands): the commands with which an author
67///   writes an xnote of the kind, without the backslash: `footnote`. Empty for
68///   a kind that no author writes, which another feature contributes through
69///   the service slot of xnote kinds
70///   ([`contribute_kind`](super::contribute_kind)).
71/// - [`words`](XnoteKind::words): the words a reference writes before an
72///   xnote's number, `Footnote~` before one number and `Footnotes~` before
73///   several. `\ref{fn:x}` prints them (`Footnote~1`); the default title of
74///   the list is made from them; and the accessible name of the link from a
75///   mark to its xnote begins with them.
76/// - [`label_type`](XnoteKind::label_type): the only label type that an
77///   xnote of the kind accepts, `fn` in `\label{fn:x}`; also the prefix of
78///   its anchors in the output (`fn-1`, `fnref--1kzmq`). It is made of ASCII
79///   letters only, like the name, so that it can be written as the label type
80///   of a `\label` and begin an anchor.
81/// - [`numbered`](XnoteKind::numbered): whether the kind's xnotes are
82///   counted, in document order, in a counter of the kind's own. A reference
83///   to a numbered xnote shows its number; a reference to an unnumbered xnote
84///   shows its content where that content is inline, and otherwise its label.
85/// - [`number_format`](XnoteKind::number_format): how a reference writes the
86///   number of a numbered kind's xnote, `#{arabic}`.
87/// - [`within`](XnoteKind::within): the counter within which a numbered kind
88///   is numbered, `None` for numbering through the whole document.
89/// - [`mark`](XnoteKind::mark): what is shown in the running text where an
90///   xnote was written. For a numbered kind it is a number template,
91///   `#{arabic}` by default, and the mark is the xnote's number written
92///   through it; for an unnumbered kind it is a fixed mark, a template with no
93///   number placeholder (`*`, `\dag`), or empty for no mark. In both cases
94///   the template is FLM text, compiled when the registry is built.
95/// - [`placement`](XnoteKind::placement): listed after the content, or shown
96///   in place ([`XnotePlacement`]).
97/// - [`layout`](XnoteKind::layout): how the content argument is laid out:
98///   inferred from what the author wrote by default, or fixed.
99/// - [`title`](XnoteKind::title) and [`title_level`](XnoteKind::title_level):
100///   the heading placed above the kind's list, and its level.
101/// - [`backlink`](XnoteKind::backlink): the text of the link from the entry
102///   of a listed xnote back to its mark, `↩`.
103/// - [`latex_command`](XnoteKind::latex_command): the LaTeX command to which
104///   the style file's default definition of `\flmXN<name>` passes the xnote
105///   (`footnote`), a command of the author's LaTeX that the author's own
106///   preamble may redefine.
107///
108/// # Numbered and unnumbered xnote kinds
109///
110/// Whether a kind is numbered is stated by its flag
111/// [`numbered`](XnoteKind::numbered) and is never inferred from its
112/// templates. The [`mark`](XnoteKind::mark) template is read the same way for
113/// both: as FLM text in the language of a counter style's number template,
114/// compiled when the registry is built, a mistake in it failing the build
115/// (see [the template
116/// language](crate::guide::concepts_overview#the-template-language-shared-by-features)).
117/// For a numbered kind it is a number template; for an unnumbered kind it is
118/// a fixed mark, and an unnumbered kind whose mark holds a number placeholder
119/// such as `#{arabic}` is refused when the registry is built, since it has no
120/// number to write ([`XnoteKind::validate`]). The
121/// [`number_format`](XnoteKind::number_format) and [`within`](XnoteKind::within)
122/// of an unnumbered kind are ignored, neither compiled nor checked, so that
123/// switching a kind between numbered and unnumbered needs no other change.
124///
125/// An xnote kind does not depend on any particular output: the mark is one
126/// text, shown as a superscript, which each output writes in its own way. For
127/// a numbered kind, a host that wants the mark written differently on one
128/// output replaces the kind's mark style, `flm.xnotes.style.<name>.mark`
129/// ([`mark_style_name`](super::mark_style_name)), through the numbering
130/// feature's configuration in that output's registry, as it replaces any
131/// declared counter style. An unnumbered kind's fixed mark is compiled by the
132/// `xnotes` feature from [`mark`](XnoteKind::mark) and is not a declared
133/// counter style: a different fixed mark on one output needs a configuration
134/// with a different `mark` in that output's registry.
135///
136/// # Examples
137///
138/// ```
139/// use flm_core::lang::mint::ArgLayout;
140/// use flm_core::stdlib::features::numbering::{NumberTemplate, PrefixWords};
141/// use flm_core::stdlib::features::xnotes::{XnoteKind, XnotePlacement};
142///
143/// // The default kind.
144/// let footnote = XnoteKind::footnote();
145/// assert_eq!(footnote.commands, ["footnote"]);
146/// assert_eq!(footnote.title.as_deref(), Some("Footnotes"));
147///
148/// // A second numbered kind, listed after the footnotes.
149/// let endnote = XnoteKind::numbered("endnote", PrefixWords::new("Endnote~", "Endnotes~"))
150///     .commands(["endnote"])
151///     .label_type("en");
152/// assert_eq!(endnote.title.as_deref(), Some("Endnotes"));
153///
154/// // An unnumbered kind shown where it is written, with no mark.
155/// let sidenote = XnoteKind::unnumbered("sidenote", PrefixWords::new("Side note~", "Side notes~"))
156///     .commands(["sidenote"])
157///     .label_type("sn")
158///     .placement(XnotePlacement::InPlace);
159/// assert!(!sidenote.numbered);
160/// assert_eq!(sidenote.mark, NumberTemplate::formats(""));
161///
162/// // A kind whose content is always paragraphs.
163/// let long = XnoteKind::footnote().layout(ArgLayout::Blocks);
164/// assert_eq!(long.layout, ArgLayout::Blocks);
165/// ```
166#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
167#[derive(schemars::JsonSchema)]
168#[serde(deny_unknown_fields)]
169#[schemars(transform = xnote_kind_schema)]
170pub struct XnoteKind {
171    /// The kind's name, ASCII letters only: `footnote`.
172    /// In settings, it is written as the entry's key, not as a field.
173    #[schemars(skip)]
174    pub name: Name,
175    /// The commands with which an xnote of the kind is written, without the
176    /// backslash; empty for a kind that only another feature creates.
177    pub commands: Vec<String>,
178    /// The words a reference writes before one number and before several,
179    /// with their variants: `Footnote~`, `Footnotes~`.
180    pub words: PrefixWords,
181    /// The only label type that an xnote of the kind accepts, and the prefix
182    /// of its anchors in the output: `fn`. ASCII letters only.
183    pub label_type: String,
184    /// Whether the kind's xnotes are numbered.
185    pub numbered: bool,
186    /// How a reference writes a numbered xnote's number; ignored for an
187    /// unnumbered kind. `#{arabic}` by default.
188    pub number_format: NumberTemplate,
189    /// The counter within which a numbered kind is numbered, or `None` for
190    /// numbering through the whole document; ignored for an unnumbered kind.
191    pub within: Option<Within>,
192    /// The text of the mark, as FLM text: a number template for a numbered
193    /// kind (`#{arabic}`), a fixed mark with no number placeholder for an
194    /// unnumbered one (empty for no mark).
195    pub mark: NumberTemplate,
196    /// Where the kind's xnotes are shown.
197    pub placement: XnotePlacement,
198    /// How the content argument is laid out:
199    /// [`InlineOrBlocks`](ArgLayout::InlineOrBlocks) by default, which makes
200    /// a note written on one run inline content and one holding a blank line
201    /// or a block paragraphs. [`Inline`](ArgLayout::Inline) refuses a blank
202    /// line in the note, as every inline argument does.
203    /// [`Blocks`](ArgLayout::Blocks) makes every note paragraphs, even an
204    /// empty one: with it, an in-place xnote is always a block of its own,
205    /// `\footnote{}` included.
206    pub layout: ArgLayout,
207    /// The heading placed above the kind's list, as FLM text; `None` for no
208    /// heading. The constructors set the plural word, capitalized and without
209    /// the non-breaking space (`Footnotes`).
210    ///
211    /// The title is compiled when the registry is built, and a title that is
212    /// not valid FLM fails the build. It is read in the language of a counter
213    /// style's number template, with no placeholder available: `#` starts a
214    /// placeholder there, so a literal `#` is written `\#` or `##`, and a
215    /// placeholder such as `#{n}` fails the build.
216    pub title: Option<String>,
217    /// The level of the heading above the list, counted from zero like every
218    /// heading level; 2 by default.
219    pub title_level: u8,
220    /// The text of the link from a listed xnote back to its mark: `↩`.
221    pub backlink: String,
222    /// The LaTeX command to which the style file's default definition of
223    /// `\flmXN<name>` passes the xnote, without the backslash (`footnote`): a
224    /// command of the author's LaTeX, which the author's own preamble may
225    /// redefine. ASCII letters only.
226    pub latex_command: String,
227}
228
229
230/// The schema of an xnote kind in settings: only `words` is required, because
231/// the entry is read over what [`XnoteKind::numbered`] makes from the name and
232/// the `words` written.
233fn xnote_kind_schema(schema: &mut schemars::Schema) {
234    crate::core::settings::named::require_only(schema, &["words"]);
235}
236impl XnoteKind {
237    /// A numbered xnote kind named `name` with the reference words `words`:
238    /// no command, the label type `name`, numbered through the document, the
239    /// number written `#{arabic}` in a reference and in the mark, listed, the
240    /// layout inferred from the content, the title made of the plural word
241    /// capitalized, at level 2, the back-link `↩`, the LaTeX command
242    /// `footnote`. The builder methods change each of these.
243    ///
244    /// The title is computed from `words` here, once: a kind whose words are
245    /// changed afterwards keeps its title until [`title`](XnoteKind::title())
246    /// sets another.
247    pub fn numbered(name: impl Into<Name>, words: PrefixWords) -> XnoteKind {
248        let name = name.into();
249        XnoteKind {
250            label_type: name.as_str().to_string(),
251            name,
252            commands: Vec::new(),
253            title: Some(plural_title(&words)),
254            words,
255            numbered: true,
256            number_format: NumberTemplate::formats("#{arabic}"),
257            within: None,
258            mark: NumberTemplate::formats("#{arabic}"),
259            placement: XnotePlacement::List,
260            layout: ArgLayout::InlineOrBlocks,
261            title_level: 2,
262            backlink: String::from("\u{21a9}"),
263            latex_command: String::from("footnote"),
264        }
265    }
266
267    /// An unnumbered xnote kind named `name` with the reference words
268    /// `words`: as [`XnoteKind::numbered`], but its xnotes are counted in no
269    /// counter and its mark is empty, so that no mark is written.
270    pub fn unnumbered(name: impl Into<Name>, words: PrefixWords) -> XnoteKind {
271        XnoteKind { numbered: false, mark: NumberTemplate::formats(""), ..XnoteKind::numbered(name, words) }
272    }
273
274    /// The default xnote kind, `footnote`: written `\footnote`, the words
275    /// `Footnote~` and `Footnotes~` (the capital variant the same), the label
276    /// type `fn`, numbered through the document, `#{arabic}` in a reference and
277    /// in the mark, listed, its layout inferred, the title `Footnotes` at
278    /// level 2, the back-link `↩`, the LaTeX command `footnote`.
279    pub fn footnote() -> XnoteKind {
280        let words = PrefixWords::new("Footnote~", "Footnotes~")
281            .with_variant(CAPITAL_VARIANT, PluralWords::new("Footnote~", "Footnotes~"));
282        XnoteKind::numbered("footnote", words).commands(["footnote"]).label_type("fn")
283    }
284
285    /// Builder: the commands with which an xnote of the kind is written,
286    /// without the backslash.
287    pub fn commands(mut self, commands: impl IntoIterator<Item = impl Into<String>>) -> XnoteKind {
288        self.commands = commands.into_iter().map(Into::into).collect();
289        self
290    }
291
292    /// Builder: the label type the kind's xnotes accept, made of ASCII
293    /// letters only.
294    pub fn label_type(mut self, label_type: impl Into<String>) -> XnoteKind {
295        self.label_type = label_type.into();
296        self
297    }
298
299    /// Builder: how a reference writes a numbered xnote's number.
300    pub fn number_format(mut self, number_format: NumberTemplate) -> XnoteKind {
301        self.number_format = number_format;
302        self
303    }
304
305    /// Builder: the counter within which a numbered kind is numbered.
306    pub fn within(mut self, within: Within) -> XnoteKind {
307        self.within = Some(within);
308        self
309    }
310
311    /// Builder: the text of the mark ([`mark`](XnoteKind::mark)).
312    pub fn mark(mut self, mark: NumberTemplate) -> XnoteKind {
313        self.mark = mark;
314        self
315    }
316
317    /// Builder: where the kind's xnotes are shown.
318    pub fn placement(mut self, placement: XnotePlacement) -> XnoteKind {
319        self.placement = placement;
320        self
321    }
322
323    /// Builder: how the content argument is laid out.
324    pub fn layout(mut self, layout: ArgLayout) -> XnoteKind {
325        self.layout = layout;
326        self
327    }
328
329    /// Builder: the heading placed above the kind's list, as FLM text,
330    /// compiled when the registry is built (a literal `#` is written `\#` or
331    /// `##`; see [`title`](XnoteKind::title)).
332    pub fn title(mut self, title: impl Into<String>) -> XnoteKind {
333        self.title = Some(title.into());
334        self
335    }
336
337    /// Builder: no heading above the kind's list.
338    pub fn without_title(mut self) -> XnoteKind {
339        self.title = None;
340        self
341    }
342
343    /// Builder: the level of the heading above the list, counted from zero.
344    pub fn title_level(mut self, level: u8) -> XnoteKind {
345        self.title_level = level;
346        self
347    }
348
349    /// Builder: the text of the link back from a listed xnote to its mark.
350    pub fn backlink(mut self, backlink: impl Into<String>) -> XnoteKind {
351        self.backlink = backlink.into();
352        self
353    }
354
355    /// Builder: the LaTeX command to which the style file's default
356    /// definition of `\flmXN<name>` passes the xnote, without the backslash
357    /// and made of ASCII letters: a command of the author's LaTeX, which the
358    /// author's own preamble may redefine.
359    pub fn latex_command(mut self, command: impl Into<String>) -> XnoteKind {
360        self.latex_command = command.into();
361        self
362    }
363
364    /// Checks what can be checked of one xnote kind on its own;
365    /// [`contribute_kind`](super::contribute_kind) calls it before it declares
366    /// anything.
367    ///
368    /// # Errors
369    ///
370    /// A sentence describing the first problem found: a name, a label type or
371    /// a LaTeX command that is empty or holds anything but ASCII letters; an
372    /// unnumbered kind whose mark holds a number placeholder. The number and
373    /// mark templates of a numbered kind are checked by the numbering feature,
374    /// when the registry compiles the kind's counter styles; the title and an
375    /// unnumbered kind's fixed mark are compiled, and checked, when the
376    /// registry is built.
377    pub fn validate(&self) -> Result<(), String> {
378        let name = self.name.as_str();
379        if name.is_empty() || !name.chars().all(|ch| ch.is_ascii_alphabetic()) {
380            return Err(format!(
381                "the xnote kind name `{name}` must consist of ASCII letters only"
382            ));
383        }
384        let label_type = self.label_type.as_str();
385        if label_type.is_empty() || !label_type.chars().all(|ch| ch.is_ascii_alphabetic()) {
386            return Err(format!(
387                "the label type `{label_type}` of the xnote kind `{name}` must consist of ASCII \
388                 letters only"
389            ));
390        }
391        let latex_command = self.latex_command.as_str();
392        if latex_command.is_empty() || !latex_command.chars().all(|ch| ch.is_ascii_alphabetic()) {
393            // The command is written into the style file as it stands: any
394            // other character would make a style file LaTeX cannot read, a
395            // mistake in configuration reported here and not when LaTeX runs.
396            return Err(format!(
397                "the LaTeX command `{latex_command}` of the xnote kind `{name}` must consist of \
398                 ASCII letters only, written without the backslash"
399            ));
400        }
401        if !self.numbered && names_number(&self.mark) {
402            return Err(format!(
403                "the mark `{}` of the unnumbered xnote kind `{name}` must not write a number, \
404                 since the kind is not numbered",
405                self.mark.text()
406            ));
407        }
408        Ok(())
409    }
410
411    /// Writes every field of the kind into `out`, for a registry digest: each
412    /// text preceded by its length, so that two different kinds never write
413    /// the same bytes.
414    ///
415    /// The fields are taken apart by name, so a field added to the kind and
416    /// not written here fails to compile.
417    pub(crate) fn digest_into(&self, out: &mut Vec<u8>) {
418        let XnoteKind {
419            name,
420            commands,
421            words,
422            label_type,
423            numbered,
424            number_format,
425            within,
426            mark,
427            placement,
428            layout,
429            title,
430            title_level,
431            backlink,
432            latex_command,
433        } = self;
434        push_text(out, name.as_str());
435        push_len(out, commands.len());
436        for command in commands {
437            push_text(out, command);
438        }
439        push_plural(out, &words.base);
440        push_len(out, words.variants.len());
441        for (variant, plural) in &words.variants {
442            push_text(out, variant);
443            push_plural(out, plural);
444        }
445        push_text(out, label_type);
446        out.push(u8::from(*numbered));
447        push_template(out, number_format);
448        match within {
449            Some(within) => {
450                out.push(1);
451                within.digest_into(out);
452            }
453            None => out.push(0),
454        }
455        push_template(out, mark);
456        out.push(match placement {
457            XnotePlacement::List => 0,
458            XnotePlacement::InPlace => 1,
459        });
460        out.push(match layout {
461            ArgLayout::Inline => 0,
462            ArgLayout::Blocks => 1,
463            ArgLayout::InlineOrBlocks => 2,
464        });
465        match title {
466            Some(title) => {
467                out.push(1);
468                push_text(out, title);
469            }
470            None => out.push(0),
471        }
472        out.push(*title_level);
473        push_text(out, backlink);
474        push_text(out, latex_command);
475    }
476}
477
478/// Whether the mark template `mark` holds a number placeholder: a `#{…}` in a
479/// [`Formats`](NumberTemplate::Formats) template, or one of the five
480/// characters that represent the number in an
481/// [`Initial`](NumberTemplate::Initial) one.
482// An unnumbered kind has no number to write, so a mark naming one is refused.
483// The placeholder test is the lists feature's, which refuses the same mistake,
484// and the five characters are every number format of a single-letter template.
485fn names_number(mark: &NumberTemplate) -> bool {
486    match mark {
487        NumberTemplate::Formats(text) => holds_placeholder(text),
488        NumberTemplate::Initial(text) => text.chars().any(|ch| matches!(ch, 'a' | 'A' | 'i' | 'I' | '1')),
489    }
490}
491
492/// The default title of an xnote kind with the reference words `words`: the
493/// plural word (the capital variant's, where one is declared) without its
494/// trailing non-breaking space, its first letter capitalized: `Footnotes~`
495/// gives `Footnotes`.
496fn plural_title(words: &PrefixWords) -> String {
497    let plural = words.variants.get(CAPITAL_VARIANT).unwrap_or(&words.base);
498    let word = plural.other.trim_end_matches(|ch: char| ch == '~' || ch.is_whitespace());
499    let mut chars = word.chars();
500    match chars.next() {
501        Some(first) => first.to_uppercase().chain(chars).collect(),
502        None => String::new(),
503    }
504}
505
506/// The configuration of the [`XnotesFeature`](super::XnotesFeature): the xnote
507/// kinds an author writes, in the order in which their lists are placed after
508/// the content.
509///
510/// The default ([`XnotesConfig::new`]) declares one xnote kind,
511/// [`XnoteKind::footnote`]: `\footnote{…}`, numbered, listed after the
512/// content under the heading `Footnotes`. A second xnote kind is added by
513/// configuration, with no new syntax:
514///
515/// ```
516/// use flm_core::stdlib::features::numbering::PrefixWords;
517/// use flm_core::stdlib::features::xnotes::{XnoteKind, XnotesConfig};
518///
519/// let config = XnotesConfig::new().kind(
520///     XnoteKind::numbered("endnote", PrefixWords::new("Endnote~", "Endnotes~"))
521///         .commands(["endnote"])
522///         .label_type("en"),
523/// );
524/// assert_eq!(config.kinds.len(), 2);
525/// assert_eq!(config.validate(), Ok(()));
526/// ```
527///
528/// [`XnotesFeature::new`](super::XnotesFeature::new) takes this value; the
529/// standard features carry it as
530/// [`StdlibConfig::xnotes`](crate::stdlib::StdlibConfig::xnotes). It is a
531/// feature's configuration: fixed when the registry is built, before any
532/// document is parsed (see [settings, options and
533/// configuration](crate::guide::concepts_overview#settings-options-and-configuration)),
534/// because the commands are part of the language, whether an xnote is a block
535/// is decided before a document's trees are frozen (no longer changed; see
536/// [frozen
537/// trees](crate::guide::concepts_overview#frozen-trees-and-computed-data)),
538/// and the counters and
539/// counter styles the feature declares depend on it. The feature therefore
540/// adds [`digest_bytes`](XnotesConfig::digest_bytes) to the registry digest,
541/// the fingerprint that decides whether a cached result may be reused.
542///
543/// The configuration is checked when the registry is built
544/// ([`XnotesConfig::validate`]): every xnote kind on its own
545/// ([`XnoteKind::validate`]), then two kinds of one name, two kinds sharing a
546/// command, and two kinds sharing a label type are refused. A kind with no
547/// command is accepted; no author can write its xnotes. A kind that another
548/// feature contributes ([`contribute_kind`](super::contribute_kind)) is
549/// checked on its own only: nothing refuses that it shares a label type with
550/// a configured kind.
551// Label types are compared within one configuration only: a contributed kind is
552// declared by its own feature and must work in a registry without the `xnotes`
553// feature, so no check of this feature could see every kind.
554#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
555#[derive(schemars::JsonSchema)]
556#[serde(default, deny_unknown_fields)]
557pub struct XnotesConfig {
558    /// The xnote kinds, in the order in which their lists are placed.
559    #[serde(deserialize_with = "crate::core::settings::named::deserialize")]
560    #[schemars(
561        transform = crate::core::settings::named::map_schema,
562        with = "std::collections::BTreeMap<String, XnoteKind>"
563    )]
564    pub kinds: Vec<XnoteKind>,
565}
566
567impl Default for XnotesConfig {
568    fn default() -> XnotesConfig {
569        XnotesConfig::new()
570    }
571}
572
573impl XnotesConfig {
574    /// The default configuration: a single xnote kind, [`XnoteKind::footnote`].
575    pub fn new() -> XnotesConfig {
576        XnotesConfig { kinds: vec![XnoteKind::footnote()] }
577    }
578
579    /// A configuration declaring no xnote kind at all.
580    pub fn empty() -> XnotesConfig {
581        XnotesConfig { kinds: Vec::new() }
582    }
583
584    /// Builder: adds the xnote kind `kind` after the kinds already declared.
585    pub fn kind(mut self, kind: XnoteKind) -> XnotesConfig {
586        self.kinds.push(kind);
587        self
588    }
589
590    /// The declared xnote kind named `name`, if there is one.
591    pub fn kind_named(&self, name: &str) -> Option<&XnoteKind> {
592        self.kinds.iter().find(|kind| kind.name.as_str() == name)
593    }
594
595    /// Checks the configuration; the feature calls it when it registers.
596    ///
597    /// # Errors
598    ///
599    /// A sentence describing the first problem found: one of
600    /// [`XnoteKind::validate`]'s, or two xnote kinds of one name, sharing a
601    /// command, or sharing a label type.
602    pub fn validate(&self) -> Result<(), String> {
603        for (at, kind) in self.kinds.iter().enumerate() {
604            kind.validate()?;
605            for earlier in &self.kinds[..at] {
606                if earlier.name == kind.name {
607                    return Err(format!(
608                        "two xnote kinds have the name `{}`; each xnote kind needs a name of its \
609                         own",
610                        kind.name
611                    ));
612                }
613                if let Some(command) = kind.commands.iter().find(|c| earlier.commands.contains(c)) {
614                    return Err(format!(
615                        "the xnote kinds `{}` and `{}` are both written `\\{command}`; each xnote \
616                         kind needs commands of its own",
617                        earlier.name, kind.name
618                    ));
619                }
620                if earlier.label_type == kind.label_type {
621                    return Err(format!(
622                        "the xnote kinds `{}` and `{}` both accept the label type `{}`; each \
623                         xnote kind needs a label type of its own",
624                        earlier.name, kind.name, kind.label_type
625                    ));
626                }
627            }
628        }
629        Ok(())
630    }
631
632    /// The canonical rendering of the configuration: what enters the registry
633    /// digest, and what `Hash` hashes.
634    ///
635    /// Every xnote kind is written out in order, every field of it, each text
636    /// preceded by its length, so two configurations give the same bytes
637    /// exactly when they are equal. Fields that have no effect (an unnumbered
638    /// kind's number format) are written too: a digest that differs where
639    /// nothing else does only prevents the reuse of a cached result, and never
640    /// produces a wrong one.
641    pub fn digest_bytes(&self) -> Vec<u8> {
642        let mut out = Vec::new();
643        push_len(&mut out, self.kinds.len());
644        for kind in &self.kinds {
645            kind.digest_into(&mut out);
646        }
647        out
648    }
649}
650
651impl Hash for XnotesConfig {
652    fn hash<H: Hasher>(&self, state: &mut H) {
653        state.write(&self.digest_bytes());
654    }
655}
656
657/// Writes a count as eight little-endian bytes.
658fn push_len(out: &mut Vec<u8>, len: usize) {
659    out.extend_from_slice(&(len as u64).to_le_bytes());
660}
661
662/// Writes a text as its length and its bytes.
663fn push_text(out: &mut Vec<u8>, text: &str) {
664    push_len(out, text.len());
665    out.extend_from_slice(text.as_bytes());
666}
667
668/// Writes the two words of `plural`.
669fn push_plural(out: &mut Vec<u8>, plural: &PluralWords) {
670    push_text(out, &plural.one);
671    push_text(out, &plural.other);
672}
673
674/// Writes which language `template` is written in, then its text.
675fn push_template(out: &mut Vec<u8>, template: &NumberTemplate) {
676    out.push(match template {
677        NumberTemplate::Formats(_) => 0,
678        NumberTemplate::Initial(_) => 1,
679    });
680    push_text(out, template.text());
681}
682
683/// An xnote kind is written in settings under its name, in the map of
684/// [`XnotesConfig::kinds`], and read over the kind that
685/// [`XnoteKind::numbered`] makes for that name and the words written; the
686/// words must be written.
687impl NamedEntry for XnoteKind {
688    fn read_entry(name: &str, data: serde_json::Value) -> Result<XnoteKind, String> {
689        let words: PrefixWords = named::required(name, &data, "words")?;
690        named::read_over(&XnoteKind::numbered(name, words), "name", name, data)
691    }
692}
693
694#[cfg(test)]
695mod tests {
696    use super::*;
697
698    #[test]
699    fn the_default_kind_is_the_footnote() {
700        let config = XnotesConfig::new();
701        assert_eq!(config.kinds.len(), 1);
702        let kind = &config.kinds[0];
703        assert_eq!(kind.name.as_str(), "footnote");
704        assert_eq!(kind.commands, ["footnote"]);
705        assert_eq!(kind.words.base, PluralWords::new("Footnote~", "Footnotes~"));
706        assert_eq!(kind.words.variants.get(CAPITAL_VARIANT), Some(&kind.words.base));
707        assert_eq!(kind.label_type, "fn");
708        assert!(kind.numbered);
709        assert_eq!(kind.number_format, NumberTemplate::formats("#{arabic}"));
710        assert_eq!(kind.mark, NumberTemplate::formats("#{arabic}"));
711        assert!(kind.within.is_none());
712        assert_eq!(kind.placement, XnotePlacement::List);
713        assert_eq!(kind.layout, ArgLayout::InlineOrBlocks);
714        assert_eq!(kind.title.as_deref(), Some("Footnotes"));
715        assert_eq!(kind.title_level, 2);
716        assert_eq!(kind.backlink, "\u{21a9}");
717        assert_eq!(kind.latex_command, "footnote");
718        assert_eq!(config.validate(), Ok(()));
719    }
720
721    #[test]
722    fn the_default_title_is_the_plural_word_capitalized() {
723        let kind = XnoteKind::numbered("endnote", PrefixWords::new("endnote~", "endnotes~"));
724        assert_eq!(kind.title.as_deref(), Some("Endnotes"));
725        let words = PrefixWords::new("n.~", "nn.~").with_variant(CAPITAL_VARIANT, PluralWords::new("Note~", "Notes~"));
726        assert_eq!(XnoteKind::unnumbered("aside", words).title.as_deref(), Some("Notes"));
727        assert_eq!(XnoteKind::numbered("x", PrefixWords::default()).title.as_deref(), Some(""));
728    }
729
730    #[test]
731    fn the_refusals_refuse_what_is_wrong() {
732        let refused = |config: XnotesConfig| config.validate().is_err();
733        let words = || PrefixWords::new("Note~", "Notes~");
734        assert!(refused(XnotesConfig::empty().kind(XnoteKind::numbered("side-note", words()))));
735        assert!(refused(XnotesConfig::empty().kind(XnoteKind::numbered("", words()))));
736        for label_type in ["", "fn:x", "side-note", "n1"] {
737            let kind = XnoteKind::numbered("other", words()).label_type(label_type);
738            assert!(refused(XnotesConfig::empty().kind(kind)), "{label_type:?}");
739        }
740        assert!(refused(XnotesConfig::new().kind(XnoteKind::footnote().label_type("x"))));
741        assert!(refused(
742            XnotesConfig::new().kind(XnoteKind::numbered("other", words()).commands(["footnote"]))
743        ));
744        assert!(refused(XnotesConfig::new().kind(XnoteKind::numbered("other", words()).label_type("fn"))));
745        let level_zero = XnoteKind::numbered("other", words()).title_level(0);
746        assert_eq!(level_zero.validate(), Ok(()), "a title level of 0 is accepted");
747        let marked = XnoteKind::unnumbered("aside", words()).mark(NumberTemplate::formats("(#{alph})"));
748        assert!(refused(XnotesConfig::empty().kind(marked)));
749        let marked = XnoteKind::unnumbered("aside", words()).mark(NumberTemplate::initial("(a)"));
750        assert!(refused(XnotesConfig::empty().kind(marked)));
751    }
752
753    #[test]
754    fn what_is_accepted() {
755        let words = || PrefixWords::new("Note~", "Notes~");
756        let config = XnotesConfig::new()
757            .kind(XnoteKind::numbered("addendum", words()).label_type("add"))
758            .kind(XnoteKind::unnumbered("aside", words()).mark(NumberTemplate::formats("\u{2020}")))
759            .kind(XnoteKind::unnumbered("star", words()).mark(NumberTemplate::formats("\\#")))
760            // An unnumbered kind's number format is ignored, not checked.
761            .kind(
762                XnoteKind::unnumbered("plain", words())
763                    .label_type("pl")
764                    .number_format(NumberTemplate::formats("#{nosuchformat}")),
765            );
766        // Two kinds with no command share none.
767        let config = config.kind(XnoteKind::numbered("other", words()));
768        assert_eq!(config.validate(), Ok(()), "{config:?}");
769    }
770
771    #[test]
772    fn the_digest_bytes_change_with_every_field() {
773        let base = XnotesConfig::new();
774        let kind = XnoteKind::footnote;
775        let one = |kind: XnoteKind| XnotesConfig { kinds: vec![kind] };
776        let changed = [
777            one(kind().commands(["fn", "footnote"])),
778            one(XnoteKind { words: PrefixWords::new("Note~", "Notes~"), ..kind() }),
779            one(kind().label_type("note")),
780            one(XnoteKind { numbered: false, ..kind() }),
781            one(kind().number_format(NumberTemplate::formats("#{roman}"))),
782            one(kind().number_format(NumberTemplate::initial("#{arabic}"))),
783            one(kind().within(Within::parent("flm.headings.section"))),
784            one(kind().mark(NumberTemplate::formats("[#{arabic}]"))),
785            one(kind().placement(XnotePlacement::InPlace)),
786            one(kind().layout(ArgLayout::Blocks)),
787            one(kind().title("Notes")),
788            one(kind().without_title()),
789            one(kind().title_level(3)),
790            one(kind().backlink("back")),
791            one(kind().latex_command("endnote")),
792            XnotesConfig::empty(),
793            base.clone().kind(XnoteKind::numbered("endnote", PrefixWords::new("E~", "Es~"))),
794        ];
795        for other in &changed {
796            assert_ne!(other.digest_bytes(), base.digest_bytes(), "{other:?}");
797        }
798        assert_eq!(XnotesConfig::new().digest_bytes(), base.digest_bytes());
799    }
800}