use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::Flm;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{ARG_SLOT, MACRO, RAW};
use crate::stdlib::backends::latex::{
LatexArgShape, LatexMacroPayload, LatexPreambleDef, LatexRawPayload, packages, preamble,
};
use crate::stdlib::backends::latex_recomposed::BACKEND;
use crate::stdlib::backends::lowering::stage_trimmed;
use crate::stdlib::backends::pres::{self, CellAlign, CellEdge, CellHeader, CellSpec, GridPosition};
use super::reader::{CellContent, read_grid};
use super::styles::Styles;
use super::{ENVIRONMENT, LATEX_PIECE};
pub const LATEX_RULE: &str = "flm.cells.cells.lower.latex-recomposed";
pub const PIECE_NAME: &str = "cells";
pub const TABLE_COMMAND: &str = "flmCellsTable";
pub const SET_COMMAND: &str = "flmCellsSet";
pub const STYLE_KEYS_COMMAND: &str = "flmCellsStyleKeys";
pub const KEYS_PREFIX: &str = "flmCellsKeys";
pub const COLOR_PREFIX: &str = "flmCellsColor";
pub const COLORS: [(&str, &str); 4] =
[("green", "200,255,200"), ("blue", "200,220,255"), ("yellow", "255,255,200"), ("red", "255,200,200")];
pub fn definition_piece() -> LatexPreambleDef {
let mut colors = String::new();
for (name, rgb) in COLORS {
colors.push_str(&format!("\\providecolor{{{COLOR_PREFIX}{name}}}{{RGB}}{{{rgb}}}\n"));
}
for (name, _) in COLORS {
colors.push_str(&format!("\\{STYLE_KEYS_COMMAND}{{{name}}}{{bg={COLOR_PREFIX}{name}}}\n"));
}
let content = format!(
"\
% Tables of cells. A table is written
% \\flmCellsTable{{<natural>}}{{<fitted>}}{{<options>}}{{<rows>}}: <natural> and
% <fitted> are two column specifications of the tblr environment of the
% tabularray package (<natural> has c for each column, <fitted> has X[-1]
% for each column),
% <options> are the table's other tblr options (the cells' spans, alignment
% and header font, and the lines), and <rows> are the rows, the cells
% separated by & and each row ended by \\\\.
% By default the table is set at its natural width with <natural>; where it
% is wider than \\flmCellsMaxWidth, it is set again at that width with
% <fitted>. It is set between \\flmCellsBeginCenter and \\flmCellsEndCenter,
% except where LaTeX sets a single line, as in a cell of another table set
% at its natural width, where no paragraph can begin. A header cell is set
% in \\flmCellsHeaderFont. Redefine \\flmCellsTable to set tables another way,
% or one of the four other commands to change one part of it.
% A cell's custom style <name> is written \\flmCellsSet{{<name>}} at the start
% of the cell's text: a tabularray table command that applies the tabularray
% cell keys held in \\flmCellsKeys<name>. \\flmCellsStyleKeys{{<name>}}{{<keys>}}
% sets those keys unless keys are already set for <name>: define
% \\flmCellsKeys<name> before loading this file, or redefine it after, to
% change how a style looks. The shipped styles green, blue, yellow and red
% set the background colors flmCellsColor<name>, which you can define before
% loading this file.
% tabularray's counter library restores LaTeX's counters after the passes in
% which tabularray sets a cell only to measure it.
% The macros with @ in their names are internals, not a customization point.
\\UseTblrLibrary{{booktabs}}
\\UseTblrLibrary{{counter}}
\\providecommand\\flmCellsHeaderFont{{\\bfseries}}
\\providecommand\\flmCellsBeginCenter{{\\begin{{center}}}}
\\providecommand\\flmCellsEndCenter{{\\end{{center}}}}
\\providecommand\\flmCellsMaxWidth{{0.96\\linewidth}}
\\ExplSyntaxOn
\\long\\def\\flm@cells@fit#1#2#3#4{{%
\\setbox0=\\hbox{{\\begin{{tblr}}{{colspec={{#1}},#3}}#4\\end{{tblr}}}}%
\\dim_compare:nNnTF {{\\wd0}} < {{\\flmCellsMaxWidth}}
{{\\leavevmode\\box0}}
{{\\begin{{tblr}}{{width=\\flmCellsMaxWidth,colspec={{#2}},#3}}#4\\end{{tblr}}}}}}
\\long\\def\\flm@cells@iflr#1#2{{\\mode_if_horizontal:TF {{\\mode_if_inner:TF {{#1}} {{#2}}}} {{#2}}}}
\\def\\flm@cells@set#1{{\\ifcsname flmCellsKeys#1\\endcsname
\\exp_args:Nnv \\tblr_set_cell:nn {{}} {{flmCellsKeys#1}}\\fi}}
\\ExplSyntaxOff
\\ProvideDocumentCommand\\flmCellsTable{{+m +m +m +m}}{{%
\\flm@cells@iflr
{{\\flm@cells@fit{{#1}}{{#2}}{{#3}}{{#4}}}}%
{{\\flmCellsBeginCenter\\flm@cells@fit{{#1}}{{#2}}{{#3}}{{#4}}\\flmCellsEndCenter}}}}
\\ProvideDocumentCommand\\flmCellsStyleKeys{{m m}}{{%
\\expandafter\\providecommand\\csname flmCellsKeys#1\\endcsname{{#2}}}}
\\ifcsname flmCellsSet\\endcsname\\else
\\NewTableCommand\\flmCellsSet[1]{{\\flm@cells@set{{#1}}}}
\\ProvideDocumentCommand\\flmCellsSet{{m}}{{}}
\\fi
{colors}"
);
LatexPreambleDef::new(
PIECE_NAME,
content,
"`\\flmCellsTable{natural}{fitted}{options}{rows}`: the LaTeX hook through which a \
table of cells is set, with `\\flmCellsSet{name}` and \
`\\flmCellsStyleKeys{name}{keys}` for a cell's custom styles, and the four shipped \
colors",
)
.requires([packages::TABULARRAY, packages::XCOLOR])
}
const RULE_LINE: &str = ".4pt,solid";
#[derive(Debug, Clone, PartialEq, Eq)]
struct LatexCell {
at: (u64, u64),
span: Vec<String>,
keys: Vec<String>,
rules: Vec<String>,
commands: Vec<Name>,
}
impl LatexCell {
fn entry(&self) -> Option<String> {
if self.span.is_empty() && self.keys == ["m"] {
return None;
}
let (row, col) = self.at;
Some(format!("cell{{{row}}}{{{col}}}={{{}}}{{{}}}", self.span.join(","), self.keys.join(", ")))
}
}
fn range(start: u64, end: u64) -> String {
if end == start + 1 { format!("{}", start + 1) } else { format!("{}-{end}", start + 1) }
}
fn latex_cell(spec: &CellSpec, rows: u32) -> LatexCell {
let (row, col) = (u64::from(spec.row), u64::from(spec.col));
let (row_end, col_end) = (spec.row_end(), spec.col_end());
let mut span = Vec::new();
if spec.row_span > 1 {
span.push(format!("r={}", spec.row_span));
}
if spec.col_span > 1 {
span.push(format!("c={}", spec.col_span));
}
let align = match spec.align {
Some(CellAlign::Left) => "l",
Some(CellAlign::Center) => "c",
Some(CellAlign::Right) => "r",
None => "m",
};
let mut keys = vec![align.to_string()];
if spec.header.is_some() {
keys.push(String::from("font={\\flmCellsHeaderFont}"));
}
let mut rules = Vec::new();
if spec.header == Some(CellHeader::Column) && row_end < u64::from(rows) {
rules.push(format!("hline{{{}}}={{{}}}{{{RULE_LINE}}}", row_end + 1, range(col, col_end)));
}
for edge in &spec.rules {
rules.push(match edge {
CellEdge::Above => format!("hline{{{}}}={{{}}}{{{RULE_LINE}}}", row + 1, range(col, col_end)),
CellEdge::Below => format!("hline{{{}}}={{{}}}{{{RULE_LINE}}}", row_end + 1, range(col, col_end)),
CellEdge::Left => format!("vline{{{}}}={{{}}}{{{RULE_LINE}}}", col + 1, range(row, row_end)),
CellEdge::Right => format!("vline{{{}}}={{{}}}{{{RULE_LINE}}}", col_end + 1, range(row, row_end)),
});
}
LatexCell { at: (row + 1, col + 1), span, keys, rules, commands: spec.styles.clone() }
}
fn cell_text(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
cell: &LatexCell,
content: CellContent<'_>,
) -> Result<Vec<BuildId>, LowerError> {
let mut text = Vec::new();
for name in &cell.commands {
let argument = vec![raw(cx, lw, name.as_str())?];
text.push(command(cx, lw, SET_COMMAND, vec![argument])?);
}
match content {
CellContent::Blocks(slice) => text.extend(lw.lower_nodes(cx, slice)?),
CellContent::Inline(slice) => {
let nodes: Vec<NodeRef<'_, Flm>> = slice.iter().collect();
text.extend(stage_trimmed(cx, lw, &nodes, |_| false)?);
}
}
Ok(text)
}
fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
lw.pres_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
}
fn command(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
name: &str,
slots: Vec<Vec<BuildId>>,
) -> Result<BuildId, LowerError> {
lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(name, vec![LatexArgShape::Mandatory; slots.len()]),
slots.into_iter().map(|slot| (String::from(ARG_SLOT), slot)).collect(),
)
}
#[derive(Debug)]
pub struct CellsLatexRule {
styles: Arc<Styles>,
}
impl CellsLatexRule {
pub fn new(styles: Arc<Styles>) -> CellsLatexRule {
CellsLatexRule { styles }
}
}
impl Lower for CellsLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let grid = read_grid(&node, &self.styles)?;
let mut staged = Vec::new();
for problem in grid.problems {
lw.diagnose(problem.diagnostic);
if let Some(mark) = problem.dropped {
staged.push(lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?);
}
}
let payload = grid.payload;
if payload.cells.is_empty() {
return Ok(Lowering::Emit(staged));
}
lw.require(&Name::from(LATEX_PIECE));
for name in &grid.styles {
if let Some(style) = self.styles.get(name.as_str()) {
for id in style.requirements_on(BACKEND) {
lw.require(id);
}
}
}
let cells: Vec<LatexCell> = payload.cells.iter().map(|spec| latex_cell(spec, payload.rows)).collect();
let mut options = String::from("hspan=minimal");
for entry in cells.iter().filter_map(LatexCell::entry) {
options.push_str(&format!(",\n {entry}"));
}
for rule in cells.iter().flat_map(|cell| &cell.rules) {
options.push_str(&format!(",\n {rule}"));
}
let mut texts = Vec::with_capacity(cells.len());
for (cell, content) in cells.iter().zip(grid.contents) {
texts.push(Some(cell_text(cx, lw, cell, content)?));
}
let mut rows = vec![raw(cx, lw, "\\toprule\n")?];
for row in payload.grid() {
for (index, position) in row.iter().enumerate() {
if index > 0 {
rows.push(raw(cx, lw, "&")?);
}
if let GridPosition::TopLeft(entry) = position {
rows.extend(texts.get_mut(*entry).and_then(Option::take).unwrap_or_default());
}
}
rows.push(raw(cx, lw, "\\\\\n")?);
}
rows.push(raw(cx, lw, "\\bottomrule\n")?);
let natural = "c".repeat(payload.cols as usize);
let fitted = "X[-1]".repeat(payload.cols as usize);
let slots = vec![
vec![raw(cx, lw, &natural)?],
vec![raw(cx, lw, &fitted)?],
vec![raw(cx, lw, &options)?],
rows,
];
staged.push(command(cx, lw, TABLE_COMMAND, slots)?);
Ok(Lowering::Emit(staged))
}
}
fn latex_rule(styles: Arc<Styles>) -> LoweringRule {
LoweringRule::new(
LATEX_RULE,
ENVIRONMENT,
LoweringDecl::new().produces(MACRO).produces(RAW).produces(pres::DROPPED),
Arc::new(CellsLatexRule::new(styles)),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a table of cells lowers to one call of the LaTeX hook `\\flmCellsTable` over its \
column specifications, its `tabularray` options and its rows, after one dropped mark \
(`flm.pres.dropped`) per thing left out",
)
}
pub(super) fn register(b: &mut FeatureBuilder<'_>, styles: Arc<Styles>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the recomposition rule is the default",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro-call construct, which the recomposition rule stages for the \
LaTeX hook `\\flmCellsTable` and a cell's table commands",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw node construct, in which the column specifications, options \
and row separators of the LaTeX hook `\\flmCellsTable` are written",
)?;
b.peer_slot::<LatexPreambleDef>(preamble::SLOT, Arc::new(definition_piece()))?;
b.lowering_rule(latex_rule(styles))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stdlib::backends::latex::preamble::piece_id;
#[test]
fn the_piece_is_named_as_its_identifier_says_and_requests_tabularray_and_xcolor() {
let piece = definition_piece();
assert_eq!(piece.id, piece_id(PIECE_NAME));
assert_eq!(piece.id.as_str(), LATEX_PIECE);
assert_eq!(piece.requires, [Name::from(packages::TABULARRAY), Name::from(packages::XCOLOR)]);
}
#[test]
fn the_piece_defines_the_hook_its_knobs_the_table_command_and_the_colors() {
let content = definition_piece().content;
for expected in [
"\\ProvideDocumentCommand\\flmCellsTable{+m +m +m +m}",
"\\providecommand\\flmCellsHeaderFont{\\bfseries}",
"\\providecommand\\flmCellsBeginCenter{\\begin{center}}",
"\\providecommand\\flmCellsEndCenter{\\end{center}}",
"\\providecommand\\flmCellsMaxWidth{0.96\\linewidth}",
"\\NewTableCommand\\flmCellsSet[1]",
"\\tblr_set_cell:nn",
"\\ProvideDocumentCommand\\flmCellsStyleKeys{m m}",
"\\UseTblrLibrary{booktabs}",
"\\UseTblrLibrary{counter}",
"\\providecolor{flmCellsColorgreen}{RGB}{200,255,200}",
"\\providecolor{flmCellsColorred}{RGB}{255,200,200}",
"\\flmCellsStyleKeys{yellow}{bg=flmCellsColoryellow}",
"\\flmCellsStyleKeys{blue}{bg=flmCellsColorblue}",
] {
assert!(content.contains(expected), "{expected}\n{content}");
}
assert!(content.ends_with('\n'));
}
#[test]
fn the_rendering_model_of_a_cell_holds_its_entry_its_rules_and_its_commands() {
let mut spec = CellSpec::at(1, 2);
spec.row_span = 2;
spec.align = Some(CellAlign::Right);
spec.header = Some(CellHeader::Column);
spec.rules = vec![CellEdge::Right, CellEdge::Above];
spec.styles = vec![Name::from("green"), Name::from("bold")];
let cell = latex_cell(&spec, 4);
assert_eq!(
cell,
LatexCell {
at: (2, 3),
span: vec![String::from("r=2")],
keys: vec![String::from("r"), String::from("font={\\flmCellsHeaderFont}")],
rules: vec![
String::from("hline{4}={3}{.4pt,solid}"),
String::from("vline{4}={2-3}{.4pt,solid}"),
String::from("hline{2}={3}{.4pt,solid}"),
],
commands: vec![Name::from("green"), Name::from("bold")],
}
);
assert_eq!(cell.entry().as_deref(), Some("cell{2}{3}={r=2}{r, font={\\flmCellsHeaderFont}}"));
assert_eq!(latex_cell(&CellSpec::at(0, 0), 1).entry(), None);
let mut last = CellSpec::at(0, 0);
last.header = Some(CellHeader::Column);
assert!(latex_cell(&last, 1).rules.is_empty());
}
}