1use 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
106pub const LATEX_RULE: &str = "flm.cells.cells.lower.latex-recomposed";
109
110pub const PIECE_NAME: &str = "cells";
113
114pub const TABLE_COMMAND: &str = "flmCellsTable";
118
119pub const SET_COMMAND: &str = "flmCellsSet";
122
123pub const STYLE_KEYS_COMMAND: &str = "flmCellsStyleKeys";
129
130pub const KEYS_PREFIX: &str = "flmCellsKeys";
138
139pub const COLOR_PREFIX: &str = "flmCellsColor";
142
143pub const COLORS: [(&str, &str); 4] =
147 [("green", "200,255,200"), ("blue", "200,220,255"), ("yellow", "255,255,200"), ("red", "255,200,200")];
148
149pub 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
253const RULE_LINE: &str = ".4pt,solid";
255
256#[derive(Debug, Clone, PartialEq, Eq)]
271struct LatexCell {
272 at: (u64, u64),
274 span: Vec<String>,
277 keys: Vec<String>,
280 rules: Vec<String>,
283 commands: Vec<Name>,
286}
287
288impl LatexCell {
289 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
300fn range(start: u64, end: u64) -> String {
303 if end == start + 1 { format!("{}", start + 1) } else { format!("{}-{end}", start + 1) }
304}
305
306fn 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 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
344fn 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
370fn 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
375fn 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#[derive(Debug)]
396pub struct CellsLatexRule {
397 styles: Arc<Styles>,
398}
399
400impl CellsLatexRule {
401 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 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
474fn 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
492pub(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 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 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}