Skip to main content

latexml_core/alignment/
template.rs

1//! Support for tabular/array environments
2use std::{
3  collections::VecDeque,
4  fmt::{self, Debug, Display},
5};
6
7use rustc_hash::FxHashMap as HashMap;
8
9use super::cell::Cell;
10use crate::{Digested, common::dimension::Dimension, state::Stored, token::Token, tokens::Tokens};
11
12// ??
13pub type Row = Template;
14#[derive(Debug, Clone, Default, PartialEq)]
15pub enum Align {
16  #[default]
17  Left,
18  Center,
19  Right,
20  Justify,
21  /// Perl: align => 'char:X' — decimal-aligned column (dcolumn.sty)
22  Char(String),
23}
24impl Align {
25  pub fn char_code(&self) -> char {
26    match self {
27      Align::Right => 'r',
28      Align::Left => 'l',
29      Align::Center => 'c',
30      Align::Justify => 'p',
31      Align::Char(_) => 'c', // fallback for sizing
32    }
33  }
34  pub fn name(&self) -> String {
35    match self {
36      Align::Right => "right".to_string(),
37      Align::Left => "left".to_string(),
38      Align::Center => "center".to_string(),
39      Align::Justify => "justify".to_string(),
40      Align::Char(ch) => format!("char:{ch}"),
41    }
42  }
43}
44impl From<char> for Align {
45  fn from(c: char) -> Align {
46    match c {
47      'l' => Align::Left,
48      'r' => Align::Right,
49      'c' => Align::Center,
50      'p' => Align::Justify,
51      _ => Align::default(), // fallback
52    }
53  }
54}
55
56/// Two axes of tabular orientation
57#[derive(Debug, Copy, Clone, PartialEq)]
58pub enum Axis {
59  Column,
60  Row,
61}
62impl Axis {
63  /// The string name of a tabular axis
64  pub fn name(&self) -> &'static str {
65    match self {
66      Axis::Column => "column",
67      Axis::Row => "row",
68    }
69  }
70  /// Maybe these may have been better named as "horizontal_group" and "vertical_group" in latexml?
71  pub fn marker_name(&self) -> &'static str {
72    match self {
73      Axis::Column => "row",
74      Axis::Row => "column",
75    }
76  }
77}
78
79#[derive(Debug, Copy, Clone, PartialEq)]
80pub enum ColumnSpec {
81  Integer,   // 'i'
82  Empty,     // '_'
83  Unknown,   // '?'
84  Text,      // 't'
85  MultiText, // 'tt' — multiple text elements (e.g. colorbox + text)
86  Math,      // 'm'
87  /// Math *and* Text, alternating
88  MathAltText, // 'mx'
89  D,         // 'd'
90  Graphics,  // 'g'
91}
92impl ColumnSpec {
93  /// The cell comparator.
94  pub fn difference_heuristic(&self, other: &ColumnSpec) -> f64 {
95    use ColumnSpec::*;
96    match self {
97      Empty => match other {
98        Empty => 0.0,
99        Math => 0.05,
100        Integer => 0.05,
101        Text => 0.05,
102        Unknown => 0.05,
103        MathAltText => 0.05,
104        _ => 0.75,
105      },
106      Math => match other {
107        Empty => 0.05,
108        Math => 0.0,
109        Integer => 0.1,
110        MathAltText => 0.2,
111        _ => 0.75,
112      },
113      Integer => match other {
114        Empty => 0.05,
115        Math => 0.1,
116        Integer => 0.0,
117        MathAltText => 0.2,
118        _ => 0.75,
119      },
120      Text => match other {
121        Empty => 0.05,
122        Text => 0.0,
123        MathAltText => 0.2,
124        _ => 0.75, // includes MultiText — Perl fallthrough 0.75
125      },
126      MultiText => match other {
127        Empty => 0.05,
128        MultiText => 0.0,
129        MathAltText => 0.2,
130        _ => 0.75, // Perl: "tt" not in diff table → 0.75 fallthrough
131      },
132      Unknown => match other {
133        Empty => 0.05,
134        Unknown => 0.0,
135        MathAltText => 0.2,
136        _ => 0.75,
137      },
138      MathAltText => match other {
139        Empty => 0.05,
140        Math => 0.2,
141        Integer => 0.2,
142        Text => 0.2,
143        Unknown => 0.2,
144        MathAltText => 0.0,
145        _ => 0.75,
146      },
147      D => match other {
148        D => 0.0,
149        _ => 0.75,
150      },
151      Graphics => match other {
152        Graphics => 0.0,
153        _ => 0.75,
154      },
155    }
156  }
157}
158impl Display for ColumnSpec {
159  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160    match self {
161      ColumnSpec::Integer => write!(f, "i"),
162      ColumnSpec::Empty => write!(f, "_"),
163      ColumnSpec::Unknown => write!(f, "?"),
164      ColumnSpec::Text => write!(f, "t"),
165      ColumnSpec::MultiText => write!(f, "tt"),
166      ColumnSpec::Math => write!(f, "m"),
167      ColumnSpec::MathAltText => write!(f, "mx"),
168      ColumnSpec::D => write!(f, "d"),
169      ColumnSpec::Graphics => write!(f, "g"),
170    }
171  }
172}
173
174#[derive(Debug, Copy, Clone, PartialEq)]
175pub enum BorderSpec {
176  Top,
177  Bottom,
178  Left,
179  Right,
180}
181impl BorderSpec {
182  /// The side a `border` letter names (Alignment.pm's `t`, `b`, `l`, `r`, upper case alike).
183  pub fn of_letter(c: char) -> Option<BorderSpec> {
184    match c {
185      't' | 'T' => Some(BorderSpec::Top),
186      'b' | 'B' => Some(BorderSpec::Bottom),
187      'l' | 'L' => Some(BorderSpec::Left),
188      'r' | 'R' => Some(BorderSpec::Right),
189      _ => None,
190    }
191  }
192}
193
194#[derive(Debug, Clone, Default)]
195pub struct TemplateConfig {
196  pub repeating:     Option<bool>,
197  pub pseudorow:     Option<bool>,
198  pub non_repeating: usize,
199  pub repeated:      Vec<Cell>,
200  pub reversion:     Option<Tokens>,
201  pub columns:       Option<Vec<Cell>>,
202  pub tokens:        Option<Vec<Token>>,
203  pub save_before:   Option<VecDeque<Token>>,
204  pub save_between:  Option<VecDeque<Token>>,
205}
206
207#[derive(Debug, Clone, Default, PartialEq)]
208pub struct Template {
209  repeating:            bool,
210  pseudorow:            bool,
211  non_repeating:        usize,
212  repeated:             Vec<Cell>,
213  reversion:            Option<Tokens>,
214  columns:              Vec<Cell>,
215  pub tokens:           Vec<Token>,
216  padding:              Option<Dimension>,
217  pub top_padding:      Option<Dimension>,
218  pub bottom_padding:   Option<Dimension>,
219  pub before:           VecDeque<Digested>,
220  pub after:            VecDeque<Digested>,
221  save_before:          VecDeque<Token>,
222  save_between:         VecDeque<Token>,
223  disabled_intercolumn: bool,
224  pub cached_width:     Option<Dimension>,
225  pub cached_height:    Option<Dimension>,
226  pub cached_depth:     Option<Dimension>,
227  pub x:                Option<Dimension>,
228  pub y:                Option<Dimension>,
229  /// Per-row properties (e.g. xml:id, tags) set during digestion
230  /// and consumed during construction. Perl: $$row{id}, $$row{tags}.
231  /// Uses Stored to preserve typed values (esp. Digested for tags).
232  pub properties:       HashMap<String, Stored>,
233}
234
235impl Display for Template {
236  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Alignment[]",) }
237}
238impl Template {
239  pub fn new(config: TemplateConfig) -> Self {
240    let repeating = config.repeating.unwrap_or(false) || !config.repeated.is_empty();
241    let pseudorow = config.pseudorow.unwrap_or(false);
242    let mut columns = config.columns.unwrap_or_default();
243    let mut repeated = config.repeated;
244    let non_repeating = columns.len();
245    let save_before = config.save_before.unwrap_or_default();
246    let save_between = config.save_between.unwrap_or_default(); // `between` comes before `before`!
247    for column in columns.iter_mut() {
248      column.empty = true;
249    }
250    for v in repeated.iter_mut() {
251      v.empty = true;
252    }
253
254    Template {
255      columns,
256      pseudorow,
257      repeating,
258      repeated,
259      non_repeating,
260      save_before,
261      save_between,
262      disabled_intercolumn: false,
263      before: VecDeque::new(),
264      after: VecDeque::new(),
265      padding: None,
266      top_padding: None,
267      bottom_padding: None,
268      cached_width: None,
269      cached_height: None,
270      cached_depth: None,
271      x: None,
272      y: None,
273      reversion: config.reversion,
274      tokens: config.tokens.unwrap_or_default(),
275      properties: rustc_hash::FxHashMap::default(),
276    }
277  }
278  pub fn set_reversion(&mut self, tks: Tokens) { self.reversion = Some(tks); }
279  pub fn set_repeating(&mut self) { self.repeating = true; }
280  /// Repeats `cell` past the template's own columns, as a preamble whose repeating part (tex.web §793: what follows
281  /// `&&`) is that one column: a row may hold more cells than the template has columns, and those get `cell`.
282  pub fn repeat_past_columns(&mut self, cell: Cell) {
283    self.repeating = true;
284    self.non_repeating = self.columns.len();
285    self.repeated = vec![Cell { empty: true, ..cell }];
286  }
287  pub fn set_padding(&mut self, d: Dimension) { self.padding = Some(d); }
288  pub fn get_padding(&self) -> Option<&Dimension> { self.padding.as_ref() }
289
290  /// Perl Template.pm L76-80: disableIntercolumn
291  /// Only sets the flag when there is a current column.
292  /// Perl: `if (my $col = $$self{current_column}) { $$self{disabled_intercolumn} = 1; }`
293  pub fn disable_intercolumn(&mut self) {
294    if !self.columns.is_empty() || !self.repeated.is_empty() {
295      self.disabled_intercolumn = true;
296    }
297  }
298
299  /// Perl Template.pm L113-118: finish
300  /// Appends \lx@intercol to last column's after unless disabled_intercolumn
301  pub fn finish(&mut self) {
302    let last = if self.repeating {
303      self.repeated.last_mut()
304    } else {
305      self.columns.last_mut()
306    };
307    if let Some(prev) = last
308      && !self.disabled_intercolumn
309    {
310      // `take()` moves out the current Option<Tokens> (replacing with
311      // None) — we immediately re-assign, so the clone in the old
312      // `.clone().unwrap_or_default().unlist()` was redundant.
313      let mut after = prev.after.take().unwrap_or_default().unlist();
314      after.push(T_CS!("\\lx@intercol"));
315      prev.after = Some(Tokens::new(after));
316      prev.has_intercol_after = true;
317    }
318  }
319
320  /// Whether a `>{…}` prefix waits for the next column (`add_column` puts it after that column's own `before`,
321  /// followed by `\ignorespaces`).
322  pub fn has_pending_prefix(&self) -> bool { !self.save_before.is_empty() }
323
324  // These add material before & after the current column
325  pub fn add_before_column(&mut self, mut new: VecDeque<Token>) {
326    let current_sb = self.save_before.drain(..);
327    new.extend(current_sb);
328    self.save_before = new; // NOTE: goes all the way to front!
329  }
330  // NOTE: \lx@column@trimright should ONLY be added to LaTeX tabular style templates!!!!
331  // NOT \halign style templates!
332  pub fn add_after_column(&mut self, new: Vec<Token>) {
333    if let Some(current_column) = self.columns.last_mut() {
334      let current_after = current_column.after.take().unwrap_or_default().unlist();
335      let own = current_column.suffix_at.unwrap_or(0);
336      current_column.suffix_at = Some(1 + new.len() + own);
337      current_column.after = Some(Tokens!(T_CS!("\\lx@column@trimright"), new, current_after));
338    }
339  }
340
341  // Perl Template.pm L65-74: addBetweenColumn
342  pub fn add_between_column(&mut self, tokens: Vec<Token>) {
343    if let Some(current_column) = self.columns.last_mut() {
344      let mut combined = Vec::new();
345      let current_after = current_column.after.take().unwrap_or_default().unlist();
346      combined.extend(current_after);
347      // Perl L69-70: prepend \lx@intercol unless disabled_intercolumn
348      if !self.disabled_intercolumn {
349        combined.push(T_CS!("\\lx@intercol"));
350      }
351      combined.extend(tokens);
352      current_column.after = Some(Tokens::new(combined));
353    } else {
354      self.save_between.extend(tokens);
355    }
356  }
357
358  // Perl Template.pm L82-110: addColumn
359  pub fn add_column(&mut self, mut col: Cell) {
360    // Perl L85-87: append \lx@intercol to previous column's after unless disabled_intercolumn
361    if let Some(prev) = if self.repeating {
362      self.repeated.last_mut()
363    } else {
364      self.columns.last_mut()
365    } && !self.disabled_intercolumn
366    {
367      let mut after = prev.after.take().unwrap_or_default().unlist();
368      after.push(T_CS!("\\lx@intercol"));
369      prev.after = Some(Tokens::new(after));
370      prev.has_intercol_after = true;
371    }
372    // Perl L88-95: build before from save_between + \lx@intercol + properties before + save_before
373    let mut before = Vec::new();
374    if !self.save_between.is_empty() {
375      before.extend(self.save_between.clone());
376    }
377    // Perl L90: push \lx@intercol unless disabled_intercolumn
378    let has_intercol_before = !self.disabled_intercolumn;
379    if has_intercol_before {
380      before.push(T_CS!("\\lx@intercol"));
381    }
382    // Perl L91: delete disabled_intercolumn
383    self.disabled_intercolumn = false;
384
385    if let Some(prop_before) = col.before {
386      before.extend(prop_before.unlist());
387    }
388    let prefix_at = before.len();
389    if !self.save_before.is_empty() {
390      before.extend(self.save_before.clone());
391      // array.sty's `\insert@column` (array.sty:97-101): the `>{…}` tokens, then `\ignorespaces`, then the cell, so a
392      // `>{\form}` whose `\form` takes an argument takes the `\ignorespaces`, not the cell's first token (2504.02110:
393      // `\form{\mbox}{x}` left the `x` and an `&` astray).
394      before.push(T_CS!("\\ignorespaces"));
395    }
396    col.before = if !before.is_empty() {
397      Some(Tokens::new(before))
398    } else {
399      None
400    };
401    col.prefix_at = Some(prefix_at);
402    col.has_intercol_before = has_intercol_before;
403    let mut after = vec![T_CS!("\\lx@column@trimright")];
404    if let Some(prop_after) = col.after {
405      after.extend(prop_after.unlist());
406    }
407    // the type's own after tokens (its fills, a paragraph column's box end) follow the group (`Cell::suffix_at`)
408    col.suffix_at = Some(1);
409    col.after = if after.is_empty() {
410      None
411    } else {
412      Some(Tokens::new(after))
413    };
414    col.empty = true;
415    self.save_between = VecDeque::new();
416    self.save_before = VecDeque::new();
417
418    if self.repeating {
419      self.non_repeating = self.columns.len();
420      self.repeated.push(col);
421    } else {
422      self.columns.push(col);
423    }
424  }
425
426  pub fn get_column_mut(&mut self, n: usize) -> Option<&mut Cell> {
427    let all_columns = self.columns.len();
428    if (n > all_columns) && self.repeating {
429      let rep = &self.repeated;
430      let m = rep.len();
431      if m > 0 {
432        for i in all_columns..n {
433          let dup = rep[(i - self.non_repeating) % m].clone();
434          self.columns.push(dup);
435        }
436      }
437    }
438    if n > 0 {
439      self.columns.get_mut(n - 1)
440    } else {
441      None
442    }
443  }
444
445  pub fn get_columns(&self) -> &[Cell] { &self.columns }
446  pub fn get_columns_mut(&mut self) -> &mut Vec<Cell> { &mut self.columns }
447  pub fn get_repeated_mut(&mut self) -> &mut Vec<Cell> { &mut self.repeated }
448  pub fn set_pseudo(&mut self) { self.pseudorow = true; }
449  pub fn unset_pseudo(&mut self) { self.pseudorow = false; }
450  pub fn is_pseudo(&self) -> bool { self.pseudorow }
451
452  /// Whether this equation row carries tags its author set. `\lx@equation@settag` (amsmath's `\tag`, `\TCItag`,
453  /// AAS's `\eqnum`, …) first retracts the row's own number — `EQUATIONROW_TAGS` becomes `{id, reset}` — and then
454  /// stores the given `tags`; the after-row step (latex_constructs `after_equation`) copies those properties onto the
455  /// row. An auto-numbered row has `tags` without `reset`, a `\nonumber` row `reset` without `tags`. A tagged row is
456  /// never empty: its tag is its content (OXIDIZED_DESIGN_DIVERGENCES #591, KNOWN_PERL_ERRORS #682).
457  pub fn has_explicit_tags(&self) -> bool {
458    self.properties.contains_key("tags")
459      && matches!(self.properties.get("reset"), Some(Stored::Bool(true)))
460  }
461}
462
463/// The internal attribute a math alignment's row element carries when its author tagged it
464/// ([`Template::has_explicit_tags`]), so the equation-group rearrangements keep that row even when its cells are
465/// empty (`… \nonumber \\ && \tag{27}`); stripped with the other `_` attributes at finalization.
466pub const TAGGED_ROW_ATTRIBUTE: &str = "_tagged";
467
468/// The property a math alignment's row carries when it prints a number that must survive though its cells are empty:
469/// latex.ltx's eqnarray number on a row of its own under an unnumbered row (`x &=& y \cr \end{eqnarray}`, the
470/// `\@@eqncr` of the end), which `rearrange_eqnarray` joins to the equation above. Normalization keeps such a row; it
471/// is stripped with the other `_` attributes at finalization.
472pub const NUMBER_ROW_PROPERTY: &str = "_number_row";
473
474#[cfg(test)]
475mod tests {
476  use super::*;
477
478  #[test]
479  fn align_default_is_left() {
480    assert_eq!(Align::default(), Align::Left);
481  }
482
483  #[test]
484  fn align_char_code() {
485    assert_eq!(Align::Left.char_code(), 'l');
486    assert_eq!(Align::Right.char_code(), 'r');
487    assert_eq!(Align::Center.char_code(), 'c');
488    assert_eq!(Align::Justify.char_code(), 'p');
489    // Char variant falls back to 'c' for sizing.
490    assert_eq!(Align::Char(".".to_string()).char_code(), 'c');
491  }
492
493  #[test]
494  fn align_name() {
495    assert_eq!(Align::Left.name(), "left");
496    assert_eq!(Align::Right.name(), "right");
497    assert_eq!(Align::Center.name(), "center");
498    assert_eq!(Align::Justify.name(), "justify");
499    assert_eq!(Align::Char(".".to_string()).name(), "char:.");
500  }
501
502  #[test]
503  fn align_from_char_basic() {
504    assert_eq!(Align::from('l'), Align::Left);
505    assert_eq!(Align::from('r'), Align::Right);
506    assert_eq!(Align::from('c'), Align::Center);
507    assert_eq!(Align::from('p'), Align::Justify);
508  }
509
510  #[test]
511  fn align_from_char_unknown_is_default() {
512    // Unknown char falls back to Default (Left).
513    assert_eq!(Align::from('x'), Align::Left);
514    assert_eq!(Align::from('?'), Align::Left);
515  }
516
517  #[test]
518  fn axis_name() {
519    assert_eq!(Axis::Column.name(), "column");
520    assert_eq!(Axis::Row.name(), "row");
521  }
522
523  #[test]
524  fn axis_marker_name_is_inverse() {
525    // marker_name is intentionally "the other axis" — column's
526    // marker is a row, row's marker is a column (possibly a naming
527    // artifact from the Perl side).
528    assert_eq!(Axis::Column.marker_name(), "row");
529    assert_eq!(Axis::Row.marker_name(), "column");
530  }
531
532  #[test]
533  fn column_spec_display_chars() {
534    assert_eq!(format!("{}", ColumnSpec::Integer), "i");
535    assert_eq!(format!("{}", ColumnSpec::Empty), "_");
536    assert_eq!(format!("{}", ColumnSpec::Unknown), "?");
537    assert_eq!(format!("{}", ColumnSpec::Text), "t");
538    assert_eq!(format!("{}", ColumnSpec::MultiText), "tt");
539    assert_eq!(format!("{}", ColumnSpec::Math), "m");
540    assert_eq!(format!("{}", ColumnSpec::MathAltText), "mx");
541    assert_eq!(format!("{}", ColumnSpec::D), "d");
542    assert_eq!(format!("{}", ColumnSpec::Graphics), "g");
543  }
544
545  #[test]
546  fn column_spec_difference_heuristic_self_is_zero() {
547    // Like-to-like distances are 0 for each non-generic variant.
548    assert_eq!(
549      ColumnSpec::Empty.difference_heuristic(&ColumnSpec::Empty),
550      0.0
551    );
552    assert_eq!(
553      ColumnSpec::Math.difference_heuristic(&ColumnSpec::Math),
554      0.0
555    );
556    assert_eq!(
557      ColumnSpec::Integer.difference_heuristic(&ColumnSpec::Integer),
558      0.0
559    );
560    assert_eq!(
561      ColumnSpec::Text.difference_heuristic(&ColumnSpec::Text),
562      0.0
563    );
564    assert_eq!(ColumnSpec::D.difference_heuristic(&ColumnSpec::D), 0.0);
565    assert_eq!(
566      ColumnSpec::Graphics.difference_heuristic(&ColumnSpec::Graphics),
567      0.0
568    );
569  }
570
571  #[test]
572  fn column_spec_difference_heuristic_incompatible_is_large() {
573    // Graphics vs anything else → 0.75 (Perl's "strong difference").
574    assert_eq!(
575      ColumnSpec::Graphics.difference_heuristic(&ColumnSpec::Math),
576      0.75
577    );
578    assert_eq!(ColumnSpec::D.difference_heuristic(&ColumnSpec::Text), 0.75);
579  }
580}