Skip to main content

flm_core/stdlib/features/math/
text.rs

1//! The text commands of math mode: `\text{…}` and the related commands, which
2//! put document text inside a formula.
3//!
4//! A **text command** is a command of math mode whose one argument is read in
5//! text mode: inside a formula, its argument is document content rather than
6//! mathematical notation. An author writes a word of text inside a formula, such
7//! as "for all *x* such that", a unit or a short remark, with `\text{…}`,
8//! `\textbf{…}`, `\mbox{…}` or another of the twelve commands of [`COMMANDS`].
9//! Everything else in a formula is carried to the output as the author wrote it
10//! (see the [`math`](super) feature).
11//!
12//! # Where the commands are declared
13//!
14//! This module declares the twelve commands **for math mode only**
15//! (`[Mode::Math]`). In text mode they are not this module's: `\textbf`,
16//! `\textit` and `\texttt` are the
17//! [`textstyles`](crate::stdlib::features::textstyles) feature's, and `\text`,
18//! `\mbox` and the others are unknown commands, an Error in text mode.
19//!
20//! The `textstyles` feature declares `\textbf`, `\textit` and `\texttt` in text
21//! mode only, the default of a declaration ([`ElementDef::modes`]). The two
22//! features therefore declare these names in modes that do not overlap: in text
23//! mode the name is the `textstyles` feature's, in math mode this feature's.
24//! Two declarations whose modes do not overlap never clash, so neither feature
25//! declares an override, and the order in which the two features are registered
26//! does not matter.
27//!
28//! # What the argument holds
29//!
30//! The argument of a text command is read in text mode, with the parsing rules of
31//! text, so it holds ordinary FLM content: formatting commands (`\emph{…}`),
32//! references (`\ref{…}`), uses of user definitions, and mathematics again
33//! (`\(…\)`). The two modes differ at the argument's edge: a command that no
34//! feature declares is kept as source in the mathematics around the argument,
35//! but is an Error inside it, because the argument is text.
36//!
37//! Three later steps follow from this, each in its own module:
38//!
39//! - the [block-structure pass](crate::lang::rewrites::blocks) lays the argument
40//!   out as inline content (whitespace resolved, typographic substitution
41//!   applied), although the formula around it is an [opaque
42//!   region](crate::guide::concepts_overview#opaque-regions) that the pass leaves
43//!   untouched;
44//! - on the `html` backend, and inside a display-math environment on the `text`
45//!   backend, the lowering puts the argument's content inside a
46//!   [`flm.pres.math-text`](crate::stdlib::backends::pres::MATH_TEXT) node among
47//!   the formula's source, the only part of the formula that is content (on the
48//!   `text` backend, `\(…\)` and `\[…\]` are copied whole as source);
49//! - the `latex-recomposed` backend writes the command back as the LaTeX macro of
50//!   the same name, its argument recomposed as text ([`super::latex`]).
51//!
52//! # The element and its rules
53//!
54//! The twelve commands form one family, declared as one element type with one
55//! element value per command ([elements and
56//! aspects](crate::guide::concepts_overview#elements-and-aspects)): the element
57//! type [`TEXT`] (`flm.math.text`), each element value carrying a
58//! [`MathTextCommand`] with the command's name, which a backend writes back.
59//!
60//! - [`RULE`] (`flm.math.text.lower.default`) is the default rule on every
61//!   backend: it stages (builds into the lowered tree; see
62//!   [`Lowerer`]) a `flm.pres.math-text` node
63//!   that carries the command's name, over the argument lowered through the
64//!   rules. The rules of the [`math`](super) feature that write a formula on the
65//!   `text` and `html` backends lower each text command they find through it.
66//! - On the `latex-recomposed` backend,
67//!   [`TEXT_LATEX_RULE`](super::latex::TEXT_LATEX_RULE) is the default instead.
68//!
69//! # Commands not declared here
70//!
71//! `\intertext` and `\shortintertext` also take text, but they set a paragraph
72//! of text between two lines of a display-math environment, not content inside a
73//! formula. FLM does not model them: the reader of equation lines
74//! ([`super::lines::equation_lines`]) would leave such a command in the content
75//! of the line that follows it. They are therefore unknown commands, kept as
76//! source like any unknown command in mathematics.
77
78// The argument's mode is part of each declaration: the argument is stated to be
79// text once, where the command is declared, and every later step reads it off
80// the parsed node without being taught about mathematics. `\fbox` is not
81// declared: it draws a frame, a construct of its own, not a change of the text's
82// face.
83
84use std::sync::Arc;
85
86use techy::core::node::NodeRef;
87use techy::latexlike::Mode;
88
89use crate::core::lowering::{
90    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
91};
92use crate::core::registry::{BuildError, FeatureBuilder};
93use crate::lang::Flm;
94use crate::lang::mint::{ArgDef, ArgStdKind, ElementDef, SyntaxDef};
95use crate::model::aspects::{BlockRole, BlockRoleAspect, FixedBlockRole};
96use crate::model::element::{ElementSpec, element_value};
97use crate::model::names::{ElementName, FeatureName, Name};
98use crate::stdlib::backends::lowering::lower_arg_or_nothing;
99use crate::stdlib::backends::pres::{self, MathTextPayload};
100
101/// The name of the element type of the text commands of math mode,
102/// `flm.math.text`. The data of each element value is a
103/// [`MathTextCommand`].
104pub const TEXT: &str = "flm.math.text";
105
106/// The name of the default lowering rule of [`TEXT`] on every backend,
107/// `flm.math.text.lower.default`, whose body is [`TextRule`].
108pub const RULE: &str = "flm.math.text.lower.default";
109
110/// The name of the only argument of every text command, `content`.
111pub const CONTENT_ARG: &str = "content";
112
113/// The text commands declared for math mode, in the order they are registered:
114/// `text`, `textnormal`, `textup`, `textrm`, `textmd`, `textbf`, `textit`,
115/// `textsl`, `textsc`, `textsf`, `texttt`, `mbox`.
116///
117/// The names are written without the leading backslash. Each command takes one
118/// mandatory argument read in text mode. The library does not apply what a
119/// command asks of the output (a bold weight for `\textbf`, nothing for
120/// `\text`): the command's name is carried by the element value
121/// ([`MathTextCommand`]) and by the payload of the presentation node
122/// ([`MathTextPayload::command`]), and the output decides.
123pub const COMMANDS: [&str; 12] = [
124    "text",
125    "textnormal",
126    "textup",
127    "textrm",
128    "textmd",
129    "textbf",
130    "textit",
131    "textsl",
132    "textsc",
133    "textsf",
134    "texttt",
135    "mbox",
136];
137
138/// The data of one element value of `flm.math.text`: which text command was
139/// written.
140///
141/// A lowering rule or a stage reads it from a node with [`element_value`].
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct MathTextCommand {
144    /// The command's name as written, without the leading backslash
145    /// (`textbf`).
146    pub command: Name,
147}
148
149/// The element value of one text command: a `flm.math.text` element value
150/// carrying the command's name, inline (the default block role).
151fn text_element(command: &str) -> Arc<ElementSpec> {
152    Arc::new(
153        ElementSpec::new(TEXT)
154            .docs(format!(
155                "`\\{command}{{…}}` inside mathematics: its argument is document content, read \
156                 in text mode."
157            ))
158            .with::<dyn BlockRoleAspect>(Arc::new(FixedBlockRole(BlockRole::DEFAULT)))
159            .with_value(Arc::new(MathTextCommand { command: Name::from(command) })),
160    )
161}
162
163/// The declaration of one text command: a macro, declared for math mode only,
164/// with one mandatory argument read in text mode.
165fn text_def(owner: &FeatureName, command: &str) -> ElementDef {
166    ElementDef::new(
167        owner.clone(),
168        [command],
169        SyntaxDef::Macro {
170            args: vec![
171                ArgDef::named(CONTENT_ARG, ArgStdKind::Mandatory)
172                    .mode(Mode::Text)
173                    .docs("The text, as document content."),
174            ],
175        },
176        text_element(command),
177    )
178    .modes([Mode::Math])
179    .docs(
180        "Writes text inside a formula. The argument is read in text mode, so it holds \
181         document content, not mathematical notation.",
182    )
183}
184
185/// The body of [`RULE`]: it stages a
186/// [`flm.pres.math-text`](crate::stdlib::backends::pres::MATH_TEXT) node that
187/// carries the command's name, over the command's argument lowered through the
188/// rules.
189///
190/// When the argument is missing (a parse recovery left it absent and the parse
191/// reported it), the node has no content and nothing more is reported. The
192/// rule returns a [`LowerError`] when the node carries no [`MathTextCommand`]
193/// or when the argument or the node could not be lowered or staged.
194#[derive(Debug, Default)]
195pub struct TextRule;
196
197impl Lower for TextRule {
198    fn lower(
199        &self,
200        node: NodeRef<'_, Flm>,
201        cx: &mut LowerCx<'_>,
202        lw: &mut dyn Lowerer,
203    ) -> Result<Lowering, LowerError> {
204        let value = element_value::<MathTextCommand>(&node)
205            .ok_or_else(|| LowerError::structure("a math text command without its element's data"))?;
206        let body = lower_arg_or_nothing(cx, lw, &node, 0)?;
207        let payload = MathTextPayload {
208            command: Some(value.command.to_string()),
209            anchor: None,
210            at_tag: false,
211        };
212        let text = lw.pres_with(cx, &ElementName::from(pres::MATH_TEXT), payload, body)?;
213        Ok(Lowering::Emit(vec![text]))
214    }
215}
216
217/// Registers the text commands and their default lowering rule, as part of the
218/// `math` feature.
219///
220/// # Errors
221///
222/// Returns the [`BuildError`] the feature builder raises, for instance for a
223/// rule already registered under the same name.
224pub(super) fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
225    let owner: FeatureName = b.feature().clone();
226    for command in COMMANDS {
227        b.element(text_def(&owner, command))?;
228    }
229    b.element_type_text(
230        TEXT,
231        "Text inside a formula: document content, read in text mode, that a text command \
232         such as `\\text` writes within mathematics.",
233    )?;
234    b.lowering_rule(
235        LoweringRule::new(
236            RULE,
237            TEXT,
238            LoweringDecl::new().produces(pres::MATH_TEXT),
239            Arc::new(TextRule),
240            DefaultMark::Everywhere,
241        )
242        .docs(
243            "a text command of math mode lowers to a `flm.pres.math-text` node that carries \
244             its name, over its argument lowered through the rules",
245        ),
246    )?;
247    Ok(())
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    #[test]
255    fn every_command_is_one_value_of_the_one_element_type() {
256        for command in COMMANDS {
257            let element = text_element(command);
258            assert_eq!(element.name, TEXT);
259            let value = element.value_as::<MathTextCommand>().expect("valued");
260            assert_eq!(value.command, command);
261        }
262    }
263
264    #[test]
265    fn a_text_command_is_a_math_mode_macro_whose_argument_is_text_mode() {
266        let def = text_def(&FeatureName::from("math"), "text");
267        assert_eq!(def.modes, vec![Mode::Math]);
268        let SyntaxDef::Macro { args } = &def.syntax else { panic!("a macro") };
269        assert_eq!(args.len(), 1);
270        assert_eq!(args[0].name.as_deref(), Some(CONTENT_ARG));
271        assert_eq!(args[0].mode, Some(Mode::Text));
272    }
273}