flm_core/stdlib/features/refs/latex.rs
1//! The LaTeX side of the [`refs`](super) feature: the recomposition rules
2//! that write `\ref` and `\hyperref` back as LaTeX for the `latex-recomposed`
3//! backend, the helpers with which a construct's own rule writes its labels,
4//! and the render options [`RefsRecomposeOptions`] that shape both.
5//!
6//! The recomposed LaTeX leaves cross-references to LaTeX: nothing is resolved
7//! here. A label is written as a LaTeX `\label` around the label's safe label
8//! (the key written in place of an FLM label, `ref1`, `ref2`, …; see
9//! [`SafeLabels`]), and a `\ref` as the LaTeX hook
10//! `\flmRef` around the same safe label, so that LaTeX pairs the two. A
11//! `\hyperref` is written as the LaTeX hook `\flmHyperref` around that safe
12//! label and the text the author wrote, recomposed as ordinary content. A
13//! LaTeX hook is a macro that the recomposed LaTeX writes and the style file
14//! defines with a plain default, which a user redefines in the document's
15//! preamble to change what the recomposed LaTeX does at that point
16//! ([`preamble`]; the rendering
17//! guide lists them under [The LaTeX
18//! hooks](crate::guide::rendering#the-latex-hooks)).
19//!
20//! Each recomposition rule is the default for its own element on the
21//! `latex-recomposed` backend only; on every other backend, the feature's
22//! rules that resolve references ([`REF_RULE`](super::REF_RULE),
23//! [`HYPERREF_RULE`](super::HYPERREF_RULE)) stay the default.
24//!
25//! No rule here writes a label: a `\label` is a field, data that the
26//! construct written before it reads, so the construct's own rule writes the
27//! labels it read (the heading rule for a heading, the math rule for an
28//! equation line) through [`stage_label`] and [`stage_label_group`].
29//!
30//! # What is written
31//!
32//! With the default options, `\section{A}\label{sec:a}` and `\ref{sec:a}`
33//! become `\flmHeading`, a newline, `\section{A}{\flmLabels{\label{ref1}}}`
34//! and `\flmRef{ref1}`.
35//! [`REF_COMMAND`](crate::stdlib::backends::latex::preamble::REF_COMMAND)
36//! (`\flmRef`) is the *reference hook*: the style file defines it with
37//! `\zcref` of the `zref-clever` package, which writes a reference with the
38//! name of its target ("Section 2"), as FLM's `\ref` does, while LaTeX's own
39//! `\ref` prints the number alone. A user who wants references typeset
40//! differently redefines that one macro instead of rendering the document
41//! again ([`refs_piece`](crate::stdlib::backends::latex::preamble::refs_piece)).
42//! The render option
43//! [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)
44//! turns the hooks off; the recomposed LaTeX then writes `\zcref[…]{ref1}`
45//! itself and requests the package, without translating the options, which
46//! the user then writes in the package's own terms.
47//!
48//! `\hyperref[sec:a]{the \emph{first} part}` becomes
49//! `\flmHyperref{ref1}{the \emph{first} part}`: the same safe label, and the
50//! author's text lowered through the ordinary rules, so that a user
51//! definition, a special character or mathematics inside it is written as it
52//! is written anywhere else.
53//! [`HYPERREF_COMMAND`](crate::stdlib::backends::latex::preamble::HYPERREF_COMMAND)
54//! (`\flmHyperref`) is the hook of such a reference: its default links the
55//! text through the `hyperref` package where the document loaded that
56//! package, and prints the text alone where it did not, so that whether a
57//! recomposed document carries links stays the author's decision
58//! ([`hyperref_piece`](crate::stdlib::backends::latex::preamble::hyperref_piece)).
59//! With the hooks off, the recomposed LaTeX writes `\hyperref[{ref1}]{…}`
60//! itself and requests the package, as it writes `\zcref` for a `\ref`. A
61//! `\hyperref` has no options argument, so nothing is translated for it.
62//!
63//! The rules record their needs as requirements: the definition piece of each
64//! hook they write (a unit of LaTeX definitions registered under an
65//! identifier `flm.latex.def.<name>`;
66//! [`LatexPreambleDef`](crate::stdlib::backends::latex::LatexPreambleDef)),
67//! or the LaTeX package they call directly
68//! ([`packages`]); the style file
69//! written beside the recomposed LaTeX holds what the document required.
70//!
71//! [`RefsRecomposeOptions`] changes the rest:
72//!
73//! - The `\ref` options are written back as an optional argument, each entry
74//! `key` or `key={value}`, separated by commas, in the order of the
75//! reference's key-value argument; a `\ref` written without options gets no
76//! optional argument. They are FLM's own options and are written in FLM's
77//! terms, without translation: the default definition of the hook
78//! translates each option that has a counterpart in `zref-clever`
79//! (`noprefix` becomes that package's `noname`, `abbreviated` its
80//! `abbrev=true`) and drops every other one, the reference then printing
81//! its default wording
82//! ([`refs_piece`](crate::stdlib::backends::latex::preamble::refs_piece)
83//! holds the table). A user who redefines `\flmRef` therefore receives the
84//! options as the document wrote them and maps them as their own reference
85//! command needs. The keys and the text of the values are document text,
86//! staged as text nodes so that the emitter escapes them (`x=Fig_1` becomes
87//! `x={Fig\_1}`); a command inside a value is lowered as anywhere else; the
88//! `=`, the braces around a value and the commas are raw nodes
89//! (`flm.pres.latex.raw`, written byte for byte). The emitter writes the
90//! argument plain, `\flmRef[S,x={Figure}]{ref1}`, and as `[{…}]` once a
91//! value holds a command (its rule for an optional argument).
92//! - [`protect`](RefsRecomposeOptions::protect) wraps either reference in
93//! `\NoCaseChange{\protect …}`, which keeps it out of a command that changes
94//! the case of its argument (`\MakeUppercase`), and requests the `textcase`
95//! package, which supplies `\NoCaseChange` on every LaTeX kernel. Off by
96//! default. Without it, the whole reference is uppercased:
97//! `\flmRef[noprefix]{ref1}` inside `\MakeUppercase` reaches the hook as
98//! `NOPREFIX`, a key the hook does not translate, so it is dropped and the
99//! name the author left out comes back; and the safe label itself is
100//! uppercased, so LaTeX looks for a label `REF1`, finds none, and prints
101//! `??` with only a warning. Both failures pass without an error.
102//! - [`safe_label_types`](RefsRecomposeOptions::safe_label_types) marks a
103//! label type as [`Raw`](SafeLabelMode::Raw): its labels are written as the
104//! document wrote them (`sec:intro`), byte for byte, and no safe label is
105//! allocated for them. Every type not listed is
106//! [`Safe`](SafeLabelMode::Safe). A text with no type (`\label{intro}`, no
107//! colon) belongs to no type, so the option cannot select it: it is
108//! allocated a safe label and written like any other, and the label scan
109//! reports it as not spelled `type:label`.
110//!
111//! [`label_spelling`] tells the two cases apart (a safe label, or a label
112//! written raw), and [`stage_spelling`] stages (builds into the lowered tree;
113//! see [`Lowerer`]) each: a safe label as document text, which the emitter
114//! escapes, and a raw label as a raw node.
115//! [`stage_label`] writes `\label` around a spelling, and
116//! [`stage_label_group`] wraps a group of labels in `\flmLabels`. The rules of
117//! the headings, math, theorems, lists, defterm, floats and xnotes features
118//! use both, so that a label is written the same way wherever it occurs. Both read the
119//! safe-labels table, so a rule that calls them declares that it reads
120//! [`SAFE_LABELS`].
121//!
122//! # A target that holds a template placeholder
123//!
124//! A user definition kept as a LaTeX definition is written once into the
125//! style file, its template lowered unchanged, placeholders included. A
126//! reference in that template whose target is fixed (`(see \ref{sec:intro})`)
127//! is written as any reference is: around the label's safe label or, where
128//! the target is a label the document never mentions, around a value name of
129//! the template's synthesized value ([`value_name`](super::value_name)). A
130//! target that points at nothing is reported as the document's own are, at
131//! each use site that stages the definition, the template being the
132//! caller's text for the document.
133//!
134//! A reference whose target holds a placeholder (`(see \ref{#1})`) points at
135//! a label that only a call supplies, and a safe label is allocated from a
136//! label's characters, which are not known before the call. So the rules
137//! read the target as characters at lowering ([`read_target_at_lowering`]),
138//! which fails for such a target, and each use site of the definition is then
139//! expanded instead of written as a call: its reference is written around the
140//! safe label of the label that use site supplies, as anywhere else. This
141//! holds for `\ref`, `\hyperref` and the math feature's `\eqref` alike. A
142//! target that a use site completes into a label that nothing carries is
143//! reported and still written with a key: the [value
144//! catch-up](crate::guide::concepts_overview#value-catch-up) of the expanded
145//! use site resolves its references against the document's labels, reports
146//! them as the document's own references are reported, and gives every
147//! target that has no safe label in the document a value name
148//! ([`value_name`](super::value_name)). [`target_spelling`] therefore falls
149//! back to a target's own characters only for a label of a type written raw.
150//!
151//! A label in such a template is a different case: it declares a fact about
152//! the document, and the definition is refused
153//! ([`userdefs::kept`](crate::stdlib::features::userdefs::kept)).
154//!
155//! # Labels are written in groups, inside `\flmLabels` when the hooks are on
156//!
157//! `\flmLabels{…}` is the *labels hook*: outside mathematics it runs the
158//! `\label` commands as they are written, and on a line of a display-math
159//! environment it makes every label after the first
160//! resolve to that line's number, which `amsmath` alone does not do
161//! ([`labels_piece`](crate::stdlib::backends::latex::preamble::labels_piece)).
162//! The hook wraps a *group* of labels, so the rule that owns the group writes
163//! it (the heading rule for a heading's label fields, the math rule for an
164//! equation line's labels) through [`stage_label_group`], around the bare
165//! `\label` commands that [`stage_label`] writes. No rule writes a label in
166//! any other way: a `\label` is a field, and a field node that reached a
167//! backend on its own would be an error. A feature that declares a labeled
168//! construct of its own calls both helpers in its own recomposition rule.
169//! With the hooks on, every label of the recomposed LaTeX is then written
170//! inside `\flmLabels`; with the render option
171//! [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)
172//! off, the same groups are written as bare `\label` commands.
173//!
174//! This also holds in a registry built without this feature. The safe-labels
175//! table is then absent, so [`label_spelling`] writes the label as the
176//! document wrote it rather than a safe label, but the group and the hook
177//! around it are the same: a definition piece of the LaTeX family
178//! ([`preamble::LABELS`]) defines `\flmLabels`, not this feature. Such a
179//! registry can also ask that an
180//! equation line's labels be left out of the output altogether
181//! ([`math_passthrough::latex`](crate::math_passthrough::latex)).
182
183use std::collections::BTreeMap;
184use std::sync::Arc;
185
186use techy::core::node::{BuildId, NodeId, NodeRef, NodeTree};
187use techy::extract::parse_keyval;
188
189use crate::core::lowering::{
190 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
191 chars_at_lowering,
192};
193use crate::core::registry::{BuildError, FeatureBuilder};
194use crate::lang::Flm;
195use crate::model::aspects::Label;
196use crate::model::names::{ElementName, Name};
197use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
198use crate::stdlib::backends::latex::{
199 LatexArgShape, LatexMacroPayload, LatexRawPayload,
200};
201use crate::stdlib::backends::latex::{packages, preamble};
202use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
203use crate::stdlib::backends::lowering::lower_arg_named_or_nothing;
204use crate::stdlib::features::numbering::PrefixWords;
205
206use super::elements::{
207 ABBREVIATED_VARIANT, CAPITAL_VARIANT, HYPERREF, LOWERCASE_VARIANT, OPTIONS_ARG, REF, TARGET_ARG,
208 TEXT_ARG, reference_targets,
209};
210use super::safe_labels::{
211 REF_DOMAIN, SAFE_LABELS, SafeLabels, VALUE_SAFE_LABELS, ValueSafeLabels, label_key,
212};
213
214/// The name of the recomposition rule of `\ref`,
215/// `flm.ref.lower.latex-recomposed`, whose implementation is
216/// [`RefLatexRule`]: the default for `flm.ref` on the `latex-recomposed`
217/// backend.
218pub const REF_LATEX_RULE: &str = "flm.ref.lower.latex-recomposed";
219
220/// The name of the recomposition rule of `\hyperref`,
221/// `flm.hyperref.lower.latex-recomposed`, whose implementation is
222/// [`HyperrefLatexRule`]: the default for `flm.hyperref` on the
223/// `latex-recomposed` backend.
224pub const HYPERREF_LATEX_RULE: &str = "flm.hyperref.lower.latex-recomposed";
225
226/// The LaTeX label command, `label`: the command in which [`stage_label`]
227/// writes a label, inside the labels hook `\flmLabels` when the hooks are on
228/// (the render option
229/// [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)).
230pub const LABEL_COMMAND: &str = "label";
231
232/// The reference command of the `zref-clever` package, `zcref`, which the
233/// recomposed LaTeX writes in place of the LaTeX hook `\flmRef` when the label
234/// hooks are off (the render option
235/// [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)).
236/// It is the command that the hook's default definition calls.
237pub const ZCREF_COMMAND: &str = "zcref";
238
239/// How the recomposed LaTeX writes the labels of one label type: by their
240/// safe label, or as the document wrote them.
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize)]
242#[derive(schemars::JsonSchema)]
243#[serde(rename_all = "kebab-case")]
244pub enum SafeLabelMode {
245 /// The safe label allocated for the label (`ref3`). The default.
246 #[default]
247 Safe,
248 /// The label as the document wrote it (`sec:intro`), byte for byte; no
249 /// safe label is allocated for it.
250 Raw,
251}
252
253/// The render options of the `refs` feature's recomposition rules: how the
254/// recomposed LaTeX writes labels and references (see the module
255/// documentation). An option type ([`crate::model::options`]) declared with
256/// [`Bind::Render`](crate::model::options::Bind::Render): its value is set per
257/// render request.
258///
259/// # Examples
260///
261/// ```
262/// use flm_core::stdlib::features::refs::{RefsRecomposeOptions, SafeLabelMode};
263///
264/// let options = RefsRecomposeOptions::default();
265/// assert!(options.safe_label_types.is_empty());
266/// assert!(!options.protect);
267/// let raw_sections = RefsRecomposeOptions {
268/// safe_label_types: [(String::from("sec"), SafeLabelMode::Raw)].into_iter().collect(),
269/// ..RefsRecomposeOptions::default()
270/// };
271/// assert_eq!(raw_sections.safe_label_types["sec"], SafeLabelMode::Raw);
272/// ```
273#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Deserialize)]
274#[derive(schemars::JsonSchema)]
275#[serde(default, deny_unknown_fields)]
276pub struct RefsRecomposeOptions {
277 /// Per label type (`sec`, `eq`), how its labels are written; a type not
278 /// listed is [`Safe`](SafeLabelMode::Safe). Empty by default. A label
279 /// with no type belongs to none of these and is always written by its
280 /// safe label.
281 ///
282 /// **You own this: a type set to [`Raw`](SafeLabelMode::Raw).** Its labels
283 /// are written as the document spelled them instead of as a generated
284 /// safe label. You must ensure that those labels are spellings LaTeX can
285 /// carry through its auxiliary file: a label holding a character LaTeX
286 /// treats specially cannot be read back, which the safe labels exist to
287 /// avoid.
288 pub safe_label_types: BTreeMap<String, SafeLabelMode>,
289 /// Whether a reference is wrapped in `\NoCaseChange{\protect …}`, which
290 /// keeps it out of a command that changes the case of its argument
291 /// (`\MakeUppercase`). Off by default; when on, the style file requests
292 /// the `textcase` package, which supplies `\NoCaseChange` on every LaTeX
293 /// kernel.
294 ///
295 /// A reference left unwrapped inside such a command is uppercased whole,
296 /// its options and its safe label alike, and it fails in two ways,
297 /// neither of which raises an error.
298 /// `\MakeUppercase{… \flmRef[noprefix]{ref1} …}` passes the hook
299 /// `NOPREFIX`, a key it does not translate, so it is dropped and the name
300 /// the author left out comes back. And the safe label itself is
301 /// uppercased, so LaTeX looks for a label `REF1`, finds none, and prints
302 /// `??` with only a warning. Turn this on for a document whose headings
303 /// or captions are uppercased.
304 pub protect: bool,
305}
306
307/// What is written for one label or reference target, as [`label_spelling`]
308/// and [`target_spelling`] return it: a safe label, or the label as written.
309#[derive(Debug, Clone, PartialEq, Eq)]
310pub enum LabelSpelling {
311 /// The safe label allocated for the label (`ref1`), or a value name
312 /// (`ref-v1`).
313 Safe(String),
314 /// The label as written, byte for byte: a label of a type written raw,
315 /// or a label in a registry without the safe-labels table.
316 Raw(String),
317}
318
319impl LabelSpelling {
320 /// The text written, in either case.
321 pub fn text(&self) -> &str {
322 match self {
323 LabelSpelling::Safe(text) | LabelSpelling::Raw(text) => text,
324 }
325 }
326}
327
328/// What to write for a label or a reference target, from the safe-labels
329/// table `table`: the safe label the table holds for it (the safe-labels
330/// stage allocates one for a well-formed label and for a text that is not
331/// spelled `type:label` alike), or the label as written when the table holds
332/// none: a label of a type written raw, or any label when the table is empty
333/// because no safe-labels stage ran (a registry without this feature).
334///
335/// `text` is the label as the document wrote it and `label` its parsed form,
336/// if it is one. A rule that writes a reference target calls
337/// [`target_spelling`] instead, which also reads the value names.
338pub fn label_spelling(table: &SafeLabels, text: &str, label: Option<&Label>) -> LabelSpelling {
339 match table.safe_name(REF_DOMAIN, &label_key(text, label)) {
340 Some(name) => LabelSpelling::Safe(String::from(name)),
341 None => LabelSpelling::Raw(match label {
342 Some(label) => label.to_string(),
343 None => String::from(text),
344 }),
345 }
346}
347
348/// What to write for a target of a reference in the node being lowered: the
349/// safe label that the document's safe-labels table holds for it
350/// ([`label_spelling`]), else the value name that the synthesized value
351/// holding the node gives it ([`VALUE_SAFE_LABELS`], written over a value
352/// spliced at lowering), else the target as written: a label of a type
353/// written raw, or any target when the rule reads the tables optionally and
354/// the plan holds neither.
355///
356/// Every rule that writes the target of a reference site calls it: those of
357/// `\ref`, `\hyperref`, the math feature's `\eqref`, the defterm feature's
358/// term link and the theorems feature's back-reference. A rule that calls it
359/// declares that it reads both tables, the value names optionally where it
360/// reads the document's safe labels optionally.
361///
362/// # Errors
363///
364/// Returns [`LowerError`] when the calling rule did not declare the reads.
365pub fn target_spelling(
366 lw: &dyn Lowerer,
367 text: &str,
368 label: Option<&Label>,
369) -> Result<LabelSpelling, LowerError> {
370 static EMPTY: SafeLabels =
371 SafeLabels { by_label: BTreeMap::new(), by_name: BTreeMap::new(), allocated: 0 };
372 let document = lw.get(SAFE_LABELS)?.unwrap_or(&EMPTY);
373 let spelling = label_spelling(document, text, label);
374 if let LabelSpelling::Raw(_) = spelling {
375 let value: Option<&ValueSafeLabels> = lw.get(VALUE_SAFE_LABELS)?;
376 let key = label_key(text, label);
377 if let Some(name) = value.and_then(|value| value.safe_name(lw.addr(), &key)) {
378 return Ok(LabelSpelling::Safe(String::from(name)));
379 }
380 }
381 Ok(spelling)
382}
383
384/// Stages a spelling: a safe label becomes a text node, which the emitter
385/// escapes like document text; a raw label becomes a raw node
386/// (`flm.pres.latex.raw`), written byte for byte. Returns that one node, as
387/// the content of a node slot of a LaTeX macro construct (techy's `ParsedSlot`,
388/// a part of a node's content outside its arguments; the construct holds the
389/// content of each argument in one).
390///
391/// # Errors
392///
393/// Returns [`LowerError`] when the node could not be built, or when the
394/// calling rule did not declare that it produces `flm.pres.latex.raw`.
395pub fn stage_spelling(
396 cx: &mut LowerCx<'_>,
397 lw: &mut dyn Lowerer,
398 spelling: &LabelSpelling,
399) -> Result<Vec<BuildId>, LowerError> {
400 let node = match spelling {
401 LabelSpelling::Safe(text) => lw.text(cx, text)?,
402 LabelSpelling::Raw(text) => lw.pres_with(
403 cx,
404 &ElementName::from(RAW),
405 LatexRawPayload::new(text.as_str()),
406 Vec::new(),
407 )?,
408 };
409 Ok(vec![node])
410}
411
412/// The safe-labels table, or an empty table where the plan holds none.
413fn safe_labels(lw: &dyn Lowerer) -> Result<&SafeLabels, LowerError> {
414 static EMPTY: SafeLabels =
415 SafeLabels { by_label: BTreeMap::new(), by_name: BTreeMap::new(), allocated: 0 };
416 Ok(lw.get(SAFE_LABELS)?.unwrap_or(&EMPTY))
417}
418
419/// Whether the labels and references of this render are written through the
420/// LaTeX hooks, read from the backend's render options.
421fn label_hooks(lw: &dyn Lowerer) -> Result<bool, LowerError> {
422 Ok(lw.option::<LatexRecomposedRenderOptions>()?.label_hooks)
423}
424
425/// Stages the options of the `\ref` node `node` as the content of an
426/// optional argument (see the module documentation): for each key-value
427/// entry with a key, the key as a text node, then, when the entry has a
428/// value, a raw node `={`, the value's nodes (its text as text nodes, any
429/// other node lowered as the node it was read from) and a raw node `}`; the
430/// entries separated by raw nodes `,`. Returns `None` when the reference has
431/// no options argument or the argument holds no entry. The value of a lone
432/// brace group is the group's content, as LaTeX reads a key-value value.
433///
434/// The calling rule must declare that it produces `flm.pres.latex.raw`.
435///
436/// # Errors
437///
438/// Returns [`LowerError`] when a node could not be built or a value's node
439/// could not be lowered.
440pub fn stage_ref_options(
441 cx: &mut LowerCx<'_>,
442 lw: &mut dyn Lowerer,
443 node: &NodeRef<'_, Flm>,
444) -> Result<Option<Vec<BuildId>>, LowerError> {
445 let Ok(Some(content)) = node.argument_content_nodes_named(OPTIONS_ARG) else {
446 return Ok(None);
447 };
448 // Each output node of the keyval parse is annotated with the node of the
449 // document it copies, or nothing for a piece of text cut at a `,` or `=`.
450 let keyvals = match parse_keyval(content, |part| {
451 (!part.is_partial()).then(|| part.original().map(|original| original.id())).flatten()
452 }) {
453 Ok(keyvals) => keyvals,
454 Err(_) => return Ok(None),
455 };
456 let tree = node.tree();
457 let raw = |cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str| {
458 lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
459 };
460 let mut nodes = Vec::new();
461 for entry in keyvals.iter().filter(|entry| !entry.key().is_empty()) {
462 if !nodes.is_empty() {
463 nodes.push(raw(cx, lw, ",")?);
464 }
465 nodes.push(lw.text(cx, entry.key())?);
466 let Some(value) = entry.value_content() else { continue };
467 nodes.push(raw(cx, lw, "={")?);
468 for piece in value.iter() {
469 if let Some(text) = piece.chars() {
470 nodes.push(lw.text(cx, text)?);
471 continue;
472 }
473 let original: Option<NodeId> = *piece.annotation();
474 let index = original.map(|id| id.index() as u32);
475 let Some(slice) = index.and_then(|index| tree.slice(index..index + 1)) else {
476 return Err(LowerError::structure(
477 "a keyval value node that copies no node of the document",
478 ));
479 };
480 nodes.extend(lw.lower_nodes(cx, slice)?);
481 }
482 nodes.push(raw(cx, lw, "}")?);
483 }
484 Ok((!nodes.is_empty()).then_some(nodes))
485}
486
487/// Stages one `\label` for a label a construct read (a heading's `\label`
488/// field, a label of an equation line): `\label` as a LaTeX macro construct
489/// whose one mandatory argument holds the label's spelling
490/// ([`label_spelling`] over the safe-labels table, staged by
491/// [`stage_spelling`]). Returns the staged node.
492///
493/// `text` is the label as the document wrote it and `label` its parsed form,
494/// as [`label_uses`](super::label_uses) returns them for a field.
495///
496/// The label is written bare; pass the labels of one group to
497/// [`stage_label_group`], which wraps them in the labels hook.
498///
499/// # Errors
500///
501/// Returns [`LowerError`] when a node could not be built, when the calling
502/// rule did not declare that it reads `flm.labels.safe`, or when it did not
503/// declare that it produces `flm.pres.latex.macro` and
504/// `flm.pres.latex.raw`.
505pub fn stage_label(
506 cx: &mut LowerCx<'_>,
507 lw: &mut dyn Lowerer,
508 text: &str,
509 label: Option<&Label>,
510) -> Result<BuildId, LowerError> {
511 let spelling = label_spelling(safe_labels(lw)?, text, label);
512 let target = stage_spelling(cx, lw, &spelling)?;
513 lw.pres_slots_with(
514 cx,
515 &ElementName::from(MACRO),
516 LatexMacroPayload::new(LABEL_COMMAND, [LatexArgShape::Mandatory]),
517 vec![(String::from(ARG_SLOT), target)],
518 )
519}
520
521/// Wraps a group of `\label` nodes, already staged by [`stage_label`], in the
522/// labels hook `\flmLabels{…}`, and requires the definition piece that
523/// defines the hook ([`preamble::LABELS`]).
524///
525/// Every group of labels in a recomposed LaTeX document goes through this
526/// function (a heading's label fields, the labels of one line of a
527/// display-math environment), so that a user changes what a group of labels
528/// does by redefining `\flmLabels`, and so that every label after the first
529/// on a line of mathematics resolves. A caller may have no labels to write at
530/// all: the math rule leaves an equation line's labels out entirely where the
531/// render options ask it to in a registry without this feature
532/// ([`math_passthrough::latex`](crate::math_passthrough::latex) says when).
533///
534/// `labels` is the group's staged nodes, which the hook holds between its
535/// braces; the result is the node to stage in their place. With
536/// [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)
537/// off, `labels` is returned unchanged and nothing is required: the
538/// recomposed LaTeX then holds bare `\label` commands.
539///
540/// An empty group is wrapped too when `empty_group` is true — the heading
541/// rule writes `{\flmLabels{}}` for a heading with no label, one shape for
542/// every heading — and is given back empty when it is false, so that a line
543/// of mathematics with no label carries nothing.
544///
545/// # Errors
546///
547/// Returns [`LowerError`] when the node could not be built, when the render
548/// options could not be read, or when the calling rule did not declare that
549/// it produces `flm.pres.latex.macro`.
550pub fn stage_label_group(
551 cx: &mut LowerCx<'_>,
552 lw: &mut dyn Lowerer,
553 labels: Vec<BuildId>,
554 empty_group: bool,
555) -> Result<Vec<BuildId>, LowerError> {
556 if !label_hooks(lw)? || (labels.is_empty() && !empty_group) {
557 return Ok(labels);
558 }
559 lw.require(&Name::from(preamble::LABELS));
560 let group = lw.pres_slots_with(
561 cx,
562 &ElementName::from(MACRO),
563 LatexMacroPayload::new(preamble::LABELS_COMMAND, [LatexArgShape::Mandatory]),
564 vec![(String::from(ARG_SLOT), labels)],
565 )?;
566 Ok(vec![group])
567}
568
569/// Stages `\flmLabelsWithDisplayText{<display text>}{<labels>}`, the LaTeX
570/// hook that makes a group of labels refer to a place LaTeX does not number,
571/// with the display text as what a reference to them prints
572/// ([`label_display_text_piece`](preamble::label_display_text_piece)), and
573/// requires the definition pieces of the hook and of the reference type that
574/// prints the text alone. Returns the staged node.
575///
576/// `text` is the display text, already lowered by the caller as ordinary
577/// content: the place's own words as the author wrote them (a defined term,
578/// an unnumbered float's caption, or the alternative text written in the
579/// caption's brackets), lowered exactly as where they are written, an xnote
580/// in them included, in the same way as the default heading hook reuses a
581/// heading's title. LaTeX typesets the display text at every reference, so a
582/// footnote in it is typeset again there; for a float, the author avoids this
583/// by writing the caption's alternative text without the footnote.
584/// `group` is the labels, already wrapped by [`stage_label_group`].
585///
586/// The definition rule of the `defterm` feature and the float rule of the
587/// `floats` feature call it; no other rule writes this hook.
588///
589/// # Errors
590///
591/// Returns [`LowerError`] when a node could not be built, or when the calling
592/// rule did not declare that it produces `flm.pres.latex.macro`.
593pub fn stage_labels_with_display_text(
594 cx: &mut LowerCx<'_>,
595 lw: &mut dyn Lowerer,
596 text: Vec<BuildId>,
597 group: Vec<BuildId>,
598) -> Result<BuildId, LowerError> {
599 lw.require(&Name::from(preamble::LABEL_DISPLAY_TEXT));
600 lw.require(&Name::from(preamble::ZREF_CLEVER_TYPE));
601 lw.pres_slots_with(
602 cx,
603 &ElementName::from(MACRO),
604 LatexMacroPayload::new(
605 preamble::LABELS_WITH_DISPLAY_TEXT_COMMAND,
606 [LatexArgShape::Mandatory, LatexArgShape::Mandatory],
607 ),
608 vec![(String::from(ARG_SLOT), text), (String::from(ARG_SLOT), group)],
609 )
610}
611
612/// Returns the keys and words of a `zref-clever` reference type, which
613/// [`stage_reference_type_setup`] writes as
614/// `\zcRefTypeSetup{<type>}{<key>={<word>},…}`. `words` holds the prefix
615/// words (such as `Theorem`) that FLM's other outputs write before the number
616/// of a reference to the type's targets. A feature that declares a
617/// `zref-clever` reference type for its numbered constructs calls it; the
618/// theorems and floats features do.
619///
620/// The keys are the package's, each mapped to the variant of `words` that
621/// FLM itself writes where the recomposed LaTeX's reference hook asks the
622/// package for that key
623/// ([`refs_piece`](crate::stdlib::backends::latex::preamble::refs_piece)):
624///
625/// | key | words |
626/// |---|---|
627/// | `Name-sg`, `Name-pl` — printed for `S` and `capital` | the [`CAPITAL_VARIANT`], else the base words |
628/// | `name-sg`, `name-pl` — printed by default and for `lowercase` | the [`LOWERCASE_VARIANT`], else the base words |
629/// | `Name-sg-ab`, `name-sg-ab`, `Name-pl-ab`, `name-pl-ab` — printed for `abbreviated` | the [`ABBREVIATED_VARIANT`], where `words` declares it; the keys are left out otherwise |
630///
631/// The abbreviated pair of words serves the capitalized and the lowercase
632/// abbreviated keys alike. Each word is given without the tie that joins it
633/// to a number on FLM's outputs (a trailing `~`) and without the whitespace
634/// around it (`Fig.~` gives `Fig.`), since `zref-clever` places its own space
635/// between the name and the number. The words are FLM text, which the caller
636/// compiles.
637///
638/// The keys come in the order of the table: `Name-sg`, `name-sg`, `Name-pl`,
639/// `name-pl`, then the four abbreviated keys.
640pub fn reference_type_words(words: &PrefixWords) -> Vec<(&'static str, &str)> {
641 let base = &words.base;
642 let capital = words.variants.get(CAPITAL_VARIANT).unwrap_or(base);
643 let lowercase = words.variants.get(LOWERCASE_VARIANT).unwrap_or(base);
644 let mut keys = vec![
645 ("Name-sg", untied(&capital.one)),
646 ("name-sg", untied(&lowercase.one)),
647 ("Name-pl", untied(&capital.other)),
648 ("name-pl", untied(&lowercase.other)),
649 ];
650 if let Some(abbreviated) = words.variants.get(ABBREVIATED_VARIANT) {
651 let (one, other) = (untied(&abbreviated.one), untied(&abbreviated.other));
652 keys.extend([("Name-sg-ab", one), ("name-sg-ab", one), ("Name-pl-ab", other), ("name-pl-ab", other)]);
653 }
654 keys
655}
656
657/// `word` without the tie that joins it to a number on FLM's own outputs (a
658/// trailing `~`) and without the whitespace around it: `Fig.~` gives `Fig.`.
659fn untied(word: &str) -> &str {
660 let word = word.trim();
661 word.strip_suffix('~').unwrap_or(word).trim_end()
662}
663
664/// Stages `\zcRefTypeSetup{<type>}{<key>={<word>},…}`, the declaration of
665/// the `zref-clever` reference type `type_name`, with its keys and words in
666/// the order of `keys` (the keys of [`reference_type_words`], each word
667/// compiled as FLM content, which is lowered here), and requires the package.
668/// Returns the staged nodes. The caller places the declaration where it
669/// belongs in the style file, with any condition it is guarded by or any
670/// text that follows it.
671///
672/// # Errors
673///
674/// Returns [`LowerError`] when a word could not be lowered or a node could
675/// not be built, or when the calling rule did not declare that it produces
676/// `flm.pres.latex.raw`.
677pub fn stage_reference_type_setup(
678 cx: &mut LowerCx<'_>,
679 lw: &mut dyn Lowerer,
680 type_name: &str,
681 keys: &[(&'static str, Arc<NodeTree<Flm>>)],
682) -> Result<Vec<BuildId>, LowerError> {
683 lw.require(&Name::from(packages::ZREF_CLEVER));
684 let raw = |cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str| {
685 lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
686 };
687 let mut body = vec![raw(cx, lw, &format!("\\zcRefTypeSetup{{{type_name}}}{{"))?];
688 for (at, (key, word)) in keys.iter().enumerate() {
689 let separator = if at == 0 { "" } else { "," };
690 body.push(raw(cx, lw, &format!("{separator}{key}={{"))?);
691 body.extend(lw.splice(cx, word)?);
692 body.push(raw(cx, lw, "}")?);
693 }
694 body.push(raw(cx, lw, "}")?);
695 Ok(body)
696}
697
698/// The implementation of [`REF_LATEX_RULE`]: it writes the reference hook
699/// `\flmRef` (or `\zcref` with the hooks off) around the spelling of each
700/// target, separated by commas, with the options as an optional argument,
701/// wrapped in `\NoCaseChange` when [`protect`](RefsRecomposeOptions::protect)
702/// is on. See the module documentation.
703#[derive(Debug, Default, Clone, Copy)]
704pub struct RefLatexRule;
705
706impl Lower for RefLatexRule {
707 fn lower(
708 &self,
709 node: NodeRef<'_, Flm>,
710 cx: &mut LowerCx<'_>,
711 lw: &mut dyn Lowerer,
712 ) -> Result<Lowering, LowerError> {
713 let options = lw.option::<RefsRecomposeOptions>()?.clone();
714 let hooks = label_hooks(lw)?;
715 let target = staged_target(cx, lw, &node)?;
716 // With the hook, the recomposed LaTeX names `\flmRef` and the style file
717 // says what it does; without it, the recomposed LaTeX writes the command
718 // the hook's default would have run and requests its package itself.
719 let command = if hooks {
720 lw.require(&Name::from(preamble::REFS));
721 preamble::REF_COMMAND
722 } else {
723 lw.require(&Name::from(packages::ZREF_CLEVER));
724 ZCREF_COMMAND
725 };
726 let mut shapes = Vec::new();
727 let mut slots = Vec::new();
728 if let Some(keyvals) = stage_ref_options(cx, lw, &node)? {
729 shapes.push(LatexArgShape::Optional);
730 slots.push((String::from(ARG_SLOT), keyvals));
731 }
732 shapes.push(LatexArgShape::Mandatory);
733 slots.push((String::from(ARG_SLOT), target));
734 let mut reference = lw.pres_slots_with(
735 cx,
736 &ElementName::from(MACRO),
737 LatexMacroPayload::new(command, shapes),
738 slots,
739 )?;
740 if options.protect {
741 reference = protected(cx, lw, reference)?;
742 }
743 Ok(Lowering::Emit(vec![reference]))
744 }
745}
746
747/// Stages the targets of a reference node (a `\ref` or a `\hyperref`) as the
748/// content of its target argument: for each target, the safe label that the
749/// safe-labels stage allocated, or the value name a synthesized value spliced
750/// at lowering gives it, or the label as the document wrote it where its type
751/// is written raw ([`target_spelling`], [`stage_spelling`]); several targets
752/// are separated by commas. A node whose target could not be read stages
753/// nothing; a target holding a template's placeholder cannot be written
754/// ([`read_target_at_lowering`]).
755///
756/// # Errors
757///
758/// Returns [`LowerError`] when the target holds a template's placeholder
759/// ([`LowerError::PlaceholderCharacters`]), when the safe-labels table cannot
760/// be read, when a node could not be built, or when the calling rule did not
761/// declare that it produces `flm.pres.latex.raw`.
762fn staged_target(
763 cx: &mut LowerCx<'_>,
764 lw: &mut dyn Lowerer,
765 node: &NodeRef<'_, Flm>,
766) -> Result<Vec<BuildId>, LowerError> {
767 read_target_at_lowering(node)?;
768 let targets = reference_targets(node).unwrap_or_default();
769 let mut out = Vec::with_capacity(targets.len());
770 for (index, target) in targets.iter().enumerate() {
771 if index > 0 {
772 out.push(lw.text(cx, ",")?);
773 }
774 let spelling = target_spelling(lw, &target.text, target.label.as_ref())?;
775 out.extend(stage_spelling(cx, lw, &spelling)?);
776 }
777 Ok(out)
778}
779
780/// Checks that the target of the reference node `node` (its argument named
781/// [`TARGET_ARG`]) can be written; it returns nothing of the target. It reads
782/// the target as characters at lowering ([`chars_at_lowering`]), which writing
783/// it requires, since a label's safe label is looked up by its characters,
784/// and discards them; the rule then reads the target through the readers the
785/// label scan ([`SCAN`](super::SCAN)) uses. Nothing is read where the node has
786/// no such argument, and
787/// content that is not characters passes, the target then pointing at
788/// nothing, as the label scan reads it.
789///
790/// Every recomposition rule of a reference command calls it before it writes
791/// its target: those of `\ref`, `\hyperref` and the math feature's
792/// `\eqref`.
793///
794/// # Errors
795///
796/// Returns [`LowerError::PlaceholderCharacters`] for a target holding a
797/// placeholder of a template lowered unchanged, whose characters only a call
798/// supplies: the user definition's use sites are then expanded (see the
799/// [module documentation](self#a-target-that-holds-a-template-placeholder)).
800pub fn read_target_at_lowering(node: &NodeRef<'_, Flm>) -> Result<(), LowerError> {
801 if let Ok(Some(content)) = node.argument_content_nodes_named(TARGET_ARG) {
802 // Characters or not, the target is then read by the label scan's
803 // own readers; only the outcome for a placeholder acts here.
804 let _characters = chars_at_lowering(content.iter())?;
805 }
806 Ok(())
807}
808
809/// Wraps a staged reference in `\NoCaseChange{\protect …}`, which keeps it
810/// out of a command that changes the case of its argument, and requests the
811/// package that supplies `\NoCaseChange`: what
812/// [`protect`](RefsRecomposeOptions::protect) asks for, written the same way
813/// for either reference command.
814///
815/// The LaTeX kernel defines `\NoCaseChange` from its 2022 release on, and the
816/// `textcase` package supplies it on every kernel, so the rule requests that
817/// package.
818///
819/// # Errors
820///
821/// Returns [`LowerError`] when a node could not be built, or when the calling
822/// rule did not declare that it produces `flm.pres.latex.macro` and
823/// `flm.pres.latex.raw`.
824fn protected(
825 cx: &mut LowerCx<'_>,
826 lw: &mut dyn Lowerer,
827 reference: BuildId,
828) -> Result<BuildId, LowerError> {
829 lw.require(&Name::from(packages::TEXTCASE));
830 let protect =
831 lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new("\\protect"), Vec::new())?;
832 lw.pres_slots_with(
833 cx,
834 &ElementName::from(MACRO),
835 LatexMacroPayload::new(preamble::NO_CASE_CHANGE, [LatexArgShape::Mandatory]),
836 vec![(String::from(ARG_SLOT), vec![protect, reference])],
837 )
838}
839
840/// The implementation of [`HYPERREF_LATEX_RULE`]: it writes the hook
841/// `\flmHyperref` (or the `hyperref` package's `\hyperref` with the hooks
842/// off) around the target's spelling and the author's text, wrapped in
843/// `\NoCaseChange` when [`protect`](RefsRecomposeOptions::protect) is on. See
844/// the module documentation.
845#[derive(Debug, Default, Clone, Copy)]
846pub struct HyperrefLatexRule;
847
848impl Lower for HyperrefLatexRule {
849 fn lower(
850 &self,
851 node: NodeRef<'_, Flm>,
852 cx: &mut LowerCx<'_>,
853 lw: &mut dyn Lowerer,
854 ) -> Result<Lowering, LowerError> {
855 let options = lw.option::<RefsRecomposeOptions>()?.clone();
856 let hooks = label_hooks(lw)?;
857 let target = staged_target(cx, lw, &node)?;
858 // The author's text is content of the document and is recomposed as
859 // content: a text a parse recovery left absent writes an empty group
860 // and is not reported a second time.
861 let shown = lower_arg_named_or_nothing(cx, lw, &node, TEXT_ARG)?;
862 // With the hook, the recomposed LaTeX names `\flmHyperref` and the
863 // style file says what it does — link the text through `hyperref`
864 // where the document loaded that package, print it alone where it did
865 // not. Without the hook, the recomposed LaTeX writes the package's own
866 // command and requests the package itself, so the choice the hook
867 // leaves to the author is made here.
868 // The two identifiers are spelled alike and are different things:
869 // `preamble::HYPERREF` is the definition piece that defines the hook
870 // `\flmHyperref`, `packages::HYPERREF` the LaTeX package `hyperref`
871 // that defines `\hyperref`.
872 let (command, shapes) = if hooks {
873 let hyperref_piece = preamble::HYPERREF;
874 lw.require(&Name::from(hyperref_piece));
875 (
876 preamble::HYPERREF_COMMAND,
877 vec![LatexArgShape::Mandatory, LatexArgShape::Mandatory],
878 )
879 } else {
880 let hyperref_package = packages::HYPERREF;
881 lw.require(&Name::from(hyperref_package));
882 (
883 preamble::HYPERREF_PACKAGE_COMMAND,
884 vec![LatexArgShape::Optional, LatexArgShape::Mandatory],
885 )
886 };
887 let mut reference = lw.pres_slots_with(
888 cx,
889 &ElementName::from(MACRO),
890 LatexMacroPayload::new(command, shapes),
891 vec![(String::from(ARG_SLOT), target), (String::from(ARG_SLOT), shown)],
892 )?;
893 if options.protect {
894 reference = protected(cx, lw, reference)?;
895 }
896 Ok(Lowering::Emit(vec![reference]))
897 }
898}
899
900/// The two recomposition rules, ready to be registered by the feature: each
901/// reads the safe-labels table, the value names, its own render options and
902/// those of the backend, produces `flm.pres.latex.macro` and
903/// `flm.pres.latex.raw`, and is the default for its own element on the
904/// `latex-recomposed` backend only.
905pub fn latex_rules() -> Vec<LoweringRule> {
906 // Each rule reads both option types: the feature's own for the
907 // protection, and the backend's for the hooks.
908 let decl = || {
909 LoweringDecl::new()
910 .reads(SAFE_LABELS)
911 .reads(VALUE_SAFE_LABELS)
912 .option::<RefsRecomposeOptions>()
913 .option::<LatexRecomposedRenderOptions>()
914 .produces(MACRO)
915 .produces(RAW)
916 };
917 vec![
918 LoweringRule::new(
919 REF_LATEX_RULE,
920 REF,
921 decl(),
922 Arc::new(RefLatexRule),
923 DefaultMark::OnBackends(vec![BACKEND.into()]),
924 )
925 .docs(
926 "a `\\ref` lowers to the LaTeX hook `\\flmRef` (or to `\\zcref` with the \
927 latex-recomposed backend's render option `label_hooks` off) around the safe labels of its targets, its options as an \
928 optional argument",
929 ),
930 LoweringRule::new(
931 HYPERREF_LATEX_RULE,
932 HYPERREF,
933 decl(),
934 Arc::new(HyperrefLatexRule),
935 DefaultMark::OnBackends(vec![BACKEND.into()]),
936 )
937 .docs(
938 "a `\\hyperref` lowers to the LaTeX hook `\\flmHyperref` (or to `\\hyperref` with the \
939 latex-recomposed backend's render option `label_hooks` off) around the safe label of its target and the \
940 author's text, recomposed as content",
941 ),
942 ]
943}
944
945/// Registers what the `refs` feature contributes to the lowering of the
946/// `latex-recomposed` backend: the peer declarations of the backend and of
947/// the two LaTeX constructs the rules stage, then [`latex_rules`]. The
948/// safe-labels tables and stages and the options the rules read belong to the
949/// feature and are registered beside this.
950///
951/// The feature registers neither the backend nor the construct elements; it
952/// writes a peer declaration ([`PeerName`](crate::core::registry::PeerName))
953/// of each, with each construct's payload type as its signature, so that a
954/// registry without the LaTeX features still builds, with the rules set aside
955/// (excluded from rule selection).
956pub fn register(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
957 b.peer_backend(
958 BACKEND,
959 "the latex-recomposed backend, on which the recomposition rules of references are \
960 the default",
961 )?;
962 b.peer_element::<LatexMacroPayload>(
963 MACRO,
964 "the LaTeX macro-call construct, which the recomposition rules of references and the \
965 label helpers stage",
966 )?;
967 b.peer_element::<LatexRawPayload>(
968 RAW,
969 "the LaTeX raw-node construct (text written byte for byte), which the recomposition \
970 rules of references and the label helpers stage",
971 )?;
972 for rule in latex_rules() {
973 b.lowering_rule(rule)?;
974 }
975 Ok(())
976}
977
978#[cfg(test)]
979mod tests {
980 use super::*;
981 use crate::stdlib::features::numbering::PluralWords;
982
983 #[test]
984 fn a_word_loses_the_tie_to_its_number() {
985 assert_eq!(untied("Fig.~"), "Fig.");
986 assert_eq!(untied("Figures~"), "Figures");
987 assert_eq!(untied("Table"), "Table");
988 assert_eq!(untied(" Tab. "), "Tab.");
989 }
990
991 #[test]
992 fn the_reference_type_keys_take_the_variants_flm_writes_for_them() {
993 // The capital variant for `Name-*`, the lowercase one for `name-*`,
994 // the base words where either is absent.
995 let words = PrefixWords::new("Fig.~", "Figs.~")
996 .with_variant(CAPITAL_VARIANT, PluralWords::new("Figure~", "Figures~"));
997 assert_eq!(
998 reference_type_words(&words),
999 [("Name-sg", "Figure"), ("name-sg", "Fig."), ("Name-pl", "Figures"), ("name-pl", "Figs.")]
1000 );
1001 let words = PrefixWords::new("Lemma", "Lemmas")
1002 .with_variant(LOWERCASE_VARIANT, PluralWords::new("lemma", "lemmas"))
1003 .with_variant(ABBREVIATED_VARIANT, PluralWords::new("Lem.", "Lems."));
1004 assert_eq!(
1005 reference_type_words(&words),
1006 [
1007 ("Name-sg", "Lemma"),
1008 ("name-sg", "lemma"),
1009 ("Name-pl", "Lemmas"),
1010 ("name-pl", "lemmas"),
1011 ("Name-sg-ab", "Lem."),
1012 ("name-sg-ab", "Lem."),
1013 ("Name-pl-ab", "Lems."),
1014 ("name-pl-ab", "Lems."),
1015 ]
1016 );
1017 }
1018
1019 #[test]
1020 fn the_two_spellings_are_told_apart_by_the_table() {
1021 let mut table = SafeLabels::default();
1022 let sec = Label::new("sec", "a");
1023 table.allocate(REF_DOMAIN, &sec.to_string());
1024 assert_eq!(
1025 label_spelling(&table, "sec:a", Some(&sec)),
1026 LabelSpelling::Safe(String::from("ref1"))
1027 );
1028 // A type marked raw is allocated nothing and written as written.
1029 let raw = Label::new("fig", "b");
1030 assert_eq!(
1031 label_spelling(&table, "fig:b", Some(&raw)),
1032 LabelSpelling::Raw(String::from("fig:b"))
1033 );
1034 // A label with no type is allocated a name like any other and
1035 // written by it; the stage keys it by its text.
1036 table.allocate(REF_DOMAIN, "plain");
1037 assert_eq!(
1038 label_spelling(&table, "plain", None),
1039 LabelSpelling::Safe(String::from("ref2"))
1040 );
1041 assert_eq!(label_spelling(&table, "plain", None).text(), "ref2");
1042 }
1043
1044 #[test]
1045 fn each_rule_is_the_default_for_its_element_on_the_recomposed_backend_only() {
1046 let rules = latex_rules();
1047 assert_eq!(rules.len(), 2);
1048 assert_eq!(rules[0].element, REF);
1049 assert_eq!(rules[1].element, HYPERREF);
1050 for rule in &rules {
1051 assert!(rule.default.is_specific_to(&BACKEND.into()));
1052 assert_eq!(rule.decl.reads.len(), 2);
1053 assert_eq!(rule.decl.produces.len(), 2);
1054 // Each reads both option types — the feature's own for the
1055 // protection, the backend's for the hooks.
1056 assert_eq!(rule.decl.options.len(), 2);
1057 }
1058 }
1059}