flm_core/stdlib/features/xnotes/latex.rs
1//! The lowering rules of the [`xnotes`](super) feature for the
2//! `latex-recomposed` backend (its recomposition rules): each xnote is written back as a LaTeX command
3//! of its xnote kind's own, `\flmXN<kind>`, which the style file defines and a
4//! LaTeX author may redefine.
5//!
6//! | written | LaTeX |
7//! |---|---|
8//! | `\footnote{Except the empty one.}` | `\flmXNfootnote{Except the empty one.}` |
9//! | `\footnote[\label{fn:a}]{See the appendix.}` | `\flmXNfootnote[{\flmLabels{\label{ref1}}}]{See the appendix.}` |
10//! | `\footnote{First paragraph.`, a blank line, `Second paragraph.}` | `\flmXNfootnote{First paragraph.`, a blank line, `Second paragraph.}` |
11//! | `\endnote{…}`, a second kind `endnote` | `\flmXNendnote{…}` |
12//!
13//! # The command
14//!
15//! An xnote of the xnote kind `<kind>` is written
16//! `\flmXN<kind>[<labels>]{<content>}` (the rule [`LATEX_RULE`], through
17//! [`stage_latex`]). The letters `XN`, for *xnote*, identify the feature, not
18//! one kind, as the letter `U` identifies the document's own definitions
19//! ([`names`](crate::stdlib::backends::latex::names)): the command of every
20//! kind is `\flmXN` followed by the kind's name, which is made of ASCII
21//! letters ([`XnoteKind::validate`]) and so makes a LaTeX command name as
22//! written.
23//!
24//! The optional argument is written only where the xnote carries labels. It
25//! holds the labels, each as its safe label (the key the recomposed LaTeX
26//! writes for an FLM label, `ref1`, `ref2`, …; see
27//! [`SafeLabels`]), wrapped in the
28//! LaTeX hook `\flmLabels` exactly as a heading's labels are
29//! ([`stage_label_group`](crate::stdlib::features::refs::stage_label_group);
30//! with the render option
31//! [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)
32//! off, the labels are written bare). A LaTeX hook is a macro that the
33//! recomposed LaTeX writes and the style file defines with a plain default,
34//! which a user redefines in the document's preamble (see
35//! [`preamble`] and [the LaTeX
36//! hooks](crate::guide::rendering#the-latex-hooks)). The content is written
37//! through the ordinary rules: text escaped, commands as their rules write
38//! them, a blank line as a blank line, so that a note of two paragraphs is two
39//! paragraphs inside the argument.
40//!
41//! The same command is written regardless of the kind's placement: a kind
42//! that the other outputs show in place is passed to LaTeX like any other,
43//! and a LaTeX author who wants it set differently redefines the command.
44//! The refused content of the optional argument
45//! ([`BadLabelArgument`](super::BadLabelArgument)) and an empty xnote
46//! ([`Empty`](super::Empty)) are reported as on every output.
47//!
48//! # Nested xnotes and xnotes in synthesized values
49//!
50//! An xnote written inside another is written as any xnote, labels included,
51//! as a command inside the other's argument, and LaTeX sets it as it sets a
52//! footnote inside a footnote: LaTeX's own `\footnote` prints the inner
53//! note's mark and number and leaves the inner note's text unset, so a label
54//! on the inner note is undefined there. No short definition of the command
55//! from LaTeX's own footnote commands (`\footnotemark`, `\footnotetext`) sets
56//! nested notes, so the default definition leaves them to the LaTeX author,
57//! who redefines the command to set them.
58//!
59//! An xnote in content lowered as a [synthesized
60//! value](crate::guide::concepts_overview#synthesized-values) (the template
61//! of a user definition kept as a call, which the style file holds, or a
62//! list's own label template) is written as its command there too: LaTeX
63//! sets the note wherever the value is used, and no missing record is
64//! reported. The other outputs write no mark for an xnote in content that the
65//! run builds itself, apart from the document's trees (such as a list's own
66//! label template), and report that the table of xnotes holds no record for
67//! it.
68//!
69//! # Numbers in LaTeX and in FLM
70//!
71//! Nothing in this module reads the table of xnotes or a number: LaTeX
72//! numbers the notes it sets. For a kind numbered through the whole document
73//! and passed to LaTeX's `\footnote` (the default kind `footnote`), the
74//! numbers LaTeX prints are the ones FLM computes, because both count in
75//! document order; a nested xnote keeps them in step too, since FLM numbers
76//! it after the xnote that holds it and LaTeX numbers it in the same order.
77//! The numbers differ in these cases:
78//!
79//! - A kind numbered within another counter
80//! ([`within`](super::XnoteKind::within)) restarts its numbers in FLM where
81//! that counter advances; LaTeX restarts the counter of the kind's LaTeX
82//! command only where the document class or the author's preamble resets
83//! it.
84//! - A second xnote kind that is also passed to `\footnote` (the default
85//! [`latex_command`](super::XnoteKind::latex_command)) shares LaTeX's
86//! footnote counter, so its numbers in LaTeX continue from the footnotes'.
87//! A LaTeX command with a counter of its own keeps them apart.
88//! - An xnote in a list's own label template is set by LaTeX beside every
89//! item's label, and again inside every `\ref` to an item that prints the
90//! label template (every `\ref` to an item of a list with no reference
91//! template of its own, since the `enumitem` package's `ref=` defaults to
92//! `label=`), whereas the other outputs write no mark there. Every later
93//! note of that counter is then numbered higher in LaTeX, by as many notes.
94//!
95//! # The definition in the style file
96//!
97//! Every xnote kind has a **definition piece** of its own,
98//! `flm.latex.def.xnotes.<kind>` ([`definition_piece`]): a unit of LaTeX
99//! definitions that a feature registers under an identifier
100//! ([`LatexPreambleDef`]). The rule requires it, so the style file holds it
101//! exactly when the document holds an xnote of that kind. For the kind
102//! `footnote` it reads
103//!
104//! ```latex
105//! % \flmXNfootnote[<labels>]{<note>}: a note of the kind `footnote' in the FLM document;
106//! % by default it passes the note, its labels first, to \footnote.
107//! % Redefine it to set these notes another way.
108//! \ProvideDocumentCommand\flmXNfootnote{+O{} +m}{\footnote{#1#2}}
109//! ```
110//!
111//! The default definition passes the note to the kind's
112//! [`latex_command`](XnoteKind::latex_command), with its labels first inside
113//! that command's argument: LaTeX's `\footnote` makes a label written in its
114//! text refer to the footnote's number, so a reference to the label prints
115//! the footnote's number. The command is defined with
116//! `\ProvideDocumentCommand`, the guarded form of a macro that a definition
117//! piece offers a user ([how a piece is
118//! written](crate::stdlib::backends::latex::preamble#how-a-piece-is-written)),
119//! so a definition the author made before loading the style file takes
120//! precedence. The command is robust, so an xnote inside a heading's title
121//! survives being written to the table of contents, and `+` lets its argument
122//! hold a paragraph break.
123//!
124//! The piece requests no LaTeX package: the author decides which LaTeX
125//! command sets a kind, and a kind whose command needs a package (an
126//! `endnote` kind passed to `\endnote`, which the `endnotes` package defines)
127//! gets the package from the author's own preamble, through the render
128//! options that add packages and preamble text
129//! ([`extra_packages`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::extra_packages),
130//! [`extra_preamble`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::extra_preamble)).
131//! An unnumbered kind gets the same default; a LaTeX author who wants such
132//! notes set as asides redefines the command, for instance
133//! `\ProvideDocumentCommand\flmXNsidenote{+O{} +m}{~[#1#2]}`, before loading
134//! the style file.
135//!
136//! # The list, the content pointer and content shown again
137//!
138//! The recomposed LaTeX places no list of xnotes by default: LaTeX sets each
139//! xnote where its command is written, and the backend places only the
140//! document-level pieces ([`Piece`](crate::core::piece::Piece)) that a render
141//! request lists for it
142//! ([`PiecesRenderOptions`](crate::stdlib::backends::pieces::PiecesRenderOptions)).
143//! The list element of every kind ([`list_element_name`]) still has a rule on
144//! this backend, [`ListLatexRule`], which writes nothing, so that a list a
145//! render places anyway writes nothing, and because a plan checks that its
146//! backend can lower every element the registry holds; so do the content
147//! pointer that the lists hold ([`PointerLatexRule`]) and the node that
148//! represents an xnote in content shown again ([`MarkOfLatexRule`]).
149//!
150//! # Registration
151//!
152//! The rules are marked default on the `latex-recomposed` backend only. They
153//! are registered under peer declarations
154//! ([`PeerName`](crate::core::registry::PeerName)) of that backend, of the
155//! LaTeX constructs they stage and of the table they read. The `xnotes`
156//! feature registers its own rules (the xnote's, the content pointer's, the
157//! mark-of node's) with these peer declarations, and
158//! [`contribute_kind`](super::contribute_kind) registers the list rule of
159//! each xnote kind with them, on behalf of the feature that contributes the
160//! kind. A registry without the LaTeX features therefore
161//! builds, with the rules set aside (excluded from rule selection), and a
162//! feature whose own rule calls [`stage_latex`] declares nothing more.
163
164use std::sync::Arc;
165
166use techy::core::node::{BuildId, NodeRef};
167
168use crate::core::lowering::{
169 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
170};
171use crate::core::registry::{BuildError, FeatureBuilder};
172use crate::lang::Flm;
173use crate::model::element::element_value;
174use crate::model::names::{ElementName, Name, RuleName};
175use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
176use crate::stdlib::backends::latex::preamble::{self, LatexPreambleDef};
177use crate::stdlib::backends::latex::{LatexArgShape, LatexMacroPayload, LatexRawPayload};
178use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
179use crate::stdlib::backends::lowering::lower_run;
180use crate::stdlib::features::refs::{self, LabelUse, SAFE_LABELS, SafeLabels};
181
182use super::config::XnoteKind;
183use super::lower::{report_empty, report_labels, Content};
184use super::{labels_of, list_element_name, XnoteElement, CONTENT_POINTER, MARK_OF, XNOTE};
185
186/// The name of the recomposition rule of an xnote (its lowering rule on the
187/// `latex-recomposed` backend), `flm.xnotes.xnote.lower.latex-recomposed`
188/// ([`XnoteLatexRule`]).
189pub const LATEX_RULE: &str = "flm.xnotes.xnote.lower.latex-recomposed";
190
191/// The prefix of the LaTeX command that writes an xnote, `flmXN`: the command
192/// of the xnote kind `<kind>` is `\flmXN<kind>` ([`command_name`]).
193pub const COMMAND_PREFIX: &str = "flmXN";
194
195/// The LaTeX command, without the backslash, that writes an xnote of the
196/// xnote kind `kind` and that its definition piece defines: `flmXN<kind>`
197/// (`flmXNfootnote`).
198pub fn command_name(kind: &str) -> String {
199 format!("{COMMAND_PREFIX}{kind}")
200}
201
202/// The identifier of the definition piece of the xnote kind `kind`,
203/// `flm.latex.def.xnotes.<kind>` ([`definition_piece`]).
204pub fn definition_piece_name(kind: &str) -> Name {
205 preamble::piece_id(&format!("xnotes.{kind}"))
206}
207
208/// The name of the lowering rule of the list element of the xnote kind
209/// `kind` on the `latex-recomposed` backend,
210/// `flm.xnotes.<kind>.list.lower.latex-recomposed` ([`ListLatexRule`]).
211pub fn list_rule_name(kind: &str) -> RuleName {
212 RuleName::from(format!("flm.xnotes.{kind}.list.lower.latex-recomposed"))
213}
214
215/// The definition piece of the xnote kind `kind`,
216/// `flm.latex.def.xnotes.<kind>` ([`LatexPreambleDef`]): the style file's
217/// definition of `\flmXN<kind>`, which passes the note, its labels first, to
218/// the kind's [`latex_command`](XnoteKind::latex_command).
219///
220/// The piece defines one macro, `\flmXN<kind>[<labels>]{<note>}`, with
221/// `\ProvideDocumentCommand`: guarded, so that the author's own definition
222/// made before the style file is loaded takes precedence; robust, so that it
223/// survives in a heading's title; and with long arguments (`+`), so that a
224/// note may hold a paragraph break. Its default is
225/// `\<latex_command>{#1#2}`. It requires nothing: the LaTeX command to which a
226/// kind is passed is the author's, loaded through the author's own preamble
227/// where a package defines it. Redefine `\flmXN<kind>` to set a kind's notes
228/// differently. See the [module documentation](self).
229pub fn definition_piece(kind: &XnoteKind) -> LatexPreambleDef {
230 let name = kind.name.as_str();
231 let command = command_name(name);
232 let target = &kind.latex_command;
233 LatexPreambleDef::new(
234 &format!("xnotes.{name}"),
235 format!(
236 "% \\{command}[<labels>]{{<note>}}: a note of the kind `{name}' in the FLM document;\n\
237 % by default it passes the note, its labels first, to \\{target}.\n\
238 % Redefine it to set these notes another way.\n\
239 \\ProvideDocumentCommand\\{command}{{+O{{}} +m}}{{\\{target}{{#1#2}}}}\n"
240 ),
241 format!(
242 "`\\{command}[<labels>]{{<note>}}`, the command that writes an xnote of the xnote \
243 kind `{name}`; by default it passes the note, its labels first, to \
244 `\\{target}`"
245 ),
246 )
247}
248
249/// Stages (builds into the lowered tree, through `lw`; see
250/// [`Lowerer`]) one xnote that the node `node` carries, of the
251/// xnote kind `kind`, as the recomposed LaTeX writes it: the command
252/// `\flmXN<kind>` ([`command_name`]), with an optional argument holding
253/// `labels` (each as its safe label, in the LaTeX hook `\flmLabels` unless
254/// the render option `label_hooks` is off) where there is a label,
255/// and a mandatory argument holding the xnote's content lowered through the
256/// ordinary rules. It requires (records as a requirement of the output) the
257/// kind's definition piece ([`definition_piece_name`]).
258///
259/// It is the only function that writes an xnote on this backend: the rule of
260/// an author's `\footnote` calls it, and so does the recomposition rule of an
261/// element of another feature that carries xnotes of a kind that feature
262/// contributed ([`contribute_kind`](super::contribute_kind)).
263///
264/// **What the caller passes.** `nth` is the xnote's position among the
265/// node's xnotes of the kind, counting from 0, and its content is the one
266/// that the node's [`XnoteSource`](super::XnoteSource) aspect returns at that
267/// position, under the pairing that aspect states: an element carrying one
268/// xnote of the kind passes `0`, and an element carrying several calls the
269/// function once for each, each xnote written as a command of its own.
270/// `labels` are the labels that the caller's element read for the xnote, the
271/// ones it passed to the [`ref_points`](super::ref_points) call of that
272/// xnote.
273///
274/// **What the calling rule must declare.** It must declare that it produces
275/// `flm.pres.latex.macro` and `flm.pres.latex.raw` (a raw node: LaTeX text
276/// written as it is), that it may read the references feature's safe-labels
277/// table (`flm.labels.safe`, an optional read: without it, a label is written
278/// as the document wrote it), and that it reads the render options
279/// [`LatexRecomposedRenderOptions`].
280///
281/// **Other cases.**
282///
283/// - A position `nth` beyond the node's xnotes of the kind is written as the
284/// command with no content, and reported as the Warning
285/// [`Empty`](super::Empty).
286/// - An xnote inside another xnote's content is written as any other, labels
287/// included, and LaTeX sets a note inside a note as it does (under the
288/// default definition, its own `\footnote` prints the inner mark and leaves
289/// the inner text unset).
290/// - An xnote in content lowered as a synthesized value (the template of a
291/// user definition kept as a call, which is written into the style file; a
292/// list's own label template; an instantiated use site) is written as the
293/// command, as anywhere else, so that LaTeX sets the note wherever the
294/// value is used. The recomposed LaTeX never leaves an xnote out, whereas
295/// the other outputs write no mark for an xnote in content that the run
296/// builds itself, apart from the document's trees. Its labels are written as anywhere else; in practice a
297/// synthesized value holds none, since a value that declares a label is
298/// refused before it is lowered.
299///
300/// An xnote with no content is still written, and is reported as the Warning
301/// [`Empty`](super::Empty). The function does not report what an element's
302/// own argument holds besides its labels: the caller does, as the rule of
303/// `\footnote` reports [`BadLabelArgument`](super::BadLabelArgument).
304///
305/// # Errors
306///
307/// [`LowerError`] when `node` is not a node of the tree being lowered, when
308/// the calling rule did not declare what it reads or produces, and from the
309/// lowering of the content and the staging of the nodes.
310pub fn stage_latex(
311 cx: &mut LowerCx<'_>,
312 lw: &mut dyn Lowerer,
313 node: &NodeRef<'_, Flm>,
314 kind: &XnoteKind,
315 nth: usize,
316 labels: &[LabelUse],
317) -> Result<Vec<BuildId>, LowerError> {
318 // Written wherever it is lowered, a value included: the template of a
319 // definition kept as a call is lowered as one into the style file, and
320 // the note must reach the page wherever the call stands.
321 report_empty(lw, node, kind, nth)?;
322 let mut shapes = Vec::new();
323 let mut slots = Vec::new();
324 if !labels.is_empty() {
325 let mut staged = Vec::new();
326 for label in labels {
327 staged.push(refs::stage_label(cx, lw, &label.text, label.label.as_ref())?);
328 }
329 shapes.push(LatexArgShape::Optional);
330 slots.push((ARG_SLOT.to_string(), refs::stage_label_group(cx, lw, staged, false)?));
331 }
332 let content = lower_run(cx, lw, Content::of(node, kind, nth).nodes())?;
333 shapes.push(LatexArgShape::Mandatory);
334 slots.push((ARG_SLOT.to_string(), content));
335 lw.require(&definition_piece_name(kind.name.as_str()));
336 let command = lw.pres_slots_with(
337 cx,
338 &ElementName::from(MACRO),
339 LatexMacroPayload::new(command_name(kind.name.as_str()), shapes),
340 slots,
341 )?;
342 Ok(vec![command])
343}
344
345/// The recomposition rule of an xnote, [`LATEX_RULE`]: it reports what the
346/// optional argument holds besides `\label`, as every rule of the element
347/// does, then writes the xnote through [`stage_latex`], with the labels of its
348/// optional argument ([`labels_of`]). The rule does not read the kind's
349/// placement: see the [module documentation](self).
350#[derive(Debug, Default, Clone, Copy)]
351pub struct XnoteLatexRule;
352
353impl Lower for XnoteLatexRule {
354 fn lower(
355 &self,
356 node: NodeRef<'_, Flm>,
357 cx: &mut LowerCx<'_>,
358 lw: &mut dyn Lowerer,
359 ) -> Result<Lowering, LowerError> {
360 let value = element_value::<XnoteElement>(&node)
361 .ok_or_else(|| LowerError::structure("an xnote without its value"))?;
362 let kind = Arc::clone(&value.kind);
363 report_labels(lw, &node, &kind);
364 let (labels, _) = labels_of(&node);
365 // The element carries one xnote, the first of its kind.
366 Ok(Lowering::Emit(stage_latex(cx, lw, &node, &kind, 0, &labels)?))
367 }
368}
369
370/// The lowering rule of an xnote kind's list element on the
371/// `latex-recomposed` backend ([`list_rule_name`]): it writes nothing. LaTeX
372/// sets each xnote where its command is written, so a list of xnotes, placed
373/// only where a render request lists it for this backend, writes nothing; the
374/// rule also exists because a plan checks that its backend can lower every
375/// element the registry holds.
376#[derive(Debug, Default, Clone, Copy)]
377pub struct ListLatexRule;
378
379impl Lower for ListLatexRule {
380 fn lower(
381 &self,
382 _node: NodeRef<'_, Flm>,
383 _cx: &mut LowerCx<'_>,
384 _lw: &mut dyn Lowerer,
385 ) -> Result<Lowering, LowerError> {
386 Ok(Lowering::Emit(Vec::new()))
387 }
388}
389
390/// The name of the rule of the content pointer on the `latex-recomposed`
391/// backend, `flm.xnotes.content-pointer.lower.latex-recomposed`
392/// ([`PointerLatexRule`]).
393pub const POINTER_LATEX_RULE: &str = "flm.xnotes.content-pointer.lower.latex-recomposed";
394
395/// The lowering rule of the content pointer ([`CONTENT_POINTER`]) on the
396/// `latex-recomposed` backend, [`POINTER_LATEX_RULE`]: it writes nothing. A
397/// pointer is placed only in a list of xnotes, which this backend's list
398/// rule writes as nothing; the rule exists because a plan checks that its backend can lower
399/// every element the registry holds.
400#[derive(Debug, Default, Clone, Copy)]
401pub struct PointerLatexRule;
402
403impl Lower for PointerLatexRule {
404 fn lower(
405 &self,
406 _node: NodeRef<'_, Flm>,
407 _cx: &mut LowerCx<'_>,
408 _lw: &mut dyn Lowerer,
409 ) -> Result<Lowering, LowerError> {
410 Ok(Lowering::Emit(Vec::new()))
411 }
412}
413
414/// The lowering rule of the content pointer on the `latex-recomposed` backend
415/// ([`PointerLatexRule`], [`POINTER_LATEX_RULE`]), marked default on that
416/// backend only.
417pub fn pointer_latex_rule() -> LoweringRule {
418 LoweringRule::new(
419 POINTER_LATEX_RULE,
420 CONTENT_POINTER,
421 LoweringDecl::new(),
422 Arc::new(PointerLatexRule),
423 DefaultMark::OnBackends(vec![BACKEND.into()]),
424 )
425 .docs(
426 "a content pointer lowers to nothing: the recomposed LaTeX places no list of xnotes, \
427 because LaTeX sets each xnote where its command is written",
428 )
429}
430
431/// The name of the lowering rule of the node that represents an xnote in
432/// content shown again ([`MARK_OF`]) on the `latex-recomposed` backend,
433/// `flm.xnotes.mark-of.lower.latex-recomposed` ([`MarkOfLatexRule`]).
434pub const MARK_OF_LATEX_RULE: &str = "flm.xnotes.mark-of.lower.latex-recomposed";
435
436/// The lowering rule of the node that represents an xnote in content shown
437/// again ([`MARK_OF`]) on the `latex-recomposed` backend,
438/// [`MARK_OF_LATEX_RULE`]: it writes nothing and reports nothing.
439///
440/// No rule of the standard features lowers content shown again on this
441/// backend, so no such node reaches it: a reference is written back as `\ref`
442/// for LaTeX to resolve; the title that a reference to a heading shows is the
443/// one LaTeX reuses through `\flmHeading`; and the display text of a float or
444/// a defined term is written as the element's own words, with an xnote there
445/// written as its command. Printing the mark of the xnote the node represents
446/// would need a key by which LaTeX knows that xnote, and the backend assigns
447/// no such key to any xnote. The rule exists because a plan checks that its
448/// backend can lower every element the registry holds.
449#[derive(Debug, Default, Clone, Copy)]
450pub struct MarkOfLatexRule;
451
452impl Lower for MarkOfLatexRule {
453 fn lower(
454 &self,
455 _node: NodeRef<'_, Flm>,
456 _cx: &mut LowerCx<'_>,
457 _lw: &mut dyn Lowerer,
458 ) -> Result<Lowering, LowerError> {
459 Ok(Lowering::Emit(Vec::new()))
460 }
461}
462
463/// The lowering rule of the node that represents an xnote in content shown
464/// again on the `latex-recomposed` backend ([`MarkOfLatexRule`],
465/// [`MARK_OF_LATEX_RULE`]), marked default on that backend only.
466pub fn mark_of_latex_rule() -> LoweringRule {
467 LoweringRule::new(
468 MARK_OF_LATEX_RULE,
469 MARK_OF,
470 LoweringDecl::new(),
471 Arc::new(MarkOfLatexRule),
472 DefaultMark::OnBackends(vec![BACKEND.into()]),
473 )
474 .docs(
475 "the mark of an xnote in content shown again lowers to nothing: no rule of the standard \
476 package lowers content shown again on the recomposed LaTeX",
477 )
478}
479
480/// The recomposition rule of an xnote, [`LATEX_RULE`] ([`XnoteLatexRule`]),
481/// marked default on the `latex-recomposed` backend only.
482pub fn latex_rule() -> LoweringRule {
483 LoweringRule::new(
484 LATEX_RULE,
485 XNOTE,
486 LoweringDecl::new()
487 .reads_opt(SAFE_LABELS)
488 .option::<LatexRecomposedRenderOptions>()
489 .produces(MACRO)
490 .produces(RAW),
491 Arc::new(XnoteLatexRule),
492 DefaultMark::OnBackends(vec![BACKEND.into()]),
493 )
494 .docs(
495 "an xnote lowers to `\\flmXN<kind>`, with its labels as the optional argument where it \
496 has any (in the LaTeX hook `\\flmLabels` unless the render option `label_hooks` is \
497 off), and its content, lowered through the rules, as the mandatory argument",
498 )
499}
500
501/// The lowering rule of the list element of the xnote kind `kind` on the
502/// `latex-recomposed` backend ([`ListLatexRule`], [`list_rule_name`]), marked
503/// default on that backend only.
504pub fn list_latex_rule(kind: &str) -> LoweringRule {
505 LoweringRule::new(
506 list_rule_name(kind),
507 list_element_name(kind),
508 LoweringDecl::new(),
509 Arc::new(ListLatexRule),
510 DefaultMark::OnBackends(vec![BACKEND.into()]),
511 )
512 .docs(
513 "the list of a kind's xnotes lowers to nothing, because LaTeX sets each xnote where its \
514 command is written",
515 )
516}
517
518/// Registers the `xnotes` feature's own recomposition rules: the content
519/// pointer's ([`pointer_latex_rule`]), the one of the node that represents an
520/// xnote in content shown again ([`mark_of_latex_rule`]), and, where the
521/// configuration declares an xnote kind with a command (where the element
522/// [`XNOTE`] exists), the xnote's ([`latex_rule`]); with the peer
523/// declarations they need ([`declare_peers`]).
524///
525/// # Errors
526///
527/// The [`BuildError`] of the registry builder when a declaration is made
528/// in a [registration round](crate::core::registry::builder#the-two-registration-rounds)
529/// that does not accept it (from a finalizer, for instance).
530pub(super) fn register(b: &mut FeatureBuilder<'_>, with_element: bool) -> Result<(), BuildError> {
531 declare_peers(b)?;
532 b.lowering_rule(pointer_latex_rule())?;
533 b.lowering_rule(mark_of_latex_rule())?;
534 if with_element {
535 b.lowering_rule(latex_rule())?;
536 }
537 Ok(())
538}
539
540/// Declares what the xnote kind `kind` needs on the LaTeX side, on behalf of
541/// the feature that `b` registers: its definition piece
542/// ([`definition_piece`]), as a peer contribution to the service slot of
543/// definition pieces ([`preamble::SLOT`]); the rule of its list element on
544/// the `latex-recomposed` backend ([`list_latex_rule`]); and the peer
545/// declarations of the names that this rule and a rule calling
546/// [`stage_latex`] use ([`declare_peers`]).
547/// [`contribute_kind`](super::contribute_kind) calls it once per kind.
548///
549/// # Errors
550///
551/// The [`BuildError`] of the registry builder when a declaration is made
552/// in a [registration round](crate::core::registry::builder#the-two-registration-rounds)
553/// that does not accept it (from a finalizer, for instance).
554pub(super) fn declare_kind(b: &mut FeatureBuilder<'_>, kind: &XnoteKind) -> Result<(), BuildError> {
555 declare_peers(b)?;
556 b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece(kind)))?;
557 b.lowering_rule(list_latex_rule(kind.name.as_str()))
558}
559
560/// Makes, on behalf of the feature that `b` registers, a peer declaration
561/// ([`PeerName`](crate::core::registry::PeerName)) of every name that the
562/// LaTeX rules of this module and a rule calling [`stage_latex`] use and that
563/// the LaTeX features or the references feature own: the `latex-recomposed`
564/// backend, the macro and raw constructs and the safe-labels table. A
565/// feature therefore builds in a registry without the LaTeX features, with
566/// its LaTeX rules set aside (excluded from rule selection). Every call
567/// declares every name: the registry merges an identical repeated peer
568/// declaration into the first.
569fn declare_peers(b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
570 // Declared for the calling feature on every call, per kind and for the
571 // feature's own rule alike: the function that adds a rule to the registry
572 // knows the names it uses, where a declaration left to each contributing
573 // feature could be forgotten and would fail only in a registry without the
574 // backend.
575 b.peer_backend(
576 BACKEND,
577 "the latex-recomposed backend, on which the recomposition rules are the default",
578 )?;
579 b.peer_element::<LatexMacroPayload>(
580 MACRO,
581 "the LaTeX family's macro-call construct, which the recomposition rule stages for \
582 `\\flmXN<kind>` and for the labels",
583 )?;
584 b.peer_element::<LatexRawPayload>(
585 RAW,
586 "the LaTeX family's raw node construct, in which a label is written as the document \
587 wrote it",
588 )?;
589 b.peer_table::<SafeLabels>(
590 SAFE_LABELS.name(),
591 "the references feature's safe-labels table, which the recomposition rule reads for the \
592 safe label of each label of an xnote",
593 )?;
594 Ok(())
595}
596
597#[cfg(test)]
598mod tests {
599 use super::*;
600 use crate::stdlib::backends::latex::names::USER_DEFINITION_PREFIX;
601 use crate::stdlib::features::numbering::PrefixWords;
602
603 #[test]
604 fn the_footnote_piece_is_the_designed_definition() {
605 let piece = definition_piece(&XnoteKind::footnote());
606 assert_eq!(piece.id.as_str(), "flm.latex.def.xnotes.footnote");
607 assert!(piece.requires.is_empty());
608 assert_eq!(
609 piece.content,
610 "% \\flmXNfootnote[<labels>]{<note>}: a note of the kind `footnote' in the FLM \
611 document;\n\
612 % by default it passes the note, its labels first, to \\footnote.\n\
613 % Redefine it to set these notes another way.\n\
614 \\ProvideDocumentCommand\\flmXNfootnote{+O{} +m}{\\footnote{#1#2}}\n"
615 );
616 }
617
618 #[test]
619 fn a_kind_s_piece_names_its_own_command_and_hands_the_note_to_its_latex_command() {
620 let kind = XnoteKind::numbered("endnote", PrefixWords::new("Endnote~", "Endnotes~"))
621 .latex_command("endnote");
622 let piece = definition_piece(&kind);
623 assert_eq!(piece.id, definition_piece_name("endnote"));
624 assert!(piece.content.contains("\\ProvideDocumentCommand\\flmXNendnote{+O{} +m}{\\endnote{#1#2}}\n"));
625 // The piece's names are the family's, never the document's.
626 assert!(!piece.content.contains(USER_DEFINITION_PREFIX));
627 }
628
629 #[test]
630 fn the_rules_are_the_defaults_on_the_recomposed_backend_only() {
631 let rule = latex_rule();
632 assert_eq!(rule.name, LATEX_RULE);
633 assert_eq!(rule.element, XNOTE);
634 assert!(rule.default.is_specific_to(&BACKEND.into()));
635 assert!(rule.decl.reads.is_empty());
636 let list = list_latex_rule("footnote");
637 assert_eq!(list.name.as_str(), "flm.xnotes.footnote.list.lower.latex-recomposed");
638 assert_eq!(list.element.as_str(), "flm.xnotes.footnote.list");
639 assert!(list.default.is_specific_to(&BACKEND.into()));
640 assert!(list.decl.produces.is_empty());
641 }
642}