Skip to main content

flm_core/stdlib/features/floats/
latex.rs

1//! The lowering rule of the [`floats`](super) feature for the
2//! `latex-recomposed` backend, which writes a float as the environment
3//! `flmFloat`, and the feature's definition piece, which defines that
4//! environment.
5//!
6//! | written | LaTeX |
7//! |---|---|
8//! | `\begin{figure}\includegraphics{a.png}\caption{A photo}\label{figure:a}\end{figure}` | `\begin{flmFloat}{figure}{NumCap}\flmIncludeGraphics{a.png}\caption{A photo}\flmLabels{\label{ref1}}\end{flmFloat}` |
9//! | `\begin{figure}\includegraphics{a.png}\label{figure:b}\end{figure}` | `\begin{flmFloat}{figure}{NumOnly}\flmIncludeGraphics{a.png}\caption{}\flmLabels{\label{ref1}}\end{flmFloat}` |
10//! | `\begin{figure}\nonumber\includegraphics{a.png}\caption{A photo}\label{figure:a}\end{figure}` | `\begin{flmFloat}{figure}{CapOnly}\flmIncludeGraphics{a.png}\caption{A photo}\phantomsection\flmLabelsWithDisplayText{A photo}{\flmLabels{\label{ref1}}}\end{flmFloat}` |
11//! | `\begin{figure}\includegraphics{a.png}\end{figure}` | `\begin{flmFloat}{figure}{Bare}\flmIncludeGraphics{a.png}\end{flmFloat}` |
12//!
13//! # The environment and its four cases
14//!
15//! The rule [`LATEX_RULE`] ([`FloatLatexRule`]) writes a float as
16//! `\begin{flmFloat}{<type>}{<case>}`, then the float's content, lowered
17//! through the ordinary rules (an image as the `graphics` feature's
18//! `\flmIncludeGraphics`), then `\caption{<caption>}` where the float has a
19//! caption (the caption's full content), then its labels, then
20//! `\end{flmFloat}`. The **case** ([`FloatCase`]) says whether the float is
21//! numbered and whether it has a caption: `NumCap`, `NumOnly`, `CapOnly` or
22//! `Bare`.
23//!
24//! Whether the float is numbered is taken from the float type's numbering
25//! policy and the float's `\label` and `\nonumber`, as [`read_float`] reads
26//! them, and never from the run's counter table: LaTeX numbers the float, so
27//! a float that its policy numbers is written as numbered even when the
28//! numbering feature is not registered. `\nonumber` is never written, since
29//! the case carries it. A `NumOnly` float is written with an empty
30//! `\caption{}` before its labels, so that LaTeX shows its number.
31//!
32//! The labels are written as their safe labels, the keys the recomposed
33//! LaTeX writes for FLM labels (`ref1`, `ref2`, …;
34//! [`SafeLabels`]), inside the LaTeX hook `\flmLabels`
35//! ([`refs::stage_label_group`]). A numbered float's labels follow its
36//! caption, so that they refer to its number. A `CapOnly` float has no number
37//! for a label to refer to: its labels are written after `\phantomsection`,
38//! which places a link target there, inside the LaTeX hook
39//! `\flmLabelsWithDisplayText{<shown>}{\flmLabels{…}}`
40//! ([`refs::stage_labels_with_display_text`]), so that a reference to the
41//! float prints `<shown>`, as on FLM's other outputs. `<shown>` is the
42//! caption's alternative text where its optional argument gives one, else its
43//! full content, lowered as ordinary content. An xnote in it (a note set apart
44//! from the running text, such as a footnote, an endnote or a side note;
45//! [`xnotes`](crate::stdlib::features::xnotes)) is written there too,
46//! and LaTeX typesets it again at every reference, so an author keeps a
47//! footnote out of a reference by giving the caption an alternative text
48//! without it. With the
49//! render option
50//! [`label_hooks`](crate::stdlib::backends::latex_recomposed::LatexRecomposedRenderOptions::label_hooks)
51//! off, the labels are written as bare `\label` commands, without either
52//! LaTeX hook. A `Bare` float's labels are written in `\flmLabels` alone: a
53//! reference to it has nothing to show, which FLM's other outputs report.
54//!
55//! # The definition piece and its LaTeX hooks
56//!
57//! A definition piece ([`LatexPreambleDef`]) is a unit of LaTeX definitions
58//! that a feature registers under an identifier `flm.latex.def.<name>`; a
59//! lowering rule requires it by identifier, and the style file holds the text
60//! of every piece the document requires. A LaTeX hook is a macro or an
61//! environment that the recomposed LaTeX writes and the style file defines
62//! with a plain default, which a user redefines in the document's preamble
63//! ([LaTeX hooks](crate::stdlib::backends::latex::preamble); [the LaTeX
64//! hooks](crate::guide::rendering#the-latex-hooks) in the rendering guide).
65//!
66//! The feature's definition piece, [`PIECE`] (`flm.latex.def.floats`,
67//! [`definition_piece`]), defines the environment `flmFloat` with
68//! `\ProvideDocumentEnvironment{flmFloat}{m m}`. The environment calls
69//! `\flmFloatSetUseConfig<case>{<type>}{<placement>}` to choose how a float of
70//! that case is set, `<placement>` being the value of
71//! `\flmFloatPlacementArgs<case>`, then centers the content with
72//! `\centering`. By default, a numbered float is set in LaTeX's environment of
73//! the type's name at the placement `[tbph]`, which lets LaTeX move it; an
74//! unnumbered float is set where it is written, in a `center` environment in
75//! which `\caption` works as in a float of the type, and a `CapOnly` float's
76//! caption is set without a number, as `\caption*` of the `caption` package,
77//! which the piece requests ([`packages::CAPTION`]; [package
78//! requests](crate::stdlib::backends::latex::packages)). Each of the eight
79//! commands `\flmFloatSetUseConfig<case>` and `\flmFloatPlacementArgs<case>` is
80//! a LaTeX hook: redefine it, before or after loading the style file, to set
81//! floats differently.
82//!
83//! # The reference type of each float type
84//!
85//! The recomposed LaTeX writes a reference through the LaTeX hook `\flmRef`,
86//! whose default is `\zcref` of the `zref-clever` package, which finds a
87//! target's words by its reference type. For each float type that the
88//! document uses, the rule writes a declaration of the type's words as that
89//! reference type
90//! (`\zcRefTypeSetup{figure}{Name-sg={Figure},name-sg={Fig.},Name-pl={Figures},name-pl={Figs.}}`),
91//! mapped as for every reference type of the LaTeX family
92//! ([`refs::reference_type_words`]): the variant `capital` where the type's
93//! words declare it (the base words otherwise) as the capitalized keys, which
94//! `\ref[S]` and `\ref[capital]` print; the variant `lowercase` where
95//! declared (the base words otherwise) as the lowercase keys, which a
96//! reference prints by default; and the variant `abbreviated`, where
97//! declared, as the abbreviated keys. Each word is written without the tie
98//! that joins it to a number on FLM's own outputs, since `zref-clever` puts
99//! its own space between a name and a number. The rule stages this
100//! declaration as a definition construct of kind
101//! [`LatexDefinitionKind::Declaration`], which the style file holds once per
102//! float type, guarded on the control sequence `\flm@float@reftype@<type>`,
103//! which it defines. An author
104//! who wants other words calls `\zcRefTypeSetup` after loading the style
105//! file. The words of every float type are compiled as FLM content once, when
106//! the registry is built; a word that does not compile fails the build.
107//!
108//! # A float type that a host configures
109//!
110//! `figure` and `table` are LaTeX's own environments. The environment of a
111//! float type that a host configures (`diagram`) is written by the type's
112//! name, and the author's LaTeX must define it as a float environment with a
113//! counter of the type's name, for instance through the `newfloat` package,
114//! as for a configured list kind or quotation environment; the style file
115//! declares none.
116//!
117//! The rule reads the float through [`read_float`], as every rule lowering a
118//! float does, so the recomposed LaTeX reports the same problems as the other
119//! backends. The rendering guide shows the result ([floats in the recomposed
120//! LaTeX](crate::guide::rendering#floats-in-the-recomposed-latex)).
121
122use std::collections::BTreeMap;
123use std::sync::{Arc, OnceLock};
124
125use techy::core::node::{BuildId, NodeRef, NodeTree};
126
127use crate::core::lowering::{
128    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
129};
130use crate::core::registry::{BuildError, FeatureBuilder, Finalizer, LateInit, LateInitError};
131use crate::lang::rewrites::userdefs::template::{PlaceholderVocabulary, TemplateLanguage};
132use crate::lang::{BuiltLang, Flm, FlmDiagnostics};
133use crate::model::element::element_value;
134use crate::model::names::{ElementName, Name};
135use crate::stdlib::backends::latex::construct::{ARG_SLOT, DEFINITION, ENVIRONMENT, MACRO, RAW};
136use crate::stdlib::backends::latex::{
137    LatexArgShape, LatexDefinitionKind, LatexDefinitionPayload, LatexEnvironmentPayload,
138    LatexMacroPayload, LatexPreambleDef, LatexRawPayload, packages, preamble,
139};
140use crate::stdlib::backends::latex_recomposed::{BACKEND, LatexRecomposedRenderOptions};
141use crate::stdlib::backends::lowering::{lower_run, lower_written_pieces};
142use crate::stdlib::backends::pres::BODY_SLOT;
143use crate::stdlib::features::numbering::{COUNTERS, compile_text, instantiate_fixed};
144use crate::stdlib::features::refs::{self, ANCHORS, SAFE_LABELS, SafeLabels};
145
146use super::body::{Caption, is_float_field, read_float};
147use super::config::FloatType;
148use super::content::Handlers;
149use super::elements::FloatElement;
150use super::{CAPTION_FIELD, CAPTION_TEXT_ARG, CHECK_HANDLERS, FEATURE, FLOAT, TYPES_SLOT};
151
152/// The name of the float's rule on the `latex-recomposed` backend,
153/// `flm.floats.float.lower.latex-recomposed`, whose body is
154/// [`FloatLatexRule`].
155pub const LATEX_RULE: &str = "flm.floats.float.lower.latex-recomposed";
156
157/// The name of the feature's definition piece, `floats`; its identifier is
158/// `flm.latex.def.floats` ([`PIECE`]).
159pub const PIECE_NAME: &str = "floats";
160
161/// The identifier of the feature's definition piece, `flm.latex.def.floats`
162/// ([`definition_piece`]).
163pub const PIECE: &str = "flm.latex.def.floats";
164
165/// The name of the environment a float is written as, `flmFloat`, a LaTeX
166/// hook that the feature's definition piece defines.
167pub const ENVIRONMENT_NAME: &str = "flmFloat";
168
169/// The prefix of the names of the four commands that choose how a float of
170/// one case is set, `flmFloatSetUseConfig`: `\flmFloatSetUseConfigNumCap` and
171/// the three others, one per [`FloatCase`].
172pub const SET_USE_CONFIG_PREFIX: &str = "flmFloatSetUseConfig";
173
174/// The prefix of the names of the four commands that hold the placement of a
175/// float of one case, `flmFloatPlacementArgs`:
176/// `\flmFloatPlacementArgsNumCap` and the three others, one per
177/// [`FloatCase`].
178pub const PLACEMENT_ARGS_PREFIX: &str = "flmFloatPlacementArgs";
179
180/// The prefix of the control sequence on which the declaration of a float
181/// type's reference type is guarded, `flm@float@reftype@`, followed by the
182/// type's name.
183pub const REFERENCE_TYPE_GUARD_PREFIX: &str = "flm@float@reftype@";
184
185/// How a float is written on the recomposed LaTeX: whether it is numbered,
186/// under its type's numbering policy and its `\label` and `\nonumber`, and
187/// whether it has a caption. The case's name is the second argument of the
188/// environment `flmFloat`: `\begin{flmFloat}{figure}{NumCap}`.
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
190pub enum FloatCase {
191    /// Numbered, with a caption: `Figure 1: A photo`.
192    NumCap,
193    /// Numbered, without a caption: `Figure 1`, written with an empty
194    /// `\caption{}`.
195    NumOnly,
196    /// A caption and no number: `A photo`.
197    CapOnly,
198    /// Neither a number nor a caption.
199    Bare,
200}
201
202impl FloatCase {
203    /// The four cases, in the order in which the definition piece defines
204    /// their commands.
205    pub const ALL: [FloatCase; 4] =
206        [FloatCase::NumCap, FloatCase::NumOnly, FloatCase::CapOnly, FloatCase::Bare];
207
208    /// Returns the case of a float, given whether it is numbered and whether
209    /// it has a caption.
210    pub fn of(numbered: bool, captioned: bool) -> FloatCase {
211        match (numbered, captioned) {
212            (true, true) => FloatCase::NumCap,
213            (true, false) => FloatCase::NumOnly,
214            (false, true) => FloatCase::CapOnly,
215            (false, false) => FloatCase::Bare,
216        }
217    }
218
219    /// Returns the case's name, as the environment's argument and the names
220    /// of the case's two commands write it: `NumCap`, `NumOnly`, `CapOnly`,
221    /// `Bare`.
222    pub fn as_str(self) -> &'static str {
223        match self {
224            FloatCase::NumCap => "NumCap",
225            FloatCase::NumOnly => "NumOnly",
226            FloatCase::CapOnly => "CapOnly",
227            FloatCase::Bare => "Bare",
228        }
229    }
230
231    /// Returns whether a float of the case is numbered.
232    pub fn is_numbered(self) -> bool {
233        matches!(self, FloatCase::NumCap | FloatCase::NumOnly)
234    }
235}
236
237/// Returns the feature's definition piece, `flm.latex.def.floats`, which
238/// defines the environment `flmFloat` and the eight LaTeX hooks it calls, the
239/// commands `\flmFloatSetUseConfig<case>` and `\flmFloatPlacementArgs<case>`
240/// of the four cases. It requests the `caption` package
241/// ([`packages::CAPTION`]) for `\caption*`. See the [module
242/// documentation](self#the-definition-piece-and-its-latex-hooks).
243pub fn definition_piece() -> LatexPreambleDef {
244    LatexPreambleDef::new(
245        PIECE_NAME,
246        "\
247% Floats: a float of FLM's figure, table or a configured float type is
248% written as \\begin{flmFloat}{<type>}{<case>} <content> \\caption{<caption>}
249% <labels> \\end{flmFloat}, <case> being NumCap (numbered, with a caption),
250% NumOnly (numbered, no caption: an empty \\caption{} shows the number),
251% CapOnly (a caption, no number) or Bare (neither).
252% \\flmFloatSetUseConfig<case>{<type>}{<placement>}: how a float of the case is
253%   set. By default a numbered float is set in the environment <type> at
254%   <placement>, and an unnumbered one where it is written, in a center
255%   environment in which \\caption works as in the float <type>; a CapOnly
256%   float's caption is set with no number (\\caption* of the caption package).
257% \\flmFloatPlacementArgs<case>: the placement of a float of the case, [tbph]
258%   for the numbered cases and [h] for the others.
259% The content is centered. Redefine these commands to set floats differently.
260\\providecommand\\flmFloatPlacementArgsNumCap{[tbph]}
261\\providecommand\\flmFloatPlacementArgsNumOnly{[tbph]}
262\\providecommand\\flmFloatPlacementArgsCapOnly{[h]}
263\\providecommand\\flmFloatPlacementArgsBare{[h]}
264\\def\\flm@float@infloat#1#2{\\edef\\flm@float@begin{\\noexpand\\begin{#1}#2}\\def\\flm@float@end{\\end{#1}}}
265\\def\\flm@float@incenter#1{\\def\\flm@float@begin{\\begin{center}\\def\\@captype{#1}}\\def\\flm@float@end{\\end{center}}}
266\\def\\flm@float@starcaption{\\let\\flm@float@caption\\caption\\def\\caption{\\flm@float@caption*}}
267\\ProvideDocumentCommand\\flmFloatSetUseConfigNumCap{m m}{\\flm@float@infloat{#1}{#2}}
268\\ProvideDocumentCommand\\flmFloatSetUseConfigNumOnly{m m}{\\flm@float@infloat{#1}{#2}}
269\\ProvideDocumentCommand\\flmFloatSetUseConfigCapOnly{m m}{\\flm@float@incenter{#1}\\flm@float@starcaption}
270\\ProvideDocumentCommand\\flmFloatSetUseConfigBare{m m}{\\flm@float@incenter{#1}}
271\\ProvideDocumentEnvironment{flmFloat}{m m}{%
272  \\edef\\flm@float@placement{\\csname flmFloatPlacementArgs#2\\endcsname}%
273  \\csname flmFloatSetUseConfig#2\\endcsname{#1}{\\flm@float@placement}%
274  \\flm@float@begin\\centering}{\\flm@float@end}
275",
276        "`\\begin{flmFloat}{type}{case}`: the LaTeX hook environment of a float, with \
277         `\\flmFloatSetUseConfig<case>` and `\\flmFloatPlacementArgs<case>` for each of its four \
278         cases",
279    )
280    .requires([packages::CAPTION])
281}
282
283/// The words of one float type's reference type in `zref-clever`, compiled
284/// as FLM content: the capitalized singular and plural, the lowercase
285/// singular and plural, and the abbreviated ones where the type's words
286/// declare them.
287struct ReferenceWords {
288    /// The keys `Name-sg`, `name-sg`, `Name-pl`, `name-pl`, then the four
289    /// abbreviated keys where declared, each with its word.
290    keys: Vec<(&'static str, Arc<NodeTree<Flm>>)>,
291}
292
293/// The compiled words of every float type of the registry, by type name,
294/// filled once the language is built ([`CompileWords`]).
295#[derive(Default)]
296pub(super) struct TypeWords {
297    by_type: OnceLock<BTreeMap<Name, ReferenceWords>>,
298}
299
300impl std::fmt::Debug for TypeWords {
301    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302        let names: Vec<&Name> = self.by_type.get().map(|by| by.keys().collect()).unwrap_or_default();
303        f.debug_struct("TypeWords").field("by_type", &names).finish()
304    }
305}
306
307/// Compiles the word `text` of the float type `name` as FLM content without
308/// placeholders.
309fn compile_word(
310    name: &Name,
311    text: &str,
312    lang: &BuiltLang,
313    language: &TemplateLanguage,
314) -> Result<Arc<NodeTree<Flm>>, LateInitError> {
315    let what = format!("the words of the float type `{name}`");
316    let refused = |detail: String| {
317        LateInitError::new(format!(
318            "the word `{text}` of the float type `{name}` is not valid FLM text: {detail}"
319        ))
320    };
321    let template = compile_text(text, &what, &PlaceholderVocabulary::new(0), lang, language)
322        .map_err(|error| refused(error.to_string()))?;
323    instantiate_fixed(&template).map_err(refused)
324}
325
326/// Returns the compiled words of `float_type`, under the keys of its
327/// reference type ([`refs::reference_type_words`]).
328fn reference_words(
329    float_type: &FloatType,
330    lang: &BuiltLang,
331    language: &TemplateLanguage,
332) -> Result<ReferenceWords, LateInitError> {
333    let mut keys = Vec::new();
334    for (key, text) in refs::reference_type_words(&float_type.words) {
335        keys.push((key, compile_word(&float_type.name, text, lang, language)?));
336    }
337    Ok(ReferenceWords { keys })
338}
339
340/// The build hook (a [`Finalizer`]) that hands every float type of the
341/// service slot [`TYPES_SLOT`], the feature's own and those other features
342/// contribute, to the late-initialization hook that compiles their words once
343/// the language is built ([`CompileWords`]).
344struct CollectTypes {
345    words: Arc<TypeWords>,
346}
347
348impl Finalizer for CollectTypes {
349    fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
350        let types: Vec<FloatType> = match b.services() {
351            Some(services) => services.services_named::<FloatType>(TYPES_SLOT).cloned().collect(),
352            None => {
353                return Err(BuildError::Feature {
354                    feature: b.feature().clone(),
355                    detail: String::from("the types slot must be assembled before the finalizer runs"),
356                });
357            }
358        };
359        b.late_init(Arc::new(CompileWords { words: Arc::clone(&self.words), types }))
360    }
361}
362
363/// The build hook (a [`LateInit`]) that compiles the words of every float
364/// type as FLM content, once the language is built. A word that does not
365/// compile fails the registry build: the words are configuration, so the
366/// problem is reported once rather than at every float.
367struct CompileWords {
368    words: Arc<TypeWords>,
369    types: Vec<FloatType>,
370}
371
372impl LateInit for CompileWords {
373    fn late_init(&self, lang: &BuiltLang, _diags: &mut FlmDiagnostics) -> Result<(), LateInitError> {
374        let language = TemplateLanguage::new(lang).map_err(|errors| {
375            LateInitError::new(format!(
376                "the template language of the floats feature: {}",
377                errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")
378            ))
379        })?;
380        let mut by_type = BTreeMap::new();
381        for float_type in &self.types {
382            by_type.insert(float_type.name.clone(), reference_words(float_type, lang, &language)?);
383        }
384        // The hook runs once per registration of the feature, and a registry
385        // holds the feature once, so the cell is empty here.
386        let _ = self.words.by_type.set(by_type);
387        Ok(())
388    }
389}
390
391/// The body of [`LATEX_RULE`]: it stages the declaration of the float type's
392/// reference type, which goes to the style file, then the environment
393/// `flmFloat` with the float's type and case as arguments, around its content,
394/// its caption and its labels. See the [module documentation](self).
395#[derive(Debug)]
396pub struct FloatLatexRule {
397    handlers: Arc<Handlers>,
398    words: Arc<TypeWords>,
399}
400
401/// Stages a raw node (`flm.pres.latex.raw`) holding the LaTeX `text`.
402fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
403    lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
404}
405
406/// Stages a call of the macro `\<name>` with arguments of the shapes
407/// `shapes`, the content of each argument given in order in `slots`.
408fn command(
409    cx: &mut LowerCx<'_>,
410    lw: &mut dyn Lowerer,
411    name: &str,
412    shapes: Vec<LatexArgShape>,
413    slots: Vec<Vec<BuildId>>,
414) -> Result<BuildId, LowerError> {
415    lw.pres_slots_with(
416        cx,
417        &ElementName::from(MACRO),
418        LatexMacroPayload::new(name, shapes),
419        slots.into_iter().map(|slot| (String::from(ARG_SLOT), slot)).collect(),
420    )
421}
422
423/// Lowers what a reference to an unnumbered float with a caption prints, as
424/// ordinary content: the caption's alternative text where its optional
425/// argument gives one, else its full content, each as the author wrote it.
426fn shown(
427    cx: &mut LowerCx<'_>,
428    lw: &mut dyn Lowerer,
429    caption: &Caption<'_>,
430) -> Result<Vec<BuildId>, LowerError> {
431    let Some(alt) = &caption.alt else {
432        return lw.lower_arg_named(cx, &caption.node, CAPTION_TEXT_ARG);
433    };
434    lower_written_pieces(cx, lw, alt)
435}
436
437impl FloatLatexRule {
438    /// Stages the declaration of the reference type of `float_type` for the
439    /// style file: `\zcRefTypeSetup{<type>}{<keys>}`, guarded on
440    /// `\flm@float@reftype@<type>`, which it defines.
441    fn reference_type(
442        &self,
443        float_type: &FloatType,
444        cx: &mut LowerCx<'_>,
445        lw: &mut dyn Lowerer,
446    ) -> Result<BuildId, LowerError> {
447        let name = float_type.name.as_str();
448        let words = self
449            .words
450            .by_type
451            .get()
452            .and_then(|by| by.get(&float_type.name))
453            .ok_or_else(|| LowerError::other(format!("the words of the float type `{name}` were not compiled")))?;
454        let mut body = refs::stage_reference_type_setup(cx, lw, name, &words.keys)?;
455        let guard = format!("{REFERENCE_TYPE_GUARD_PREFIX}{name}");
456        body.push(raw(cx, lw, &format!("\\def\\{guard}{{}}"))?);
457        let payload =
458            LatexDefinitionPayload::new(LatexDefinitionKind::Declaration, &guard, 0).of_feature(FEATURE);
459        lw.pres_slots_with(cx, &ElementName::from(DEFINITION), payload, vec![(String::from(BODY_SLOT), body)])
460    }
461}
462
463impl Lower for FloatLatexRule {
464    fn lower(
465        &self,
466        node: NodeRef<'_, Flm>,
467        cx: &mut LowerCx<'_>,
468        lw: &mut dyn Lowerer,
469    ) -> Result<Lowering, LowerError> {
470        let reading = read_float(&node, &self.handlers, lw)?;
471        let fields = &reading.fields;
472        let float_type = &element_value::<FloatElement>(&node)
473            .ok_or_else(|| LowerError::structure("a float without its value"))?
474            .float_type;
475        // The policy's answer, never the counter table's: LaTeX numbers the
476        // float.
477        let case = FloatCase::of(fields.numbered, fields.caption.is_some());
478        lw.require(&Name::from(PIECE));
479        let declaration = self.reference_type(float_type, cx, lw)?;
480        // The body as written, the fields left out: on the raw tree this
481        // backend reads, the fields stand among the body's children.
482        let body: Vec<NodeRef<'_, Flm>> = node.body().map(|body| body.iter().collect()).unwrap_or_default();
483        let mut content = Vec::new();
484        for run in body.split(is_float_field) {
485            content.extend(lower_run(cx, lw, run)?);
486        }
487        let caption = match &fields.caption {
488            Some(caption) => Some(lw.lower_arg_named(cx, &caption.node, CAPTION_TEXT_ARG)?),
489            // A numbered float with no caption: an empty one, so that LaTeX
490            // shows the number.
491            None if case.is_numbered() => Some(Vec::new()),
492            None => None,
493        };
494        if let Some(text) = caption {
495            content.push(command(cx, lw, CAPTION_FIELD, vec![LatexArgShape::Mandatory], vec![text])?);
496        }
497        let mut labels = Vec::new();
498        for written in refs::label_uses_in(fields.body.labels.iter().copied()) {
499            labels.push(refs::stage_label(cx, lw, &written.text, written.label.as_ref())?);
500        }
501        match (&fields.caption, case) {
502            (Some(caption), FloatCase::CapOnly) if !labels.is_empty() => {
503                // No number to refer to: an anchor here, and the labels
504                // showing the caption, as an unnumbered heading's do.
505                lw.require(&Name::from(packages::HYPERREF));
506                content.push(command(cx, lw, preamble::PHANTOMSECTION_COMMAND, Vec::new(), Vec::new())?);
507                let hooks = lw.option::<LatexRecomposedRenderOptions>()?.label_hooks;
508                let group = refs::stage_label_group(cx, lw, labels, false)?;
509                if hooks {
510                    let shown = shown(cx, lw, caption)?;
511                    content.push(refs::stage_labels_with_display_text(cx, lw, shown, group)?);
512                } else {
513                    content.extend(group);
514                }
515            }
516            _ => content.extend(refs::stage_label_group(cx, lw, labels, false)?),
517        }
518        let type_arg = vec![raw(cx, lw, float_type.name.as_str())?];
519        let case_arg = vec![raw(cx, lw, case.as_str())?];
520        let environment = lw.pres_slots_with(
521            cx,
522            &ElementName::from(ENVIRONMENT),
523            LatexEnvironmentPayload::new(ENVIRONMENT_NAME, [LatexArgShape::Mandatory, LatexArgShape::Mandatory]),
524            vec![
525                (String::from(ARG_SLOT), type_arg),
526                (String::from(ARG_SLOT), case_arg),
527                (String::from(BODY_SLOT), content),
528            ],
529        )?;
530        Ok(Lowering::Emit(vec![declaration, environment]))
531    }
532}
533
534/// Returns the float's rule on the `latex-recomposed` backend,
535/// [`LATEX_RULE`], the default on that backend only. It tests a float's
536/// content against the content handlers `handlers` and writes the float
537/// types' compiled words `words`.
538fn latex_rule(handlers: Arc<Handlers>, words: Arc<TypeWords>) -> LoweringRule {
539    LoweringRule::new(
540        LATEX_RULE,
541        FLOAT,
542        LoweringDecl::new()
543            .reads_opt(ANCHORS)
544            .reads_opt(COUNTERS)
545            .reads_opt(SAFE_LABELS)
546            .requires(CHECK_HANDLERS)
547            .option::<LatexRecomposedRenderOptions>()
548            .produces(DEFINITION)
549            .produces(ENVIRONMENT)
550            .produces(MACRO)
551            .produces(RAW),
552        Arc::new(FloatLatexRule { handlers, words }),
553        DefaultMark::OnBackends(vec![BACKEND.into()]),
554    )
555    .docs(
556        "a float lowers to the LaTeX hook environment `flmFloat` over its type and case, \
557         around its content, `\\caption{…}` and its labels, after the declaration of its type's \
558         reference type",
559    )
560}
561
562/// Registers what the feature contributes to the `latex-recomposed` backend:
563/// the peer declarations of the backend, of the LaTeX constructs the rule
564/// stages and of the safe-labels table it reads; the definition piece, as a
565/// peer contribution to the service slot of definition pieces
566/// ([`preamble::SLOT`]); the build hooks that compile the float types' words;
567/// and [`latex_rule`]. A peer declaration
568/// ([`PeerName`](crate::core::registry::PeerName)) tells the registry build
569/// that another feature owns a name. A registry without the LaTeX features
570/// therefore builds, with the rule set aside (excluded from rule selection;
571/// see [`PeerName`](crate::core::registry::PeerName)).
572pub(super) fn register(b: &mut FeatureBuilder<'_>, handlers: Arc<Handlers>) -> Result<(), BuildError> {
573    b.peer_backend(
574        BACKEND,
575        "the latex-recomposed backend, on which the recomposition rule is the default",
576    )?;
577    b.peer_element::<LatexDefinitionPayload>(
578        DEFINITION,
579        "the LaTeX family's definition construct, which the recomposition rule stages for the \
580         declaration of a float type's reference type",
581    )?;
582    b.peer_element::<LatexEnvironmentPayload>(
583        ENVIRONMENT,
584        "the LaTeX family's environment construct, which the recomposition rule stages for the \
585         float",
586    )?;
587    b.peer_element::<LatexMacroPayload>(
588        MACRO,
589        "the LaTeX family's macro-call construct, which the recomposition rule stages for the \
590         caption and the labels",
591    )?;
592    b.peer_element::<LatexRawPayload>(
593        RAW,
594        "the LaTeX family's raw node construct, in which the environment's arguments, the \
595         reference type's keys and a label are written",
596    )?;
597    b.peer_table::<SafeLabels>(
598        SAFE_LABELS.name(),
599        "the references feature's safe-labels table, which the recomposition rule reads for the \
600         safe label of each label",
601    )?;
602    b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
603    let words = Arc::new(TypeWords::default());
604    b.finalizer(Arc::new(CollectTypes { words: Arc::clone(&words) }))?;
605    b.lowering_rule(latex_rule(handlers, words))
606}
607
608#[cfg(test)]
609mod tests {
610    use super::*;
611    use crate::stdlib::backends::latex::preamble::piece_id;
612
613    #[test]
614    fn the_piece_is_named_as_its_identifier_says_and_requests_the_caption_package() {
615        let piece = definition_piece();
616        assert_eq!(piece.id, piece_id(PIECE_NAME));
617        assert_eq!(piece.id.as_str(), PIECE);
618        assert_eq!(piece.requires, [Name::from(packages::CAPTION)]);
619    }
620
621    #[test]
622    fn the_piece_defines_the_environment_and_the_two_commands_of_each_case() {
623        let piece = definition_piece();
624        for case in FloatCase::ALL {
625            for prefix in [SET_USE_CONFIG_PREFIX, PLACEMENT_ARGS_PREFIX] {
626                let name = format!("\\{prefix}{}{{", case.as_str());
627                assert!(piece.content.contains(&name), "{name}");
628            }
629        }
630        assert!(piece.content.contains("\\ProvideDocumentEnvironment{flmFloat}{m m}"));
631        assert!(piece.content.contains("\\providecommand\\flmFloatPlacementArgsNumCap{[tbph]}"));
632        assert!(piece.content.contains("\\providecommand\\flmFloatPlacementArgsCapOnly{[h]}"));
633        assert!(piece.content.contains("\\flm@float@caption*"));
634        assert!(piece.content.contains("\\centering"));
635    }
636
637    #[test]
638    fn the_case_follows_the_number_and_the_caption() {
639        assert_eq!(FloatCase::of(true, true).as_str(), "NumCap");
640        assert_eq!(FloatCase::of(true, false).as_str(), "NumOnly");
641        assert_eq!(FloatCase::of(false, true).as_str(), "CapOnly");
642        assert_eq!(FloatCase::of(false, false).as_str(), "Bare");
643        assert!(FloatCase::NumOnly.is_numbered() && !FloatCase::CapOnly.is_numbered());
644    }
645}