Skip to main content

flm_core/stdlib/features/math/
tex.rs

1//! The TeX of a formula, with holes: what a renderer of mathematics converts,
2//! written from the formula's nodes.
3//!
4//! A processing feature that hands its formulas to a typesetter of TeX
5//! notation (MathJax, a converter to Unicode text) needs each formula's TeX as
6//! a string, except where the formula holds document text: the argument of a
7//! text command (`\text{…}`, `\textbf{…}`, `\mbox{…}`, the commands of
8//! [`text`](super::text)) is content the feature lowers itself, so that a
9//! reference in it is a link and its style is FLM's. This module writes the
10//! TeX as a list of [parts](TexPart), each a piece of TeX text or a
11//! [hole](TextHole) standing for one text command.
12//!
13//! # What it reads
14//!
15//! - [`group_tex`]: a math group (`\(…\)`, `\[…\]`, a node of the element
16//!   [`flm.math`](crate::lang::structural::MATH)), whose TeX is its content,
17//!   without the delimiters.
18//! - [`line_tex`]: one equation line of a display-math environment, an
19//!   [`EquationLine`] as [`equation_lines`](super::lines::equation_lines)
20//!   reads it, whose TeX is its [content](EquationLine::content) written
21//!   under the newline rule (below). A line's `\\`, `\tag`, `\nonumber` and
22//!   labels are not part of its content and are never written: they are data
23//!   of the line, which its [frame](super::frame::LineFrame) holds. The
24//!   environment as a whole is not assembled here: a caller that writes it
25//!   writes `\begin{name}`, then per line its content, what its frame shows,
26//!   its line break and its trailing run (below), then `\end{name}`, passing
27//!   each line's [`LineTex::ends_line`] to [`line_tex`] for the next line.
28//!
29//! # How the nodes are written
30//!
31//! The nodes are those of any processor's commands of math mode, each written
32//! by its source:
33//!
34//! - a command of the processor (a macro, an environment) and a run of
35//!   characters, as their source as written;
36//! - a group, as its delimiters around its content;
37//! - `\ensuremath{…}` ([`ensuremath`](super::ensuremath)), as its argument's
38//!   content alone, the command left out, since inside a formula it stands for
39//!   its argument;
40//! - a text command, as a hole, at any depth (inside a group or a command's
41//!   argument);
42//! - a comment, as one space: the comment takes in its line end, so that
43//!   dropping it would run the tokens on either side together (`\alpha%%c`
44//!   then `b` on the next line is `\alpha b`, not `\alphab`).
45//!
46//! A command that holds a text command, a comment or `\ensuremath{…}` is
47//! written as its call as written (an environment as `\begin{name}` and
48//! `\end{name}` around its arguments and body), then each argument by the same
49//! rules; any other node is written as its source, unchanged.
50//!
51//! Where the TeX written so far ends with a control word (a backslash and
52//! letters, `\rangle`) and the next text begins with a letter, one space stands
53//! between them, which TeX skips after a control word: the two come from
54//! places the source did not write side by side (the end of a user
55//! definition's expansion and the letter after its use; `\alpha` and the
56//! argument of `\ensuremath{b}`), and the letter would otherwise continue the
57//! control word (`\rangleA`, `\alphab`).
58//!
59//! # The newline rule on a line
60//!
61//! A line's content is written under the `math` library's newline rule
62//! ([`normalize_line_newlines`]; the module documentation of
63//! [`latex`](super::latex), *The newline rule*), so that a `\label`, `\tag` or
64//! `\nonumber` taken off a line of its own leaves no blank line, which LaTeX
65//! refuses inside mathematics. Each TeX part of the content is normalized; the
66//! run of whitespace that ends the content is taken off and returned as the
67//! line's [`trailing`](LineTex::trailing) run, for the caller to write after
68//! the line's tag and its line break; when it is not empty, the run that
69//! begins the next line's content is dropped. A hole is not a line's end, and
70//! a comment, written as a space, does not end a line either.
71//!
72//! # The shape of the result
73//!
74//! The result holds strings and node handles only, so that an extension can
75//! receive it across a binding as data: a part is `{tex}` or `{hole: {command,
76//! node}}`, and a line adds its trailing run.
77//!
78//! The functions recompose the source of the nodes they write as source
79//! ([`recompose_source`]), so call them on a worker thread, as every stage
80//! and lowering rule of a run already executes.
81
82use techy::core::node::NodeRef;
83use techy::latexlike::InvocationSyntaxData;
84
85use crate::lang::Flm;
86use crate::lang::mint::is_math_text_command;
87use crate::model::element::element_of;
88use crate::stdlib::backends::pres::read::ends_with_control_word;
89use crate::stdlib::backends::pres::recompose_source;
90
91use super::ensuremath::ENSUREMATH;
92use super::latex::normalize_line_newlines;
93use super::lines::EquationLine;
94
95/// One part of a formula's TeX, in order: TeX text, or a hole for a text
96/// command (see the module documentation).
97///
98/// Two TeX parts never stand side by side: the text between two holes is one
99/// part.
100#[derive(Debug, Clone)]
101pub enum TexPart<'t> {
102    /// TeX text, never empty.
103    Tex(String),
104    /// The place of a text command, which the caller writes.
105    Hole(TextHole<'t>),
106}
107
108/// A text command inside a formula (`\text{…}`, `\textbf{…}`, `\mbox{…}`; see
109/// [`is_math_text_command`]), which the TeX leaves as a hole: the caller
110/// lowers its argument itself and decides how the hole is written.
111#[derive(Debug, Clone)]
112pub struct TextHole<'t> {
113    /// The command's name, without the escape character (`textbf`).
114    pub command: String,
115    /// The text command's node.
116    pub node: NodeRef<'t, Flm>,
117}
118
119/// The TeX of one equation line's content (see the module documentation,
120/// *The newline rule on a line*): what [`line_tex`] returns.
121#[derive(Debug, Clone)]
122pub struct LineTex<'t> {
123    /// The content's TeX, in order, each TeX part under the newline rule.
124    pub parts: Vec<TexPart<'t>>,
125    /// The run of whitespace that ended the line's content, reduced by the
126    /// newline rule, for a caller that assembles the environment to write
127    /// after the line's tag and its line break; empty when the content did
128    /// not end with a run holding a newline.
129    pub trailing: String,
130}
131
132impl LineTex<'_> {
133    /// Whether this line, once its trailing run is written, ends a line of
134    /// the output: the run is not empty. It is the `after_line_end` argument
135    /// of [`line_tex`] for the next line of the environment.
136    pub fn ends_line(&self) -> bool {
137        !self.trailing.is_empty()
138    }
139}
140
141/// The TeX of the math group `node` (a node of
142/// [`flm.math`](crate::lang::structural::MATH)): its content, without its
143/// delimiters, written by the rules of the module documentation. A formula
144/// that holds no text command gives one TeX part, an empty formula none.
145pub fn group_tex<'t>(node: &NodeRef<'t, Flm>) -> Vec<TexPart<'t>> {
146    let mut writer = Writer::default();
147    writer.nodes(&node.children().iter().collect::<Vec<_>>());
148    writer.parts
149}
150
151/// The TeX of the equation line `line`'s content, written by the rules of the
152/// module documentation, each TeX part under the newline rule, and the run of
153/// whitespace that ended the content.
154///
155/// `after_line_end` says whether the output before this line's content ends a
156/// line: `false` for the first line of an environment, and for a later line
157/// the previous line's [`LineTex::ends_line`]. The run that begins the content
158/// is then dropped.
159pub fn line_tex<'t>(line: &EquationLine<'t>, after_line_end: bool) -> LineTex<'t> {
160    let mut writer = Writer::default();
161    writer.nodes(&line.content);
162    let count = writer.parts.len();
163    let mut after_line_end = after_line_end;
164    let mut parts = Vec::with_capacity(count);
165    let mut trailing = String::new();
166    for (index, part) in writer.parts.into_iter().enumerate() {
167        match part {
168            TexPart::Tex(text) => {
169                let line = normalize_line_newlines(&text, after_line_end, index + 1 < count);
170                if !line.text.is_empty() {
171                    parts.push(TexPart::Tex(line.text));
172                }
173                trailing = line.trailing;
174            }
175            TexPart::Hole(hole) => {
176                parts.push(TexPart::Hole(hole));
177                after_line_end = false;
178            }
179        }
180    }
181    LineTex { parts, trailing }
182}
183
184/// Whether `node` is written by the walk ([`Writer::node`]) rather than as its
185/// source: it is, or holds, a text command, a comment or `\ensuremath{…}`.
186fn needs_walk(node: &NodeRef<'_, Flm>) -> bool {
187    let walked = |node: &NodeRef<'_, Flm>| {
188        node.is_comment() || is_math_text_command(node) || element_of(node).name == ENSUREMATH
189    };
190    walked(node) || node.descendants().any(|descendant| walked(&descendant))
191}
192
193/// The beginning of a macro call as written: the escape character, the name,
194/// and the whitespace after the name, which belongs to the call and not to
195/// the argument that follows it.
196fn macro_call(node: &NodeRef<'_, Flm>) -> String {
197    let name = node.name().unwrap_or_default();
198    match node.invocation_syntax() {
199        Some(InvocationSyntaxData::Macro { escape_char, post_space }) => {
200            format!("{escape_char}{name}{}", post_space.resolve(node.span().source()))
201        }
202        _ => format!("\\{name}"),
203    }
204}
205
206/// Collects the parts of a formula's TeX, joining adjacent TeX text.
207#[derive(Debug, Default)]
208struct Writer<'t> {
209    parts: Vec<TexPart<'t>>,
210}
211
212impl<'t> Writer<'t> {
213    /// Appends TeX text, one space between a control word that ends the TeX
214    /// written so far and a letter that begins `text`.
215    fn text(&mut self, text: &str) {
216        if text.is_empty() {
217            return;
218        }
219        if let Some(TexPart::Tex(previous)) = self.parts.last_mut() {
220            if text.starts_with(|c: char| c.is_ascii_alphabetic()) && ends_with_control_word(previous) {
221                previous.push(' ');
222            }
223            previous.push_str(text);
224        } else {
225            self.parts.push(TexPart::Tex(String::from(text)));
226        }
227    }
228
229    /// Writes the nodes `nodes`: each run of nodes that need no walk as its
230    /// source, every other node by the walk.
231    fn nodes(&mut self, nodes: &[NodeRef<'t, Flm>]) {
232        let mut run: Vec<NodeRef<'t, Flm>> = Vec::new();
233        for node in nodes {
234            if needs_walk(node) {
235                self.source(&mut run);
236                self.node(*node);
237            } else {
238                run.push(*node);
239            }
240        }
241        self.source(&mut run);
242    }
243
244    /// Writes the run `run` as its source and empties it.
245    fn source(&mut self, run: &mut Vec<NodeRef<'t, Flm>>) {
246        if !run.is_empty() {
247            self.text(&recompose_source(run));
248            run.clear();
249        }
250    }
251
252    /// Writes one node by the walk (see the module documentation).
253    // This walk carries no depth limit of its own, as the source walk of the
254    // `math-passthrough` feature carries none: the parse that made the tree
255    // refuses a formula nested far less deeply than this walk could go.
256    fn node(&mut self, node: NodeRef<'t, Flm>) {
257        if node.is_comment() {
258            self.text(" ");
259            return;
260        }
261        if is_math_text_command(&node) {
262            let command = String::from(node.name().unwrap_or_default());
263            self.parts.push(TexPart::Hole(TextHole { command, node }));
264            return;
265        }
266        if element_of(&node).name == ENSUREMATH {
267            let content: Vec<NodeRef<'t, Flm>> =
268                node.argument_content_nodes(0).map(|slice| slice.iter().collect()).unwrap_or_default();
269            self.nodes(&content);
270            return;
271        }
272        if let Some((open, close)) = node.group_delimiters() {
273            self.text(open);
274            self.nodes(&node.children().iter().collect::<Vec<_>>());
275            self.text(close);
276            return;
277        }
278        if node.is_list() {
279            self.nodes(&node.children().iter().collect::<Vec<_>>());
280            return;
281        }
282        if let Some(body) = node.body() {
283            let name = node.name().unwrap_or_default();
284            self.text(&format!("\\begin{{{name}}}"));
285            self.arguments(&node);
286            self.nodes(&body.iter().collect::<Vec<_>>());
287            self.text(&format!("\\end{{{name}}}"));
288            return;
289        }
290        if node.callable().is_some_and(|callable| !callable.arguments.is_empty()) {
291            self.text(&macro_call(&node));
292            self.arguments(&node);
293            return;
294        }
295        self.text(&recompose_source(&[node]));
296    }
297
298    /// Writes the arguments of `node` in the order they were written. The
299    /// delimiters of an argument are nodes of the argument, so they are
300    /// written with it.
301    fn arguments(&mut self, node: &NodeRef<'t, Flm>) {
302        let count = node.callable().map_or(0, |callable| callable.arguments.len());
303        for index in 0..count {
304            if let Some(region) = node.argument_nodes(index) {
305                self.nodes(&region.iter().collect::<Vec<_>>());
306            }
307        }
308    }
309}