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