Skip to main content

flm_core/stdlib/features/citations/
mod.rs

1//! The `citations` feature: citing works by key, numbering the cited works in
2//! order of first citation, showing a citation mark where each citation is
3//! written, and listing the cited works after the document's content.
4//!
5//! # What an author writes
6//!
7//! `\cite[note]{key1,key2}` cites the works whose citation keys are `key1`
8//! and `key2`; it is shown as a **citation mark**, such as `[1,3–5]`, that holds the numbers of the cited
9//! works, each number a link to the work in the list of cited works.
10//! `\R[flags]\cite{keys}` writes the citation as a noun of its sentence: a
11//! word, `ref.~` for one number and `refs.~` for several, comes before the
12//! citation mark (the citation counter style holds the words; see "The
13//! configuration" below), so `\R\cite{a,b}` reads `refs.~[1,2]`. After the content, the list of cited works shows each work's
14//! **citation entry**, such as `Knuth, The Art of Computer Programming, 1984`,
15//! labeled with its number. The language guide describes both commands for
16//! authors ([Citations](crate::guide::language_syntax#citations)).
17//!
18//! # Citation keys and notes
19//!
20//! A **citation key** refers to a cited work: it is the FLM code written for it
21//! between the braces of `\cite`, kept as typed. The whitespace handling and
22//! the typographic substitutions of the document's text do not apply between
23//! those braces, because the keys argument is declared with an opaque wrapper
24//! ([`ArgDef::with_opaque_wrapper`](crate::lang::mint::ArgDef::with_opaque_wrapper)):
25//! the quotes and the dashes of a citation key stay as written. When the
26//! citation key is read, it is recomposed from the parsed nodes, with every run
27//! of whitespace made one space and the ends trimmed
28//! ([`spelling_identity`](crate::stdlib::backends::pres::spelling_identity)):
29//! `arxiv:1234.5678`, `knuth84`, `manual:{A. Author, "Some title" -- 2024}`. A
30//! comma inside a group, a command's argument or a formula belongs to the
31//! citation key, and a citation key may hold a command. The feature reads no
32//! meaning into a citation key: the citation providers decide what it refers to
33//! (see "Citation entries and citation providers" below).
34//!
35//! A **note** is the optional argument of a `\cite`: content shown after the
36//! numbers (`[31; Thm 4]`). It belongs to every citation key of that call.
37//!
38//! # Citation chunks
39//!
40//! `\cite` calls written directly one after the other, with nothing between
41//! them but spaces, a single line break and comments, are one **citation
42//! chunk**, shown as one citation mark. A citation chunk is one `\cite` node
43//! ([`CITE`], `flm.citations.cite`) whose last argument, a tack-on argument
44//! (the trailing argument that absorbs field macros written after a
45//! construct; see [fields](crate::guide::concepts_overview#fields-data-a-construct-reads))
46//! named [`MORE_ARG`], holds the further calls as fields named `cite`
47//! ([`CITE_FIELD`]). A paragraph break, a `~` or a `\ `, or any other
48//! content ends the citation chunk.
49//!
50//! [`read_chunk`] reads a citation chunk as a list of **items**, each a
51//! citation key and the note of its call, in the order written:
52//! `\cite{b}\cite[Thm 4]{a,c}` gives `(b)`, `(a, Thm 4)`, `(c, Thm 4)`. The
53//! keys argument of a call is parsed FLM code, split at the commas that are
54//! outside every group (`\cite{a,{b,c},d}` gives `a`, `{b,c}`, `d`); each part is
55//! recomposed into its citation key, and an empty part is skipped. Because a
56//! citation key is recomposed from the nodes rather than copied from the
57//! source text, a citation key that a user definition writes into a `\cite`
58//! is the one the expansion produced: `\cite{manual:\emph{#1}}`, used with the
59//! argument `{Title}`, gives `manual:\emph{Title}`.
60//!
61//! `\R` ([`REFCITE`], `flm.citations.refcite`) takes an optional flags
62//! argument (`S` for the capitalized word, `Refs.~`; `I` for no word) and,
63//! as a field of its tack-on argument [`CITATION_ARG`], the `\cite`
64//! written directly after it, together with that call's further calls. In
65//! `\R[S]{\cite{a}}` the `\cite` is inside a group, so the `\R` holds no
66//! citation.
67//!
68//! The citation keys and the flags are not words of the text around them
69//! ([`ApartFromText`](crate::model::aspects::ApartFromText)); the notes are. A
70//! heading without a label gets an identifier encoded from the text of its
71//! title; when the title holds `\cite[Thm 4]{a}`, that text is the title's own
72//! words and `Thm 4`, without the citation key `a`.
73//!
74//! # Cited works, numbers and identifiers
75//!
76//! A **cited work** is the article or book that a citation key refers to.
77//! Two citation keys may refer to one work (`arXiv:1211.1037` and
78//! `arxiv:1211.1037`), and only a citation provider can know it: its answer
79//! gives the work's **identity**, one spelling that every citation key of the
80//! work shares ([`CitationAnswer`]). The library compares identities as
81//! characters. A citation key that no citation provider answered refers to the work
82//! whose identity is the citation key as written, so a citation key spelled
83//! exactly like a work's identity is a citation key of that work.
84//!
85//! The collect stage `flm.citations.collect` ([`COLLECT`]) walks every
86//! citation chunk of the document in document order and records each distinct
87//! citation key at its first citation, with where it is first cited, in the
88//! table [`KEYS`] (`flm.citations.keys`).
89//!
90//! After the citation providers have been asked (below), the retrieve stage
91//! numbers the cited works ([`number_works`]): one work per distinct identity,
92//! in the order of the first citation of any of its citation keys. It writes
93//! the table [`CITATIONS`] (`flm.citations`): for each citation key, its
94//! work's number, its work's identifier `citation-<n>` and its work's
95//! identity, the citation keys of one work sharing all three. The numbers
96//! therefore depend only on the document and on the citation providers'
97//! answers. The identifier prefix [`IDENTIFIER_PREFIX`], `citation-`, belongs
98//! to this feature, and no other feature creates identifiers with it. A cited
99//! work is not a [reference point](crate::model::aspects::RefPoint), and a
100//! citation is not a reference: nothing refers to a cited work by label.
101//!
102//! # The citation mark
103//!
104//! [`stage_mark`] stages (builds into the lowered tree; see
105//! [`Lowerer`](crate::core::lowering::Lowerer)) a citation chunk's citation
106//! mark: a span of role [`MARK_ROLE`] (a role is a name on a presentation
107//! node that says what it is; see [roles and kind
108//! tokens](crate::stdlib::backends::pres::payload)) whose numbers are links of
109//! kind `cite` to their works' identifiers, with the delimiters and the join
110//! texts outside the links. The items without a note come first, in one group,
111//! their numbers sorted and compressed into ranges as the citation counter
112//! style says (see "The configuration" below) (`[1–3,5]`); then
113//! one group per distinct note, in the order of the note's first appearance.
114//! With `a`, `b`, `c`, `d`, `e` cited in that order earlier,
115//! `\cite{c,b}\cite[Thm 4]{a}\cite{d}\cite[Thm 4]{e}` reads `[2–4][1,5; Thm
116//! 4]`. Each work appears once in a group: with `arXiv:1211.1037` and
117//! `arxiv:1211.1037` one work, `\cite{arXiv:1211.1037,arxiv:1211.1037}` reads
118//! `[1]`.
119//!
120//! The citation mark of a `\cite` is **attached** to the content before it
121//! (kind token [`ATTACHED`]): the whitespace written before `\cite` is
122//! removed, the spaces `~` and `\ ` included (`word~\cite{a}`, `word ~ \cite{a}`
123//! and `word \cite{a}` read alike), and a no-break space is written before the
124//! citation mark ([`space_before`]), as a character in a span of role
125//! [`SPACE_ROLE`], under the bracketed form of the citation mark and under the
126//! in-place placement; under the superscript form nothing is written (the form
127//! and the placement are settings of the configuration; see "The
128//! configuration" below). The
129//! content around a citation mark is not read: a `\cite` at the start of a
130//! paragraph or after `(` also has its space written, and an author writes
131//! `\R[I]\cite{a}` there instead. The citation mark of an `\R` is
132//! **standalone** (kind token [`STANDALONE`]): shown inline, never raised, with
133//! no space written before it and none removed.
134//!
135//! # Citation entries and citation providers
136//!
137//! The **citation entry** of a cited work ([`CitationEntry`]) is what is shown
138//! for it: inline content written with the commands of the registry's
139//! language (text, `\emph`, a link, a formula), which may not declare a label
140//! (see [`CitationEntry`]). The library performs no input or output: the citation
141//! entries come from **citation providers** ([`CitationProvider`]), which the
142//! host contributes to the service slot [`PROVIDERS_SLOT`]
143//! (`flm.citations.providers`; see
144//! [`service_slot`](crate::core::registry::FeatureBuilder::service_slot) and
145//! [services](crate::core::services)). The service slot takes any number of
146//! citation providers and the feature never requires one. A citation provider
147//! returns, for a citation key, an answer holding its citation entry, "not
148//! mine", or an error.
149//!
150//! The retrieve stage `flm.citations.retrieve` ([`RETRIEVE`]) asks the
151//! citation providers about the cited keys, in the order of precedence of the
152//! service slot (the providers of the feature placed last in the feature order
153//! first, each feature's in the order it contributed them, the host's last;
154//! [`PROVIDERS_SLOT`]): the first citation provider receives every citation key in one call, in
155//! order of first citation ([`CitationProvider::answer_all`]), and each later
156//! one receives, in one call, the citation keys that every citation provider
157//! before it answered "not mine". A citation provider written for one citation
158//! key at a time implements [`CitationProvider::answer`] alone. The first
159//! citation provider that claims a citation key decides it: its answer
160//! ([`CitationAnswer`]: the citation entry and the work's identity), or an
161//! error that is final for that citation key. The stage writes the table
162//! [`ENTRIES`] (`flm.citations.entries`): for each citation key, its answer or
163//! the reason it has no citation entry ([`MissingEntry`]); then it numbers the
164//! cited works. Each citation entry is read as the document would show it,
165//! with user definitions expanded, and is refused when it holds a citation or
166//! block content (a paragraph break, a list, a heading). A citation key with no
167//! citation entry is numbered and shown in citation marks like any other.
168//!
169//! A citation provider makes a citation entry from FLM source
170//! ([`ProviderCx::parse_entry`]) or from parts ([`EntryPiece`],
171//! [`ProviderCx::build_entry`]): characters, FLM source, emphasis, strong
172//! importance and links. Each part with a meaning is written as the command of
173//! the feature that owns that meaning (`\emph`, `\textbf`, `\href`), so the
174//! citation entry is shown exactly as the same content written in FLM.
175//!
176//! # The check that every cited key has a citation entry
177//!
178//! The check stage `flm.citations.check` ([`CHECK`]) reports every cited key
179//! that has no citation entry ([`NoEntry`]), one report per citation key, even
180//! when several citation keys refer to one work. It provides a member of the
181//! collection [`flm.validated`](crate::stdlib::VALIDATED), which every
182//! workflow demands (asks the plan to run a stage that provides it; see
183//! [`PlanRequest::demand`](crate::core::plan::PlanRequest::demand)), so the
184//! check runs under every workflow, the `check` workflow included; because it
185//! reads the citation entries, the citation providers are asked under every
186//! workflow.
187//!
188//! # The list of cited works
189//!
190//! The **bibliography** is a piece ([`BIBLIOGRAPHY`],
191//! `flm.citations.bibliography`): a document-level [synthesized
192//! value](crate::guide::concepts_overview#synthesized-values) that a
193//! backend places beside the document's content
194//! ([`Piece`](crate::core::piece::Piece)), here after it. It holds a heading
195//! (the configured title, `References` by default, at the configured level, 2
196//! by default; no heading where the configuration sets no title) and one
197//! citation entry per cited work, in the order of the numbers, each labeled
198//! with its number (`[1]`) and carrying its work's identifier. The citation
199//! entry shown for a work is the one answered for the citation key under which
200//! the work was first cited; a work with no citation entry shows a dropped
201//! mark (a `flm.pres.dropped` node; see
202//! [recovery](crate::stdlib::backends::lowering::error)) in its place.
203//!
204//! [`build_list`] builds such a list from any set of cited works; the builder
205//! stage `flm.citations.build-bibliography` ([`BUILD_BIBLIOGRAPHY`]) calls it
206//! over every cited work of the document. The feature contributes the piece's
207//! declaration to the `pieces` feature's service slot as a peer contribution
208//! ([`FeatureBuilder::peer_slot`](crate::core::registry::FeatureBuilder::peer_slot)):
209//! without the `pieces` feature, the list is built and no backend places it.
210//! Two pieces placed after the content are placed in the order their features
211//! contributed them; among the standard features
212//! ([`stdlib::add_features`](crate::stdlib::add_features)) the `xnotes` feature comes
213//! first, so the list of cited works follows the lists of xnotes (notes set
214//! apart from the running text, such as footnotes; see
215//! [`xnotes`](crate::stdlib::features::xnotes)). On the `latex-recomposed`
216//! backend ([`latex`]), no list is placed and no citation entry is written:
217//! LaTeX writes its own list of cited works there.
218//!
219//! # The placements of the citation entries
220//!
221//! The configuration's **placement** ([`CitationPlacement`]) decides where
222//! the citation entries are shown. Under *listed*, the default, the
223//! bibliography is placed after the content and the citation marks show
224//! numbers. Under *in place*, a citation mark shows, for each item in the
225//! order written, the item's citation entry between the citation counter
226//! style's delimiters, then the note separator and the note:
227//! `[Knuth, 1984][Lamport, 1994; Thm 4]`. The citation mark then holds no
228//! link and carries the kind token [`IN_PLACE`], and no list is placed. A
229//! `\cite` writes its no-break space before an in-place citation mark, and an
230//! `\R` writes its word.
231//!
232//! # The configuration
233//!
234//! [`CitationsConfig`] is the feature's configuration, fixed when the registry
235//! is built ([configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
236//! It holds:
237//!
238//! - the placement of the citation entries (see above);
239//! - the **form** of a citation mark ([`MarkForm`]): bracketed, the default,
240//!   or superscript. Under the superscript form, no delimiters are written
241//!   wherever numbers are shown, the numbers of a `\cite` are raised, and
242//!   those of an `\R` stay inline. The form has no effect under the in-place
243//!   placement;
244//! - the **citation counter style**, the counter style
245//!   ([`CounterStyleDecl`](crate::stdlib::features::numbering::CounterStyleDecl))
246//!   that writes the numbers of the cited works, the delimiters, the texts
247//!   joining several numbers and the words `\R` writes. This feature compiles
248//!   it when the registry is built, and the counter styles a host sets in the
249//!   numbering feature's configuration
250//!   ([`NumberingConfig::styles`](crate::stdlib::features::numbering::NumberingConfig::styles))
251//!   do not replace it;
252//! - the **heading** above the list of cited works (its title and its level,
253//!   or no heading);
254//! - the text written before a note.
255//!
256//! # What the feature registers
257//!
258//! - Elements: `\cite` ([`CITE`]) and `\R` ([`REFCITE`]), available in text
259//!   mode; the synthesized list and list-entry elements of the bibliography
260//!   ([`BIBLIOGRAPHY`], [`BIBLIOGRAPHY_ENTRY`]), which no author writes.
261//! - The argument role [`KEY_ARG_ROLE`] (`flm.citations.key`), which states
262//!   that an argument holds citation keys
263//!   ([`ArgDef::role`](crate::lang::mint::ArgDef::role)): the role of the keys
264//!   argument of `\cite` and of the `cite` fields of `\cite` and `\R`.
265//! - Tables: [`KEYS`], [`ENTRIES`], [`CITATIONS`] and the piece table
266//!   [`BIBLIOGRAPHY`] ([`bibliography_table`]).
267//! - Stages, all of document scope: collect ([`COLLECT`]); retrieve
268//!   ([`RETRIEVE`]), which reads what collect writes; and the bibliography's
269//!   builder ([`BUILD_BIBLIOGRAPHY`]) and check ([`CHECK`], which also
270//!   provides the capability of that name), which read what retrieve writes.
271//! - The service slot [`PROVIDERS_SLOT`], which the host fills with citation
272//!   providers.
273//! - The settings of the feature (see "The configuration").
274//! - The stylesheet `flm.citations.style` ([`html::stylesheet`]) and the
275//!   definition piece `flm.latex.def.citations` ([`latex::definition_piece`]),
276//!   the latter contributed to the style file's service slot as a peer
277//!   contribution.
278//! - Lowering rules: on every backend, the general rules of `\cite` and `\R`
279//!   ([`CITE_RULE`], [`REFCITE_RULE`]), which stage the citation mark, and of
280//!   the list of cited works ([`BIBLIOGRAPHY_RULE`]), which stages a block
281//!   holding a heading and a labeled list. The general rules of `\cite` and
282//!   `\R` require the feature's style identifier `flm.citations.style`
283//!   ([`html::STYLE`]), which on the `html` backend names the stylesheet, so
284//!   a page holding no citation does not carry it.
285//!   On the `latex-recomposed` backend, rules ([`latex`]) that write a
286//!   citation as the author wrote it through three LaTeX hooks, and write
287//!   nothing for the list. The rendering guide shows the output on each
288//!   backend ([Citations](crate::guide::rendering#citations), [Citations in
289//!   HTML](crate::guide::rendering#citations-in-html), [Citations in the
290//!   recomposed LaTeX](crate::guide::rendering#citations-in-the-recomposed-latex)).
291//! - A build hook ([`LateInit`](crate::core::registry::LateInit)) that
292//!   compiles the citation counter style, the note separator and the title of
293//!   the list: a text that is not valid FLM fails
294//!   the registry build.
295//!
296//! # Dependencies
297//!
298//! The feature requires the element index (the `index` feature,
299//! [`index`](crate::stdlib::features::index)), whose table the stages walk,
300//! and the presentation vocabulary of the `lowering` feature. It does not
301//! depend on the `numbering` feature (it uses the counter-style code, not the
302//! counters), nor on `refs` or `xnotes`. The `latex-recomposed` backend,
303//! the LaTeX family's constructs and the `pieces` feature are peer
304//! declarations ([`PeerName`](crate::core::registry::PeerName)) and peer
305//! contributions: the feature builds without them, with its rules for an
306//! absent backend set aside (excluded from rule selection; see
307//! [`PeerName`](crate::core::registry::PeerName)).
308//!
309//! # Map of the items
310//!
311//! - The feature: [`Citations`], [`feature`], [`FEATURE`]; its configuration
312//!   [`CitationsConfig`], [`CitationPlacement`], [`MarkForm`],
313//!   [`default_style`].
314//! - The elements and the citation chunk reader: [`CITE`], [`REFCITE`],
315//!   [`CitationElement`], [`read_chunk`], [`calls`], [`leading_call`],
316//!   [`Chunk`], [`CitationItem`], [`ChunkMistake`], [`Reading`].
317//! - The cited keys and the numbers: [`KEYS`], [`CitedKeys`], [`CITATIONS`],
318//!   [`CitedWorks`], [`CitedWork`], [`number_works`].
319//! - The citation providers: [`PROVIDERS_SLOT`], [`CitationProvider`],
320//!   [`CitationRequest`], [`CitationAnswer`], [`CitationEntry`],
321//!   [`EntryPiece`], [`ProviderCx`], [`CitationProviderError`].
322//! - The citation entries: [`ENTRIES`], [`CitationEntries`], [`Retrieval`],
323//!   [`MissingEntry`].
324//! - The citation mark: [`stage_mark`], [`StagedMark`], [`MarkSettings`],
325//!   [`space_before`], [`Standing`], [`CiteRule`], [`RefCiteRule`],
326//!   [`report_mistakes`], and the role and kind-token constants.
327//! - The list of cited works: [`build_list`], [`ListedWork`],
328//!   [`ListedEntry`], [`BibliographyRule`], [`BIBLIOGRAPHY`].
329//! - The diagnostics: [`NoKey`], [`NoCitation`], [`UnknownFlag`],
330//!   [`Uncollected`], [`NoProvider`], [`ProviderFailed`],
331//!   [`ProviderWarning`], [`EntryCites`], [`EntryNotInline`], [`NoEntry`],
332//!   [`StageFailed`].
333//! - The stylesheet: [`html`]. The `latex-recomposed` backend's rules:
334//!   [`latex`]. The `latex-rendered` backend's definition piece:
335//!   [`latex_rendered`].
336
337pub mod html;
338pub mod latex;
339pub mod latex_rendered;
340
341mod bibliography;
342mod check;
343mod config;
344mod diagnostics;
345mod elements;
346mod entries;
347mod mark;
348mod numbers;
349mod providers;
350
351use std::sync::Arc;
352
353use crate::core::settings::SettingsDecl;
354use crate::core::registry::{BuildError, CapabilityDef, FeatureBuilder, FeatureInfo, FlmFeature};
355use crate::core::services::Arity;
356use crate::lang::mint::{ElementDef, SyntaxDef};
357use crate::model::names::FeatureName;
358use crate::stdlib::VALIDATED;
359
360pub use bibliography::{
361    bibliography_table, build_list, BibliographyRule, ListedEntry, ListedWork, BIBLIOGRAPHY,
362    BIBLIOGRAPHY_ENTRY, BIBLIOGRAPHY_ENTRY_RULE, BIBLIOGRAPHY_RULE, BUILD_BIBLIOGRAPHY,
363    ENTRY_NUMBER_ROLE, KIND_CITATIONS,
364};
365pub use check::CHECK;
366pub use config::{
367    default_style, CitationPlacement, CitationsConfig, MarkForm, CAPITAL_VARIANT, STYLE_NAME,
368};
369pub use diagnostics::{
370    EntryCites, EntryNotInline, NoCitation, NoEntry, NoKey, NoProvider,
371    ProviderFailed, ProviderWarning, Uncollected, UnknownFlag,
372};
373pub use elements::{
374    calls, cite_args, cite_element, leading_call, read_chunk, refcite_args, refcite_element,
375    CitationElement, CitationItem, Chunk, ChunkMistake, Reading, CITATION_ARG, CITE, CITE_FIELD,
376    FLAGS_ARG, KEYS_ARG, KEY_ARG_ROLE, MORE_ARG, NOTE_ARG, REFCITE,
377};
378pub use entries::{CitationEntries, MissingEntry, Retrieval, ENTRIES, RETRIEVE};
379pub use providers::{
380    CitationAnswer, CitationEntry, CitationProvider, CitationProviderError, CitationRequest,
381    CitationResult, EntryPiece, ProviderCx, PROVIDERS_SLOT,
382};
383pub use mark::{
384    report_mistakes, space_before, stage_mark, CiteRule, MarkSettings, RefCiteRule, Standing,
385    StagedMark, ATTACHED, CAPITAL_FLAG, CITE_RULE, INLINE_FLAG, IN_PLACE, LINK_KIND, MARK_ROLE,
386    NO_BREAK_SPACE, REFCITE_RULE, SPACE_ROLE, STANDALONE, WORD_ROLE,
387};
388pub use numbers::{
389    number_works, CitedKeys, CitedWork, CitedWorks, StageFailed, CITATIONS, COLLECT, KEYS,
390    IDENTIFIER_PREFIX,
391};
392
393/// The feature's registered name, `citations`.
394pub const FEATURE: &str = "citations";
395
396/// The declaration of the feature's settings: the fields of [`CitationsConfig`]
397/// are its settings keys, and the texts among them are FLM markup. See
398/// [`crate::core::settings`].
399fn settings() -> SettingsDecl {
400    SettingsDecl::new(FEATURE)
401        .config::<CitationsConfig>(
402            "Where the citation entries are shown (`placement`: `listed` after the content, or \
403            `in-place` in the citation marks), how a citation mark shows its numbers (`mark`: \
404            `bracketed` or `superscript`), the citation counter style (`style`: the number format, the \
405            delimiters, the texts joining several numbers, whether consecutive numbers make a \
406            range, and the words `\\R` writes), the heading above the list of cited works \
407            (`heading_title`, or null for no heading, and `heading_level`), and the text written \
408            between the numbers and a note (`note_separator`). Fixed when the registry is built: \
409            it cannot vary per document or per render.",
410        )
411        .markup("heading_title")
412        .markup("note_separator")
413        .markup("style.prefix_words")
414        .markup("style.number_format")
415        .markup("style.sub_levels")
416        .markup("style.delimiters")
417        .markup("style.join")
418}
419
420/// The `citations` feature ([`FlmFeature`]): it registers the elements
421/// `\cite` and `\R`, the collect, retrieve, check and bibliography-builder
422/// stages with their tables (the cited keys, the citation entries, the cited
423/// works, the bibliography piece), the service slot of the citation
424/// providers, and the lowering rules of the citation marks and of the list of
425/// cited works on every backend, the `html` backend and the recomposed LaTeX.
426/// The [module documentation](self) describes the feature in full.
427///
428/// Construct it with [`Citations::new`] from a [`CitationsConfig`], or take
429/// the default configuration with [`feature`];
430/// [`stdlib::add_features`](crate::stdlib::add_features) constructs it from
431/// [`StdlibConfig::citations`](crate::stdlib::StdlibConfig::citations).
432#[derive(Debug, Clone, Default)]
433pub struct Citations {
434    config: CitationsConfig,
435}
436
437impl Citations {
438    /// The feature constructed from `config`, which stays fixed for the life
439    /// of every registry the feature is built into.
440    pub fn new(config: CitationsConfig) -> Citations {
441        Citations { config }
442    }
443
444    /// The configuration this feature was constructed with.
445    pub fn config(&self) -> &CitationsConfig {
446        &self.config
447    }
448}
449
450impl FlmFeature for Citations {
451    fn info(&self) -> FeatureInfo {
452        FeatureInfo::new(FEATURE, "Citations").docs(
453            "Citing works by key: `\\cite[note]{keys}`, adjacent calls read as one citation \
454             chunk, and `\\R\\cite{keys}`, a citation written as a noun of its sentence. The \
455             host's citation providers give each cited citation key its citation entry and say \
456             which citation keys refer to the same work; the works are numbered in order of first citation, each \
457             citation chunk is shown as a citation mark linking to its works, and the works are \
458             listed after the content, or their citation entries are shown in the citation marks.",
459        )
460    }
461
462    fn settings(&self) -> Option<SettingsDecl> {
463        Some(settings())
464    }
465
466    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
467        let owner: FeatureName = b.feature().clone();
468        b.argument_role(
469            KEY_ARG_ROLE,
470            "Citation keys, each identifying a cited work, separated by commas.",
471        )?;
472        b.element(
473            ElementDef::new(owner.clone(), ["cite"], SyntaxDef::Macro { args: cite_args() }, cite_element())
474                .docs(
475                    "Cites works by key; calls written next to one another are one citation \
476                     chunk, attached to the content before it.",
477                ),
478        )?;
479        b.element(
480            ElementDef::new(owner.clone(), ["R"], SyntaxDef::Macro { args: refcite_args() }, refcite_element())
481                .docs(
482                    "Writes the citation chunk of the `\\cite` written after it as a noun of its \
483                     sentence, after a word, `ref.~` or `refs.~` by default.",
484                ),
485        )?;
486        b.element_type_text(
487            elements::CITE,
488            "A citation chunk: one or more works cited by key, shown as their marks and \
489             attached to the content before it.",
490        )?;
491        b.element_type_text(
492            elements::REFCITE,
493            "A citation chunk written as a noun of its sentence, after a word such as `ref.~`.",
494        )?;
495        b.table_named::<numbers::CitedKeys>(
496            KEYS.name(),
497            "Every citation key the document cites, once, in order of first citation, with where \
498             it is first cited.",
499        )?;
500        b.table_named::<numbers::CitedWorks>(
501            CITATIONS.name(),
502            "The cited works of the document: for each citation key, the work it refers to, with \
503             the work's number (in order of the first citation of any of its keys), its \
504             identifier `citation-<n>` and its identity.",
505        )?;
506        b.stage(Arc::new(numbers::Collect))?;
507        b.service_slot::<dyn CitationProvider>(
508            PROVIDERS_SLOT,
509            Arity::OrderedMany,
510            "The citation providers, which give the citation entries of the cited works and are \
511             asked in order for each cited key; the feature never requires one.",
512        )?;
513        b.table_named::<entries::CitationEntries>(
514            ENTRIES.name(),
515            "The citation entries of the cited works: for each citation key, its citation entry \
516             or the reason it has none.",
517        )?;
518        b.stage(Arc::new(entries::Retrieve))?;
519        b.capability(CapabilityDef::new(CHECK).docs(
520            "The citations have been checked: every cited key with no citation entry was \
521             reported as an Error. A member of `flm.validated`.",
522        ))?;
523        b.stage(Arc::new(check::Check))?;
524        b.collection_member(VALIDATED, CHECK)?;
525        let settings = Arc::new(mark::MarkSettings::new(self.config.clone()));
526        b.late_init(Arc::new(mark::CompileSettings { settings: Arc::clone(&settings) }))?;
527        for rule in mark::rules(&settings) {
528            b.lowering_rule(rule)?;
529        }
530        bibliography::declare(b, &owner, &settings)?;
531        html::register(b)?;
532        latex_rendered::register(b)?;
533        latex::register(b, &settings)?;
534        b.digest_input(&self.config.digest_bytes())?;
535        Ok(())
536    }
537}
538
539/// The `citations` feature constructed from the default configuration
540/// ([`CitationsConfig::new`]).
541pub fn feature() -> Arc<dyn FlmFeature> {
542    Arc::new(Citations::default())
543}