flm_core/stdlib/features/defterm/latex.rs
1//! The lowering rules of the [`defterm`](super) feature for the
2//! `latex-recomposed` backend, and the definition piece they require. A term
3//! definition is written back as the environment `defterm` the author wrote,
4//! its labels made to refer to it with the term as the text a reference
5//! prints; the style file defines the environment from the configured
6//! lead-in; and a term link is written as a LaTeX hook. The rendering guide
7//! describes this output for users under [Defined terms in the recomposed
8//! LaTeX](crate::guide::rendering#defined-terms-in-the-recomposed-latex).
9//!
10//! | written | LaTeX |
11//! |---|---|
12//! | `\begin{defterm}{Entropy}\label{topic:s}\aliasterm{Entropies} A measure. \end{defterm}` | `\begin{defterm}{Entropy}\phantomsection\flmLabelsWithDisplayText{Entropy}{\flmLabels{\label{ref1}\label{ref2}\label{ref3}}}\ignorespaces A measure.\end{defterm}` |
13//! | the lead-in `#{term}: ` (the default) | `\ProvideDocumentEnvironment{defterm}{+m}{#1: }{}` in the style file |
14//! | the lead-in `\textbf{Definition} (\emph{#{term}}): ` | `\ProvideDocumentEnvironment{defterm}{+m}{\textbf{Definition} (\emph{#1}): }{}` |
15//! | no lead-in | `\ProvideDocumentEnvironment{defterm}{+m}{}{}` |
16//! | `\term{entropy}`, `\term[entropy]{the entropy}` | `\flmTerm{ref1}{entropy}`, `\flmTerm{ref1}{the entropy}` |
17//! | `\term{Entropy}` inside the definition of `Entropy` | `\flmTermInDefterm{Entropy}` |
18//!
19//! The rules use the LaTeX family's vocabulary: a **LaTeX hook** is a macro
20//! that the recomposed LaTeX writes and the style file defines with a plain
21//! default, which a user redefines in the document's preamble
22//! ([`preamble`]; the rendering guide lists the hooks under [the LaTeX
23//! hooks](crate::guide::rendering#the-latex-hooks)); a **definition piece**
24//! is a unit of LaTeX definitions that a rule requires by identifier and the
25//! style file holds ([`LatexPreambleDef`]); a **package request** is a LaTeX
26//! package that a rule or a definition piece requires by identifier ([`packages`]); and
27//! a **safe label** is the key the recomposed LaTeX writes for an FLM label
28//! (`ref1`, `ref2`, …; [`SafeLabels`]).
29//!
30//! # A term definition
31//!
32//! [`DEFINITION_LATEX_RULE`] writes a term definition as the environment
33//! `defterm` ([`ENVIRONMENT`]), with the term, lowered as the content it is,
34//! as its one argument. Its body opens with three things before the term
35//! definition's own paragraphs:
36//!
37//! - `\phantomsection`, the `hyperref` command that places an anchor where no
38//! sectioning command is, so that a link to the term definition leads to it
39//! rather than to the place anchored last;
40//! - `\flmLabelsWithDisplayText{<term>}{<labels>}`, the LaTeX family's
41//! single command for labels that refer to a place with no number and
42//! print a text of their own
43//! ([`label_display_text_piece`](crate::stdlib::backends::latex::preamble::label_display_text_piece)):
44//! here the term, so that `\ref` or `\zcref` to a label of the term
45//! definition prints the term. The labels are every label of the term
46//! definition's reference point, in its order (the label computed from the
47//! term, one computed from each alias, then the ones the author wrote),
48//! each under the safe label the references feature allocated for it,
49//! inside the labels hook `\flmLabels`, as every group of labels is written
50//! ([`stage_label`](crate::stdlib::features::refs::stage_label),
51//! [`stage_label_group`](crate::stdlib::features::refs::stage_label_group));
52//! - `\ignorespaces`, which drops the line break after the labels, so that
53//! the term definition's text follows the lead-in with only the lead-in's
54//! own space.
55//!
56//! The term is written twice, once as the environment's argument and once as
57//! the text a reference prints, so that the lead-in and a reference each have
58//! it. With the render option
59//! [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)
60//! off, the labels are written bare after `\phantomsection`, with no display
61//! text, as every label is then: a reference to the term definition prints
62//! what LaTeX recorded last, and giving it a text is left to the author.
63//!
64//! The term definition's fields, `\label{…}` and `\aliasterm{…}`, label it
65//! and are not written anywhere else. A term definition whose term is empty is
66//! reported as on every other backend ([`EmptyTerm`]).
67//!
68//! # The LaTeX definition of the environment
69//!
70//! The style file defines the environment `defterm` from the configured
71//! lead-in ([`DeftermConfig::lead_in`](super::DeftermConfig::lead_in)). The
72//! begin code is the lead-in template, instantiated once as on every other
73//! output and lowered through the ordinary rules, with `#{term}` written as
74//! the environment's parameter `#1`; the end code is empty; with no lead-in,
75//! the begin code is empty too. The lead-in a compiled document shows
76//! therefore follows the configuration, and a LaTeX author changes it by
77//! defining `defterm` before loading the style file, or with
78//! `\RenewDocumentEnvironment` after.
79//!
80//! The rule stages (builds into the lowered tree; see [`Lowerer`]) that LaTeX
81//! definition at every term definition, as the
82//! LaTeX family's definition construct written by this feature
83//! ([`LatexDefinitionPayload::feature`]), which the style file holds once,
84//! guarded, before the document's own user definitions. It is not part of a
85//! definition piece, because a definition piece is fixed text and the begin
86//! code is a template lowered through the rules.
87//!
88//! The feature's definition piece ([`definition_piece`],
89//! `flm.latex.def.defterm`) requires what the recomposed term definition
90//! uses: the `hyperref` package, which defines `\phantomsection`; the labels
91//! hook; the display-text hook; and the `zref-clever` reference type that
92//! makes a reference to such a label print its text alone. A recomposed
93//! document that holds a term definition therefore loads `hyperref`, as one
94//! that holds a hyperlink does; a document that loads it itself, with options
95//! of its own, lists it in the render option
96//! [`skip_packages`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::skip_packages).
97//!
98//! # A term link
99//!
100//! [`TERM_LATEX_RULE`] writes a term link as one of two LaTeX hooks, which
101//! the feature's definition piece defines and a LaTeX author may redefine.
102//! The text written for the link is lowered as the content it is, as it is
103//! for `\flmHyperref`:
104//!
105//! - `\flmTerm{<label>}{<shown>}` ([`TERM_COMMAND`]) anywhere but inside the
106//! definition of its own term, `<label>` being the safe label of the label
107//! the link targets; by default `\flmHyperref{#1}{#2}`, a link where the
108//! document loads `hyperref`;
109//! - `\flmTermInDefterm{<shown>}` ([`TERM_IN_DEFTERM_COMMAND`]) inside the
110//! definition of its own term: the term being defined, set apart and linked
111//! to nothing; by default `\emph{#1}`.
112//!
113//! Which of the two is written is decided at lowering, from the structure of
114//! the tree, by the function every output calls,
115//! [`in_own_definition`](super::in_own_definition); LaTeX keeps no state of
116//! its own for it. A term link to a term that no term definition carries is
117//! given a safe label as every reference to nothing is, so the term's own
118//! characters, markup included, never reach a label name, and LaTeX reports
119//! an undefined reference. A term link whose term is empty is reported as on
120//! every other output ([`EmptyTerm`]) and written with an empty label.
121//!
122//! A user definition whose template holds a term link with a placeholder in
123//! its term (`\term[#1]{…}`, `\term{#1}`, `\term[\emph{#1}]{…}`) is not kept
124//! as a LaTeX definition: the label such a link targets is computed from the
125//! term, which a call supplies. The rule returns
126//! [`LowerError::PlaceholderCharacters`] through the reading of source text at
127//! lowering ([`spelling_at_lowering`]), and each use site is expanded instead,
128//! its link written under the safe label of its own term. A term link with a
129//! fixed term in the template of a kept definition (a user definition whose
130//! use sites a plan leaves in the tree; see [kept
131//! definitions](crate::stdlib::features::userdefs::kept)) is written as
132//! anywhere else, under its safe label.
133//!
134//! # The term pointer
135//!
136//! A term pointer occurs only in the lead-in's instance, which this backend
137//! lowers as the begin code of the environment's LaTeX definition. Its rule
138//! ([`PointerLatexRule`]) writes the environment's parameter there, `#1`,
139//! which LaTeX replaces by the term at each term definition.
140
141use std::sync::Arc;
142
143use techy::core::node::{BuildId, NodeRef};
144
145use crate::core::lowering::{
146 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
147 spelling_at_lowering,
148};
149use crate::core::registry::{BuildError, FeatureBuilder};
150use crate::lang::Flm;
151use crate::model::names::{ElementName, Name};
152use crate::stdlib::backends::latex::construct::{
153 ARG_SLOT, BEGIN_SLOT, DEFINITION, END_SLOT, ENVIRONMENT as ENVIRONMENT_CONSTRUCT, MACRO, RAW,
154};
155use crate::stdlib::backends::latex::{
156 LatexArgShape, LatexDefinitionKind, LatexDefinitionPayload, LatexEnvironmentPayload,
157 LatexMacroPayload, LatexPreambleDef, LatexRawPayload, packages, preamble,
158};
159use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
160use crate::stdlib::backends::lowering::lower_arg_named_or_nothing;
161use crate::stdlib::backends::pres::{BODY_SLOT, spelling_identity};
162use crate::stdlib::features::refs::{
163 self, SAFE_LABELS, SafeLabels, VALUE_SAFE_LABELS, ValueSafeLabels, stage_spelling,
164 target_spelling,
165};
166
167use super::FEATURE;
168use super::diagnostics::EmptyTerm;
169use super::elements::{
170 DEFTERM, SHOWN_ARG, TERM, TERM_ARG, computed_labels, decide_term, written_term,
171};
172use super::lead_in::{LeadIn, TERM_POINTER, lead_in_instance};
173
174/// The name of the term definition's rule on the `latex-recomposed` backend,
175/// `flm.defterm.lower.latex-recomposed` ([`DefinitionLatexRule`]).
176pub const DEFINITION_LATEX_RULE: &str = "flm.defterm.lower.latex-recomposed";
177
178/// The name of the term link's rule on the `latex-recomposed` backend,
179/// `flm.term.lower.latex-recomposed` ([`TermLatexRule`]).
180pub const TERM_LATEX_RULE: &str = "flm.term.lower.latex-recomposed";
181
182/// The name of the term pointer's rule on the `latex-recomposed` backend,
183/// `flm.defterm.term-pointer.lower.latex-recomposed` ([`PointerLatexRule`]).
184pub const POINTER_LATEX_RULE: &str = "flm.defterm.term-pointer.lower.latex-recomposed";
185
186/// The LaTeX environment that a term definition is written as, `defterm`:
187/// the name the author wrote, which the style file defines
188/// ([`DefinitionLatexRule`]).
189pub const ENVIRONMENT: &str = "defterm";
190
191/// The command that ends the opening of a term definition's body,
192/// `ignorespaces`: the spaces after it (the line break after the labels) are
193/// dropped, so that the term definition's text follows the lead-in with only
194/// the lead-in's own space.
195const IGNORE_SPACES_COMMAND: &str = "ignorespaces";
196
197/// The parameter that the term pointer is written as in the environment's
198/// LaTeX definition, `#1`: the environment's one argument, the term.
199pub const TERM_PARAMETER: &str = "#1";
200
201/// The LaTeX hook that a term link is written as outside the definition of
202/// its own term, `flmTerm`: `\flmTerm{<label>}{<shown>}`, `<label>` being a
203/// safe label.
204pub const TERM_COMMAND: &str = "flmTerm";
205
206/// The LaTeX hook that a term link is written as inside the definition of
207/// its own term, `flmTermInDefterm`: `\flmTermInDefterm{<shown>}`.
208pub const TERM_IN_DEFTERM_COMMAND: &str = "flmTermInDefterm";
209
210/// The name of the feature's definition piece, `defterm`; its identifier is
211/// `flm.latex.def.defterm` ([`PIECE`]).
212pub const PIECE_NAME: &str = "defterm";
213
214/// The identifier of the feature's definition piece, `flm.latex.def.defterm`
215/// ([`definition_piece`]).
216pub const PIECE: &str = "flm.latex.def.defterm";
217
218/// The feature's definition piece, `flm.latex.def.defterm` ([`PIECE`]). It
219/// defines the two LaTeX hooks of a term link, `\flmTerm{<label>}{<shown>}`
220/// (by default `\flmHyperref{#1}{#2}`) and `\flmTermInDefterm{<shown>}` (by
221/// default `\emph{#1}`), each with `\ProvideDocumentCommand`, so that a
222/// definition the user made first is kept; and what each hook contributes to
223/// a PDF bookmark: its text alone. It requires what the hooks and a term
224/// definition use: the `\flmHyperref` definition piece ([`preamble::HYPERREF`]); the
225/// `hyperref` package ([`packages::HYPERREF`]), for `\phantomsection`; the
226/// labels hook ([`preamble::LABELS`]); the display-text hook
227/// ([`preamble::LABEL_DISPLAY_TEXT`]); and the `zref-clever` reference type
228/// that makes a reference to such a label print its text alone
229/// ([`preamble::ZREF_CLEVER_TYPE`]). The environment `defterm` itself is not
230/// in the definition piece: the style file defines it from the configured lead-in (see
231/// [the LaTeX definition of the
232/// environment](self#the-latex-definition-of-the-environment)).
233///
234/// Redefine a hook, before loading the style file or after it, to write term
235/// links another way.
236pub fn definition_piece() -> LatexPreambleDef {
237 LatexPreambleDef::new(
238 PIECE_NAME,
239 "\
240% Defined terms. A term definition is written as the environment defterm,
241% whose one argument is the term. This file defines the environment further
242% below, in the part headed \"definitions written from the configuration of
243% FLM features\"; the environment's opening text is the lead-in that the
244% document was recomposed with. The body of a term definition opens with
245% \\phantomsection, so that a link to the term definition leads to it, and
246% with \\flmLabelsWithDisplayText, so that a reference to one of its labels
247% prints the term.
248% \\flmTerm{<label>}{<shown>}: <shown>, a link to the definition of a term,
249% <label> being a label of that definition, as \\flmHyperref takes it.
250% \\flmTermInDefterm{<shown>}: <shown> written inside the definition of its
251% own term: the term being defined, set apart, with no link.
252% Redefine either command to set term links another way.
253\\ProvideDocumentCommand\\flmTerm{m m}{\\flmHyperref{#1}{#2}}
254\\ProvideDocumentCommand\\flmTermInDefterm{m}{\\emph{#1}}
255% What a term link contributes to a PDF bookmark: its text alone. The code
256% below runs when the document begins (\\AtBeginDocument) and does nothing
257% where hyperref is not loaded.
258\\AtBeginDocument{\\ifdefined\\pdfstringdefDisableCommands
259 \\pdfstringdefDisableCommands{%
260 \\def\\flmTerm#1#2{#2}%
261 \\def\\flmTermInDefterm#1{#1}%
262 }\\fi}
263",
264 "`\\flmTerm{label}{shown}` and `\\flmTermInDefterm{shown}`: the LaTeX hooks of a term \
265 link; and the package and definition pieces that a term definition requires",
266 )
267 .requires([
268 preamble::HYPERREF,
269 packages::HYPERREF,
270 preamble::LABELS,
271 preamble::LABEL_DISPLAY_TEXT,
272 preamble::ZREF_CLEVER_TYPE,
273 ])
274}
275
276/// The lowering rule [`DEFINITION_LATEX_RULE`], the default on the
277/// `latex-recomposed` backend: the environment's LaTeX definition from the
278/// lead-in, then the environment around `\phantomsection`, the labels with
279/// the term as their display text, `\ignorespaces` and the body. See the
280/// [module documentation](self#a-term-definition).
281#[derive(Debug)]
282pub struct DefinitionLatexRule {
283 lead_in: Arc<LeadIn>,
284}
285
286impl Lower for DefinitionLatexRule {
287 fn lower(
288 &self,
289 node: NodeRef<'_, Flm>,
290 cx: &mut LowerCx<'_>,
291 lw: &mut dyn Lowerer,
292 ) -> Result<Lowering, LowerError> {
293 let term = node.argument_content_nodes_named(TERM_ARG).ok().flatten();
294 if term.is_none_or(|content| spelling_identity(content.iter()).is_empty()) {
295 lw.error(EmptyTerm { what: String::from("defterm") }, node.span().clone());
296 }
297 lw.require(&Name::from(PIECE));
298 let definition = environment_definition(&self.lead_in, &node, cx, lw)?;
299 // Every label of the point, in its order: the computed ones, then the
300 // written ones, each under its safe key.
301 let mut labels = Vec::new();
302 for label in computed_labels(&node) {
303 labels.push(refs::stage_label(cx, lw, &label.to_string(), Some(&label))?);
304 }
305 for written in refs::label_uses(&node) {
306 labels.push(refs::stage_label(cx, lw, &written.text, written.label.as_ref())?);
307 }
308 let hooks = lw.option::<LatexRecomposedRenderOptions>()?.label_hooks;
309 let labels = refs::stage_label_group(cx, lw, labels, true)?;
310 let phantom = lw.pres_slots_with(
311 cx,
312 &ElementName::from(MACRO),
313 LatexMacroPayload::new(preamble::PHANTOMSECTION_COMMAND, []),
314 Vec::new(),
315 )?;
316 let mut body = vec![phantom];
317 if hooks {
318 let shown = lower_arg_named_or_nothing(cx, lw, &node, TERM_ARG)?;
319 body.push(refs::stage_labels_with_display_text(cx, lw, shown, labels)?);
320 } else {
321 body.extend(labels);
322 }
323 // The begin code ends with the lead-in, whose default ends in a space,
324 // and the anchor, the labels and the line break after them would add
325 // a second space before the definition's text: `\ignorespaces` drops
326 // the spaces that follow it, so one space stands after the lead-in.
327 body.push(lw.pres_slots_with(
328 cx,
329 &ElementName::from(MACRO),
330 LatexMacroPayload::new(IGNORE_SPACES_COMMAND, []),
331 Vec::new(),
332 )?);
333 body.extend(lw.lower_body(cx, &node)?);
334 let term = lower_arg_named_or_nothing(cx, lw, &node, TERM_ARG)?;
335 let environment = lw.pres_slots_with(
336 cx,
337 &ElementName::from(ENVIRONMENT_CONSTRUCT),
338 LatexEnvironmentPayload::new(ENVIRONMENT, [LatexArgShape::Mandatory]),
339 vec![(String::from(ARG_SLOT), term), (String::from(BODY_SLOT), body)],
340 )?;
341 Ok(Lowering::Emit(vec![definition, environment]))
342 }
343}
344
345/// Stages the LaTeX definition of the environment [`ENVIRONMENT`] for the
346/// style file: one argument; its begin code the lead-in's instance lowered
347/// through the rules ([`lead_in_instance`]), with the pointer written as
348/// [`TERM_PARAMETER`], or nothing where no lead-in is configured; its end
349/// code empty. As a definition written by a feature, it is guarded.
350fn environment_definition(
351 lead_in: &LeadIn,
352 node: &NodeRef<'_, Flm>,
353 cx: &mut LowerCx<'_>,
354 lw: &mut dyn Lowerer,
355) -> Result<BuildId, LowerError> {
356 let begin = match lead_in_instance(lead_in, node, lw)? {
357 Some(instance) => lw.splice(cx, &instance)?,
358 None => Vec::new(),
359 };
360 let payload = LatexDefinitionPayload::new(LatexDefinitionKind::Environment, ENVIRONMENT, 1)
361 .of_feature(FEATURE);
362 lw.pres_slots_with(
363 cx,
364 &ElementName::from(DEFINITION),
365 payload,
366 vec![(String::from(BEGIN_SLOT), begin), (String::from(END_SLOT), Vec::new())],
367 )
368}
369
370/// The term definition's rule on the `latex-recomposed` backend,
371/// [`DEFINITION_LATEX_RULE`], writing the environment's begin code from
372/// `lead_in`.
373fn definition_latex_rule(lead_in: Arc<LeadIn>) -> LoweringRule {
374 LoweringRule::new(
375 DEFINITION_LATEX_RULE,
376 DEFTERM,
377 LoweringDecl::new()
378 .reads_opt(SAFE_LABELS)
379 .option::<LatexRecomposedRenderOptions>()
380 .produces(DEFINITION)
381 .produces(ENVIRONMENT_CONSTRUCT)
382 .produces(MACRO)
383 .produces(RAW),
384 Arc::new(DefinitionLatexRule { lead_in }),
385 DefaultMark::OnBackends(vec![BACKEND.into()]),
386 )
387 .docs(
388 "a term definition lowers to the environment `defterm` around its term, its body \
389 opening with `\\phantomsection` and `\\flmLabelsWithDisplayText` over its labels; the \
390 style file defines the environment from the lead-in template",
391 )
392}
393
394/// The lowering rule [`TERM_LATEX_RULE`], the default on the
395/// `latex-recomposed` backend: `\flmTerm` around the safe label of the label
396/// the term link targets and the text written for it, or
397/// `\flmTermInDefterm` around that text inside the definition of its own
398/// term. See the [module documentation](self#a-term-link).
399#[derive(Debug, Default, Clone, Copy)]
400pub struct TermLatexRule;
401
402impl Lower for TermLatexRule {
403 fn lower(
404 &self,
405 node: NodeRef<'_, Flm>,
406 cx: &mut LowerCx<'_>,
407 lw: &mut dyn Lowerer,
408 ) -> Result<Lowering, LowerError> {
409 let shown = lower_arg_named_or_nothing(cx, lw, &node, SHOWN_ARG)?;
410 let Some(decision) = decide_term(&node) else {
411 // The target is computed from the term's spelling, not its
412 // characters: see [`spelling_at_lowering`].
413 if let Some(written) = written_term(&node) {
414 spelling_at_lowering(written.iter())?;
415 }
416 // An empty term names nothing: reported, and written as a
417 // reference naming nothing is, with an empty label.
418 lw.error(EmptyTerm { what: String::from("\\term") }, node.span().clone());
419 return Ok(Lowering::Emit(vec![term_hook(cx, lw, Vec::new(), shown)?]));
420 };
421 if decision.in_own_definition {
422 lw.require(&Name::from(PIECE));
423 let hook = lw.pres_slots_with(
424 cx,
425 &ElementName::from(MACRO),
426 LatexMacroPayload::new(TERM_IN_DEFTERM_COMMAND, [LatexArgShape::Mandatory]),
427 vec![(String::from(ARG_SLOT), shown)],
428 )?;
429 return Ok(Lowering::Emit(vec![hook]));
430 }
431 let target = decision.target;
432 let spelling = target_spelling(lw, &target.to_string(), Some(&target))?;
433 let key = stage_spelling(cx, lw, &spelling)?;
434 Ok(Lowering::Emit(vec![term_hook(cx, lw, key, shown)?]))
435 }
436}
437
438/// Stages `\flmTerm{<key>}{<shown>}`, `key` being the safe label, and
439/// requires the definition piece that defines the hook.
440fn term_hook(
441 cx: &mut LowerCx<'_>,
442 lw: &mut dyn Lowerer,
443 key: Vec<BuildId>,
444 shown: Vec<BuildId>,
445) -> Result<BuildId, LowerError> {
446 lw.require(&Name::from(PIECE));
447 lw.pres_slots_with(
448 cx,
449 &ElementName::from(MACRO),
450 LatexMacroPayload::new(TERM_COMMAND, [LatexArgShape::Mandatory, LatexArgShape::Mandatory]),
451 vec![(String::from(ARG_SLOT), key), (String::from(ARG_SLOT), shown)],
452 )
453}
454
455/// The term link's rule on the `latex-recomposed` backend,
456/// [`TERM_LATEX_RULE`].
457fn term_latex_rule() -> LoweringRule {
458 LoweringRule::new(
459 TERM_LATEX_RULE,
460 TERM,
461 LoweringDecl::new()
462 .reads_opt(SAFE_LABELS)
463 .reads_opt(VALUE_SAFE_LABELS)
464 .produces(MACRO)
465 .produces(RAW),
466 Arc::new(TermLatexRule),
467 DefaultMark::OnBackends(vec![BACKEND.into()]),
468 )
469 .docs(
470 "a term link lowers to `\\flmTerm` around its target's safe label and its text, or, \
471 inside the definition of its own term, to `\\flmTermInDefterm` around its text",
472 )
473}
474
475/// The lowering rule [`POINTER_LATEX_RULE`], the default on the
476/// `latex-recomposed` backend: the environment's parameter
477/// [`TERM_PARAMETER`], as a raw node (`flm.pres.latex.raw`). A term pointer
478/// occurs only in the lead-in's instance, which this backend lowers as the
479/// begin code of the environment's LaTeX definition, where the term is that
480/// parameter.
481#[derive(Debug, Default, Clone, Copy)]
482pub struct PointerLatexRule;
483
484impl Lower for PointerLatexRule {
485 fn lower(
486 &self,
487 _node: NodeRef<'_, Flm>,
488 cx: &mut LowerCx<'_>,
489 lw: &mut dyn Lowerer,
490 ) -> Result<Lowering, LowerError> {
491 let parameter = lw.pres_with(
492 cx,
493 &ElementName::from(RAW),
494 LatexRawPayload::new(TERM_PARAMETER),
495 Vec::new(),
496 )?;
497 Ok(Lowering::Emit(vec![parameter]))
498 }
499}
500
501/// Registers the three rules, each the default on the `latex-recomposed`
502/// backend only, and contributes the definition piece to the service slot of
503/// definition pieces ([`preamble::SLOT`]). The names they use that other
504/// features own (the backend, the LaTeX family's construct elements, the
505/// safe-labels tables, the service slot of definition pieces) are declared through
506/// peer declarations ([`PeerName`](crate::core::registry::PeerName)), so that
507/// a registry without them still builds, with these rules set aside
508/// (excluded from rule selection).
509///
510/// # Errors
511///
512/// The [`BuildError`] of the registry builder.
513pub(super) fn register(b: &mut FeatureBuilder<'_>, lead_in: Arc<LeadIn>) -> Result<(), BuildError> {
514 b.peer_backend(
515 BACKEND,
516 "the latex-recomposed backend, on which the feature's LaTeX rules are the default",
517 )?;
518 b.peer_element::<LatexDefinitionPayload>(
519 DEFINITION,
520 "the LaTeX family's definition construct, which the term definition's rule stages for \
521 the environment's LaTeX definition",
522 )?;
523 b.peer_element::<LatexEnvironmentPayload>(
524 ENVIRONMENT_CONSTRUCT,
525 "the LaTeX family's environment construct, which the term definition's rule stages",
526 )?;
527 b.peer_element::<LatexMacroPayload>(
528 MACRO,
529 "the LaTeX family's macro-call construct, which the rules stage for the hooks and labels",
530 )?;
531 b.peer_element::<LatexRawPayload>(
532 RAW,
533 "the LaTeX family's raw node construct, in which the term pointer writes the \
534 environment's parameter, and a term link a label whose label type the references \
535 feature marks as raw (written byte for byte)",
536 )?;
537 b.peer_table::<SafeLabels>(
538 SAFE_LABELS.name(),
539 "the references feature's safe-labels table, which the term definition's and the term \
540 link's rules read for the safe label written for a label",
541 )?;
542 b.peer_table::<ValueSafeLabels>(
543 VALUE_SAFE_LABELS.name(),
544 "the references feature's value names, which the term link's rule reads for the safe \
545 label of the target of a term link inside a synthesized value",
546 )?;
547 b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
548 let on_latex = || DefaultMark::OnBackends(vec![BACKEND.into()]);
549 b.lowering_rule(definition_latex_rule(lead_in))?;
550 b.lowering_rule(term_latex_rule())?;
551 b.lowering_rule(
552 LoweringRule::new(
553 POINTER_LATEX_RULE,
554 TERM_POINTER,
555 LoweringDecl::new().produces(RAW),
556 Arc::new(PointerLatexRule),
557 on_latex(),
558 )
559 .docs(
560 "a term pointer lowers to the environment's parameter `#1`: it occurs only in the \
561 lead-in written as the begin code of the environment's LaTeX definition",
562 ),
563 )?;
564 Ok(())
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570 use crate::stdlib::backends::latex::preamble::piece_id;
571
572 #[test]
573 fn the_piece_is_named_as_its_identifier_says_and_requests_what_a_definition_uses() {
574 let piece = definition_piece();
575 assert_eq!(piece.id, piece_id(PIECE_NAME));
576 assert_eq!(piece.id.as_str(), PIECE);
577 assert!(piece.requires.contains(&Name::from(packages::HYPERREF)));
578 assert!(piece.requires.contains(&Name::from(preamble::LABEL_DISPLAY_TEXT)));
579 assert!(piece.requires.contains(&Name::from(preamble::ZREF_CLEVER_TYPE)));
580 assert!(piece.requires.contains(&Name::from(preamble::HYPERREF)));
581 for hook in [TERM_COMMAND, TERM_IN_DEFTERM_COMMAND] {
582 assert!(piece.content.contains(&format!("\\ProvideDocumentCommand\\{hook}")));
583 }
584 }
585}