Skip to main content

flm_core/stdlib/
mod.rs

1//! The standard features of flm-core: the features and backends that make the library
2//! a working FLM processor, and the function that adds them to a package.
3//!
4//! A *feature* ([`FlmFeature`]) is a Rust value that contributes a related bundle of
5//! things to a registry (elements, stages, tables, lowering rules, backends, services,
6//! settings) through the feature builder ([`FeatureBuilder`]), and a *package* is a
7//! named bundle of features together with the packages it builds on
8//! ([`PackageEntry`]). A program declares its own package and adds the standard
9//! features to it with [`add_features`]. The standard features provide:
10//!
11//! - the commands and environments an author writes: inline formatting, literal
12//!   characters, headings, mathematics, labels and references, verbatim content, lists,
13//!   footnotes and the other xnotes, hyperlinks, defined terms, theorems, quotations,
14//!   annotations, images, floats, tables of cells, citations, included files and user
15//!   definitions;
16//! - the stages that structure and check a document: block structure, the element
17//!   index, the table of reference points, numbering, and the checks every workflow runs
18//!   (see [Every workflow validates](#every-workflow-validates-the-collection-flmvalidated)
19//!   below);
20//! - the document's metadata (title, authors, date), shown before the content, and the
21//!   table of contents;
22//! - four output formats: plain text (`text`), HTML (`html`), rendered LaTeX
23//!   (`latex-rendered`) and recomposed LaTeX (`latex-recomposed`), the last two built
24//!   on `latex`, which every LaTeX backend shares, with the lowering stage, the
25//!   presentation elements and the pieces (document-level values such as the title,
26//!   placed before or after the content; [`Piece`](crate::core::piece::Piece)) they
27//!   share ([`backends`]);
28//! - the `check` workflow, which validates a document and writes no output.
29//!
30//! The standard features process no mathematics: the `math` feature introduces
31//! mathematics into the language, and another feature processes it, for example the
32//! feature [`math-passthrough`](crate::math_passthrough), which carries every formula to
33//! the output as written, or a feature of an extension that typesets formulas. A
34//! registry that holds the standard features and no such feature builds and plans every
35//! standard workflow, and a render reports each formula as an Error (the
36//! [`math`](features::math) module documentation, *Processing mathematics*).
37//!
38//! The standard features have no special status: each registers through the same
39//! feature builder a feature of another crate uses, so a program can add commands,
40//! change how a standard element is rendered or add an output format without an
41//! extension point made for the purpose (see [features and
42//! packages](crate::guide::concepts_overview#features-and-packages), and [the extension
43//! guide](crate::guide::extending) for writing a feature or a package).
44//!
45//! # Adding the standard features to a package
46//!
47//! A program written in Rust declares its package entry, adds the standard features to
48//! it with [`add_features`] from a [`StdlibConfig`], and adds the entry to a registry
49//! builder with
50//! [`RegistryBuilder::use_package`](crate::core::registry::RegistryBuilder::use_package):
51//!
52//! ```
53//! use flm_core::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
54//! use flm_core::stdlib::{self, StdlibConfig};
55//!
56//! let mut builder = RegistryBuilder::new();
57//! builder.use_package(stdlib::add_features(PackageEntry::new("std"), StdlibConfig::new()));
58//! let registry = builder.build(&RegistryInputs::new())?;
59//!
60//! // The standard features ship the `check` workflow: validation, no output.
61//! assert!(registry.workflow(stdlib::CHECK_WORKFLOW).is_some());
62//! # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
63//! ```
64//!
65//! The package's name is the program's choice, and so are the features it adds to the
66//! package after the standard ones.
67//!
68//! [`StdlibConfig`] holds the configuration of each of the sixteen standard features
69//! that take one; the other seventeen take none. A feature's configuration is the plain
70//! Rust value the feature is constructed from; it is fixed when the registry is built
71//! and cannot vary per document or per render (see [settings, options and
72//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
73//!
74//! A program that reads its settings as data, for example from a document's front
75//! matter, uses [`add_features_from_settings`] instead, in the build function of its
76//! package's [`PackageFactory`](crate::core::registry::PackageFactory): the function
77//! reads each feature's configuration from the settings it is given and leaves out the
78//! features those settings switch off.
79//!
80//! The pipeline guide ([`crate::guide::pipeline`]) explains what a run does with the
81//! stages the features declare, and the embedding guide ([`crate::guide::embedding`])
82//! shows a complete program.
83//!
84//! # The standard features and where each is documented
85//!
86//! [`add_features`] adds the thirty-three features in this order, each once, after the
87//! features the package entry holds. Each is given with the module that documents it:
88//!
89//! 1. `textstyles` ([`features::textstyles`]): `\emph`, `\textbf`, `\textit`, `\texttt`.
90//! 2. `literals` ([`features::literals`]): the commands and characters that stand for
91//!    one character of text, such as `\%` and `~`.
92//! 3. `blocks` ([`features::blocks`]): paragraphs and blocks, typographic
93//!    substitutions, and the check of the tree contract.
94//! 4. `index` ([`features::index`]): the table of the nodes whose elements carry each
95//!    aspect.
96//! 5. `refpoints` ([`features::refpoints`]): the table of every reference point.
97//! 6. `numbering` ([`features::numbering`]): counters, counter styles, and the number
98//!    of every numbered reference point.
99//! 7. `math` ([`features::math`]): inline and display mathematics: the display-math
100//!    environments, their equation lines and numbers, the text commands of mathematics.
101//! 8. `refs` ([`features::refs`]): `\label`, `\ref`, `\hyperref`, anchors, and the
102//!    label check.
103//! 9. `headings` ([`features::headings`]): `\section` to `\subparagraph`, and heading
104//!    kinds a program declares.
105//! 10. `verbatim` ([`features::verbatim`]): content taken exactly as written.
106//! 11. `lists` ([`features::lists`]): `itemize`, `enumerate`, `description` and their
107//!     `\item`s.
108//! 12. `xnotes` ([`features::xnotes`]): `\footnote` and the other kinds of xnote.
109//! 13. `href` ([`features::href`]): `\href`, `\url` and `\email`.
110//! 14. `defterm` ([`features::defterm`]): the `defterm` environment and `\term`.
111//! 15. `theorems` ([`features::theorems`]): `theorem`, `lemma`, `proof` and the other
112//!     theorem kinds.
113//! 16. `quote` ([`features::quote`]): `quote`, `blockquote` and `address`.
114//! 17. `annotations` ([`features::annotations`]): a reviewer's highlights and
115//!     comments, one command per configured reviewer.
116//! 18. `graphics` ([`features::graphics`]): `\includegraphics`.
117//! 19. `floats` ([`features::floats`]): `figure`, `table` and other float types, with
118//!     their captions.
119//! 20. `cells` ([`features::cells`]): tables of cells, the `cells` environment.
120//! 21. `citations` ([`features::citations`]): `\cite` and the list of cited works.
121//! 22. `input` ([`features::input`]): `\input`, the content of another file.
122//! 23. `userdefs` ([`features::userdefs`]): macros and environments defined by
123//!     substitution.
124//! 24. `lowering` ([`backends::lowering`]): the lowering stage, and the lowering rules
125//!     of the structural elements.
126//! 25. `metadata` ([`features::metadata`]): the document's title, authors and date.
127//! 26. `toc` ([`features::toc`]): the table of contents, a table of the listed
128//!     headings and a piece placed before the content.
129//! 27. `pieces` ([`backends::pieces`]): what a backend places before or after the
130//!     document's content.
131//! 28. `text` ([`backends::text`]): the plain-text backend and the `text` workflow.
132//! 29. `latex` ([`backends::latex`]): what every LaTeX backend shares.
133//! 30. `latex-recomposed` ([`backends::latex_recomposed`]): the recomposed-LaTeX
134//!     backend and the `latex-recomposed` workflow.
135//! 31. `latex-rendered` ([`backends::latex_rendered`]): the rendered-LaTeX
136//!     backend and the `latex-rendered` workflow.
137//! 32. `html` ([`backends::html`]): the HTML backend and the `html` workflow.
138//! 33. `check` ([`CheckWorkflow`]): the collection `flm.validated` and the `check`
139//!     workflow.
140//!
141//! The order is the order in which the registry registers them. It breaks the tie between two
142//! stages a plan could run in either order, it decides which feature is recorded as
143//! the owner of an element value two features both declare (the one placed last), and, where two
144//! features define one command name in the same parsing mode, it decides whose
145//! definition applies: the later one, and the clash is reported unless the feature
146//! order places that feature explicitly after the other, or that feature declares an
147//! override. A weak declaration of the name applies only where no feature declares the
148//! name ordinarily in that mode, whatever the order (see [`crate::lang::mint::packages`]).
149//!
150//! # Every workflow validates: the collection `flm.validated`
151//!
152//! A *collection* is a name for a set of capabilities that any feature may add to:
153//! demanding the collection demands every member, and a collection can be demanded but
154//! never provided ([`CollectionDef`]).
155//!
156//! The `check` feature ([`CheckWorkflow`]) declares the collection [`VALIDATED`]
157//! (`flm.validated`) and the workflow [`CHECK_WORKFLOW`] (`check`), which demands the
158//! collection and nothing else: a run of `check` validates the document and writes no
159//! output. The workflows of the four standard backends, `text`, `html`,
160//! `latex-rendered` and `latex-recomposed`, demand the collection beside their output. A render therefore
161//! reports the problems `check` reports: a label written twice or a cited key with no
162//! entry is reported alike by a render and by `check`.
163//!
164//! The members the standard features add are:
165//!
166//! - `flm.blocks.contract-checked` ([`blocks`](features::blocks)): every tree
167//!   satisfies the [tree contract](crate::lang::rewrites::blocks::check), or its
168//!   violations are reported.
169//! - `flm.refs.check-labels` ([`refs`]): no label is written twice,
170//!   every label's type is one its construct accepts, and every reference that
171//!   resolves to nothing is reported.
172//! - `flm.theorems.check-proofs` ([`theorems`](features::theorems)): every statement
173//!   that expects a proof and has none is reported, and so is every malformed
174//!   back-reference of a proof.
175//! - `flm.floats.check-handlers` ([`floats`](features::floats)): every content handler
176//!   that a float type used in the document requires and no feature registers is
177//!   reported.
178//! - `flm.citations.check` ([`citations`](features::citations)): every cited key with
179//!   no entry is reported.
180//! - `flm.metadata.read` ([`metadata`]): the document's metadata is parsed, and
181//!   the problems the parse finds are reported.
182//! - `flm.input.spliced` ([`input`]): the content of every included
183//!   file is in place in the document's trees.
184//!
185//! The feature that processes mathematics adds one more member, the check of the
186//! formulas. Its check stage provides `flm.math.content`, which the
187//! [`math`](features::math) feature declares (a stage has checked the content of every
188//! formula), and which no standard feature provides or adds. The feature
189//! [`math-passthrough`](crate::math_passthrough) adds `flm.math.content` itself; its
190//! stage `flm.math-passthrough.check` accepts every formula and reports every equation
191//! line that holds no mathematics. An extension adds to a collection
192//! only a capability named under its own stem, so the `math-mathjax` extension adds
193//! `math-mathjax.check`, which its check provides beside `flm.math.content`. Where two
194//! such features are registered, the plan request prefers one stage, because a
195//! capability with two providers and nothing to choose between them makes the plan
196//! build fail ([`PlanError::Contested`](crate::core::plan::PlanError::Contested)).
197//!
198//! A feature adds its member from its own registration
199//! ([`FeatureBuilder::collection_member`]), in any order of registration. In a
200//! registry that does not hold the `check` feature, the build drops the member without
201//! a diagnostic, so a feature that adds a check still registers on its own. A registry
202//! that holds a standard backend feature but not the `check` feature fails to build,
203//! because the backend's workflow demands the collection `flm.validated`, which no
204//! feature then declares; a
205//! program that wants the checks without the rest of the standard features registers
206//! [`check_feature`] beside its own features.
207//!
208//! The checks read the document's trees as the plan's rewrites leave them. Where a
209//! render of the recomposed LaTeX keeps the use sites of a user definition (to write
210//! them back as calls), the checks see the call and not the definition's expansion;
211//! LaTeX checks that content when it compiles the output.
212//!
213//! An Error a check reports does not stop a render. The stages of the standard
214//! backends have no effect outside the run's store, so the run's error gate (see [the
215//! error gate](crate::guide::embedding#the-error-gate)) does not stop them: the output
216//! is computed, and the diagnostics are reported beside it.
217//!
218//! **An unresolved reference is the only problem whose severity depends on the
219//! workflow.** The label check of the [`refs`] feature reads how the
220//! references were resolved, so every plan that demands the collection runs the
221//! resolution of references and reports the references that resolve to nothing. A plan
222//! that renders nothing cannot know whether a label would resolve in a render, because
223//! a render may install the external index of labels defined in other documents
224//! ([`EXTERNAL_INDEX`](features::refs::EXTERNAL_INDEX)). An unresolved
225//! reference is therefore a Warning under `check`, regardless of
226//! [`RefsRenderOptions`](features::refs::RefsRenderOptions), and an Error under a
227//! rendering workflow unless those options allow it. A label written twice and a label
228//! of a type its construct does not accept are Errors under every workflow, because
229//! each is a fact of the document alone.
230
231pub mod backends;
232pub mod features;
233
234use std::sync::Arc;
235
236use crate::core::registry::{
237    BuildError, CollectionDef, FeatureBuilder, FeatureInfo, FlmFeature, PackageEntry, WorkflowDef,
238};
239use crate::core::settings::PackageSettings;
240use crate::stdlib::backends::{html, latex, latex_recomposed, latex_rendered, lowering, pieces, text};
241use crate::stdlib::features::annotations::{AnnotationsConfig, AnnotationsFeature};
242use crate::stdlib::features::blocks::{Blocks, BlocksConfig};
243use crate::stdlib::features::defterm::{Defterm, DeftermConfig};
244use crate::stdlib::features::cells::{Cells, CellsConfig};
245use crate::stdlib::features::citations::{Citations, CitationsConfig};
246use crate::stdlib::features::floats::{Floats, FloatsConfig};
247use crate::stdlib::features::graphics::{Graphics, GraphicsConfig};
248use crate::stdlib::features::headings::{Headings, HeadingsConfig};
249use crate::stdlib::features::lists::{Lists, ListsConfig};
250use crate::stdlib::features::math::{Math, MathConfig};
251use crate::stdlib::features::numbering::{Numbering, NumberingConfig};
252use crate::stdlib::features::quote::{Quote, QuoteConfig};
253use crate::stdlib::features::refs::RefsConfig;
254use crate::stdlib::features::theorems::{Theorems, TheoremsConfig};
255use crate::stdlib::features::userdefs::{Userdefs, UserdefsConfig};
256use crate::stdlib::features::xnotes::{XnotesConfig, XnotesFeature};
257use crate::stdlib::features::{
258    href, index, input, literals, metadata, refpoints, refs, textstyles, toc, verbatim,
259};
260
261/// The registered name of the [`CheckWorkflow`] feature, `check`. The feature
262/// and the workflow it declares ([`CHECK_WORKFLOW`]) have the same name.
263pub const CHECK_FEATURE: &str = "check";
264
265/// The name of the collection `flm.validated`, which every check of the standard
266/// features joins: demanding it demands every member, so a plan that demands it
267/// runs every check the registry holds.
268///
269/// The [`CheckWorkflow`] feature declares the collection. Every workflow the
270/// standard features register demands it: [`CHECK_WORKFLOW`] demands it alone, and the
271/// workflows of the `text`, `html` and `latex-recomposed` backends demand it beside
272/// their output, so a document gets the same diagnostics under every workflow
273/// (with one exception, an unresolved reference). The [module
274/// documentation](self#every-workflow-validates-the-collection-flmvalidated) lists
275/// the members.
276pub const VALIDATED: &str = "flm.validated";
277
278/// The name of the `check` workflow, `check`: it demands [`VALIDATED`] and
279/// nothing else, so a run of it validates the document and writes no output.
280///
281/// A rendering workflow runs the same checks, because it demands [`VALIDATED`]
282/// beside its output. The only diagnostic whose severity differs is an
283/// unresolved reference: a Warning under `check`, an Error under a rendering
284/// workflow unless the render options of the `refs` feature allow it (see the
285/// [module documentation](self#every-workflow-validates-the-collection-flmvalidated)).
286pub const CHECK_WORKFLOW: &str = "check";
287
288/// The configuration of the standard features: one field for each of the sixteen
289/// standard features that take a configuration. The other seventeen features take
290/// none.
291///
292/// [`add_features`] constructs each of these features from its field. Each field's
293/// documentation says what it holds and what its default is; [`StdlibConfig::new`]
294/// is the default of every field. A feature's configuration is the plain Rust
295/// value the feature is constructed from; it is fixed when the registry is built
296/// and cannot vary per document or per render (see [settings, options and
297/// configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
298/// The configurations are fixed then because the commands the language knows, the
299/// trees a run freezes and the reference points that are numbered depend on them.
300///
301/// A program that reads the configurations as data uses
302/// [`add_features_from_settings`], which reads each field from the settings of
303/// its feature.
304///
305/// # Examples
306///
307/// ```
308/// use flm_core::stdlib::StdlibConfig;
309/// use flm_core::stdlib::features::blocks::BlocksConfig;
310/// use flm_core::stdlib::features::headings::HeadingsConfig;
311///
312/// let config = StdlibConfig::new()
313///     .blocks(BlocksConfig::no_typography())
314///     .headings(HeadingsConfig::new().run_in_levels([4, 5]));
315/// assert!(!config.blocks.auto_unicode_quotes);
316/// assert!(config.headings.heading("paragraph").is_some_and(|kind| kind.run_in));
317/// ```
318#[derive(Debug, Clone, Default)]
319pub struct StdlibConfig {
320    /// The `blocks` feature's text options.
321    pub blocks: BlocksConfig,
322    /// The `userdefs` feature's user definitions and expansion depth limit. A
323    /// program that gathers definitions from several sources merges them into
324    /// this one configuration.
325    pub userdefs: UserdefsConfig,
326    /// The `headings` feature's heading kinds and heading commands, and which
327    /// kinds are numbered. By default, the five standard kinds `section` to
328    /// `subparagraph`, none set as a run-in heading and none numbered.
329    pub headings: HeadingsConfig,
330    /// The `numbering` feature's style replacements: counter styles that each
331    /// replace, by name, the counter style a feature declared. No replacement by
332    /// default.
333    pub numbering: NumberingConfig,
334    /// The `math` feature's configuration: whether equations are numbered. They
335    /// are by default.
336    pub math: MathConfig,
337    /// The `refs` feature's configuration: the texts that join the items of a
338    /// reference to several targets. By default, `A and B` and `A, B, and C`.
339    pub refs: RefsConfig,
340    /// The `lists` feature's list environments: whether each numbers its
341    /// items, and the labels it writes beside them at each depth. By default,
342    /// `itemize`, `enumerate` and `description`.
343    pub lists: ListsConfig,
344    /// The `xnotes` feature's xnote kinds: each kind's commands, words,
345    /// numbering, placement and list. By default, the one kind `footnote`,
346    /// written `\footnote{…}`, numbered and listed after the content.
347    pub xnotes: XnotesConfig,
348    /// The `defterm` feature's configuration: the lead-in a term definition
349    /// opens with, a template in which `#{term}` is the term. By default,
350    /// `#{term}: `.
351    pub defterm: DeftermConfig,
352    /// The `theorems` feature's theorem classes and theorem kinds: the
353    /// theorem-like environments, their words, numbering, heading, closing mark
354    /// and back-reference. By default, the eight standard kinds, `theorem` to
355    /// `proof`.
356    pub theorems: TheoremsConfig,
357    /// The `quote` feature's quote environments: the quotation section commands
358    /// each accepts, and what content written outside any quotation section is
359    /// read as. By default, `quote`, `blockquote` and `address`.
360    pub quote: QuoteConfig,
361    /// The `annotations` feature's annotators: each one's command and
362    /// initials, in order. By default, no annotator, and therefore no command.
363    pub annotations: AnnotationsConfig,
364    /// The `graphics` feature's configuration: whether `\includegraphics` can be
365    /// written anywhere in the document's text, and not only in a float's body.
366    /// Not by default.
367    pub graphics: GraphicsConfig,
368    /// The `floats` feature's float types: each one's numbering policy,
369    /// words, content handlers and label types. By default, `figure` and
370    /// `table`, each numbered when it carries a `\label`.
371    pub floats: FloatsConfig,
372    /// The `cells` feature's configuration: whether the `cells` environment can
373    /// be written anywhere a block can, and not only in the body of a float of
374    /// the `table` float type. Not by default.
375    pub cells: CellsConfig,
376    /// The `citations` feature's configuration: the form of a citation mark, the
377    /// citation counter style and the text before a note. By default, bracketed marks:
378    /// arabic numbers between `[` and `]`, the words `ref.~` and `refs.~`, and
379    /// `; ` before a note.
380    pub citations: CitationsConfig,
381}
382
383impl StdlibConfig {
384    /// The default configuration: every family of typographic substitutions
385    /// on, no user definitions, the five standard heading kinds and their
386    /// commands with none numbered, no counter style replaced, equations
387    /// numbered, the default texts that join a reference to several targets,
388    /// the three standard list environments, the one xnote kind `footnote`, the
389    /// lead-in `#{term}: `, the eight standard theorem kinds, the three standard
390    /// quote environments, no annotator, `\includegraphics` only in a float's
391    /// body, the float types `figure` and `table`, the `cells` environment only
392    /// in the body of a `table` float, and bracketed citation marks in the
393    /// default citation counter style.
394    pub fn new() -> StdlibConfig {
395        StdlibConfig::default()
396    }
397
398    /// Builder: sets the `blocks` feature's text options.
399    pub fn blocks(mut self, blocks: BlocksConfig) -> StdlibConfig {
400        self.blocks = blocks;
401        self
402    }
403
404    /// Builder: sets the `userdefs` feature's user definitions and expansion
405    /// depth limit.
406    pub fn userdefs(mut self, userdefs: UserdefsConfig) -> StdlibConfig {
407        self.userdefs = userdefs;
408        self
409    }
410
411    /// Builder: sets the `headings` feature's heading kinds, heading commands, and
412    /// which kinds are numbered.
413    pub fn headings(mut self, headings: HeadingsConfig) -> StdlibConfig {
414        self.headings = headings;
415        self
416    }
417
418    /// Builder: sets the `numbering` feature's counter style replacements.
419    pub fn numbering(mut self, numbering: NumberingConfig) -> StdlibConfig {
420        self.numbering = numbering;
421        self
422    }
423
424    /// Builder: sets the `math` feature's configuration.
425    pub fn math(mut self, math: MathConfig) -> StdlibConfig {
426        self.math = math;
427        self
428    }
429
430    /// Builder: sets the `refs` feature's configuration.
431    pub fn refs(mut self, refs: RefsConfig) -> StdlibConfig {
432        self.refs = refs;
433        self
434    }
435
436    /// Builder: sets the `lists` feature's list environments.
437    pub fn lists(mut self, lists: ListsConfig) -> StdlibConfig {
438        self.lists = lists;
439        self
440    }
441
442    /// Builder: sets the `xnotes` feature's xnote kinds.
443    pub fn xnotes(mut self, xnotes: XnotesConfig) -> StdlibConfig {
444        self.xnotes = xnotes;
445        self
446    }
447
448    /// Builder: sets the `defterm` feature's configuration.
449    pub fn defterm(mut self, defterm: DeftermConfig) -> StdlibConfig {
450        self.defterm = defterm;
451        self
452    }
453
454    /// Builder: sets the `theorems` feature's theorem classes and theorem kinds.
455    pub fn theorems(mut self, theorems: TheoremsConfig) -> StdlibConfig {
456        self.theorems = theorems;
457        self
458    }
459
460    /// Builder: sets the `quote` feature's quote environments.
461    pub fn quote(mut self, quote: QuoteConfig) -> StdlibConfig {
462        self.quote = quote;
463        self
464    }
465
466    /// Builder: sets the `annotations` feature's annotators.
467    pub fn annotations(mut self, annotations: AnnotationsConfig) -> StdlibConfig {
468        self.annotations = annotations;
469        self
470    }
471
472    /// Builder: sets the `graphics` feature's configuration.
473    pub fn graphics(mut self, graphics: GraphicsConfig) -> StdlibConfig {
474        self.graphics = graphics;
475        self
476    }
477
478    /// Builder: sets the `floats` feature's float types.
479    pub fn floats(mut self, floats: FloatsConfig) -> StdlibConfig {
480        self.floats = floats;
481        self
482    }
483
484    /// Builder: sets the `cells` feature's configuration.
485    pub fn cells(mut self, cells: CellsConfig) -> StdlibConfig {
486        self.cells = cells;
487        self
488    }
489
490    /// Builder: sets the `citations` feature's configuration.
491    pub fn citations(mut self, citations: CitationsConfig) -> StdlibConfig {
492        self.citations = citations;
493        self
494    }
495}
496
497/// Returns `entry` with the thirty-three standard features added after the
498/// features it holds, each once, in the order the [module
499/// documentation](self#the-standard-features-and-where-each-is-documented)
500/// lists them, with the sixteen configurable features constructed from the
501/// fields of `config`.
502///
503/// A program declares its package, adds the standard features to it, and adds
504/// its own features after them; the module documentation has an example. A
505/// program that reads its settings as data uses [`add_features_from_settings`]
506/// instead.
507pub fn add_features(mut entry: PackageEntry, config: StdlibConfig) -> PackageEntry {
508    entry.features.extend(standard_features(config));
509    entry
510}
511
512/// Returns `entry` with the standard features added after the features it
513/// holds, in the order of [`add_features`], each configured from the settings,
514/// and without the features the settings switch off.
515///
516/// The function reads the configuration of each of the sixteen configurable
517/// features from its settings, and takes the default where the settings give
518/// none. A program that chooses its packages by name and reads their settings
519/// as data calls it in the build function of its package's
520/// [`PackageFactory`](crate::core::registry::PackageFactory): the factory then
521/// lists each standard feature with the declaration of its settings when it
522/// takes some ([`FlmFeature::settings`]), and the program reads the settings
523/// against those declarations. The features
524/// the entry already holds are kept, whatever the settings say about them.
525///
526/// The settings also hold option values (values of a feature's option types).
527/// The package entry does not take them: the program sets them on the document
528/// and on the render request (see [`crate::core::settings::FeatureSettings`]).
529/// A program written in Rust that builds its configuration in code calls
530/// [`add_features`].
531///
532/// # Examples
533///
534/// ```
535/// use flm_core::core::registry::{PackageEntry, PackageFactory, RegistryBuilder, RegistryInputs};
536/// use flm_core::core::settings::PackageSettings;
537/// use flm_core::stdlib;
538///
539/// let factory = PackageFactory::new("std", |settings: &PackageSettings| {
540///     Ok(stdlib::add_features_from_settings(PackageEntry::new("std"), settings))
541/// })?;
542/// let math = factory.settings("math").expect("math takes settings");
543/// let data = serde_json::json!({ "numbered_equations": false });
544///
545/// let mut settings = PackageSettings::new();
546/// settings.insert(math.read(data.as_object().unwrap()).unwrap());
547/// settings.switch_off("annotations");
548///
549/// let entry = factory.build(&settings)?;
550/// assert!(entry.features.iter().all(|feature| feature.info().name != "annotations"));
551/// let mut builder = RegistryBuilder::new();
552/// builder.use_package(entry);
553/// assert!(builder.build(&RegistryInputs::new()).is_ok());
554/// # Ok::<(), flm_core::core::registry::PackageError>(())
555/// ```
556pub fn add_features_from_settings(mut entry: PackageEntry, settings: &PackageSettings) -> PackageEntry {
557    use crate::stdlib::features::{
558        annotations, blocks, cells, citations, defterm, floats, graphics, headings, lists, math,
559        numbering, quote, theorems, userdefs, xnotes,
560    };
561    fn take<C: Clone + 'static>(settings: &PackageSettings, feature: &str, into: &mut C) {
562        if let Some(config) = settings.config::<C>(feature) {
563            *into = config.clone();
564        }
565    }
566    let mut config = StdlibConfig::new();
567    take(settings, blocks::FEATURE, &mut config.blocks);
568    take(settings, userdefs::FEATURE, &mut config.userdefs);
569    take(settings, headings::FEATURE, &mut config.headings);
570    take(settings, numbering::FEATURE, &mut config.numbering);
571    take(settings, math::FEATURE, &mut config.math);
572    take(settings, refs::FEATURE, &mut config.refs);
573    take(settings, lists::FEATURE, &mut config.lists);
574    take(settings, xnotes::FEATURE, &mut config.xnotes);
575    take(settings, defterm::FEATURE, &mut config.defterm);
576    take(settings, theorems::FEATURE, &mut config.theorems);
577    take(settings, quote::FEATURE, &mut config.quote);
578    take(settings, annotations::FEATURE, &mut config.annotations);
579    take(settings, graphics::FEATURE, &mut config.graphics);
580    take(settings, floats::FEATURE, &mut config.floats);
581    take(settings, cells::FEATURE, &mut config.cells);
582    take(settings, citations::FEATURE, &mut config.citations);
583    entry.features.extend(
584        standard_features(config).into_iter().filter(|feature| !settings.is_off(&feature.info().name)),
585    );
586    entry
587}
588
589/// The thirty-three standard features, in the order of [`add_features`], with
590/// the configurable ones constructed from the fields of `config`.
591fn standard_features(config: StdlibConfig) -> Vec<Arc<dyn FlmFeature>> {
592    vec![
593        textstyles::feature(),
594        literals::feature(),
595        Arc::new(Blocks::new(config.blocks)),
596        index::feature(),
597        refpoints::feature(),
598        // The owner of the two counter slots stands before every feature that
599        // fills them, so that the list is easy to follow, although the order
600        // decides nothing here: the contributions to a slot are gathered over
601        // the whole first round, wherever the slot is declared.
602        Arc::new(Numbering::new(config.numbering)),
603        Arc::new(Math::new(config.math)),
604        Arc::new(refs::Refs::new(config.refs)),
605        Arc::new(Headings::new(config.headings)),
606        verbatim::feature(),
607        Arc::new(Lists::new(config.lists)),
608        Arc::new(XnotesFeature::new(config.xnotes)),
609        href::feature(),
610        Arc::new(Defterm::new(config.defterm)),
611        Arc::new(Theorems::new(config.theorems)),
612        Arc::new(Quote::new(config.quote)),
613        Arc::new(AnnotationsFeature::new(config.annotations)),
614        Arc::new(Graphics::new(config.graphics)),
615        Arc::new(Floats::new(config.floats)),
616        Arc::new(Cells::new(config.cells)),
617        Arc::new(Citations::new(config.citations)),
618        input::feature(),
619        Arc::new(Userdefs::new(config.userdefs)),
620        lowering::feature(),
621        metadata::feature(),
622        toc::feature(),
623        // The owner of the pieces slot and option stands before the backends
624        // that read them, so that the list is easy to follow, although the
625        // order decides nothing here.
626        pieces::feature(),
627        text::feature(),
628        latex::feature(),
629        latex_recomposed::feature(),
630        latex_rendered::feature(),
631        html::feature(),
632        check_feature(),
633    ]
634}
635
636/// The `check` feature: it declares the collection [`VALIDATED`]
637/// (`flm.validated`) and the workflow [`CHECK_WORKFLOW`] (`check`), which
638/// demands that collection, and nothing else.
639///
640/// The feature declares no element and no stage. A program that registers its
641/// own features without the rest of the standard features can register this one
642/// beside them ([`check_feature`]) to get the `check` workflow over the checks its
643/// features add to the collection.
644///
645/// The workflow of every standard backend demands [`VALIDATED`] too, so a
646/// registry that holds a standard backend feature must hold this feature: without
647/// it, the registry build fails with an error that gives the backend's workflow
648/// and the missing name `flm.validated`. See the [module
649/// documentation](self#every-workflow-validates-the-collection-flmvalidated).
650#[derive(Debug, Default, Clone, Copy)]
651pub struct CheckWorkflow;
652
653impl FlmFeature for CheckWorkflow {
654    fn info(&self) -> FeatureInfo {
655        FeatureInfo::new(CHECK_FEATURE, "The check workflow").docs(
656            "The collection `flm.validated`, which every check joins, and the `check` \
657             workflow, which demands it: the document is validated and no output is written.",
658        )
659    }
660
661    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
662        b.collection(CollectionDef::new(VALIDATED).docs(
663            "Every check the registry's features add has run. The standard features add \
664             `flm.blocks.contract-checked`, `flm.refs.check-labels`, \
665             `flm.theorems.check-proofs`, `flm.floats.check-handlers`, `flm.citations.check`, \
666             `flm.metadata.read` and `flm.input.spliced`; the feature that processes mathematics \
667             adds its check (`math-passthrough` adds `flm.math.content`). Demanding the \
668             collection demands every member.",
669        ))?;
670        b.workflow(
671            WorkflowDef::new(CHECK_WORKFLOW)
672                .demand(VALIDATED)
673                .docs("validate the document: run every check the features add, and write no output"),
674        )?;
675        Ok(())
676    }
677}
678
679/// Returns the [`CheckWorkflow`] feature, ready to be listed in a package entry or
680/// registered beside the features whose checks the collection `flm.validated`
681/// gathers.
682pub fn check_feature() -> Arc<dyn FlmFeature> {
683    Arc::new(CheckWorkflow)
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689
690    #[test]
691    fn the_check_feature_declares_the_collection_and_the_workflow() {
692        let info = CheckWorkflow.info();
693        assert_eq!(info.name, CHECK_FEATURE);
694        assert_eq!(VALIDATED, "flm.validated");
695        assert_eq!(CHECK_WORKFLOW, "check");
696    }
697
698    #[test]
699    fn add_features_adds_the_standard_features_once_each_in_order() {
700        let entry = add_features(PackageEntry::new("std"), StdlibConfig::new());
701        assert_eq!(entry.name, "std");
702        assert!(entry.uses.is_empty());
703        let names: Vec<String> =
704            entry.features.iter().map(|feature| feature.info().name.to_string()).collect();
705        assert_eq!(
706            names,
707            [
708                "textstyles", "literals", "blocks", "index", "refpoints", "numbering", "math",
709                "refs", "headings", "verbatim", "lists", "xnotes", "href", "defterm", "theorems",
710                "quote",
711                "annotations",
712                "graphics",
713                "floats",
714                "cells",
715                "citations",
716                "input",
717                "userdefs", "lowering", "metadata", "toc", "pieces", "text", "latex", "latex-recomposed", "latex-rendered", "html",
718                "check"
719            ]
720        );
721        assert_eq!(names.len(), 33);
722    }
723
724    #[test]
725    fn the_configuration_builders_set_their_fields() {
726        use crate::stdlib::features::numbering::CounterStyleDecl;
727        let config = StdlibConfig::new()
728            .blocks(BlocksConfig::no_typography())
729            .userdefs(UserdefsConfig::new().recursion_limit(3))
730            .headings(HeadingsConfig::new().run_in_levels([4, 5]))
731            .numbering(NumberingConfig::new().style(CounterStyleDecl::new("a.style")));
732        assert!(!config.blocks.auto_unicode_quotes);
733        assert_eq!(config.userdefs.recursion_limit, 3);
734        assert!(config.headings.heading("subparagraph").is_some_and(|kind| kind.run_in));
735        assert_eq!(config.numbering.styles.len(), 1);
736    }
737}