Skip to main content

flm_core/stdlib/features/math/
mod.rs

1//! The `math` feature: mathematics written in LaTeX notation, its
2//! display-math environments, its equation lines and their numbers.
3//!
4//! This feature introduces mathematics into the language and nothing more. It
5//! declares the few things FLM reads inside mathematics: the display-math
6//! environments and the lines they are made of, the commands that put document
7//! text inside a formula, and references to equations. It checks no formula
8//! and processes none: a *processing feature* does, a feature that reads the
9//! mathematical content and gives every formula its lowering rules (*Processing
10//! mathematics*, below). Its one rule on a formula is the rule of last resort
11//! of the display-math environments, which reports an environment that no
12//! processing feature lowers ([`unprocessed`]). The guide to the language
13//! describes mathematics for authors
14//! ([mathematics](crate::guide::language_syntax#mathematics)).
15//!
16//! # What an author writes
17//!
18//! - **Inline and displayed mathematics**, `\(…\)` and `\[…\]` (and `$…$`,
19//!   `$$…$$` when the parsing option
20//!   [`FlmParsing::dollar_math`](crate::lang::FlmParsing::dollar_math) is on). The language
21//!   layer reads these as math groups, nodes of the element `flm.math`
22//!   ([`MATH`](crate::lang::structural::MATH)).
23//! - **Six display-math environments**: `equation`, `align`, `gather` and their
24//!   starred forms `equation*`, `align*`, `gather*`. The unstarred forms number
25//!   their lines.
26//! - **Inside a display-math environment's body**, the four commands `\\`,
27//!   `\label{eq:…}`, `\tag{…}` (or `\tag*{…}`) and `\nonumber`, which divide the
28//!   body into equation lines and say how each line is labeled and numbered
29//!   ([`lines`]).
30//! - **Text inside a formula**: `\text{…}`, `\textbf{…}`, `\mbox{…}` and the other
31//!   text commands of math mode, whose argument is document content ([`text`]).
32//! - **`\ensuremath{…}`**, in both modes ([`ensuremath`]): in text, an inline
33//!   formula, read as `\(…\)` is (its braces delimit a math group, a node of
34//!   `flm.math`); inside a formula, its argument, as if written in its place.
35//! - **References to equations**: `\eqref{eq:…}`, which shows an equation line's
36//!   number without a word before it ([`eqref`]).
37//!
38//! Displayed mathematics, a group `\[…\]` or `$$…$$` and a display-math
39//! environment alike, is a [displayed item](BlockRole::Displayed): it stands
40//! inside the paragraph it is written in, set on lines of its own, and the
41//! text that follows it with no blank line between continues that paragraph.
42//! The environments declare that role here; the group's element answers it
43//! from the group's form
44//! ([`StructuralElementSpecs::math`](crate::lang::structural::StructuralElementSpecs::math)).
45//!
46//! Every other command of mathematics (`\alpha`, `\frac`, a `cases`
47//! environment) is the processing feature's to declare or accept.
48//!
49//! A processing feature needs to know nothing of `\ensuremath` written in text:
50//! the formula is a math group like any other, the content of the command's
51//! argument, which the feature's own rule ([`ensuremath::RULE`]) lowers. On the
52//! recomposed LaTeX, [`latex::group_opening`] and [`latex::group_closing`],
53//! which the feature's rule for `flm.math` calls, write that formula
54//! `\ensuremath{…}` as written. Inside a formula, a writer of the formula's TeX
55//! for a renderer writes the argument's content in place of the command
56//! ([`ensuremath`], *In mathematics*).
57//!
58//! # Processing mathematics
59//!
60//! A processing feature does four things, which this feature leaves to it:
61//!
62//! - it says what a command of mathematics is, for instance with a *fallback*
63//!   ([`FallbackDef`](crate::lang::mint::FallbackDef)) for macros and
64//!   environments in math mode, or with declared elements in math mode;
65//! - it provides the capability [`CONTENT`] (`flm.math.content`) with a check
66//!   stage of its own, and adds its check to the collection
67//!   [`flm.validated`](crate::stdlib::VALIDATED): [`CONTENT`] itself, or, for
68//!   an extension, which adds to a collection only a capability named under
69//!   its own stem, a capability of its own that the stage provides beside
70//!   [`CONTENT`];
71//! - it registers the lowering rules of `flm.math` and of
72//!   [`ENVIRONMENT`] (`flm.math.environment`) on the backends it serves;
73//! - on the HTML backend, it marks the outermost element it writes for each
74//!   formula with the class of the role [`html::FORMULA_ROLE`]
75//!   (`flm-math-formula`) and the attributes `data-flm-display` and, for an
76//!   environment, `data-flm-env` ([`html`]), whatever element it chooses, so
77//!   that a stylesheet or a script of the page finds every formula alike.
78//!
79//! The rules may be the library's own: a processing feature that writes its
80//! formulas as LaTeX on a backend registers there the rules of
81//! [`math-passthrough`](crate::math_passthrough) under rule names of its own
82//! ([`math_rule_named`](crate::math_passthrough::math_rule_named) and the other
83//! constructors; that module's documentation, *The rules under another
84//! feature's names*), as the `math-techxt` extension does on the two LaTeX
85//! backends. A feature that hands its formulas to a typesetter of TeX notation
86//! reads each formula's TeX with the writer of [`tex`], which leaves a hole for
87//! each text command for the feature to lower.
88//!
89//! No standard feature processes mathematics: a registry adds such a feature
90//! from another package, for example the feature of the package
91//! [`math-passthrough`](crate::math_passthrough), which accepts every formula
92//! and carries its source to the output as written, or an extension that
93//! typesets formulas. Every standard workflow demands the collection
94//! [`flm.validated`](crate::stdlib::VALIDATED), which holds the check of the
95//! mathematics exactly when a processing feature is registered. A registry that holds
96//! this feature and no processing feature therefore builds, and so does the
97//! plan of every standard workflow: a document without formulas renders
98//! without error, and each formula is an Error
99//! ([`MathUnprocessed`](crate::stdlib::backends::lowering::MathUnprocessed),
100//! `flm.math.unprocessed`), reported where a backend lowers it through a rule
101//! of last resort: the `lowering` feature's for a math group
102//! ([`MathGroupRule`](crate::stdlib::backends::lowering::MathGroupRule)),
103//! this feature's for a display-math environment ([`unprocessed::RULE`]).
104//!
105//! # Equation lines, reference points and numbers
106//!
107//! The body of a display-math environment is an [opaque
108//! region](crate::guide::concepts_overview#opaque-regions) in math mode: the
109//! rewrite passes leave it untouched. The feature reads it once as a list of
110//! [equation lines](crate::guide::concepts_overview#equation-lines), the parts of
111//! the body between two `\\`, with their labels, tags and no-number marks
112//! ([`lines::equation_lines`]).
113//!
114//! Each equation line is a reference point
115//! ([`RefPoint`]; see [reference points, labels
116//! and anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)):
117//! a place in the document that can be referred to, numbered and given an anchor.
118//! The environment declares one point per line ([`MathEnvironment`] implements
119//! [`Referenceable`]), of the reference kind [`KIND`] (`equation`).
120//!
121//! - A line **can be numbered** when its environment is unstarred and the line
122//!   carries no `\nonumber`. It keeps the labels written on it and accepts labels
123//!   of the type [`LABEL_TYPES`] (`eq`), so `\ref{eq:name}` refers to the line
124//!   that carries `\label{eq:name}`.
125//! - A line that can be numbered and carries no `\tag` is numbered, unless the
126//!   feature's configuration numbers no equations
127//!   ([`MathConfig::numbered_equations`]). It counts in the counter [`COUNTER`]
128//!   (`flm.math.equation`) and its number is shown in the counter style
129//!   [`COUNTER_STYLE`] (`flm.math.style.equation`): `(1)`, and `Eq.~(1)` in a
130//!   reference ([counters and counter
131//!   styles](crate::guide::concepts_overview#counters-and-counter-styles)).
132//! - A line with a `\tag` counts in nothing: a reference to it shows the tag
133//!   instead of a number.
134//! - A line that **cannot be numbered** (every line of a starred environment,
135//!   and a line marked `\nonumber`) keeps no label and accepts no label type, so
136//!   nothing can refer to it. A `\label` or `\tag` written on such a line is an
137//!   Error ([`lines::LabelWithoutNumber`]).
138//! - **Every line has an anchor**, the identifier a link points at: for a
139//!   labeled line, the anchor of its first label (`eq-euler` for
140//!   `\label{eq:euler}`), and otherwise [`ANCHOR_PREFIX`] (`eq`), a
141//!   double hyphen, the line's position among the document's equation lines and
142//!   four letters, as in `eq--8kqzt`
143//!   ([`auto_anchor`](crate::stdlib::features::refs::auto_anchor)).
144//!
145//! The counter and the counter style belong to the numbering feature
146//! ([`numbering`](crate::stdlib::features::numbering)): this feature contributes
147//! their declarations ([`counter_decl`], [`counter_style`]) to that feature's
148//! service slots as peer contributions, contributions to a service slot that
149//! another feature owns, which the registry build drops with one Note when that
150//! feature is not registered ([`services`](crate::core::services)). The numbers
151//! are then not computed, and no line shows one.
152//!
153//! The table references [`ANCHORS`](crate::stdlib::features::refs::ANCHORS) (the anchors table of the references
154//! feature) and [`COUNTERS`] (the counter table of the numbering feature) are
155//! where a processing feature's rules read each line's anchor and number; the
156//! library of [`frame`] reads them for it ([`frame::line_frames`]).
157//!
158//! # What the feature's own elements become on each backend
159//!
160//! The feature's rules lower the commands it declares outside the formulas
161//! themselves: a text command, `\ensuremath` and `\eqref`. Each stages (builds
162//! into the lowered tree; see [`Lowerer`](crate::core::lowering::Lowerer))
163//! presentation nodes, except the rule of `\ensuremath`, which lowers its
164//! argument through the rules and stages nothing of its own.
165//!
166//! | element | `text` | `html` | `latex-recomposed` |
167//! |---|---|---|---|
168//! | `flm.math.text` | [`text::RULE`] | [`text::RULE`] | [`latex::TEXT_LATEX_RULE`] |
169//! | `flm.math.ensuremath` | [`ensuremath::RULE`] | [`ensuremath::RULE`] | [`ensuremath::RULE`] |
170//! | `flm.math.eqref` | [`eqref::RULE`] | [`eqref::RULE`] | [`eqref::LATEX_RULE`] |
171//!
172//! The feature also registers, on every backend, the rule of last resort of
173//! the display-math environments, [`unprocessed::RULE`], which is chosen only
174//! where no processing feature has a rule for [`ENVIRONMENT`] on the backend
175//! ([`unprocessed`]).
176//!
177//! **A text command becomes content**: its argument is document text, so
178//! [`text::RULE`] lowers it like inline content anywhere else, into a
179//! [`flm.pres.math-text`](crate::stdlib::backends::pres::MATH_TEXT) node; a
180//! reference in it is a link, and a character the output format must escape is
181//! escaped. A processing feature decides whether a text command inside a
182//! formula is lowered through these rules (`math-passthrough` does).
183//!
184//! The rendering guide describes the result under [mathematics in
185//! HTML](crate::guide::rendering#mathematics-in-html) and [mathematics in the
186//! recomposed LaTeX](crate::guide::rendering#mathematics-in-the-recomposed-latex).
187//!
188//! # The capabilities
189//!
190//! A capability is a registered dotted name for a state of processing that a
191//! stage brings about ([`CapabilityDef`]). The feature registers two:
192//!
193//! - [`CONTENT`] (`flm.math.content`): the mathematics of the document has been
194//!   checked. No stage of this feature provides it: a processing feature
195//!   provides it with a check of its own (the feature of the package
196//!   `math-passthrough` accepts every formula) and adds its check to the
197//!   collection [`flm.validated`](crate::stdlib::VALIDATED) (*Processing
198//!   mathematics*, above), so that every workflow that validates a document,
199//!   the [`check` workflow](crate::stdlib::CHECK_WORKFLOW) among them, runs
200//!   that check exactly when a processing feature is registered. Where two
201//!   registered features provide it, a plan request prefers one of their two
202//!   stages; otherwise the plan build fails
203//!   ([`PlanError::Contested`](crate::core::plan::PlanError::Contested)), so a
204//!   registry usually holds one processing feature.
205//! - [`RENDERED`] (`flm.math.rendered`): some rendered form of the mathematics
206//!   exists. No standard feature provides it. An extension that renders
207//!   mathematics provides a refinement of it, named in the extension's own
208//!   namespace (the `math-mathjax` extension's table `math-mathjax.rendered`,
209//!   the MathML of each formula, in its `mathml` mode; the `math-techxt`
210//!   extension's table `math-techxt.rendered`, each formula as Unicode text),
211//!   and a rule that needs rendered mathematics of any kind requires
212//!   `flm.math.rendered`. A plan that demands it cannot be built until such an
213//!   extension is registered.
214//!
215//! # Settings
216//!
217//! - [`MathConfig`], the feature's configuration (fixed when the registry is
218//!   built; see [settings, options and
219//!   configuration](crate::guide::concepts_overview#settings-options-and-configuration)):
220//!   whether the lines of the unstarred environments are numbered.
221//! - [`MathRecomposeOptions`], an option type set per render request: what the
222//!   recomposed LaTeX writes around a display-math environment, and whether it
223//!   writes the environment through the LaTeX hook `\flmMathEnvironment`. The
224//!   rules of a processing feature on the `latex-recomposed` backend read it.
225//!
226//! Each field of the two types is a settings key under its own name
227//! ([`crate::core::settings`]).
228//!
229//! # Map of the module
230//!
231//! - [`Math`] — the feature, configured by [`MathConfig`]; [`feature`] returns it
232//!   with the default configuration.
233//! - [`ENVIRONMENT`], [`MathEnvironment`], [`ENVIRONMENTS`] — the element and the
234//!   data of an environment's element values.
235//! - [`KIND`], [`LABEL_TYPES`], [`ANCHOR_PREFIX`], [`COUNTER`],
236//!   [`COUNTER_STYLE`], [`counter_decl`], [`counter_style`] — the reference points
237//!   of the equation lines and their numbering.
238//! - [`CONTENT`], [`RENDERED`] — the capabilities.
239//! - [`lines`] — the four commands of an environment's body and the reader of
240//!   equation lines.
241//! - [`text`] — the text commands of math mode.
242//! - [`ensuremath`] — `\ensuremath`, an inline formula in text and its
243//!   argument inside a formula.
244//! - [`eqref`] — `\eqref`.
245//! - [`unprocessed`] — the rule of last resort of the display-math
246//!   environments.
247//! - [`frame`] — the library a processing feature computes a formula's frame
248//!   with: whether a math group is displayed, and each equation line's anchor
249//!   and number or tag.
250//! - [`latex`] — the recomposition rule of the text commands, the LaTeX names
251//!   of the environments, [`MathRecomposeOptions`], the library a processing
252//!   feature writes a formula's frame and an environment's lines as LaTeX
253//!   with, and the newline rule that every LaTeX writer of the lines applies.
254//! - [`tex`] — the writer of a formula's TeX with a hole for each text
255//!   command, for a processing feature that hands its formulas to a
256//!   typesetter: a math group's content, an equation line's content under the
257//!   newline rule.
258
259// `flm.math.rendered` has no provider in the standard library, which renders no
260// mathematics: it gives the extensions that do one name to refine and hosts one
261// name to demand, and an extension cannot declare a name under `flm.` itself.
262
263pub mod ensuremath;
264pub mod eqref;
265pub mod frame;
266pub mod html;
267pub mod latex;
268pub mod lines;
269pub mod tex;
270pub mod text;
271pub mod unprocessed;
272
273pub use latex::MathRecomposeOptions;
274
275
276use std::sync::Arc;
277
278use techy::core::node::NodeRef;
279use techy::latexlike::Mode;
280
281use crate::core::settings::SettingsDecl;
282use crate::model::aspects::{
283    AcceptedRefTypes, AnchorPolicy, BlockRole, BlockRoleAspect, FixedBlockRole, NumberSource,
284    RefPoint, Referenceable,
285};
286use crate::model::element::ElementSpec;
287use crate::model::names::{FeatureName, Name, RefKind};
288use crate::core::registry::{BuildError, CapabilityDef, FeatureBuilder, FeatureInfo, FlmFeature};
289use crate::lang::Flm;
290use crate::lang::mint::{BodyDef, ElementDef, SyntaxDef};
291use crate::model::options::Bind;
292use crate::stdlib::features::numbering::{
293    COUNTERS, COUNTERS_SLOT, CounterDecl, CounterStyleDecl, Counters, Delimiters, JoinDecl,
294    NumberTemplate, PluralWords, PrefixWords, STYLES_SLOT,
295};
296use crate::stdlib::features::refs;
297
298/// The feature's registered name, `math`.
299pub const FEATURE: &str = "math";
300
301/// The declaration of the feature's settings: the fields of [`MathConfig`] and
302/// of [`MathRecomposeOptions`] are its settings keys. See
303/// [`crate::core::settings`].
304fn settings() -> SettingsDecl {
305    SettingsDecl::new(FEATURE)
306        .config::<MathConfig>(
307            "Whether the lines of `equation`, `align` and `gather` are numbered (`true` by \
308            default). Fixed when the registry is built: it cannot vary per document or per \
309            render.",
310        )
311        .options::<MathRecomposeOptions>(
312            Bind::Render,
313            "How the recomposed LaTeX writes a display-math environment: the LaTeX written \
314            before and after it, and whether the environment is written through the command \
315            `\\flmMathEnvironment`. Set per render request.",
316        )
317}
318
319
320/// The name of the element type of the six display-math environments,
321/// `flm.math.environment`. The data of each element value is a
322/// [`MathEnvironment`].
323pub const ENVIRONMENT: &str = "flm.math.environment";
324
325/// The name of the capability `flm.math.content`: the mathematics of the
326/// document has been checked. No stage of this feature provides it: a feature
327/// that processes mathematics provides it with a check of its own and adds that
328/// check to the collection [`flm.validated`](crate::stdlib::VALIDATED), so that
329/// a workflow that validates a document runs it exactly when such a feature is
330/// registered (the feature of the package
331/// [`math-passthrough`](crate::math_passthrough) accepts every formula). See
332/// the module documentation, *The capabilities*.
333pub const CONTENT: &str = "flm.math.content";
334
335/// The name of the capability `flm.math.rendered`: some rendered form of the
336/// mathematics exists.
337///
338/// No standard feature provides it or a refinement of it. An extension that
339/// renders mathematics provides a refinement named in its own namespace, and a
340/// rule that needs rendered mathematics of any kind requires
341/// `flm.math.rendered`. A plan that demands it fails to build when no
342/// registered feature provides a refinement.
343pub const RENDERED: &str = "flm.math.rendered";
344
345
346/// The reference kind of every equation line's reference point, `equation`:
347/// the name that says what sort of place a reference point is
348/// ([`RefPoint`]).
349pub const KIND: &str = "equation";
350
351/// The label types that an equation line that can be numbered accepts: `eq`.
352///
353/// A label is written `\label{type:label}`, and its type, the part before the
354/// colon, says what sort of place it marks ([reference points, labels and
355/// anchors](crate::guide::concepts_overview#reference-points-labels-and-anchors)).
356/// An equation line takes `\label{eq:euler}`; a label of any other type on
357/// that line is reported by the label check of the references feature
358/// ([`CHECK_LABELS`](crate::stdlib::features::refs::CHECK_LABELS)) as
359/// `flm.refs.label-type-not-accepted`.
360pub const LABEL_TYPES: [&str; 1] = ["eq"];
361
362/// The name of the counter that a numbered equation line counts in,
363/// `flm.math.equation`: its counter value at the line is the line's number
364/// ([`CounterDecl`]).
365///
366/// This feature declares the counter ([`counter_decl`]). Every line that can
367/// be numbered and carries no `\tag` counts in it, unless the feature's
368/// configuration numbers no equations ([`MathConfig`]). The counter is not
369/// numbered within another counter; a document that wants equations numbered
370/// within sections, `(1.1)`, `(1.2)`, sets that in its numbering options
371/// ([`NumberingOptions`](crate::stdlib::features::numbering::NumberingOptions)).
372pub const COUNTER: &str = "flm.math.equation";
373
374/// The name of the counter style that an equation line's number is shown in,
375/// `flm.math.style.equation` ([`CounterStyleDecl`]): the number format, the
376/// words a reference writes before the number and the parentheses around it.
377///
378/// This feature declares the counter style; [`counter_style`] says what it
379/// writes. See [`COUNTER`].
380pub const COUNTER_STYLE: &str = "flm.math.style.equation";
381
382/// The text that the anchor of an equation line without a label begins with,
383/// `eq`: the first of the [`LABEL_TYPES`].
384///
385/// Every equation line has an anchor, the identifier a link points at
386/// ([`ANCHORS`](crate::stdlib::features::refs::ANCHORS)), so that a link from
387/// a table of contents, another page or a script can lead to any line. A line
388/// labeled `eq:euler` has the anchor `eq-euler`; a line without a label has
389/// the anchor `eq--`, its position among the document's equation lines and
390/// four letters, as in `eq--8kqzt`
391/// ([`auto_anchor`](crate::stdlib::features::refs::auto_anchor)).
392pub const ANCHOR_PREFIX: &str = LABEL_TYPES[0];
393
394
395/// The display-math environments the feature declares, as `(name, numbered)`,
396/// where `numbered` is the value of [`MathEnvironment::numbered`].
397pub const ENVIRONMENTS: [(&str, bool); 6] = [
398    ("equation", true),
399    ("equation*", false),
400    ("align", true),
401    ("align*", false),
402    ("gather", true),
403    ("gather*", false),
404];
405
406/// The data of one element value of `flm.math.environment`: which display-math
407/// environment was written, and whether its lines are numbered.
408///
409/// The value is also the element's [`Referenceable`] aspect: it reads the
410/// environment's body as equation lines and declares one reference point per
411/// line (see the module documentation, *Equation lines, reference points and
412/// numbers*).
413///
414/// A lowering rule or a stage reads it from a node with
415/// [`element_value`](crate::model::element::element_value).
416#[derive(Debug, Clone, PartialEq, Eq)]
417pub struct MathEnvironment {
418    /// The environment's name as written (`align*`).
419    pub name: Name,
420    /// Whether the environment is an unstarred form, whose lines can be
421    /// numbered. Such a line states a [number
422    /// source](crate::model::aspects::NumberSource) unless `\nonumber` or a
423    /// `\tag` is written on it, or the configuration numbers no equations.
424    pub numbered: bool,
425    /// Whether the registry numbers equations at all
426    /// ([`MathConfig::numbered_equations`]), as the configuration was when the
427    /// registry was built. A line states a number source only when this and
428    /// [`numbered`](MathEnvironment::numbered) are both `true`; a line of an
429    /// unstarred environment keeps its labels in either case.
430    pub numbered_equations: bool,
431}
432
433/// The configuration of the [`math`](self) feature: whether the lines of the
434/// unstarred display-math environments are numbered.
435///
436/// A feature's configuration is the plain Rust value the feature is
437/// constructed from; it is fixed when the registry is built ([settings,
438/// options and
439/// configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
440/// This setting must be fixed when the registry is built, because the
441/// reference points that an environment declares depend on it, and the code
442/// that declares them (the element's [`Referenceable`] aspect; see [elements
443/// and aspects](crate::guide::concepts_overview#elements-and-aspects)) cannot
444/// read an option set per document or per render. The feature adds
445/// [`digest_bytes`](MathConfig::digest_bytes) to the registry digest, so that
446/// two registries built with different configurations have different
447/// digests.
448///
449/// # Examples
450///
451/// ```
452/// use flm_core::stdlib::features::math::MathConfig;
453///
454/// assert!(MathConfig::new().numbered_equations);
455/// let unnumbered = MathConfig::new().numbered_equations(false);
456/// assert!(!unnumbered.numbered_equations);
457/// ```
458#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
459#[derive(schemars::JsonSchema)]
460#[serde(default, deny_unknown_fields)]
461pub struct MathConfig {
462    /// Whether the lines of `equation`, `align` and `gather` that carry no
463    /// `\nonumber` and no `\tag` are numbered. `true` by default. The lines
464    /// of `equation*`, `align*` and `gather*` are never numbered.
465    pub numbered_equations: bool,
466}
467
468impl Default for MathConfig {
469    fn default() -> MathConfig {
470        MathConfig { numbered_equations: true }
471    }
472}
473
474impl MathConfig {
475    /// The default configuration: the lines of the unstarred environments are
476    /// numbered.
477    pub fn new() -> MathConfig {
478        MathConfig::default()
479    }
480
481    /// Builder: sets [`numbered_equations`](MathConfig::numbered_equations).
482    pub fn numbered_equations(mut self, numbered: bool) -> MathConfig {
483        self.numbered_equations = numbered;
484        self
485    }
486
487    /// The bytes this configuration adds to the [registry
488    /// digest](crate::model::digest), one per field.
489    pub fn digest_bytes(&self) -> Vec<u8> {
490        let MathConfig { numbered_equations } = self;
491        vec![u8::from(*numbered_equations)]
492    }
493}
494
495impl std::hash::Hash for MathConfig {
496    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
497        state.write(&self.digest_bytes());
498    }
499}
500
501/// The reference points of a display-math environment: one per equation line,
502/// in the order the lines are written ([`lines::equation_lines`]), including
503/// the lines that cannot be numbered.
504///
505/// **A line that can be numbered** (a line of an unstarred environment with no
506/// `\nonumber`) keeps the labels written on it and accepts the
507/// [`LABEL_TYPES`]. It states:
508///
509/// - a [number source](NumberSource) when it carries no `\tag` and the
510///   feature's configuration numbers equations
511///   ([`MathConfig::numbered_equations`]): the [`COUNTER`], the
512///   [`COUNTER_STYLE`] and one level to advance, so that a reference to the
513///   line shows its number;
514/// - the content of its `\tag` when it carries one, and no number source: a
515///   reference to the line shows the tag as the author wrote it, formatting
516///   included, and the line counts in nothing.
517///
518/// A line with a `\tag` therefore states no number source and still keeps its
519/// labels, because a reference to it shows the tag.
520///
521/// **A line that cannot be numbered** (every line of `equation*`, `align*` and
522/// `gather*`, and a line marked `\nonumber`) keeps no label and accepts no
523/// label type, so no reference resolves to it and no safe label is assigned
524/// for a `\label` written on it. Such a `\label` or `\tag` is reported once,
525/// when the body is parsed, as `flm.math.label-without-number`
526/// ([`lines::LabelWithoutNumber`]); a `\ref` to that label is then
527/// unresolved. The line is still a reference point, so that a tool can walk
528/// every line of every environment, and it still has an anchor.
529///
530/// Every line's anchor follows [`AnchorPolicy::Auto`] with the prefix
531/// [`ANCHOR_PREFIX`]: the anchor of its first label, or one derived from its
532/// position. A line's mathematics is never stated as content, because a
533/// reference shows a number or a tag, never a formula.
534impl Referenceable for MathEnvironment {
535    fn points(&self, node: &NodeRef<'_, Flm>) -> Vec<RefPoint> {
536        lines::equation_lines(node)
537            .iter()
538            .map(|line| {
539                let can_be_numbered = self.numbered && !line.nonumber;
540                let (labels, malformed) = if can_be_numbered {
541                    refs::point_labels(line.labels.iter())
542                } else {
543                    (Vec::new(), Vec::new())
544                };
545                RefPoint {
546                    kind: RefKind::from(KIND),
547                    labels,
548                    malformed,
549                    computed: 0,
550                    // A line with a label of its own is anchored on it; one
551                    // without takes its position among the equation lines.
552                    anchor: AnchorPolicy::Auto { prefix: ANCHOR_PREFIX.to_string() },
553                    number: (can_be_numbered && self.numbered_equations && line.tag.is_none())
554                        .then(|| NumberSource {
555                        counter: Name::from(COUNTER),
556                        instances: Vec::new(),
557                        style: Name::from(COUNTER_STYLE),
558                        advance: vec![0],
559                        number_format: None,
560                    }),
561                    content: line.tag.as_ref().and_then(|tag| tag.content_ref()),
562                    accepts: if can_be_numbered {
563                        AcceptedRefTypes::these(LABEL_TYPES)
564                    } else {
565                        // Nothing may be written for a line with no number.
566                        AcceptedRefTypes::These(Vec::new())
567                    },
568                }
569            })
570            .collect()
571    }
572}
573
574/// The element value of one display-math environment, `name`: a [displayed
575/// item](BlockRole::Displayed) whose [`MathEnvironment`] value records the
576/// name and declares the reference points of its lines, numbered where
577/// `numbered` and `numbered_equations` are both `true`.
578fn environment_element(name: &str, numbered: bool, numbered_equations: bool) -> Arc<ElementSpec> {
579    let value = Arc::new(MathEnvironment { name: Name::from(name), numbered, numbered_equations });
580    Arc::new(
581        ElementSpec::new(ENVIRONMENT)
582            .docs(format!("The `{name}` display-math environment."))
583            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::Displayed)))
584            .with::<dyn Referenceable>(Arc::clone(&value) as Arc<dyn Referenceable>)
585            .with_value(value),
586    )
587}
588
589/// The declaration of the counter [`COUNTER`] (`flm.math.equation`), shown by
590/// default in the counter style [`COUNTER_STYLE`] and numbered within no other
591/// counter.
592///
593/// Numbered within no other counter means that the counter never restarts and
594/// that no other counter's number is written before its own. A document that
595/// wants equations numbered within sections, `(1.1)`, `(1.2)`, `(2.1)`, sets
596/// that in its numbering options
597/// ([`NumberingOptions`](crate::stdlib::features::numbering::NumberingOptions)).
598///
599/// The [`Math`] feature contributes this declaration to the numbering
600/// feature's service slot of counters as a peer contribution, a contribution to
601/// a service slot that another feature owns ([`services`](crate::core::services)):
602/// where the numbering feature is not registered, the contribution is dropped
603/// with one Note and no equation is numbered.
604///
605/// # Examples
606///
607/// ```
608/// use flm_core::stdlib::features::math;
609///
610/// let decl = math::counter_decl();
611/// assert_eq!(decl.name, math::COUNTER);
612/// assert_eq!(decl.default_style, math::COUNTER_STYLE);
613/// assert!(decl.within.is_none());
614/// ```
615pub fn counter_decl() -> CounterDecl {
616    CounterDecl::new(COUNTER, COUNTER_STYLE).docs(
617        "The equation counter: every numbered line of a display-math environment counts in \
618         it, in the order of the document.",
619    )
620}
621
622/// The declaration of the counter style [`COUNTER_STYLE`]
623/// (`flm.math.style.equation`): the number in decimal digits between
624/// parentheses, `(3)`; the prefix words `Eq.~` before one number and `Eqs.~`
625/// before several, and `Equation~` and `Equations~` in the variant `capital`;
626/// several numbers joined compactly (`(1,2)`, `(1–3)`).
627///
628/// A counter style says how a counter value is shown ([`CounterStyleDecl`];
629/// see [counters and counter
630/// styles](crate::guide::concepts_overview#counters-and-counter-styles)). A
631/// `\ref` to an equation writes the prefix words before the number, and
632/// `\ref[noprefix]` and `\eqref` leave them out; the parentheses are written in
633/// every case. The option `S` of a `\ref` selects the variant `capital`, for a
634/// reference at the start of a sentence.
635///
636/// Every text of the counter style is written in the template language and
637/// compiled once when the registry is built: the `~` of `Eq.~` is FLM's
638/// non-breaking space.
639///
640/// The [`Math`] feature contributes this declaration to the numbering
641/// feature's service slot of counter styles as a peer contribution, like
642/// [`counter_decl`].
643///
644/// # Examples
645///
646/// ```
647/// use flm_core::stdlib::features::math;
648///
649/// let style = math::counter_style();
650/// assert_eq!(style.name, math::COUNTER_STYLE);
651/// assert_eq!(style.delimiters.open, "(");
652/// assert_eq!(style.prefix_words.base.one, "Eq.~");
653/// assert_eq!(style.prefix_words.variants["capital"].other, "Equations~");
654/// ```
655pub fn counter_style() -> CounterStyleDecl {
656    let mut style = CounterStyleDecl::new(COUNTER_STYLE);
657    style.number_format = NumberTemplate::formats("#{arabic}");
658    style.delimiters = Delimiters::new("(", ")");
659    style.prefix_words = PrefixWords::new("Eq.~", "Eqs.~")
660        .with_variant(refs::CAPITAL_VARIANT, PluralWords::new("Equation~", "Equations~"));
661    style.join = JoinDecl::compact();
662    style
663}
664
665/// The `math` feature: it registers the six display-math environments and the
666/// commands of their bodies, the text commands of math mode, `\ensuremath`,
667/// `\eqref`, the counter and counter style of equations, and the two
668/// capabilities. It
669/// registers no fallback, no check and no rule on a formula: a feature that
670/// processes mathematics does (the module documentation, *Processing
671/// mathematics*).
672#[derive(Debug, Default, Clone, Copy)]
673pub struct Math {
674    config: MathConfig,
675}
676
677impl Math {
678    /// The feature with the configuration `config`.
679    pub fn new(config: MathConfig) -> Math {
680        Math { config }
681    }
682}
683
684impl FlmFeature for Math {
685    fn info(&self) -> FeatureInfo {
686        FeatureInfo::new(FEATURE, "Math").docs(
687            "Mathematics: the display-math environments and their equation lines, the text \
688             commands of math mode, `\\ensuremath`, `\\eqref`, equation numbering, and the capabilities \
689             `flm.math.content` and `flm.math.rendered`. A feature that processes mathematics \
690             (`math-passthrough`) checks and lowers the formulas.",
691        )
692    }
693
694    fn settings(&self) -> Option<SettingsDecl> {
695        Some(settings())
696    }
697
698    fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
699        let owner: FeatureName = b.feature().clone();
700        for (name, numbered) in ENVIRONMENTS {
701            b.element(
702                ElementDef::new(
703                    owner.clone(),
704                    [name],
705                    SyntaxDef::Environment {
706                        args: Vec::new(),
707                        body: BodyDef::new()
708                            .mode(Mode::Math)
709                            .scoped(lines::PACKAGE)
710                            .parser(lines::body_behavior(numbered)),
711                    },
712                    environment_element(name, numbered, self.config.numbered_equations),
713                )
714                .docs(if numbered && self.config.numbered_equations {
715                    format!(
716                        "Displays mathematics as the LaTeX environment `{name}` does; each line \
717                         is numbered unless it is marked `\\nonumber` or given a `\\tag`."
718                    )
719                } else {
720                    format!("Displays mathematics as the LaTeX environment `{name}` does, unnumbered.")
721                }),
722            )?;
723        }
724        b.element_type_text(
725            ENVIRONMENT,
726            "Displayed mathematics written as an environment (`equation`, `align`, `gather` and \
727             their starred forms): lines of mathematics set apart from the text. Whether a line \
728             is numbered depends on the environment, on the line (`\\nonumber`, `\\tag`) and on \
729             the feature's setting `numbered_equations`.",
730        )?;
731        text::register(b)?;
732        ensuremath::register(b)?;
733        // The `\label` of an equation line holds a label as the references
734        // feature's `\label` does, with that feature's role; declared as a
735        // peer, so that a registry without that feature still builds.
736        b.peer_argument_role(refs::DEFINED_LABEL_ARG_ROLE)?;
737        b.scoped_package(lines::package(owner.clone()))?;
738        // The counter and its style belong to the feature that numbers
739        // documents; this feature hands them over as peer contributions, so
740        // that it builds where that feature is not registered.
741        b.peer_slot::<CounterDecl>(COUNTERS_SLOT, Arc::new(counter_decl()))?;
742        b.peer_slot::<CounterStyleDecl>(STYLES_SLOT, Arc::new(counter_style()))?;
743        // The feature that processes mathematics provides the capability and
744        // adds its check to `flm.validated`; this feature only declares it. The
745        // processing feature is the one that knows what it accepts, and a
746        // registry without one still runs every standard workflow.
747        b.capability(CapabilityDef::new(CONTENT).docs(
748            "The mathematics of the document has been checked. No stage of the `math` feature \
749             provides it: a feature that processes mathematics provides it with a check of its \
750             own and adds that check to the collection `flm.validated` (the feature of the \
751             package `math-passthrough` accepts every formula).",
752        ))?;
753        b.capability(CapabilityDef::new(RENDERED).docs(
754            "Some rendered form of the mathematics exists. No standard feature provides it; \
755             an extension that renders mathematics provides a refinement.",
756        ))?;
757        // The counter table belongs to the feature that numbers; a registry
758        // need not hold it, so the `\eqref` rule reads it optionally, under
759        // this peer declaration, and shows no number without it.
760        b.peer_table::<Counters>(
761            COUNTERS.name(),
762            "the numbering feature's counter table, which the `\\eqref` rule reads for the \
763             number of the equation line it refers to",
764        )?;
765        b.digest_input(&self.config.digest_bytes())?;
766        latex::register(b)?;
767        eqref::register(b, &owner)?;
768        unprocessed::register(b)?;
769        Ok(())
770    }
771}
772
773/// The [`Math`] feature with the default configuration, as a shared value
774/// ready to be listed in a package entry.
775pub fn feature() -> Arc<dyn FlmFeature> {
776    Arc::new(Math::default())
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782
783    #[test]
784    fn an_environment_value_is_a_displayed_item_carrying_its_name() {
785        let element = environment_element("align*", false, true);
786        assert_eq!(element.name, ENVIRONMENT);
787        assert!(element.has_aspect::<dyn BlockRoleAspect>());
788        let value = element.value_as::<MathEnvironment>().expect("valued");
789        assert_eq!(value.name, "align*");
790        assert!(!value.numbered);
791        assert!(value.numbered_equations);
792    }
793
794    #[test]
795    fn the_configuration_digests_its_one_field() {
796        assert_ne!(
797            MathConfig::new().digest_bytes(),
798            MathConfig::new().numbered_equations(false).digest_bytes()
799        );
800    }
801}