Skip to main content

latexml_core/alignment/
cell.rs

1use libxml::tree::Node;
2
3use super::template::{Align, BorderSpec, ColumnSpec};
4use crate::{
5  common::{dimension::Dimension, glue::Glue},
6  digested::Digested,
7  tokens::Tokens,
8};
9
10#[derive(Debug, Clone, Default, PartialEq)]
11pub struct Cell {
12  pub empty:               bool,
13  pub skippable:           bool,
14  pub omitted:             bool,
15  /// An `\omit`ted cell of an alignment whose math is its template's (amsmath's, `template_math`): TeX sets it in
16  /// restricted horizontal mode (tex.web §789), so its material is boxed as text ([`crate::alignment::Alignment::
17  /// get_column_before`]).
18  pub omit_text_box:       bool,
19  pub skipped:             bool,
20  pub thead_in_row:        bool,
21  pub thead_in_column:     bool,
22  pub before:              Option<Tokens>,
23  pub after:               Option<Tokens>,
24  pub align:               Option<Align>,
25  pub width:               Option<Dimension>,
26  pub height:              Option<Dimension>,
27  pub depth:               Option<Dimension>,
28  pub cached_width:        Option<Dimension>,
29  pub cached_height:       Option<Dimension>,
30  pub cached_depth:        Option<Dimension>,
31  pub colspan:             Option<usize>,
32  pub colspanned:          Option<usize>,
33  pub rowspan:             Option<usize>,
34  /// The rows a negative `\multirow{-n}` spans, this one and the n-1 above it (multirow.sty:172 raises the box over
35  /// them): `normalize_upward_spans` moves the content to the top row with that `rowspan` when the cells above are
36  /// empty.
37  pub rowspan_up:          Option<usize>,
38  pub rowspanned:          Option<usize>,
39  pub boxes:               Option<Digested>,
40  pub cell_type:           Option<char>,
41  pub content_class:       Option<ColumnSpec>,
42  pub content_length:      Option<usize>,
43  pub border_left:         Option<usize>,
44  pub border_right:        Option<usize>,
45  pub border_top:          Option<usize>,
46  pub border_bottom:       Option<usize>,
47  pub top_padding:         Option<usize>,
48  pub bottom_padding:      Option<usize>,
49  pub right_padding:       Option<usize>,
50  pub left_padding:        Option<usize>,
51  pub vattach:             Option<String>,
52  pub cell:                Option<Node>,
53  pub x:                   Option<Dimension>,
54  pub y:                   Option<Dimension>,
55  pub border:              String,
56  /// The colour of each side's rule when it was drawn (colortbl's `\arrayrulecolor`, the
57  /// `RULE_COLOR`, or a `|` rule box's `border_color`), by [`BorderSpec`]: top, bottom, left, right; `None` the default ink.
58  pub border_color:        [Option<String>; 4],
59  /// Whether each side's rules are dashed (arydshln's `\hdashline`, `\cdashline`, `:`), by [`BorderSpec`]: a side is
60  /// dashed only when every rule on it is.
61  pub border_dashed:       [bool; 4],
62  /// Perl: $$colspec{tabskip} — intercolumn glue from \halign template
63  pub tabskip:             Option<Glue>,
64  /// Perl: $$colspec{lspaces} — left-side spacing (incl. tabskip)
65  pub lspaces:             Option<Digested>,
66  /// Perl: $$colspec{rspaces} — right-side spacing
67  pub rspaces:             Option<Digested>,
68  /// Perl: $$cell{class} — CSS class for the cell
69  pub class:               Option<String>,
70  /// Whether this column has \lx@intercol in its before tokens (from template).
71  /// Set during template building, used by nopad heuristic to distinguish
72  /// regular columns (has intercolumn padding) from @{}-disabled columns.
73  pub has_intercol_before: bool,
74  /// Whether this column has \lx@intercol in its after tokens (from template).
75  /// Set during template building, used by nopad heuristic to distinguish
76  /// regular columns (has intercolumn padding) from @{}-disabled columns.
77  pub has_intercol_after:  bool,
78  /// Background color from \columncolor/\cellcolor (set during digestion by \@setcellcolor)
79  pub backgroundcolor:     Option<String>,
80  /// Where the column's array.sty `>{…}` tokens begin in `before` (`Template::add_column`): right after the column
81  /// type's own before tokens (a paragraph column's box opening), ahead of the `>{…}` declarations and `\ignorespaces`.
82  pub prefix_at:           Option<usize>,
83  /// Where the column's array.sty `<{…}` tokens end in `after` (`Template::add_column`, `add_after_column`), ahead of
84  /// the column type's own after tokens (its fills, a paragraph column's box end) and the intercolumn material: the
85  /// cell's group ends there (array.sty:146-148 `\d@llarbegin\insert@column\d@llarend\do@row@strut\hfil`).
86  pub suffix_at:           Option<usize>,
87  /// The cell's content overprints the cells to its right, as an `\rlap` does (`\lefteqn`, latex.ltx:15800): the
88  /// empty cells that follow it join its span (`normalize_overprint_spans`). Set by `\lx@alignment@cell@overprint`.
89  pub overprint:           bool,
90  /// The most columns an overprinting cell spans, its own included (a nicematrix `\Block{i-j}`'s `j`); `None` for no
91  /// bound.
92  pub overprint_columns:   Option<usize>,
93}
94impl Cell {
95  /// Marks the column padded on its right when its after tokens hold an intercolumn macro (`\lx@intercol`, or a
96  /// binding's `…intercol` one), for the nopad heuristic: a column built outside `Template::add_column`'s own marking
97  /// (`tabular_bindings`, blkarray's block columns).
98  pub fn mark_intercol_after(&mut self) {
99    if self.after.as_ref().is_some_and(|after| {
100      after
101        .unlist_ref()
102        .iter()
103        .any(|t| t.with_str(|s| s.contains("intercol")))
104    }) {
105      self.has_intercol_after = true;
106    }
107  }
108
109  /// Adds the `border` letters (`t`/`b`/`l`/`r`, upper case alike), each side now drawn in `color`: a rule drawn
110  /// later is on top, as in TeX. A side stays dashed only while every rule added to it is `dashed`.
111  pub fn add_border(&mut self, sides: &str, color: Option<&str>, dashed: bool) {
112    for letter in sides.chars() {
113      if let Some(side) = BorderSpec::of_letter(letter) {
114        let first = self.border_at_side(side).next().is_none();
115        self.border_dashed[side as usize] = dashed && (first || self.border_dashed[side as usize]);
116        self.border_color[side as usize] = color.map(str::to_string);
117      }
118      self.border.push(letter);
119    }
120  }
121
122  /// The `border` letters on `side`.
123  fn border_at_side(&self, side: BorderSpec) -> impl Iterator<Item = char> + '_ {
124    self
125      .border
126      .chars()
127      .filter(move |&c| BorderSpec::of_letter(c) == Some(side))
128  }
129
130  pub fn border_color_at(&self, side: BorderSpec) -> Option<&str> {
131    self.border_color[side as usize].as_deref()
132  }
133
134  pub fn border_dashed_at(&self, side: BorderSpec) -> bool { self.border_dashed[side as usize] }
135
136  /// The classes of the dashed sides the cell's `border` keeps (`ltx_border_r_dashed`), in the `border` attribute's
137  /// order.
138  pub fn border_dashed_classes(&self) -> Vec<String> {
139    [
140      (BorderSpec::Bottom, 'b'),
141      (BorderSpec::Left, 'l'),
142      (BorderSpec::Right, 'r'),
143      (BorderSpec::Top, 't'),
144    ]
145    .into_iter()
146    .filter(|&(side, _)| self.border_dashed_at(side) && self.border_at_side(side).next().is_some())
147    .map(|(_, letter)| format!("ltx_border_{letter}_dashed"))
148    .collect()
149  }
150
151  /// The `cssstyle` of the coloured sides the cell's `border` keeps (`border-top-color:#FF0000`).
152  pub fn border_color_style(&self) -> Option<String> {
153    let mut style = Vec::new();
154    for (side, name) in [
155      (BorderSpec::Top, "top"),
156      (BorderSpec::Bottom, "bottom"),
157      (BorderSpec::Left, "left"),
158      (BorderSpec::Right, "right"),
159    ] {
160      if let Some(color) = self.border_color_at(side)
161        && self.border_at_side(side).next().is_some()
162      {
163        style.push(format!("border-{name}-color:{color}"));
164      }
165    }
166    (!style.is_empty()).then(|| style.join(";"))
167  }
168
169  pub fn border_at(&self, side: BorderSpec) -> Option<usize> {
170    match side {
171      BorderSpec::Left => self.border_left,
172      BorderSpec::Right => self.border_right,
173      BorderSpec::Top => self.border_top,
174      BorderSpec::Bottom => self.border_bottom,
175    }
176  }
177}
178
179#[cfg(test)]
180mod tests {
181  use super::*;
182
183  #[test]
184  fn cell_default_flags_all_false() {
185    let c = Cell::default();
186    assert!(!c.empty);
187    assert!(!c.skippable);
188    assert!(!c.omitted);
189    assert!(!c.skipped);
190    assert!(!c.thead_in_row);
191    assert!(!c.thead_in_column);
192    assert!(!c.has_intercol_before);
193    assert!(!c.has_intercol_after);
194    assert!(!c.overprint);
195  }
196
197  #[test]
198  fn cell_default_options_all_none() {
199    let c = Cell::default();
200    assert!(c.before.is_none());
201    assert!(c.after.is_none());
202    assert!(c.align.is_none());
203    assert!(c.width.is_none());
204    assert!(c.height.is_none());
205    assert!(c.depth.is_none());
206    assert!(c.cached_width.is_none());
207    assert!(c.cached_height.is_none());
208    assert!(c.cached_depth.is_none());
209    assert!(c.colspan.is_none());
210    assert!(c.colspanned.is_none());
211    assert!(c.rowspan.is_none());
212    assert!(c.rowspanned.is_none());
213    assert!(c.boxes.is_none());
214    assert!(c.cell_type.is_none());
215    assert!(c.border_left.is_none());
216    assert!(c.border_right.is_none());
217    assert!(c.border_top.is_none());
218    assert!(c.border_bottom.is_none());
219    assert!(c.backgroundcolor.is_none());
220  }
221
222  #[test]
223  fn cell_default_border_is_empty_string() {
224    let c = Cell::default();
225    assert_eq!(c.border, "");
226  }
227
228  #[test]
229  fn cell_border_at_reads_correct_side() {
230    let c = Cell {
231      border_left: Some(1),
232      border_right: Some(2),
233      border_top: Some(3),
234      border_bottom: Some(4),
235      ..Default::default()
236    };
237    assert_eq!(c.border_at(BorderSpec::Left), Some(1));
238    assert_eq!(c.border_at(BorderSpec::Right), Some(2));
239    assert_eq!(c.border_at(BorderSpec::Top), Some(3));
240    assert_eq!(c.border_at(BorderSpec::Bottom), Some(4));
241  }
242
243  #[test]
244  fn cell_border_at_none_by_default() {
245    let c = Cell::default();
246    assert_eq!(c.border_at(BorderSpec::Left), None);
247    assert_eq!(c.border_at(BorderSpec::Right), None);
248    assert_eq!(c.border_at(BorderSpec::Top), None);
249    assert_eq!(c.border_at(BorderSpec::Bottom), None);
250  }
251
252  #[test]
253  fn cell_partial_eq_defaults() {
254    // Default cells are equal.
255    let a = Cell::default();
256    let b = Cell::default();
257    assert_eq!(a, b);
258  }
259
260  #[test]
261  fn cell_partial_eq_distinguishes_flags() {
262    let mut a = Cell::default();
263    let b = Cell::default();
264    a.empty = true;
265    assert_ne!(a, b);
266  }
267}