flm_core/stdlib/features/headings/latex.rs
1//! The headings on the `latex-recomposed` backend: each heading written back as the
2//! LaTeX sectioning command its heading kind maps to, starred when the heading is not
3//! numbered, inside the LaTeX hook `\flmHeading`, with the heading's labels after it.
4//!
5//! A *LaTeX hook* is a macro that the recomposed LaTeX writes and the style file (the
6//! `.sty` file written beside the recomposed LaTeX;
7//! [`style`](crate::stdlib::backends::latex::style)) defines with a plain default,
8//! which a user redefines in the document's preamble to change what the recomposed
9//! LaTeX does at that point
10//! ([`latex::preamble`](crate::stdlib::backends::latex::preamble); see [the LaTeX
11//! hooks](crate::guide::rendering#the-latex-hooks)).
12//!
13//! # What the rule writes
14//!
15//! [`LATEX_RULE`] (`flm.heading.lower.latex-recomposed`), implemented by
16//! [`HeadingLatexRule`], is the default lowering rule of `flm.heading` on the
17//! `latex-recomposed` backend only. For a heading with two labels it writes:
18//!
19//! ```text
20//! \flmHeading[toc=true]
21//! \section*{Title}{\flmLabels{\label{ref1}\label{ref2}}}
22//! ```
23//!
24//! that is, the hook with the key `toc`, a newline, the sectioning command with the
25//! title as its mandatory argument, and one braced group that holds the heading's
26//! labels inside the LaTeX hook `\flmLabels`. A heading written with an alternative
27//! title (`\section[alt={Short title}]{…}`) adds the hook's key `alt`:
28//! `\flmHeading[toc=true,alt={Short title}]`. Where the alternative title holds a
29//! command, the whole optional argument is braced, as every optional argument holding
30//! a command is written, so that a `]` inside it cannot end it:
31//! `\flmHeading[{toc=true,alt={Short \emph{title}}}]`; LaTeX removes those braces
32//! when it reads the argument.
33//!
34//! The sectioning command is the one the render option
35//! [`HeadingsLatexOptions::latex_commands`] maps the heading kind's name to, or the
36//! kind's name itself where the option gives no command for it: by default a
37//! `section` is written `\section`, and under a mapping of `section` to `chapter` it
38//! is written `\chapter`. It does not depend on the command the heading was written
39//! with, so a heading written with a second command of the kind `section` is written
40//! as every `section` is.
41//!
42//! The star is written when the heading is not numbered (written with a star or with
43//! `numbered=false`, see [`heading_options`](super::heading_options)), because the
44//! star is how LaTeX writes an unnumbered heading. LaTeX numbers the other headings
45//! itself, so the rule writes no number. Whether the heading is listed in a table of
46//! contents ([`Sectioning::in_toc`](crate::model::aspects::Sectioning::in_toc)) is
47//! written as the hook's key, `toc=true` or `toc=false`, on every heading. The hook's
48//! default definition adds a starred heading written with `toc=true` to LaTeX's table
49//! of contents, which LaTeX does not do for a starred command, and emits a warning
50//! that `toc=false` on an unstarred heading is not honored
51//! ([`heading_piece`](crate::stdlib::backends::latex::preamble::heading_piece)). With
52//! the render option `heading_hook` off, nothing carries the key and nothing is
53//! written for it.
54//!
55//! An alternative title written with the key `alt` ([`heading_alt`])
56//! is written as the hook's key `alt`, after `toc`, its value the alternative title's
57//! pieces lowered as ordinary content inside braces. The hook hands it to the
58//! sectioning command as its own optional argument on an unstarred heading, and adds it
59//! as the starred heading's table-of-contents line where that heading is listed; LaTeX
60//! builds its table of contents and its PDF bookmarks from it. With the render option
61//! `heading_hook` off, nothing carries the key and nothing is written for it, as for
62//! `toc`.
63//!
64//! The heading's bracket of options is never written back. The rule reports what that
65//! bracket holds that it cannot read, as the default rule does (see the [feature's
66//! documentation](super#the-options-of-a-heading)).
67//!
68//! The labels are the heading's own data: the rule reads its `\label` fields
69//! ([`label_uses`](crate::stdlib::features::refs::label_uses)) and writes each as
70//! `\label{<safe label>}` with [`stage_label`](crate::stdlib::features::refs::stage_label),
71//! where a safe label is the key the recomposed LaTeX writes for an FLM label
72//! ([`SafeLabels`]); [`stage_label_group`] wraps them in the LaTeX hook `\flmLabels`. A
73//! `\label` field is never lowered on its own: a field that reaches a backend is an
74//! error.
75//!
76//! The newline between the hook and the sectioning command is there for a person
77//! reading the recomposed LaTeX: the sectioning command then starts a line of its own.
78//! LaTeX reads the same tokens either way (a command name followed by a newline is the
79//! same token sequence as the command name alone), so the sectioning command is still
80//! the hook's first mandatory argument. The hook's optional argument, `[toc=…]`, is on
81//! the hook's line, before the newline. Every heading gets the newline, including a
82//! run-in heading in the middle of a paragraph (`text \flmHeading[toc=true]`, a
83//! newline, `\paragraph{P}{…} and more`), where LaTeX reads the newline as ordinary
84//! whitespace.
85//!
86//! # What the hook is for
87//!
88//! A LaTeX label refers to the last thing that was numbered. A heading the document
89//! class did not number (`\section*`, or a level below the class's `secnumdepth`)
90//! numbers nothing, so a reference to a label after it prints the number of the last
91//! thing that was numbered before it, which is wrong and not reported. `\flmHeading`
92//! corrects this without modifying any LaTeX command: it runs the sectioning command as
93//! written, asks the LaTeX kernel whether a counter was advanced, and where none was,
94//! makes the labels refer to the heading with its **title** as what a reference prints
95//! ([`heading_piece`](crate::stdlib::backends::latex::preamble::heading_piece) says
96//! how). A `\ref` to a starred heading therefore prints "Introduction".
97//!
98//! With the hook, the group that holds the labels is written for **every** heading,
99//! as `{\flmLabels{}}` when the heading has no label, so that a user who redefines
100//! `\flmHeading` can rely on its last argument, the labels group, always being present.
101//!
102//! # The hook's key-value argument
103//!
104//! `\flmHeading` takes an optional key-value argument with two keys
105//! ([`heading_piece`](crate::stdlib::backends::latex::preamble::heading_piece) says
106//! what each does):
107//!
108//! - `toc=true|false`, whether the heading is listed in a table of contents. This rule
109//! writes it on every heading, from the heading's
110//! [`Sectioning::in_toc`](crate::model::aspects::Sectioning::in_toc).
111//! - `alt={Short title}`, an alternative title passed to the sectioning command as its
112//! own optional argument, for the table of contents and the PDF bookmark. This rule
113//! writes it where the heading's options give an alternative title with the key
114//! `alt` ([`heading_alt`]), and nowhere else.
115//!
116//! # The two render options of the recomposed LaTeX
117//!
118//! With [`heading_hook`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::heading_hook)
119//! off, the hook is left out: the recomposed LaTeX is `\section*{Title}` followed by
120//! the labels, and the labels group is written only where the heading has a label.
121//! The hook's test then does not run and nothing replaces it: a reference to an
122//! unnumbered heading prints what LaTeX recorded last, and giving it a display text
123//! is the user's responsibility. Nothing carries the keys `toc` and `alt` either, so
124//! nothing is written for them.
125//!
126//! With [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)
127//! off, `\flmLabels` is left out of the group, which then holds plain `\label`
128//! commands; with the heading hook still on, `\flmHeading` receives them directly and
129//! works unchanged.
130//!
131//! A title that a parse left absent after reporting it lowers to an empty argument.
132//! Whether a kind is set as a run-in heading does not change the recomposed LaTeX:
133//! LaTeX itself sets `\paragraph` and `\subparagraph` as run-in headings.
134//!
135//! # Registration without the LaTeX features
136//!
137//! The feature registers the rule with a peer declaration
138//! ([`PeerName`](crate::core::registry::PeerName)) of each name the rule uses that the
139//! LaTeX features own: the backend `latex-recomposed`, the
140//! macro construct `flm.pres.latex.macro` and the raw construct `flm.pres.latex.raw`
141//! (a raw node holds LaTeX text written as it is). A registry without the LaTeX
142//! features therefore still builds, with the rule set aside (excluded from rule
143//! selection; see [`PeerName`](crate::core::registry::PeerName)). See [`register`].
144
145use std::collections::BTreeMap;
146use std::sync::Arc;
147
148use techy::core::node::NodeRef;
149
150use crate::core::lowering::{
151 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
152};
153use crate::core::registry::{BuildError, FeatureBuilder};
154use crate::lang::Flm;
155use crate::model::element::element_value;
156use crate::model::names::ElementName;
157use crate::model::names::Name;
158use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
159use crate::stdlib::backends::latex::preamble;
160use crate::stdlib::backends::latex::{LatexArgShape, LatexMacroPayload, LatexRawPayload};
161use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
162use crate::stdlib::backends::lowering::{lower_arg_named_or_nothing, lower_written_pieces};
163use crate::stdlib::features::refs::{self, SAFE_LABELS, SafeLabels, stage_label_group};
164
165use super::title::NUMBER_ELEMENT;
166use super::{HEADING, HeadingElement, TITLE_ARG, heading_alt, report_option_problems};
167
168/// The name of the recomposition rule, `flm.heading.lower.latex-recomposed`.
169pub const LATEX_RULE: &str = "flm.heading.lower.latex-recomposed";
170
171/// The name of the lowering rule of a heading's number ([`NUMBER_ELEMENT`]) on
172/// the `latex-recomposed` backend, `flm.heading.number.lower.latex-recomposed`
173/// ([`number_latex_rule`]).
174pub const NUMBER_LATEX_RULE: &str = "flm.heading.number.lower.latex-recomposed";
175
176/// The render options of the headings on the recomposed LaTeX: which LaTeX
177/// sectioning command each heading kind is written as.
178///
179/// The option type is declared with
180/// [`Bind::Render`](crate::model::options::Bind::Render), so its value is set on
181/// the render request and is part of the plan key
182/// ([`PlanKey`](crate::core::plan::PlanKey)), the digest under which a built plan can
183/// be cached. The feature declares it
184/// whether or not the registry holds the `latex-recomposed` backend; only
185/// [`LATEX_RULE`] reads it. In settings data, its key is `latex_commands`.
186///
187/// # Examples
188///
189/// ```
190/// use flm_core::model::names::Name;
191/// use flm_core::stdlib::features::headings::latex::HeadingsLatexOptions;
192///
193/// // A `section` is written `\chapter`, every other kind under its own name.
194/// let options = HeadingsLatexOptions::new().command("section", "chapter");
195/// assert_eq!(options.command_for(&Name::from("section")), "chapter");
196/// assert_eq!(options.command_for(&Name::from("subsection")), "subsection");
197/// ```
198#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Deserialize)]
199#[derive(schemars::JsonSchema)]
200#[serde(default, deny_unknown_fields)]
201pub struct HeadingsLatexOptions {
202 /// The LaTeX sectioning command, without the backslash, that each heading
203 /// kind is written as, keyed by the kind's name. A kind the map does not list
204 /// is written as the command of its own name. Empty by default.
205 pub latex_commands: BTreeMap<Name, String>,
206}
207
208impl HeadingsLatexOptions {
209 /// Returns the default options: every kind written as the command of its
210 /// own name.
211 pub fn new() -> HeadingsLatexOptions {
212 HeadingsLatexOptions::default()
213 }
214
215 /// Builder: the kind `heading` is written as the LaTeX command `command`.
216 pub fn command(
217 mut self,
218 heading: impl Into<Name>,
219 command: impl Into<String>,
220 ) -> HeadingsLatexOptions {
221 self.latex_commands.insert(heading.into(), command.into());
222 self
223 }
224
225 /// Returns the LaTeX command, without the backslash, that the kind `heading`
226 /// is written as: its entry in [`latex_commands`](Self::latex_commands), else
227 /// its own name.
228 pub fn command_for(&self, heading: &Name) -> String {
229 self.latex_commands.get(heading).cloned().unwrap_or_else(|| heading.to_string())
230 }
231}
232
233/// The implementation of the lowering rule [`LATEX_RULE`]: it stages the hook
234/// `\flmHeading` with its key `toc`, and its key `alt` where the heading has an
235/// alternative title, a newline, the sectioning command the
236/// heading's kind maps to ([`HeadingsLatexOptions`]) as a LaTeX macro construct,
237/// starred when the heading is not numbered, and a group holding the labels the
238/// heading read from its `\label` fields, each written as its safe label. See the
239/// [module documentation](self).
240#[derive(Debug, Default, Clone, Copy)]
241pub struct HeadingLatexRule;
242
243impl Lower for HeadingLatexRule {
244 fn lower(
245 &self,
246 node: NodeRef<'_, Flm>,
247 cx: &mut LowerCx<'_>,
248 lw: &mut dyn Lowerer,
249 ) -> Result<Lowering, LowerError> {
250 let value = element_value::<HeadingElement>(&node)
251 .ok_or_else(|| LowerError::structure("a heading without its element's data"))?;
252 report_option_problems(&node, value, lw)?;
253 let hook = lw.option::<LatexRecomposedRenderOptions>()?.heading_hook;
254 let command = lw.option::<HeadingsLatexOptions>()?.command_for(&value.decl.name);
255 let occurrence = value.occurrence(&node);
256 let mut args = Vec::new();
257 if !occurrence.numbered {
258 args.push(LatexArgShape::Star);
259 }
260 args.push(LatexArgShape::Mandatory);
261 let title = lower_arg_named_or_nothing(cx, lw, &node, TITLE_ARG)?;
262 let payload = LatexMacroPayload::new(command, args);
263 let heading = lw.pres_slots_with(
264 cx,
265 &ElementName::from(MACRO),
266 payload,
267 vec![(String::from(ARG_SLOT), title)],
268 )?;
269 // With the hook, every heading carries the group, empty or not; it
270 // is the hook's fourth argument, and one shape means a user who
271 // redefines `\flmHeading` can count on four arguments always being
272 // there. Without the hook nothing takes the group, so it is written
273 // only where the heading has a label — which is why the hook itself
274 // is what decides whether an empty group is written.
275 let write_empty_group = hook;
276 let mut labels = Vec::new();
277 for written in refs::label_uses(&node) {
278 labels.push(refs::stage_label(cx, lw, &written.text, written.label.as_ref())?);
279 }
280 let labels = stage_label_group(cx, lw, labels, write_empty_group)?;
281 if !hook {
282 let mut nodes = vec![heading];
283 nodes.extend(labels);
284 return Ok(Lowering::Emit(nodes));
285 }
286 lw.require(&Name::from(preamble::HEADING));
287 // Whether the heading is listed in a table of contents travels as the
288 // hook's key `toc`, on every heading: the hook's argument is the one
289 // place a heading's key-values are written, never the sectioning
290 // command's.
291 let listed = !value.decl.skip_toc && occurrence.toc;
292 let mut keys = vec![raw(cx, lw, if listed { "toc=true" } else { "toc=false" })?];
293 // The alternative title travels as the hook's key `alt`, its pieces
294 // lowered as the author wrote them, inside braces.
295 if let Some(alt) = heading_alt(&node) {
296 keys.push(raw(cx, lw, ",alt={")?);
297 keys.extend(lower_written_pieces(cx, lw, &alt)?);
298 keys.push(raw(cx, lw, "}")?);
299 }
300 let token = lw.pres_slots_with(
301 cx,
302 &ElementName::from(MACRO),
303 LatexMacroPayload::new(preamble::HEADING_COMMAND, [LatexArgShape::Optional]),
304 vec![(String::from(ARG_SLOT), keys)],
305 )?;
306 // The newline after the hook token puts the sectioning command on a
307 // line of its own, for the reader; LaTeX reads the same tokens.
308 let newline = raw(cx, lw, "\n")?;
309 // The group's braces: the hook's fourth argument is a braced group
310 // holding the labels, and a rule has no other way to write one.
311 let open = raw(cx, lw, "{")?;
312 let close = raw(cx, lw, "}")?;
313 let mut nodes = vec![token, newline, heading, open];
314 nodes.extend(labels);
315 nodes.push(close);
316 Ok(Lowering::Emit(nodes))
317 }
318}
319
320/// Stages one raw node (`flm.pres.latex.raw`, LaTeX text written as it is)
321/// holding `text`: the hook's keys, the braces around the value of its key
322/// `alt`, the newline after the hook and the braces of the hook's label group.
323fn raw(
324 cx: &mut LowerCx<'_>,
325 lw: &mut dyn Lowerer,
326 text: &str,
327) -> Result<techy::core::node::BuildId, LowerError> {
328 lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
329}
330
331/// Returns the lowering rule [`LATEX_RULE`], ready to be registered: it produces
332/// `flm.pres.latex.macro` and `flm.pres.latex.raw`, reads the safe-labels table
333/// optionally, and is the default on the `latex-recomposed` backend only.
334pub fn latex_rule() -> LoweringRule {
335 LoweringRule::new(
336 LATEX_RULE,
337 HEADING,
338 LoweringDecl::new()
339 .reads_opt(SAFE_LABELS)
340 .option::<LatexRecomposedRenderOptions>()
341 .option::<HeadingsLatexOptions>()
342 .produces(MACRO)
343 .produces(RAW),
344 Arc::new(HeadingLatexRule),
345 DefaultMark::OnBackends(vec![BACKEND.into()]),
346 )
347 .docs(
348 "a heading lowers to the LaTeX hook `\\flmHeading[toc=…]` (with `alt={…}` where the \
349 heading has an alternative title), a newline, the LaTeX \
350 sectioning command its heading kind maps to, starred when not numbered, and a group \
351 holding the labels it read from its `\\label` fields",
352 )
353}
354
355/// Returns the lowering rule [`NUMBER_LATEX_RULE`] of a heading's number
356/// ([`NUMBER_ELEMENT`]) on the `latex-recomposed` backend: the number's content,
357/// lowered through the lowering rules, and nothing around it. It produces no
358/// element of its own and is the default on that backend only.
359///
360/// The number node occurs only inside what the default heading rule writes
361/// before a title. This backend writes a heading back as its sectioning command
362/// through [`latex_rule`] and leaves the numbering to LaTeX, so the node never
363/// reaches it. The rule exists because a plan checks that its backend can lower
364/// every element a document may hold.
365pub fn number_latex_rule() -> LoweringRule {
366 LoweringRule::new(
367 NUMBER_LATEX_RULE,
368 NUMBER_ELEMENT,
369 LoweringDecl::new(),
370 Arc::new(NumberLatexRule),
371 DefaultMark::OnBackends(vec![BACKEND.into()]),
372 )
373 .docs(
374 "a heading's number lowers to its content; the heading itself is written back as its \
375 sectioning command, so the number never reaches this backend",
376 )
377}
378
379/// The implementation of the lowering rule [`number_latex_rule`].
380#[derive(Debug, Default, Clone, Copy)]
381struct NumberLatexRule;
382
383impl Lower for NumberLatexRule {
384 fn lower(
385 &self,
386 node: NodeRef<'_, Flm>,
387 cx: &mut LowerCx<'_>,
388 lw: &mut dyn Lowerer,
389 ) -> Result<Lowering, LowerError> {
390 Ok(Lowering::Emit(lw.lower_body(cx, &node)?))
391 }
392}
393
394/// Registers what the headings feature contributes to the `latex-recomposed`
395/// backend: the peer declarations of the backend, of the constructs the rule
396/// stages and of the table it reads, then [`latex_rule`] and
397/// [`number_latex_rule`]. (The feature declares the render options
398/// [`HeadingsLatexOptions`] through its settings.)
399///
400/// The backend, the constructs and the safe-labels table belong to other
401/// features, so this function declares each as a peer declaration
402/// ([`PeerName`](crate::core::registry::PeerName)): a forward declaration of
403/// something another feature owns, with the construct's payload type, or the
404/// table's value type, as its signature. A registry without the LaTeX features
405/// therefore still builds, with the rules set aside (excluded from rule
406/// selection). The safe-labels table is read optionally, so that a registry
407/// holding the backend but not the `refs` feature still renders: the labels are
408/// then written as the document wrote them.
409///
410/// # Errors
411///
412/// Never fails: the builder methods it calls report their problems when the
413/// registry is built.
414pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
415 b.peer_backend(
416 BACKEND,
417 "the latex-recomposed backend, on which the recomposition rule of a heading is the default",
418 )?;
419 b.peer_element::<LatexMacroPayload>(
420 MACRO,
421 "the LaTeX family's macro-call construct, which the recomposition rule stages",
422 )?;
423 b.peer_element::<LatexRawPayload>(
424 RAW,
425 "the LaTeX family's raw construct (LaTeX text written as it is), which the \
426 recomposition rule stages for the newline after the LaTeX hook `\\flmHeading` and the \
427 braces of the hook's label group",
428 )?;
429 b.peer_table::<SafeLabels>(
430 SAFE_LABELS.name(),
431 "the references feature's safe-labels table, which the recomposition rule reads for \
432 the safe label of each label the heading read from its `\\label` fields",
433 )?;
434 b.lowering_rule(latex_rule())?;
435 b.lowering_rule(number_latex_rule())
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441
442 #[test]
443 fn the_rule_is_the_default_on_the_recomposed_backend_only() {
444 let rule = latex_rule();
445 assert_eq!(rule.name, LATEX_RULE);
446 assert_eq!(rule.element, HEADING);
447 assert_eq!(rule.decl.produces, [ElementName::from(MACRO), ElementName::from(RAW)]);
448 assert!(rule.default.is_specific_to(&BACKEND.into()));
449 assert_eq!(rule.decl.options.len(), 2);
450 // The labels are written from the heading's own fields, through the
451 // safe-labels table where a feature of the registry declares it.
452 assert!(rule.decl.reads.is_empty());
453 assert_eq!(rule.decl.reads_opt.len(), 1);
454 }
455}