Skip to main content

flm_core/stdlib/features/cells/
latex.rs

1//! The recomposition rule of a table of cells on the `latex-recomposed`
2//! backend ([`LATEX_RULE`], [`CellsLatexRule`]): the table is written as one
3//! call of the LaTeX hook `\flmCellsTable`
4//! ([LaTeX hooks](crate::stdlib::backends::latex::preamble)), which the
5//! feature's definition piece ([`definition_piece`]) defines over the
6//! `tabularray` package.
7//!
8//! A definition piece is a unit of LaTeX definitions that a feature registers
9//! under an identifier `flm.latex.def.<name>`
10//! ([`LatexPreambleDef`]); the style file holds every piece the document
11//! requires. The rendering guide describes the output for LaTeX authors in
12//! [*Tables of cells in the recomposed LaTeX*](crate::guide::rendering#tables-of-cells-in-the-recomposed-latex),
13//! and the LaTeX hooks in general in
14//! [*The LaTeX hooks*](crate::guide::rendering#the-latex-hooks).
15//!
16//! | written | LaTeX |
17//! |---|---|
18//! | `\begin{cells}\celldata<H>{One & Two}\celldata{A & B}\end{cells}` | `\flmCellsTable{cc}{X[-1]X[-1]}{hspan=minimal,`<br>`  cell{1}{1}={}{m, font={\flmCellsHeaderFont}},`<br>`  cell{1}{2}={}{m, font={\flmCellsHeaderFont}},`<br>`  hline{2}={1}{.4pt,solid},`<br>`  hline{2}={2}{.4pt,solid}}{\toprule`<br>`One&Two\\`<br>`A&B\\`<br>`\bottomrule`<br>`}` |
19//! | `\cell<r green>[\merge{1-2};1]{X}` | the entry `cell{1}{1}={r=2}{r}` and the cell's text `\flmCellsSet{green}X` |
20//!
21//! # The call
22//!
23//! A table is written `\flmCellsTable{<natural>}{<fitted>}{<options>}{<rows>}`,
24//! from the table's model as the feature's reader ([`read_grid`]) builds it
25//! and from the positions of the grid that each cell occupies
26//! ([`grid`](crate::stdlib::backends::pres::CellsPayload::grid)):
27//!
28//! - `<natural>` is the column specification of `tabularray`'s `tblr`
29//!   environment with which the table is first set, `c` for each column, and
30//!   `<fitted>` the one with which it is set where it is too wide, `X[-1]`
31//!   for each column;
32//! - `<options>` is `hspan=minimal`, then one `cell{<row>}{<column>}=
33//!   {<span>}{<keys>}` entry for each cell that spans rows or columns
34//!   (`r=2`, `c=3`) or has an alignment or a header kind (its keys: `l`, `c`
35//!   or `r`, else `m`, then `font={\flmCellsHeaderFont}` for a header), then the
36//!   lines: `hline{<row>}={<columns>}{.4pt,solid}` under a cell that heads its
37//!   column (unless it is in the table's last row, which `\bottomrule`
38//!   closes) and at a cell's top or bottom edge where a cell style draws a
39//!   line, and `vline{<column>}={<rows>}{.4pt,solid}` at a cell's left or
40//!   right edge where a cell style draws one; one entry per cell and edge,
41//!   rows and columns counted from 1 and a range written `2-3`;
42//! - `<rows>` is `\toprule`, then the rows, each its cells' texts separated
43//!   by `&` and ended by `\\`, with an empty text at an empty position and at
44//!   a position that a spanning cell covers, then `\bottomrule`.
45//!
46//! A cell's text is one `\flmCellsSet{<name>}` for each custom style it
47//! carries, in the order of its tokens, then its content, recomposed through
48//! the ordinary rules: a `\cell`'s content with its blank lines, a
49//! `\celldata` entry's inline content with the whitespace at its edges
50//! trimmed ([`stage_trimmed`]), as on every backend. `\flmCellsSet` is a
51//! *table command*, a command that `tabularray` reads only at the start of a
52//! cell's text. What a cell style states is written from the model's facts,
53//! never from a token as written. Each cell is first read into what it
54//! writes around its content on this backend (the span and keys of its
55//! `cell{..}` option entry, the lines it draws, its table commands: the
56//! rendering model of a cell), and
57//! then written: the table commands, then its content.
58//!
59//! # What the rule requires, reports and leaves out
60//!
61//! The rule requires (records a requirement for) the feature's definition
62//! piece ([`LATEX_PIECE`], [`definition_piece`]), which requests the LaTeX
63//! packages `tabularray` and `xcolor`, and, for every cell style the table
64//! uses, what the cell style requires on this backend
65//! ([`CellStyle::requirements_on`](super::CellStyle::requirements_on)): the
66//! shipped colors require the feature's piece, and a cell style of another
67//! feature requires that feature's own piece, which registers its keys. The
68//! rule reports every problem the reader found, as the feature's general
69//! rule does, and stages one dropped mark (`flm.pres.dropped`) for each
70//! thing the reader left out, immediately before the call; the
71//! `latex-recomposed` backend's emitter writes each dropped mark as a comment
72//! line. An empty table writes nothing but
73//! its dropped marks. A command of the tables of cells written out of place
74//! is lowered on this backend too by the feature's own rule for every
75//! backend ([`OutsideRule`](super::lower::OutsideRule)).
76//!
77//! A float inside a cell is left to LaTeX and the author: a cell is a box,
78//! and LaTeX cannot place a float in one.
79//!
80//! This backend reads the tree before block structure is built, so a blank
81//! line inside a `\celldata`'s data is written as the document wrote it and
82//! not reported, as for every other construct on this backend.
83
84use std::sync::Arc;
85
86use techy::core::node::{BuildId, NodeRef};
87
88use crate::core::lowering::{
89    DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
90};
91use crate::core::registry::{BuildError, FeatureBuilder};
92use crate::lang::Flm;
93use crate::model::names::{ElementName, Name};
94use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
95use crate::stdlib::backends::latex::{
96    LatexArgShape, LatexMacroPayload, LatexPreambleDef, LatexRawPayload, packages, preamble,
97};
98use crate::stdlib::backends::latex_recomposed::BACKEND;
99use crate::stdlib::backends::lowering::stage_trimmed;
100use crate::stdlib::backends::pres::{self, CellAlign, CellEdge, CellHeader, CellSpec, GridPosition};
101
102use super::reader::{CellContent, read_grid};
103use super::styles::Styles;
104use super::{ENVIRONMENT, LATEX_PIECE};
105
106/// The name of the recomposition rule, `flm.cells.cells.lower.latex-recomposed`
107/// ([`CellsLatexRule`]).
108pub const LATEX_RULE: &str = "flm.cells.cells.lower.latex-recomposed";
109
110/// The name of the feature's definition piece, `cells`; its identifier is
111/// `flm.latex.def.cells` ([`LATEX_PIECE`], [`definition_piece`]).
112pub const PIECE_NAME: &str = "cells";
113
114/// The name of the LaTeX hook `\flmCellsTable`, which the recomposition
115/// rule calls once for each table of cells:
116/// `\flmCellsTable{<natural colspec>}{<fitted colspec>}{<options>}{<rows>}`.
117pub const TABLE_COMMAND: &str = "flmCellsTable";
118
119/// The name of the table command as which a cell's custom style is written,
120/// `flmCellsSet`: `\flmCellsSet{<name>}` at the start of the cell's text.
121pub const SET_COMMAND: &str = "flmCellsSet";
122
123/// The name of the command that registers the `tabularray` cell keys of a
124/// custom style, `flmCellsStyleKeys`: `\flmCellsStyleKeys{<name>}{<keys>}`.
125/// The definition piece of a feature that declares a custom style calls it
126/// to give that style its keys; the first registration of a name is kept, as
127/// `\providecommand` keeps the first definition.
128pub const STYLE_KEYS_COMMAND: &str = "flmCellsStyleKeys";
129
130/// The prefix of the name of the command that holds the cell keys
131/// registered for a custom style, `flmCellsKeys`: `\flmCellsKeysgreen` holds
132/// `bg=flmCellsColorgreen`. An author defines this command before loading
133/// the style file, or redefines it after, to give a style other keys; for a
134/// name holding a digit, the command is written
135/// `\csname flmCellsKeys<name>\endcsname`, since a command name written
136/// after a backslash holds letters only.
137pub const KEYS_PREFIX: &str = "flmCellsKeys";
138
139/// The prefix of the name of a shipped style's background color,
140/// `flmCellsColor`: `flmCellsColorgreen` and the three others.
141pub const COLOR_PREFIX: &str = "flmCellsColor";
142
143/// The shipped background colors, each with its value in the RGB model, from
144/// 0 to 255: the colors of the custom styles `green`, `blue`, `yellow` and
145/// `red`.
146pub const COLORS: [(&str, &str); 4] =
147    [("green", "200,255,200"), ("blue", "200,220,255"), ("yellow", "255,255,200"), ("red", "255,200,200")];
148
149/// The feature's definition piece ([`LatexPreambleDef`]),
150/// `flm.latex.def.cells`. It defines:
151///
152/// - the LaTeX hook `\flmCellsTable` and the four commands that change one
153///   part of what it does: `\flmCellsHeaderFont`, `\flmCellsBeginCenter`,
154///   `\flmCellsEndCenter` and `\flmCellsMaxWidth`;
155/// - the table command `\flmCellsSet`, and `\flmCellsStyleKeys`, which
156///   registers a custom style's cell keys;
157/// - the four shipped colors, registered as the keys of the custom styles of
158///   the same names;
159/// - the loading of `tabularray`'s `booktabs` library, and of its `counter`
160///   library, which restores LaTeX's counters after the passes in which
161///   `tabularray` sets a cell only to measure it, so that a footnote in a
162///   cell advances its number once, except in the cases that
163///   [*Tables of cells in the recomposed LaTeX*](crate::guide::rendering#tables-of-cells-in-the-recomposed-latex)
164///   describes.
165///
166/// It records package requests for `tabularray` and `xcolor`
167/// ([`packages::TABULARRAY`], [`packages::XCOLOR`]).
168///
169/// By default the hook sets the table at its natural width with the natural
170/// column specification. Where that is wider than `\flmCellsMaxWidth`
171/// (`0.96\linewidth`), it sets the table again at that width with the fitted
172/// column specification, whose columns share the width and break their
173/// lines. It sets the table between `\flmCellsBeginCenter` and
174/// `\flmCellsEndCenter` (a `center` environment), except where LaTeX sets a
175/// single line, as in a cell of another table set at its natural width or
176/// in an `\mbox`: no paragraph can begin there, and the table is set
177/// without them.
178pub fn definition_piece() -> LatexPreambleDef {
179    let mut colors = String::new();
180    for (name, rgb) in COLORS {
181        colors.push_str(&format!("\\providecolor{{{COLOR_PREFIX}{name}}}{{RGB}}{{{rgb}}}\n"));
182    }
183    for (name, _) in COLORS {
184        colors.push_str(&format!("\\{STYLE_KEYS_COMMAND}{{{name}}}{{bg={COLOR_PREFIX}{name}}}\n"));
185    }
186    let content = format!(
187        "\
188% Tables of cells. A table is written
189% \\flmCellsTable{{<natural>}}{{<fitted>}}{{<options>}}{{<rows>}}: <natural> and
190% <fitted> are two column specifications of the tblr environment of the
191% tabularray package (<natural> has c for each column, <fitted> has X[-1]
192% for each column),
193% <options> are the table's other tblr options (the cells' spans, alignment
194% and header font, and the lines), and <rows> are the rows, the cells
195% separated by & and each row ended by \\\\.
196% By default the table is set at its natural width with <natural>; where it
197% is wider than \\flmCellsMaxWidth, it is set again at that width with
198% <fitted>. It is set between \\flmCellsBeginCenter and \\flmCellsEndCenter,
199% except where LaTeX sets a single line, as in a cell of another table set
200% at its natural width, where no paragraph can begin. A header cell is set
201% in \\flmCellsHeaderFont. Redefine \\flmCellsTable to set tables another way,
202% or one of the four other commands to change one part of it.
203% A cell's custom style <name> is written \\flmCellsSet{{<name>}} at the start
204% of the cell's text: a tabularray table command that applies the tabularray
205% cell keys held in \\flmCellsKeys<name>. \\flmCellsStyleKeys{{<name>}}{{<keys>}}
206% sets those keys unless keys are already set for <name>: define
207% \\flmCellsKeys<name> before loading this file, or redefine it after, to
208% change how a style looks. The shipped styles green, blue, yellow and red
209% set the background colors flmCellsColor<name>, which you can define before
210% loading this file.
211% tabularray's counter library restores LaTeX's counters after the passes in
212% which tabularray sets a cell only to measure it.
213% The macros with @ in their names are internals, not a customization point.
214\\UseTblrLibrary{{booktabs}}
215\\UseTblrLibrary{{counter}}
216\\providecommand\\flmCellsHeaderFont{{\\bfseries}}
217\\providecommand\\flmCellsBeginCenter{{\\begin{{center}}}}
218\\providecommand\\flmCellsEndCenter{{\\end{{center}}}}
219\\providecommand\\flmCellsMaxWidth{{0.96\\linewidth}}
220\\ExplSyntaxOn
221\\long\\def\\flm@cells@fit#1#2#3#4{{%
222  \\setbox0=\\hbox{{\\begin{{tblr}}{{colspec={{#1}},#3}}#4\\end{{tblr}}}}%
223  \\dim_compare:nNnTF {{\\wd0}} < {{\\flmCellsMaxWidth}}
224    {{\\leavevmode\\box0}}
225    {{\\begin{{tblr}}{{width=\\flmCellsMaxWidth,colspec={{#2}},#3}}#4\\end{{tblr}}}}}}
226\\long\\def\\flm@cells@iflr#1#2{{\\mode_if_horizontal:TF {{\\mode_if_inner:TF {{#1}} {{#2}}}} {{#2}}}}
227\\def\\flm@cells@set#1{{\\ifcsname flmCellsKeys#1\\endcsname
228  \\exp_args:Nnv \\tblr_set_cell:nn {{}} {{flmCellsKeys#1}}\\fi}}
229\\ExplSyntaxOff
230\\ProvideDocumentCommand\\flmCellsTable{{+m +m +m +m}}{{%
231  \\flm@cells@iflr
232    {{\\flm@cells@fit{{#1}}{{#2}}{{#3}}{{#4}}}}%
233    {{\\flmCellsBeginCenter\\flm@cells@fit{{#1}}{{#2}}{{#3}}{{#4}}\\flmCellsEndCenter}}}}
234\\ProvideDocumentCommand\\flmCellsStyleKeys{{m m}}{{%
235  \\expandafter\\providecommand\\csname flmCellsKeys#1\\endcsname{{#2}}}}
236\\ifcsname flmCellsSet\\endcsname\\else
237  \\NewTableCommand\\flmCellsSet[1]{{\\flm@cells@set{{#1}}}}
238  \\ProvideDocumentCommand\\flmCellsSet{{m}}{{}}
239\\fi
240{colors}"
241    );
242    LatexPreambleDef::new(
243        PIECE_NAME,
244        content,
245        "`\\flmCellsTable{natural}{fitted}{options}{rows}`: the LaTeX hook through which a \
246         table of cells is set, with `\\flmCellsSet{name}` and \
247         `\\flmCellsStyleKeys{name}{keys}` for a cell's custom styles, and the four shipped \
248         colors",
249    )
250    .requires([packages::TABULARRAY, packages::XCOLOR])
251}
252
253/// The key-value pair that sets the line of a `hline` or `vline` option entry.
254const RULE_LINE: &str = ".4pt,solid";
255
256/// The rendering model of one cell of a table of cells: what the cell writes
257/// around its content on this backend, filled from the cell's record in the
258/// table's model ([`latex_cell`]) before anything is written. The
259/// recomposition rule writes the cell's `cell{..}` option entry and its
260/// `hline`/`vline` option entries among the table's options, and the cell's
261/// text (the
262/// table commands, then the content) with [`cell_text`]. The content is not
263/// part of the model: the reader provides it, and it is lowered through the
264/// ordinary rules.
265///
266/// This is the only place where a cell's facts become LaTeX, so that how a
267/// cell is written can be changed in one place.
268// Nothing of it is public; a trait a host implements could later stand in its
269// place.
270#[derive(Debug, Clone, PartialEq, Eq)]
271struct LatexCell {
272    /// The row and the column of the cell's top-left position, counted from 1.
273    at: (u64, u64),
274    /// The span keys of the cell's `cell{..}` option entry, `r=2` and `c=3`,
275    /// where it spans more than one row or column.
276    span: Vec<String>,
277    /// The cell keys of its `cell{..}` option entry: its alignment, `l`, `c`
278    /// or `r` (`m` where it has none), then `font={\flmCellsHeaderFont}` where it is a header.
279    keys: Vec<String>,
280    /// The table options that add the cell's lines: its `hline` and `vline`
281    /// option entries, in order.
282    rules: Vec<String>,
283    /// The custom styles it carries, each written as a table command
284    /// `\flmCellsSet{<name>}` at the start of its text, in order.
285    commands: Vec<Name>,
286}
287
288impl LatexCell {
289    /// The cell's `cell{<row>}{<column>}={<span>}{<keys>}` entry, where it
290    /// needs one: a span, an alignment or a header kind.
291    fn entry(&self) -> Option<String> {
292        if self.span.is_empty() && self.keys == ["m"] {
293            return None;
294        }
295        let (row, col) = self.at;
296        Some(format!("cell{{{row}}}{{{col}}}={{{}}}{{{}}}", self.span.join(","), self.keys.join(", ")))
297    }
298}
299
300/// A range of rows or columns counted from 1, `3` or `3-4`, from the first
301/// and one past the last counted from 0.
302fn range(start: u64, end: u64) -> String {
303    if end == start + 1 { format!("{}", start + 1) } else { format!("{}-{end}", start + 1) }
304}
305
306/// The rendering model of the cell `spec` of a table of `rows` rows: what it
307/// writes on this backend ([`LatexCell`]).
308fn latex_cell(spec: &CellSpec, rows: u32) -> LatexCell {
309    let (row, col) = (u64::from(spec.row), u64::from(spec.col));
310    let (row_end, col_end) = (spec.row_end(), spec.col_end());
311    let mut span = Vec::new();
312    if spec.row_span > 1 {
313        span.push(format!("r={}", spec.row_span));
314    }
315    if spec.col_span > 1 {
316        span.push(format!("c={}", spec.col_span));
317    }
318    let align = match spec.align {
319        Some(CellAlign::Left) => "l",
320        Some(CellAlign::Center) => "c",
321        Some(CellAlign::Right) => "r",
322        None => "m",
323    };
324    let mut keys = vec![align.to_string()];
325    if spec.header.is_some() {
326        keys.push(String::from("font={\\flmCellsHeaderFont}"));
327    }
328    let mut rules = Vec::new();
329    // The table's last row is closed by `\bottomrule`.
330    if spec.header == Some(CellHeader::Column) && row_end < u64::from(rows) {
331        rules.push(format!("hline{{{}}}={{{}}}{{{RULE_LINE}}}", row_end + 1, range(col, col_end)));
332    }
333    for edge in &spec.rules {
334        rules.push(match edge {
335            CellEdge::Above => format!("hline{{{}}}={{{}}}{{{RULE_LINE}}}", row + 1, range(col, col_end)),
336            CellEdge::Below => format!("hline{{{}}}={{{}}}{{{RULE_LINE}}}", row_end + 1, range(col, col_end)),
337            CellEdge::Left => format!("vline{{{}}}={{{}}}{{{RULE_LINE}}}", col + 1, range(row, row_end)),
338            CellEdge::Right => format!("vline{{{}}}={{{}}}{{{RULE_LINE}}}", col_end + 1, range(row, row_end)),
339        });
340    }
341    LatexCell { at: (row + 1, col + 1), span, keys, rules, commands: spec.styles.clone() }
342}
343
344/// Stages the text of `cell` from its rendering model: one table command
345/// `\flmCellsSet{<name>}` per custom style, in order, then `content` lowered
346/// through the ordinary rules: a `\cell`'s blocks as written, a `\celldata`
347/// entry's inline content with the whitespace at its edges trimmed
348/// ([`stage_trimmed`]).
349fn cell_text(
350    cx: &mut LowerCx<'_>,
351    lw: &mut dyn Lowerer,
352    cell: &LatexCell,
353    content: CellContent<'_>,
354) -> Result<Vec<BuildId>, LowerError> {
355    let mut text = Vec::new();
356    for name in &cell.commands {
357        let argument = vec![raw(cx, lw, name.as_str())?];
358        text.push(command(cx, lw, SET_COMMAND, vec![argument])?);
359    }
360    match content {
361        CellContent::Blocks(slice) => text.extend(lw.lower_nodes(cx, slice)?),
362        CellContent::Inline(slice) => {
363            let nodes: Vec<NodeRef<'_, Flm>> = slice.iter().collect();
364            text.extend(stage_trimmed(cx, lw, &nodes, |_| false)?);
365        }
366    }
367    Ok(text)
368}
369
370/// Stages a raw node (`flm.pres.latex.raw`) holding the LaTeX text `text`.
371fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
372    lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
373}
374
375/// Stages a macro call `\<name>` with one mandatory argument per entry of
376/// `slots`, each entry the staged content of one argument, in order.
377fn command(
378    cx: &mut LowerCx<'_>,
379    lw: &mut dyn Lowerer,
380    name: &str,
381    slots: Vec<Vec<BuildId>>,
382) -> Result<BuildId, LowerError> {
383    lw.pres_slots_with(
384        cx,
385        &ElementName::from(MACRO),
386        LatexMacroPayload::new(name, vec![LatexArgShape::Mandatory; slots.len()]),
387        slots.into_iter().map(|slot| (String::from(ARG_SLOT), slot)).collect(),
388    )
389}
390
391/// The recomposition rule [`LATEX_RULE`] of a table of cells, the default on
392/// the `latex-recomposed` backend: it stages the table's dropped marks, then
393/// one call of the LaTeX hook `\flmCellsTable`. See the
394/// [module documentation](self).
395#[derive(Debug)]
396pub struct CellsLatexRule {
397    styles: Arc<Styles>,
398}
399
400impl CellsLatexRule {
401    /// The rule, reading style tokens against the cell style declarations
402    /// `styles`.
403    pub fn new(styles: Arc<Styles>) -> CellsLatexRule {
404        CellsLatexRule { styles }
405    }
406}
407
408impl Lower for CellsLatexRule {
409    fn lower(
410        &self,
411        node: NodeRef<'_, Flm>,
412        cx: &mut LowerCx<'_>,
413        lw: &mut dyn Lowerer,
414    ) -> Result<Lowering, LowerError> {
415        let grid = read_grid(&node, &self.styles)?;
416        // Every report is made, by each render that lowers the table.
417        let mut staged = Vec::new();
418        for problem in grid.problems {
419            lw.diagnose(problem.diagnostic);
420            if let Some(mark) = problem.dropped {
421                staged.push(lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?);
422            }
423        }
424        let payload = grid.payload;
425        if payload.cells.is_empty() {
426            return Ok(Lowering::Emit(staged));
427        }
428        lw.require(&Name::from(LATEX_PIECE));
429        for name in &grid.styles {
430            if let Some(style) = self.styles.get(name.as_str()) {
431                for id in style.requirements_on(BACKEND) {
432                    lw.require(id);
433                }
434            }
435        }
436        let cells: Vec<LatexCell> = payload.cells.iter().map(|spec| latex_cell(spec, payload.rows)).collect();
437        let mut options = String::from("hspan=minimal");
438        for entry in cells.iter().filter_map(LatexCell::entry) {
439            options.push_str(&format!(",\n  {entry}"));
440        }
441        for rule in cells.iter().flat_map(|cell| &cell.rules) {
442            options.push_str(&format!(",\n  {rule}"));
443        }
444        let mut texts = Vec::with_capacity(cells.len());
445        for (cell, content) in cells.iter().zip(grid.contents) {
446            texts.push(Some(cell_text(cx, lw, cell, content)?));
447        }
448        let mut rows = vec![raw(cx, lw, "\\toprule\n")?];
449        for row in payload.grid() {
450            for (index, position) in row.iter().enumerate() {
451                if index > 0 {
452                    rows.push(raw(cx, lw, "&")?);
453                }
454                if let GridPosition::TopLeft(entry) = position {
455                    rows.extend(texts.get_mut(*entry).and_then(Option::take).unwrap_or_default());
456                }
457            }
458            rows.push(raw(cx, lw, "\\\\\n")?);
459        }
460        rows.push(raw(cx, lw, "\\bottomrule\n")?);
461        let natural = "c".repeat(payload.cols as usize);
462        let fitted = "X[-1]".repeat(payload.cols as usize);
463        let slots = vec![
464            vec![raw(cx, lw, &natural)?],
465            vec![raw(cx, lw, &fitted)?],
466            vec![raw(cx, lw, &options)?],
467            rows,
468        ];
469        staged.push(command(cx, lw, TABLE_COMMAND, slots)?);
470        Ok(Lowering::Emit(staged))
471    }
472}
473
474/// The recomposition rule of a table of cells, [`LATEX_RULE`], reading
475/// style tokens against `styles`: the default on the `latex-recomposed`
476/// backend only.
477fn latex_rule(styles: Arc<Styles>) -> LoweringRule {
478    LoweringRule::new(
479        LATEX_RULE,
480        ENVIRONMENT,
481        LoweringDecl::new().produces(MACRO).produces(RAW).produces(pres::DROPPED),
482        Arc::new(CellsLatexRule::new(styles)),
483        DefaultMark::OnBackends(vec![BACKEND.into()]),
484    )
485    .docs(
486        "a table of cells lowers to one call of the LaTeX hook `\\flmCellsTable` over its \
487         column specifications, its `tabularray` options and its rows, after one dropped mark \
488         (`flm.pres.dropped`) per thing left out",
489    )
490}
491
492/// Registers what the feature contributes to the `latex-recomposed` backend:
493/// the peer declarations ([`PeerName`](crate::core::registry::PeerName)) of
494/// the backend and of the constructs the rule stages, the definition piece
495/// (a peer contribution to the service slot [`preamble::SLOT`]), then
496/// [`latex_rule`], reading style tokens against `styles`. A registry without
497/// the LaTeX features still builds, with the rule set aside (excluded from
498/// rule selection; see [`PeerName`](crate::core::registry::PeerName)).
499///
500/// # Errors
501///
502/// The [`BuildError`] of the registry builder when a declaration is made in
503/// a registration round that does not accept it (see
504/// [`FeatureBuilder`](crate::core::registry::FeatureBuilder)).
505pub(super) fn register(b: &mut FeatureBuilder<'_>, styles: Arc<Styles>) -> Result<(), BuildError> {
506    b.peer_backend(
507        BACKEND,
508        "the latex-recomposed backend, on which the recomposition rule is the default",
509    )?;
510    b.peer_element::<LatexMacroPayload>(
511        MACRO,
512        "the LaTeX family's macro-call construct, which the recomposition rule stages for the \
513         LaTeX hook `\\flmCellsTable` and a cell's table commands",
514    )?;
515    b.peer_element::<LatexRawPayload>(
516        RAW,
517        "the LaTeX family's raw node construct, in which the column specifications, options \
518         and row separators of the LaTeX hook `\\flmCellsTable` are written",
519    )?;
520    b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
521    b.lowering_rule(latex_rule(styles))
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527    use crate::stdlib::backends::latex::preamble::piece_id;
528
529    #[test]
530    fn the_piece_is_named_as_its_identifier_says_and_requests_tabularray_and_xcolor() {
531        let piece = definition_piece();
532        assert_eq!(piece.id, piece_id(PIECE_NAME));
533        assert_eq!(piece.id.as_str(), LATEX_PIECE);
534        assert_eq!(piece.requires, [Name::from(packages::TABULARRAY), Name::from(packages::XCOLOR)]);
535    }
536
537    #[test]
538    fn the_piece_defines_the_hook_its_knobs_the_table_command_and_the_colors() {
539        let content = definition_piece().content;
540        for expected in [
541            "\\ProvideDocumentCommand\\flmCellsTable{+m +m +m +m}",
542            "\\providecommand\\flmCellsHeaderFont{\\bfseries}",
543            "\\providecommand\\flmCellsBeginCenter{\\begin{center}}",
544            "\\providecommand\\flmCellsEndCenter{\\end{center}}",
545            "\\providecommand\\flmCellsMaxWidth{0.96\\linewidth}",
546            "\\NewTableCommand\\flmCellsSet[1]",
547            "\\tblr_set_cell:nn",
548            "\\ProvideDocumentCommand\\flmCellsStyleKeys{m m}",
549            "\\UseTblrLibrary{booktabs}",
550            "\\UseTblrLibrary{counter}",
551            "\\providecolor{flmCellsColorgreen}{RGB}{200,255,200}",
552            "\\providecolor{flmCellsColorred}{RGB}{255,200,200}",
553            "\\flmCellsStyleKeys{yellow}{bg=flmCellsColoryellow}",
554            "\\flmCellsStyleKeys{blue}{bg=flmCellsColorblue}",
555        ] {
556            assert!(content.contains(expected), "{expected}\n{content}");
557        }
558        // Every line is a whole line, and no line is a comment's continuation.
559        assert!(content.ends_with('\n'));
560    }
561
562    #[test]
563    fn the_rendering_model_of_a_cell_holds_its_entry_its_rules_and_its_commands() {
564        let mut spec = CellSpec::at(1, 2);
565        spec.row_span = 2;
566        spec.align = Some(CellAlign::Right);
567        spec.header = Some(CellHeader::Column);
568        spec.rules = vec![CellEdge::Right, CellEdge::Above];
569        spec.styles = vec![Name::from("green"), Name::from("bold")];
570        let cell = latex_cell(&spec, 4);
571        assert_eq!(
572            cell,
573            LatexCell {
574                at: (2, 3),
575                span: vec![String::from("r=2")],
576                keys: vec![String::from("r"), String::from("font={\\flmCellsHeaderFont}")],
577                rules: vec![
578                    String::from("hline{4}={3}{.4pt,solid}"),
579                    String::from("vline{4}={2-3}{.4pt,solid}"),
580                    String::from("hline{2}={3}{.4pt,solid}"),
581                ],
582                commands: vec![Name::from("green"), Name::from("bold")],
583            }
584        );
585        assert_eq!(cell.entry().as_deref(), Some("cell{2}{3}={r=2}{r, font={\\flmCellsHeaderFont}}"));
586        // A plain cell needs no entry; a column header in the last row draws no
587        // rule under it, `\bottomrule` closing the table.
588        assert_eq!(latex_cell(&CellSpec::at(0, 0), 1).entry(), None);
589        let mut last = CellSpec::at(0, 0);
590        last.header = Some(CellHeader::Column);
591        assert!(latex_cell(&last, 1).rules.is_empty());
592    }
593}