flm_core/stdlib/features/math/frame.rs
1//! The frame of a formula: what the [`math`](super) feature knows of a
2//! formula without reading its content, computed by plain functions that a
3//! processing feature's stages and rules call.
4//!
5//! A *processing feature* is a feature that reads mathematical content and
6//! lowers formulas (the module documentation of [`math`](super), *Processing
7//! mathematics*). Whatever it does with the mathematics itself, it writes the
8//! same frame around it: whether a math group is displayed, and for each
9//! equation line of a display-math environment its anchor and what it shows at
10//! its tag's place (a number, the author's `\tag`, or nothing). This module
11//! computes that frame; [`super::latex`] holds the parts that write it as LaTeX.
12//!
13//! The functions are *parts called in order*, never a callback: a rule calls
14//! [`line_frames`], then, for each line, writes the line's content its own way
15//! and calls [`stage_tag_content`] for what goes at the tag's place. The
16//! functions that read tables take the tables as values, what
17//! [`StageCx::get`](crate::core::run::StageCx::get) or
18//! [`Lowerer::get_erased`] answered (through the typed `get` on `dyn Lowerer`),
19//! so that a stage and a rule call them alike.
20//!
21//! - [`formula_display`] — whether a math group is displayed.
22//! - [`line_frames`], [`LineFrame`], [`LineShows`] — the frame of each
23//! equation line of an environment.
24//! - [`number_text`] — a line's number as plain characters.
25//! - [`stage_tag_content`] — what to stage at a line's tag's place.
26//!
27//! The reader of equation lines, [`equation_lines`],
28//! stays in [`lines`](super::lines).
29
30use techy::core::node::{BuildId, NodeRef};
31use techy::latexlike::MathGroupForm;
32
33use crate::core::lowering::{LowerCx, LowerError, Lowerer};
34use crate::lang::text::plain_text;
35use crate::lang::{Flm, FlmGroupType};
36use crate::model::addr::NodeAddr;
37use crate::model::aspects::PointId;
38use crate::model::element::element_value;
39use crate::stdlib::backends::lowering::lower_run;
40use crate::stdlib::features::numbering::{Counters, FormatError, FormatOptions, NumberSegment};
41use crate::stdlib::features::refs::Anchors;
42
43use super::MathEnvironment;
44use super::lines::{EquationLine, equation_lines};
45
46/// Whether the math group `node` is displayed: `true` for `\[…\]` (and
47/// `$$…$$`), `false` for `\(…\)` (and `$…$`) and for a node that is not a math
48/// group. Read from the node's group class
49/// ([`FlmGroupType::Math`]).
50///
51/// A processing feature's rule of `flm.math` calls it to choose between its
52/// inline and its displayed output.
53pub fn formula_display(node: &NodeRef<'_, Flm>) -> bool {
54 matches!(node.group_type(), Some(FlmGroupType::Math(MathGroupForm::Display)))
55}
56
57/// The frame of one equation line of a display-math environment, as
58/// [`line_frames`] computes it: the line, its anchor, and what it shows at its
59/// tag's place.
60#[derive(Debug, Clone)]
61pub struct LineFrame<'t> {
62 /// The line as [`equation_lines`] read it.
63 pub line: EquationLine<'t>,
64 /// The line's anchor from the anchors table; `None` where no references
65 /// feature is registered (the table is absent), or where the table holds
66 /// no anchor for the line.
67 pub anchor: Option<String>,
68 /// What the line shows at its tag's place.
69 pub shows: LineShows<'t>,
70}
71
72/// What an equation line shows at its tag's place ([`LineFrame::shows`]).
73#[derive(Debug, Clone)]
74pub enum LineShows<'t> {
75 /// Nothing: a line of a starred environment, a line marked `\nonumber`, or
76 /// any line where the feature's configuration numbers no equations
77 /// ([`MathConfig::numbered_equations`](super::MathConfig::numbered_equations)),
78 /// when the line carries no `\tag`.
79 Nothing,
80 /// The line's number, as the numbering feature formats it, with the
81 /// counter style's delimiters (`(3)`) and without the words a reference
82 /// writes before it; empty where no numbering feature is registered (the
83 /// counter table is absent), or where the table holds no number for the
84 /// line.
85 Number(Vec<NumberSegment>),
86 /// The author's `\tag`: its content nodes, and whether the star was
87 /// written (`\tag*{…}`). A line shows the tag written on it even where it
88 /// cannot be numbered (that case is reported when the body is parsed, as
89 /// [`LabelWithoutNumber`](super::lines::LabelWithoutNumber)).
90 Tag {
91 /// Whether the star was written: `\tag*{A}` shows `A`, and `\tag{A}`
92 /// shows `(A)`.
93 starred: bool,
94 /// The nodes of the tag's argument, document content.
95 content: Vec<NodeRef<'t, Flm>>,
96 },
97}
98
99/// The frame of each equation line of the display-math environment `node`, in
100/// order: the line ([`equation_lines`]), its anchor and what it shows at its
101/// tag's place.
102///
103/// `anchors` and `counters` are the anchors table of the references feature
104/// ([`ANCHORS`](crate::stdlib::features::refs::ANCHORS)) and the counter table of the numbering feature
105/// ([`COUNTERS`](crate::stdlib::features::numbering::COUNTERS)), as the caller read them, or `None` where
106/// the table is absent; `addr` is the address of `node` in its tree
107/// ([`Lowerer::addr`] in a rule, [`StageCx::addr`](crate::core::run::StageCx::addr)
108/// in a stage), under which both tables key the lines' reference points. The
109/// caller's feature declares the two tables as optional reads and as peer
110/// tables of its own.
111///
112/// A processing feature's rule (or stage) of `flm.math.environment` calls it
113/// first, then writes each line around its frame. A line shows its `\tag` when
114/// one is written; otherwise its number when the line can be numbered (an
115/// unstarred environment, no `\nonumber`, and a configuration that numbers
116/// equations), empty when the counter table is absent; otherwise nothing. A
117/// node that carries no [`MathEnvironment`] value is read as an environment
118/// whose lines cannot be numbered.
119///
120/// # Errors
121///
122/// Returns [`FormatError`] when a number could not be written: a counter
123/// record that does not fit the counter style it was made with, which the
124/// numbering stage prevents.
125pub fn line_frames<'t>(
126 anchors: Option<&Anchors>,
127 counters: Option<&Counters>,
128 addr: NodeAddr,
129 node: &NodeRef<'t, Flm>,
130) -> Result<Vec<LineFrame<'t>>, FormatError> {
131 let numbered = element_value::<MathEnvironment>(node)
132 .is_some_and(|value| value.numbered && value.numbered_equations);
133 // The word before a number belongs to a reference to the line, not to the
134 // line itself: a formula shows `(3)`, and `Eq.~(3)` is what a `\ref` to it
135 // shows.
136 let options = FormatOptions::new().without_word();
137 let mut frames = Vec::new();
138 for (index, line) in equation_lines(node).into_iter().enumerate() {
139 let point = PointId { addr, index: index as u32 };
140 let anchor = anchors.and_then(|anchors| anchors.id(point)).map(String::from);
141 let shows = match &line.tag {
142 Some(tag) => LineShows::Tag { starred: tag.star, content: tag.content.clone() },
143 None if numbered && !line.nonumber => {
144 let number = match counters.and_then(|counters| counters.format(point, &options)) {
145 None => Vec::new(),
146 Some(written) => written?,
147 };
148 LineShows::Number(number)
149 }
150 None => LineShows::Nothing,
151 };
152 frames.push(LineFrame { line, anchor, shows });
153 }
154 Ok(frames)
155}
156
157/// The number a line shows, as plain characters: the segments of
158/// [`LineShows::Number`] joined, the counter style's delimiters included
159/// (`(3)`); an empty text where the number is empty. `None` where the line
160/// shows nothing or a tag.
161///
162/// A processing feature calls it where it hands the number to a renderer as
163/// text rather than staging its segments.
164pub fn number_text(frame: &LineFrame<'_>) -> Option<String> {
165 match &frame.shows {
166 LineShows::Number(segments) => {
167 Some(segments.iter().map(|segment| plain_text(segment.content())).collect())
168 }
169 LineShows::Nothing | LineShows::Tag { .. } => None,
170 }
171}
172
173/// Stages what an equation line shows at its tag's place, and returns the
174/// nodes to emit: the number's segments spliced (synthesized values, each
175/// brought up to date and lowered); the author's tag lowered through the
176/// rules, between `(` and `)` when it is not starred; nothing when the line
177/// shows nothing.
178///
179/// A processing feature's rule of `flm.math.environment` calls it for each
180/// line, after the line's content, and wraps the result in whatever its output
181/// writes a tag as.
182///
183/// # Errors
184///
185/// Returns [`LowerError`] when a node could not be lowered or staged.
186pub fn stage_tag_content(
187 cx: &mut LowerCx<'_>,
188 lw: &mut dyn Lowerer,
189 frame: &LineFrame<'_>,
190) -> Result<Vec<BuildId>, LowerError> {
191 let mut content = Vec::new();
192 match &frame.shows {
193 LineShows::Nothing => {}
194 LineShows::Number(segments) => {
195 for segment in segments {
196 content.extend(lw.splice(cx, segment.content())?);
197 }
198 }
199 LineShows::Tag { starred, content: nodes } => {
200 if !starred {
201 content.push(lw.text(cx, "(")?);
202 }
203 content.extend(lower_run(cx, lw, nodes)?);
204 if !starred {
205 content.push(lw.text(cx, ")")?);
206 }
207 }
208 }
209 Ok(content)
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 fn frame(shows: LineShows<'static>) -> LineFrame<'static> {
217 LineFrame { line: EquationLine::default(), anchor: None, shows }
218 }
219
220 #[test]
221 fn a_line_showing_nothing_or_a_tag_has_no_number_text() {
222 assert_eq!(number_text(&frame(LineShows::Nothing)), None);
223 let tag = LineShows::Tag { starred: true, content: Vec::new() };
224 assert_eq!(number_text(&frame(tag)), None);
225 }
226
227 #[test]
228 fn an_empty_number_is_an_empty_text() {
229 assert_eq!(number_text(&frame(LineShows::Number(Vec::new()))), Some(String::new()));
230 }
231}