flm_core/stdlib/features/math/latex.rs
1//! What the [`math`](super) feature contributes to the `latex-recomposed`
2//! backend: the recomposition rule of the text commands, the names a
3//! processing feature writes a display-math environment with, the options
4//! that change how an environment is written, the parts and the line writer a
5//! processing feature writes a formula with, and the newline rule that every
6//! LaTeX writer of an environment's lines applies.
7//!
8//! The `latex-recomposed` backend writes the document back as LaTeX source. Its
9//! rules stage (build into the lowered tree; see
10//! [`Lowerer`]) construct elements, presentation
11//! elements that mirror one construct of LaTeX each ([backends, lowering and
12//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)): a
13//! macro call, an environment, a raw node (`flm.pres.latex.raw`, text written
14//! byte for byte), or a definition for the style file. The rendering guide
15//! describes the result under [mathematics in the recomposed
16//! LaTeX](crate::guide::rendering#mathematics-in-the-recomposed-latex).
17//!
18//! The formulas themselves (`\(…\)`, `\[…\]` and the display-math
19//! environments) are written by the rules of a feature that processes
20//! mathematics, for example
21//! [`math-passthrough`](crate::math_passthrough), whose
22//! [`latex`](crate::math_passthrough::latex) module writes
23//! them as they were written. Those rules read [`MathRecomposeOptions`], and
24//! write an environment as [`FLM_MATH_ENVIRONMENT`] when the options ask for it
25//! and request `amsmath` for every environment but [`KERNEL_ENVIRONMENT`].
26//!
27//! # The LaTeX frame of a formula
28//!
29//! Five plain functions write what surrounds a formula's content in the
30//! recomposed LaTeX, for the rules a processing feature registers on this
31//! backend. They are parts called in order, never a callback: each stages raw
32//! nodes (and, for a line, the constructs of its tag, labels and `\nonumber`)
33//! and returns the build identifiers to emit, and the rule stages its own
34//! content between them (the source as written, lowered content, or a
35//! renderer's output). A sixth function, [`stage_lines`], writes the lines of
36//! an environment as they were written.
37//!
38//! - A math group: [`group_opening`], the content, [`group_closing`]. A
39//! displayed group (`\[…\]`) is surrounded by the texts of
40//! [`surround_display_math`](MathRecomposeOptions::surround_display_math)
41//! as an environment is. An inline group is written `\(…\)`, but the
42//! formula of `\ensuremath{…}` written in text, which is written
43//! `\ensuremath{…}`.
44//! - A display-math environment: [`environment_opening`]; for each equation
45//! line ([`line_frames`](super::frame::line_frames)) the line's content, then
46//! [`line_closing`]; then [`environment_closing`]. [`stage_lines`] writes
47//! every line this way, the content as written by the mathematics writer of
48//! the `userdefs` feature ([`write_math_run`]) under the newline rule (see
49//! *The newline rule* below); a rule that writes a line's content otherwise
50//! calls [`line_closing`] itself.
51//!
52//! The parts read [`MathRecomposeOptions`], the backend's
53//! [`LatexRecomposedRenderOptions`] and the safe-labels table ([`SAFE_LABELS`])
54//! through the [`Lowerer`]: the calling rule declares those reads (the two
55//! option types, and the table as an optional read under a peer declaration
56//! of its own feature), and declares that it produces the raw and macro
57//! constructs (and, for [`stage_lines`], the definition construct, which the
58//! mathematics writer stages for a user definition used on a line).
59//!
60//! **An environment** is written as `\begin{<name>}` … `\end{<name>}`, or,
61//! when [`emit_flm_math_environment_macro`](MathRecomposeOptions::emit_flm_math_environment_macro)
62//! is set, as `\flmMathEnvironment{<name>}{}{` … `}`, through the LaTeX hook
63//! [`FLM_MATH_ENVIRONMENT`] defined by the definition piece
64//! [`MATH_ENVIRONMENT`](crate::stdlib::backends::latex::preamble::MATH_ENVIRONMENT),
65//! which the opening then requires; the six environments take no arguments, so
66//! the second group is empty. The texts of
67//! [`surround_display_math`](MathRecomposeOptions::surround_display_math) are
68//! written byte for byte before the opening and after the closing. Every
69//! environment but [`KERNEL_ENVIRONMENT`] needs the LaTeX package `amsmath`,
70//! which the opening requests.
71//!
72//! **A line's closing** is, in order: `\tag*{…}` when the line has a tag (the
73//! tag's content lowered through the rules, between `(` and `)` when the author
74//! wrote `\tag` without the star, so that LaTeX adds nothing of its own); the
75//! line's labels, in order, as one group in the LaTeX hook `\flmLabels`; the
76//! line's `\nonumber`; and the line's `\\` with its spacing as written, when
77//! another line follows. Each label is written as its safe label when the
78//! safe-labels table is present, and as the document wrote it when it is
79//! absent; when the table is absent and the backend's render option
80//! [`drop_math_labels_without_refs`](LatexRecomposedRenderOptions::drop_math_labels_without_refs)
81//! is set, nothing is written for the labels
82//! ([`stage_label`], [`stage_label_group`]). No part numbers a line: the
83//! recomposed LaTeX leaves the numbering to LaTeX.
84//!
85//! **A math group** is written between `\(` and `\)` when it is inline and
86//! between `\[` and `\]` when it is displayed
87//! ([`formula_display`]), whichever delimiters
88//! the author used; the formula of an `\ensuremath{…}` written in text is
89//! written `\ensuremath{`…`}`.
90//!
91//! # The newline rule
92//!
93//! The `\label`, `\tag` and `\nonumber` of an equation line are taken out of
94//! the line's content, and a final `\\` followed only by whitespace is not
95//! written ([`equation_lines`](super::lines::equation_lines)); the whitespace
96//! around them stays in the content. Where such a command stood on a line of
97//! its own, the whitespace before it and the whitespace after it meet, and the
98//! content written as it was written would hold a blank line, which LaTeX
99//! refuses inside mathematics. Every LaTeX writer of an environment's lines
100//! (the recomposed LaTeX through [`stage_lines`], and the rendered LaTeX)
101//! therefore writes the text of each line's content under the newline rule
102//! ([`normalize_line_newlines`]):
103//!
104//! - Every run of spaces, tabs and newlines that holds a newline is written as
105//! one newline followed by the indentation after the run's last newline. A
106//! run that holds no newline is kept as it is.
107//! - A run that ends the line's content is taken off it and written after the
108//! line's closing part (its tag, labels, `\nonumber` and `\\`), so that the
109//! closing part ends the line as written and the next line begins where the
110//! author's newline put it.
111//! - A run that begins a text part of the content is dropped when what was
112//! written just before it ends a line: the run that the previous line's
113//! content ended with, written after that line's `\\`, or a comment, which
114//! ends its own line. Two newlines therefore never follow each other.
115//! - When the content is written in several parts (text around a staged
116//! construct or a comment), only the last part can end the content, and
117//! anything written between two text parts other than a comment is not a
118//! line's end.
119//!
120//! When the content of a line ends with a comment, the line's closing part is
121//! written after the comment's newline, on the next line: a comment never hides
122//! the commands of its line.
123//!
124//! # Text commands
125//!
126//! [`TEXT_LATEX_RULE`] (`flm.math.text.lower.latex-recomposed`) writes a text
127//! command as the LaTeX macro of the same name, over its argument lowered through
128//! the ordinary rules: the emitter escapes the text, a user definition used in it
129//! is written as a call, and mathematics inside it is written by the rule of the
130//! feature that processes mathematics. `\text` is the only text command that the
131//! LaTeX kernel does not define; the rule requests `amsmath` where it writes one.
132//!
133//! # Peer declarations
134//!
135//! The feature owns neither the backend nor the construct elements nor the
136//! safe-labels table that the recomposition rules of its text commands and of
137//! `\eqref` ([`eqref::LATEX_RULE`](super::eqref::LATEX_RULE)) use. [`register`]
138//! declares them as peer declarations ([`PeerName`](crate::core::registry::PeerName)),
139//! so that a registry without the LaTeX features still builds; the rules are
140//! then set aside (excluded from rule selection). The safe-labels table is read
141//! optionally, so that a registry with the backend and without the references
142//! feature still renders.
143
144use std::sync::Arc;
145
146use techy::core::node::{BuildId, NodeRef};
147
148use crate::core::lowering::{
149 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
150};
151use crate::core::registry::{BuildError, FeatureBuilder};
152use crate::lang::Flm;
153use crate::model::element::{element_of, element_value};
154use crate::model::names::{ElementName, Name};
155use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
156use crate::stdlib::backends::latex::{
157 LatexArgShape, LatexMacroPayload, LatexRawPayload, packages, preamble,
158};
159use crate::stdlib::backends::lowering::{lower_arg_or_nothing, lower_run};
160use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
161use crate::stdlib::features::refs::{SAFE_LABELS, SafeLabels, stage_label, stage_label_group};
162
163use crate::stdlib::features::userdefs::kept::{MathPiece, write_math_run};
164
165use super::ensuremath::ENSUREMATH;
166use super::frame::{LineFrame, formula_display};
167use super::lines::{LINEBREAK_COMMAND, NONUMBER_COMMAND, TAG_COMMAND};
168use super::text::{MathTextCommand, TEXT};
169use super::MathEnvironment;
170
171/// The name of the recomposition rule of the text commands of math mode
172/// (`flm.math.text`), `flm.math.text.lower.latex-recomposed`, whose body is
173/// [`TextLatexRule`].
174pub const TEXT_LATEX_RULE: &str = "flm.math.text.lower.latex-recomposed";
175
176/// The LaTeX hook that a display-math environment is written through when
177/// [`emit_flm_math_environment_macro`](MathRecomposeOptions::emit_flm_math_environment_macro)
178/// is set, `flmMathEnvironment`.
179pub const FLM_MATH_ENVIRONMENT: &str = "flmMathEnvironment";
180
181/// The only display-math environment that the LaTeX kernel defines,
182/// `equation`; the other five need the LaTeX package `amsmath`.
183pub const KERNEL_ENVIRONMENT: &str = "equation";
184
185/// The only text command of math mode that the LaTeX kernel does not define,
186/// `text`; the `amsmath` package defines it, and the LaTeX kernel defines
187/// every other command of [`COMMANDS`](super::text::COMMANDS).
188pub const AMSMATH_COMMAND: &str = "text";
189
190/// The options of the `math` feature that say how the recomposed LaTeX writes a
191/// displayed formula: an option type ([`crate::model::options`]) whose
192/// values are set on a render request
193/// ([`Bind::Render`](crate::model::options::Bind::Render)). The rules of a
194/// feature that processes mathematics read them on the `latex-recomposed`
195/// backend, through the parts of this module (see the module documentation).
196///
197/// # Examples
198///
199/// ```
200/// use flm_core::stdlib::features::math::MathRecomposeOptions;
201///
202/// let options = MathRecomposeOptions::default();
203/// assert_eq!(options.surround_display_math, (String::new(), String::new()));
204/// assert!(!options.emit_flm_math_environment_macro);
205/// ```
206#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, serde::Deserialize)]
207#[derive(schemars::JsonSchema)]
208#[serde(default, deny_unknown_fields)]
209pub struct MathRecomposeOptions {
210 /// The LaTeX written, byte for byte, before and after every displayed
211 /// formula: every display-math environment and every displayed math group
212 /// (`\[…\]`). Both empty by default.
213 pub surround_display_math: (String, String),
214 /// Whether an environment is written as
215 /// `\flmMathEnvironment{<name>}{<arguments>}{<body>}` rather than as
216 /// `\begin{<name>}…\end{<name>}`. Off by default. The style file then
217 /// holds the definition of `\flmMathEnvironment`, which a user may
218 /// redefine.
219 pub emit_flm_math_environment_macro: bool,
220}
221
222/// The body of [`TEXT_LATEX_RULE`]: a text command of math mode written as a
223/// macro construct of the same name, over its argument lowered through the
224/// ordinary rules.
225///
226/// The argument is document text, so it is written as text is written
227/// anywhere else: the emitter escapes it, a user definition used in it is
228/// written as a call with its definition for the style file, and mathematics
229/// inside it is written by the rule of the feature that processes mathematics.
230/// Copying the command's source
231/// instead would leave out all three.
232///
233/// `\text` is the only command of the list that the LaTeX kernel does not
234/// define, so the rule requests the package `amsmath` where it writes one
235/// ([`AMSMATH_COMMAND`]).
236///
237/// When the argument is missing (a parse recovery left it absent and the parse
238/// reported it), the macro is written with an empty argument and nothing more
239/// is reported. The rule returns a [`LowerError`] when the node carries no
240/// [`MathTextCommand`] or when a node could not be lowered or staged.
241#[derive(Debug, Default, Clone, Copy)]
242pub struct TextLatexRule;
243
244impl Lower for TextLatexRule {
245 fn lower(
246 &self,
247 node: NodeRef<'_, Flm>,
248 cx: &mut LowerCx<'_>,
249 lw: &mut dyn Lowerer,
250 ) -> Result<Lowering, LowerError> {
251 let value = element_value::<MathTextCommand>(&node)
252 .ok_or_else(|| LowerError::structure("a math text command without its element's data"))?;
253 if value.command == AMSMATH_COMMAND {
254 lw.require(&Name::from(packages::AMSMATH));
255 }
256 let argument = lower_arg_or_nothing(cx, lw, &node, 0)?;
257 let call = lw.pres_slots_with(
258 cx,
259 &ElementName::from(MACRO),
260 LatexMacroPayload::new(value.command.as_str(), [LatexArgShape::Mandatory]),
261 vec![(String::from(ARG_SLOT), argument)],
262 )?;
263 Ok(Lowering::Emit(vec![call]))
264 }
265}
266
267/// The rule [`TEXT_LATEX_RULE`], ready to be registered: it targets
268/// `flm.math.text`, produces the macro construct, requests the package
269/// `amsmath` where it writes `\text`, and is the default on the
270/// `latex-recomposed` backend only.
271pub fn text_rule() -> LoweringRule {
272 LoweringRule::new(
273 TEXT_LATEX_RULE,
274 TEXT,
275 LoweringDecl::new().produces(MACRO),
276 Arc::new(TextLatexRule),
277 DefaultMark::OnBackends(vec![BACKEND.into()]),
278 )
279 .docs(
280 "a text command of math mode lowers to the LaTeX macro of the same name, over its \
281 argument lowered as document text",
282 )
283}
284
285
286// --- the LaTeX frame of a formula -------------------------------------------------------
287
288/// Stages a raw node holding `text`, written byte for byte.
289fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
290 lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
291}
292
293/// The name of the display-math environment `node`, from its element value.
294fn environment_name(node: &NodeRef<'_, Flm>) -> Result<String, LowerError> {
295 element_value::<MathEnvironment>(node)
296 .map(|value| value.name.to_string())
297 .ok_or_else(|| LowerError::structure("a math environment without its element's data"))
298}
299
300/// The opening part of a display-math environment in the recomposed LaTeX:
301/// the text before every displayed formula
302/// ([`surround_display_math`](MathRecomposeOptions::surround_display_math)),
303/// then `\begin{<name>}`, or `\flmMathEnvironment{<name>}{}{` when the options
304/// ask for the hook (see the module documentation, *The LaTeX frame of a
305/// formula*). It requests `amsmath` for every environment but
306/// [`KERNEL_ENVIRONMENT`], and requires the definition piece of the hook when
307/// it writes it.
308///
309/// A processing feature's rule of `flm.math.environment` on the
310/// `latex-recomposed` backend calls it first, then writes each line's content
311/// followed by [`line_closing`], then calls [`environment_closing`]. Under the
312/// hook, what it writes between the parts is inside a LaTeX argument, while
313/// the lowered tree holds it as siblings of raw nodes and not inside a macro's
314/// argument, so the emitter does not know it is there: such a rule must not
315/// stage block verbatim content there directly (verbatim content inside a text
316/// command's argument is written as such an argument requires).
317///
318/// # Errors
319///
320/// Returns [`LowerError`] when `node` carries no [`MathEnvironment`], when the
321/// calling rule does not declare that it reads [`MathRecomposeOptions`], or
322/// when a node could not be staged.
323pub fn environment_opening(
324 cx: &mut LowerCx<'_>,
325 lw: &mut dyn Lowerer,
326 node: &NodeRef<'_, Flm>,
327) -> Result<Vec<BuildId>, LowerError> {
328 let name = environment_name(node)?;
329 let options = lw.option::<MathRecomposeOptions>()?.clone();
330 if name != KERNEL_ENVIRONMENT {
331 lw.require(&Name::from(packages::AMSMATH));
332 }
333 let mut nodes = Vec::with_capacity(2);
334 let (before, _) = &options.surround_display_math;
335 if !before.is_empty() {
336 nodes.push(raw(cx, lw, before)?);
337 }
338 let opening = if options.emit_flm_math_environment_macro {
339 lw.require(&Name::from(preamble::MATH_ENVIRONMENT));
340 format!("\\{FLM_MATH_ENVIRONMENT}{{{name}}}{{}}{{")
341 } else {
342 format!("\\begin{{{name}}}")
343 };
344 nodes.push(raw(cx, lw, &opening)?);
345 Ok(nodes)
346}
347
348/// The closing part of an equation line in the recomposed LaTeX, what follows
349/// the line's content: `\tag*{…}` when the line has a tag, the line's labels in
350/// `\flmLabels`, `\nonumber`, and the line's `\\` when another line follows
351/// (see the module documentation, *The LaTeX frame of a formula*).
352///
353/// A processing feature's rule of `flm.math.environment` on the
354/// `latex-recomposed` backend calls it after each line's content, with the
355/// line's frame ([`line_frames`](super::frame::line_frames)); only the line
356/// ([`LineFrame::line`]) is read, since LaTeX numbers the lines itself.
357///
358/// # Errors
359///
360/// Returns [`LowerError`] when the calling rule does not declare that it reads
361/// the safe-labels table (optionally) and [`LatexRecomposedRenderOptions`], or
362/// when a node could not be lowered or staged.
363pub fn line_closing(
364 cx: &mut LowerCx<'_>,
365 lw: &mut dyn Lowerer,
366 frame: &LineFrame<'_>,
367) -> Result<Vec<BuildId>, LowerError> {
368 let line = &frame.line;
369 let mut pieces = Vec::new();
370 if let Some(tag) = &line.tag {
371 // `\tag*{…}` always, with FLM's parentheses written here where the
372 // author's `\tag` asks for them, so that LaTeX adds none of its own.
373 // The tag's content is inline text of the document and goes through
374 // the ordinary lowering: the emitter escapes it, and a text command
375 // inside it comes out as its own LaTeX.
376 let mut argument = Vec::new();
377 if tag.parenthesized() {
378 argument.push(lw.text(cx, "(")?);
379 }
380 argument.extend(lower_run(cx, lw, &tag.content)?);
381 if tag.parenthesized() {
382 argument.push(lw.text(cx, ")")?);
383 }
384 pieces.push(lw.pres_slots_with(
385 cx,
386 &ElementName::from(MACRO),
387 LatexMacroPayload::new(TAG_COMMAND, [LatexArgShape::Star, LatexArgShape::Mandatory]),
388 vec![(String::from(ARG_SLOT), argument)],
389 )?);
390 }
391 // The line's labels, at the line's end whatever place in the line they
392 // were written at, wrapped as one group in the labels hook: on a line of
393 // a display-math environment that is what makes every label past the
394 // first resolve to the line's number, which `amsmath` alone does not.
395 // The labels are left out only where the safe-labels table is absent and
396 // the render options ask for that.
397 let written = lw.get(SAFE_LABELS)?.is_some()
398 || !lw.option::<LatexRecomposedRenderOptions>()?.drop_math_labels_without_refs;
399 if written {
400 let mut group = Vec::new();
401 for label in &line.labels {
402 group.push(stage_label(cx, lw, &label.text, label.label.as_ref())?);
403 }
404 pieces.extend(stage_label_group(cx, lw, group, false)?);
405 }
406 if line.nonumber {
407 pieces.push(lw.pres_slots_with(
408 cx,
409 &ElementName::from(MACRO),
410 LatexMacroPayload::new(NONUMBER_COMMAND, []),
411 Vec::new(),
412 )?);
413 }
414 if let Some(brk) = &line.linebreak {
415 let mut text = format!("\\{LINEBREAK_COMMAND}");
416 if let Some(spacing) = &brk.spacing {
417 text.push('[');
418 text.push_str(spacing);
419 text.push(']');
420 }
421 pieces.push(raw(cx, lw, &text)?);
422 }
423 Ok(pieces)
424}
425
426/// The closing part of a display-math environment in the recomposed LaTeX:
427/// `\end{<name>}`, or `}` when the options ask for the hook
428/// `\flmMathEnvironment`, then the text after every displayed formula
429/// ([`surround_display_math`](MathRecomposeOptions::surround_display_math)).
430///
431/// A processing feature's rule of `flm.math.environment` on the
432/// `latex-recomposed` backend calls it last, after the last line's
433/// [`line_closing`] and whatever the rule writes after it.
434///
435/// # Errors
436///
437/// Returns [`LowerError`] when `node` carries no [`MathEnvironment`], when the
438/// calling rule does not declare that it reads [`MathRecomposeOptions`], or
439/// when a node could not be staged.
440pub fn environment_closing(
441 cx: &mut LowerCx<'_>,
442 lw: &mut dyn Lowerer,
443 node: &NodeRef<'_, Flm>,
444) -> Result<Vec<BuildId>, LowerError> {
445 let name = environment_name(node)?;
446 let options = lw.option::<MathRecomposeOptions>()?.clone();
447 let closing = if options.emit_flm_math_environment_macro {
448 String::from("}")
449 } else {
450 format!("\\end{{{name}}}")
451 };
452 let mut nodes = vec![raw(cx, lw, &closing)?];
453 let (_, after) = &options.surround_display_math;
454 if !after.is_empty() {
455 nodes.push(raw(cx, lw, after)?);
456 }
457 Ok(nodes)
458}
459
460// --- the newline rule ------------------------------------------------------------------------
461
462/// One part of a line's content after the newline rule (see the module
463/// documentation, *The newline rule*): what [`normalize_line_newlines`]
464/// returns.
465#[derive(Debug, Clone, PartialEq, Eq, Default)]
466pub struct NormalizedLine {
467 /// The text to write: every run of whitespace that holds a newline
468 /// reduced to one newline and the indentation after it, the run at the
469 /// beginning dropped where the rule drops it, and the run at the end
470 /// taken off where the rule takes it off.
471 pub text: String,
472 /// The run that ended the content, reduced in the same way, when the rule
473 /// took it off, to be written after the line's closing part (its tag,
474 /// labels, `\nonumber` and `\\`); empty otherwise.
475 pub trailing: String,
476}
477
478/// Whether `ch` is a space, a tab or a newline: the characters of a run of
479/// whitespace for the newline rule.
480fn is_run_char(ch: char) -> bool {
481 matches!(ch, ' ' | '\t' | '\n')
482}
483
484/// Applies the newline rule to one text part of a line's content (see the
485/// module documentation, *The newline rule*).
486///
487/// - Every run of spaces, tabs and newlines that holds a newline becomes one
488/// newline followed by the spaces and tabs after the run's last newline.
489/// - A run that begins `content` is dropped when `after_line_end` is `true`:
490/// what was written just before this part ends a line (the run the
491/// previous line's content ended with, written after that line's `\\`, or
492/// a comment).
493/// - A run that ends `content` is taken off and returned as
494/// [`trailing`](NormalizedLine::trailing), to be written after the line's
495/// closing part, unless `inner` is `true` (this part is not the last of the
496/// line's content, so it does not end the content).
497/// - A run that both begins and ends `content` (a part made only of
498/// whitespace) is treated as a run that begins it.
499/// - A run that holds no newline is kept as it is.
500///
501/// # Examples
502///
503/// ```
504/// use flm_core::stdlib::features::math::latex::{NormalizedLine, normalize_line_newlines};
505///
506/// let line = normalize_line_newlines("\n a &= 1 \n \n ", false, false);
507/// assert_eq!(line, NormalizedLine { text: String::from("\n a &= 1"), trailing: String::from("\n ") });
508/// // After a line end, the run that begins the part is dropped.
509/// assert_eq!(normalize_line_newlines("\n b &= 2", true, false).text, "b &= 2");
510/// // A part that is not the last of the line's content keeps its run in place.
511/// let line = normalize_line_newlines("c\n ", false, true);
512/// assert_eq!(line, NormalizedLine { text: String::from("c\n "), trailing: String::new() });
513/// ```
514pub fn normalize_line_newlines(content: &str, after_line_end: bool, inner: bool) -> NormalizedLine {
515 let mut line = NormalizedLine::default();
516 let mut rest = content;
517 let mut at = 0;
518 while !rest.is_empty() {
519 let run_end = rest.find(|ch: char| !is_run_char(ch)).unwrap_or(rest.len());
520 let run = &rest[..run_end];
521 match run.rfind('\n') {
522 None => line.text.push_str(run),
523 Some(last) => {
524 let normalized = &run[last..];
525 if at == 0 {
526 if !after_line_end {
527 line.text.push_str(normalized);
528 }
529 } else if run_end == rest.len() && !inner {
530 line.trailing.push_str(normalized);
531 } else {
532 line.text.push_str(normalized);
533 }
534 }
535 }
536 rest = &rest[run_end..];
537 at += run_end;
538 let text_end = rest.find(is_run_char).unwrap_or(rest.len());
539 line.text.push_str(&rest[..text_end]);
540 rest = &rest[text_end..];
541 at += text_end;
542 }
543 line
544}
545
546/// Whether the output ends a line once `text` is written, written as it is
547/// after output that ended a line when `after_line_end`: only spaces and tabs
548/// follow the last newline of `text`, or `text` holds no newline and only
549/// spaces and tabs while the output before it ended a line.
550fn ends_line(text: &str, after_line_end: bool) -> bool {
551 let only_blanks = |text: &str| text.chars().all(|ch| matches!(ch, ' ' | '\t'));
552 match text.rsplit_once('\n') {
553 Some((_, last)) => only_blanks(last),
554 None => after_line_end && only_blanks(text),
555 }
556}
557
558/// The newline rule applied across the lines of one environment, piece by
559/// piece, in the order a writer writes them: it keeps whether the output
560/// written so far ends a line (see the module documentation, *The newline
561/// rule*). The LaTeX writers of `flm-core` use it: [`stage_lines`], and the
562/// rule of the `math-passthrough` feature that writes the lines as source
563/// ([`EnvironmentRule`](crate::math_passthrough::EnvironmentRule)).
564#[derive(Debug, Clone, Copy, Default)]
565pub(crate) struct NewlineRule {
566 /// Whether the output written so far ends a line.
567 after_line_end: bool,
568}
569
570impl NewlineRule {
571 /// A text part of a line's content, `last` when no part of the content
572 /// follows it: the text to write and, for the last part, the run to write
573 /// after the line's closing part ([`normalize_line_newlines`]).
574 pub(crate) fn text(&mut self, text: &str, last: bool) -> NormalizedLine {
575 let line = normalize_line_newlines(text, self.after_line_end, !last);
576 self.after_line_end = ends_line(&line.text, self.after_line_end);
577 line
578 }
579
580 /// A piece of a line's content written as it is, as the text `written`
581 /// (a comment written as its source).
582 pub(crate) fn written(&mut self, written: &str) {
583 self.after_line_end = ends_line(written, self.after_line_end);
584 }
585
586 /// A piece of a line's content that ends a line (`true`: a comment that
587 /// the emitter writes) or does not (`false`: a construct).
588 pub(crate) fn piece(&mut self, ends_line: bool) {
589 self.after_line_end = ends_line;
590 }
591
592 /// The end of a line: `closed` when the line's closing part wrote
593 /// something (a tag, a label, `\nonumber` or `\\`), `trailing` the run
594 /// the rule took off the content's end, written after it.
595 pub(crate) fn line_end(&mut self, closed: bool, trailing: &str) {
596 if closed {
597 self.after_line_end = false;
598 }
599 if !trailing.is_empty() {
600 self.after_line_end = true;
601 }
602 }
603}
604
605/// Stages the equation lines of a display-math environment in the recomposed
606/// LaTeX, as they were written (see the module documentation, *The LaTeX frame
607/// of a formula* and *The newline rule*): for each line of `frames`, in order,
608/// the line's content written by the mathematics writer of the `userdefs`
609/// feature ([`write_math_run`]), its text under the newline rule; the line's
610/// closing part ([`line_closing`]); and the run of whitespace the newline
611/// rule took off the content's end. Returns the nodes to emit.
612///
613/// A processing feature's rule of `flm.math.environment` on the
614/// `latex-recomposed` backend calls it between [`environment_opening`] and
615/// [`environment_closing`], with the frames of the environment's lines
616/// ([`line_frames`](super::frame::line_frames), read without the two tables,
617/// since LaTeX numbers the lines itself). A comment on a line is staged as its
618/// comment node, which the emitter writes ending its line; under the render
619/// option
620/// [`drop_comments`](LatexRecomposedRenderOptions::drop_comments) it writes
621/// nothing, and the rule then counts it as nothing written.
622///
623/// # Errors
624///
625/// Returns [`LowerError`] when the calling rule does not declare that it reads
626/// the safe-labels table (optionally) and [`LatexRecomposedRenderOptions`], or
627/// that it produces the raw, macro and definition constructs, or when a node
628/// could not be lowered, written or staged.
629pub fn stage_lines(
630 cx: &mut LowerCx<'_>,
631 lw: &mut dyn Lowerer,
632 frames: &[LineFrame<'_>],
633) -> Result<Vec<BuildId>, LowerError> {
634 let drop_comments = lw.option::<LatexRecomposedRenderOptions>()?.drop_comments;
635 let mut rule = NewlineRule::default();
636 let mut nodes = Vec::new();
637 for frame in frames {
638 let pieces = write_math_run(cx, lw, &frame.line.content)?;
639 let count = pieces.len();
640 let mut trailing = String::new();
641 for (index, piece) in pieces.into_iter().enumerate() {
642 match piece {
643 MathPiece::Text(text) => {
644 let line = rule.text(&text, index + 1 == count);
645 if !line.text.is_empty() {
646 nodes.push(raw(cx, lw, &line.text)?);
647 }
648 trailing = line.trailing;
649 }
650 MathPiece::Comment(id) => {
651 nodes.push(id);
652 if !drop_comments {
653 rule.piece(true);
654 }
655 }
656 MathPiece::Node(id) => {
657 nodes.push(id);
658 rule.piece(false);
659 }
660 }
661 }
662 let closing = line_closing(cx, lw, frame)?;
663 rule.line_end(!closing.is_empty(), &trailing);
664 nodes.extend(closing);
665 if !trailing.is_empty() {
666 nodes.push(raw(cx, lw, &trailing)?);
667 }
668 }
669 Ok(nodes)
670}
671
672// --- math groups ------------------------------------------------------------------------------
673
674/// Whether the math group `node` is the formula of `\ensuremath{…}` written
675/// in text: the group is the command's argument, so its parent is an
676/// [`ENSUREMATH`] node.
677fn ensuremath_formula(node: &NodeRef<'_, Flm>) -> bool {
678 node.parent().is_some_and(|parent| element_of(&parent).name == ENSUREMATH)
679}
680
681/// The opening part of a math group in the recomposed LaTeX: for a displayed
682/// group, the text before every displayed formula
683/// ([`surround_display_math`](MathRecomposeOptions::surround_display_math))
684/// then `\[`; for an inline one, `\(` ([`formula_display`]), whichever
685/// delimiters the author used, except for the formula of `\ensuremath{…}`
686/// written in text (the math group its braces delimit; see
687/// [`ensuremath`](super::ensuremath)), whose opening is `\ensuremath{`. The
688/// command is kept as written because such a formula may end up inside another
689/// formula in LaTeX (written in a kept user definition's template, or in an
690/// argument the template places in mathematics), where LaTeX refuses `\(`.
691///
692/// A processing feature's rule of `flm.math` on the `latex-recomposed`
693/// backend calls it before the group's content, and [`group_closing`] after.
694///
695/// # Errors
696///
697/// Returns [`LowerError`] when the calling rule does not declare that it reads
698/// [`MathRecomposeOptions`], or when the raw node could not be staged, for
699/// instance when the calling rule does not declare that it produces the raw
700/// construct.
701pub fn group_opening(
702 cx: &mut LowerCx<'_>,
703 lw: &mut dyn Lowerer,
704 node: &NodeRef<'_, Flm>,
705) -> Result<Vec<BuildId>, LowerError> {
706 let options = lw.option::<MathRecomposeOptions>()?.clone();
707 if !formula_display(node) {
708 let opening = if ensuremath_formula(node) { "\\ensuremath{" } else { "\\(" };
709 return Ok(vec![raw(cx, lw, opening)?]);
710 }
711 let mut nodes = Vec::with_capacity(2);
712 let (before, _) = &options.surround_display_math;
713 if !before.is_empty() {
714 nodes.push(raw(cx, lw, before)?);
715 }
716 nodes.push(raw(cx, lw, "\\[")?);
717 Ok(nodes)
718}
719
720/// The closing part of a math group in the recomposed LaTeX: for a displayed
721/// group, `\]` then the text after every displayed formula
722/// ([`surround_display_math`](MathRecomposeOptions::surround_display_math));
723/// for an inline one, `\)`, or `}` for the formula of `\ensuremath{…}`
724/// written in text; see [`group_opening`].
725///
726/// # Errors
727///
728/// Returns [`LowerError`] when the calling rule does not declare that it reads
729/// [`MathRecomposeOptions`], or when the raw node could not be staged.
730pub fn group_closing(
731 cx: &mut LowerCx<'_>,
732 lw: &mut dyn Lowerer,
733 node: &NodeRef<'_, Flm>,
734) -> Result<Vec<BuildId>, LowerError> {
735 let options = lw.option::<MathRecomposeOptions>()?.clone();
736 if !formula_display(node) {
737 let closing = if ensuremath_formula(node) { "}" } else { "\\)" };
738 return Ok(vec![raw(cx, lw, closing)?]);
739 }
740 let mut nodes = vec![raw(cx, lw, "\\]")?];
741 let (_, after) = &options.surround_display_math;
742 if !after.is_empty() {
743 nodes.push(raw(cx, lw, after)?);
744 }
745 Ok(nodes)
746}
747
748/// Registers what the `math` feature contributes to the `latex-recomposed`
749/// backend: a peer declaration ([`PeerName`](crate::core::registry::PeerName))
750/// of the backend, of the two construct elements the rules of the text
751/// commands and of `\eqref` stage (each with its payload type) and of the
752/// safe-labels table (with its value type), then [`text_rule`]. The options
753/// [`MathRecomposeOptions`] are declared with the feature's settings.
754///
755/// In a registry without the LaTeX features the peer declarations resolve to
756/// nothing and the rules are set aside (excluded from rule selection); the
757/// registry still builds.
758///
759/// # Errors
760///
761/// Returns the [`BuildError`] the feature builder raises, for instance for a
762/// rule already registered under the same name.
763pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
764 b.peer_backend(
765 BACKEND,
766 "the latex-recomposed backend, on which the recomposition rules of the text commands \
767 and of `\\eqref` are the default",
768 )?;
769 b.peer_element::<LatexMacroPayload>(
770 MACRO,
771 "the LaTeX family's macro construct, which the recomposition rules of the text \
772 commands and of `\\eqref` stage",
773 )?;
774 b.peer_element::<LatexRawPayload>(
775 RAW,
776 "the LaTeX family's raw construct, which the recomposition rule of `\\eqref` stages",
777 )?;
778 b.peer_table::<SafeLabels>(
779 SAFE_LABELS.name(),
780 "the references feature's safe-labels table, which the recomposition rule of \
781 `\\eqref` reads for the safe label of the label it refers to",
782 )?;
783 b.lowering_rule(text_rule())
784}
785
786#[cfg(test)]
787mod tests {
788 use super::*;
789
790 fn normalized(content: &str, after_line_end: bool, inner: bool) -> (String, String) {
791 let line = normalize_line_newlines(content, after_line_end, inner);
792 (line.text, line.trailing)
793 }
794
795 #[test]
796 fn every_newline_run_becomes_one_newline_and_the_last_indentation() {
797 assert_eq!(normalized("\n \n x &= 0.\n", false, false), ("\n x &= 0.".into(), "\n".into()));
798 assert_eq!(normalized("a\n\n\n\tb c\n", false, false), ("a\n\tb c".into(), "\n".into()));
799 assert_eq!(normalized("x = 1 \n", false, false), ("x = 1".into(), "\n".into()));
800 assert_eq!(normalized("x = 1 ", false, false), ("x = 1 ".into(), String::new()));
801 assert_eq!(normalized("a \t b", false, false), ("a \t b".into(), String::new()));
802 assert_eq!(normalized("", false, false), (String::new(), String::new()));
803 assert_eq!(normalized(" ", false, false), (" ".into(), String::new()));
804 }
805
806 #[test]
807 fn the_run_that_begins_a_part_is_dropped_only_after_a_line_end() {
808 assert_eq!(normalized("\n b &= 2 \n", false, false), ("\n b &= 2".into(), "\n".into()));
809 assert_eq!(normalized("\n b &= 2 \n", true, false), ("b &= 2".into(), "\n".into()));
810 // A content of whitespace only follows the rule for the run that begins it.
811 assert_eq!(normalized("\n ", false, false), ("\n ".into(), String::new()));
812 assert_eq!(normalized("\n ", true, false), (String::new(), String::new()));
813 }
814
815 #[test]
816 fn a_part_that_is_not_the_last_keeps_its_run_in_place() {
817 assert_eq!(normalized("a %% c\n ", false, true), ("a %% c\n ".into(), String::new()));
818 assert_eq!(normalized("a %% c\n \n ", false, true), ("a %% c\n ".into(), String::new()));
819 }
820
821 #[test]
822 fn whether_written_text_ends_a_line() {
823 assert!(ends_line("a\n ", false));
824 assert!(ends_line("a\n", false));
825 assert!(!ends_line("a\n b", false));
826 assert!(!ends_line("a", true));
827 assert!(ends_line(" ", true));
828 assert!(!ends_line(" ", false));
829 assert!(!ends_line("", false));
830 assert!(ends_line("", true));
831 }
832
833 /// The parts of one line written under the rule, as `(text, trailing)`:
834 /// each part a text or, as `None`, a comment that ends its line.
835 fn written_line(rule: &mut NewlineRule, parts: &[Option<&str>], closed: bool) -> (String, String) {
836 let mut text = String::new();
837 let mut trailing = String::new();
838 for (index, part) in parts.iter().enumerate() {
839 match part {
840 Some(part) => {
841 let line = rule.text(part, index + 1 == parts.len());
842 text.push_str(&line.text);
843 trailing = line.trailing;
844 }
845 None => {
846 text.push_str("%c\n ");
847 rule.piece(true);
848 }
849 }
850 }
851 rule.line_end(closed, &trailing);
852 (text, trailing)
853 }
854
855 #[test]
856 fn the_rule_follows_the_line_ends_across_lines_and_comments() {
857 // `a &= b` / `\label{x}` / `\\` / `c &= d` / `\\` (final): the run
858 // after the label goes after the first line's `\\`, so the second
859 // line's first run goes; the run before the final `\\` and the one
860 // after it go after the last line.
861 let mut rule = NewlineRule::default();
862 assert_eq!(written_line(&mut rule, &[Some("\n a &= b\n \n ")], true), ("\n a &= b".into(), "\n ".into()));
863 assert_eq!(written_line(&mut rule, &[Some("\n c &= d\n \n")], false), ("c &= d".into(), "\n".into()));
864 // `a &= b \\ %c` / `\label{x}` / `c &= d`: the comment ends its line,
865 // so the run after the label, which begins the next part, goes.
866 let mut rule = NewlineRule::default();
867 assert_eq!(written_line(&mut rule, &[Some("\n a &= b ")], true), ("\n a &= b ".into(), String::new()));
868 assert_eq!(
869 written_line(&mut rule, &[Some(" "), None, Some("\n c &= d\n")], false),
870 (" %c\n c &= d".into(), "\n".into())
871 );
872 // A construct between two parts is not a line's end.
873 let mut rule = NewlineRule::default();
874 rule.piece(true);
875 rule.piece(false);
876 assert_eq!(rule.text("\n x", false).text, "\n x");
877 // A comment written as source ends a line only when its text does.
878 let mut rule = NewlineRule::default();
879 rule.written("%c");
880 assert_eq!(rule.text("\n\n x", true).text, "\n x");
881 rule.written("%c\n ");
882 assert_eq!(rule.text("\n y", true).text, "y");
883 }
884
885 #[test]
886 fn the_text_rule_is_the_default_on_the_recomposed_backend_only() {
887 let rule = text_rule();
888 assert_eq!(rule.name, TEXT_LATEX_RULE);
889 assert_eq!(rule.element, TEXT);
890 assert!(rule.default.is_specific_to(&BACKEND.into()));
891 assert_eq!(rule.decl.produces, [ElementName::from(MACRO)]);
892 }
893}