Skip to main content

latexml_core/
alignment.rs

1//! # Representation of aligned structures
2//! An "Alignment" is an array/tabular construct as:
3//!  `<tabular><tr><td>...`
4//! or, for math mode
5//!   `<XMArray><XMRow><XMCell>...`
6//! (where initially, each XMCell will contain an XMArg to indicate
7//! individual parsing of each cell's content is desired)
8//!
9//! An Alignment object is a sort of fake Whatsit;
10//! It takes some magic to sneak it into the Digestion stream
11//! (see TeX.pool \lx@begin@alignment), but it needs to be created
12//! BEFORE the contents of the alignment are digested,
13//! since we stuff a lot of information into it
14//! (row, column boxes, borders, spacing, etc...)
15//! But once it has been captured, it should otherwise act
16//! like a Whatsit and be responsible for construction (be_absorbed),
17//! and sizing estimation (computeSize)
18//!
19//! Ultimately, this should be better tied into DefConstructor
20//! because an Alignment currently doesn't know what CS created it (debugging!);
21//! Also, it would better connect the things being constructed, reversion, etc.
22
23// keep in until code is completed.
24pub mod cell;
25mod normalize;
26pub mod template;
27
28use std::sync::LazyLock;
29
30use libxml::tree::{Node, NodeType};
31
32use self::{
33  cell::Cell,
34  normalize::*,
35  template::{Align, Axis, BorderSpec, ColumnSpec, Row, Template, TemplateConfig},
36};
37use crate::{
38  BoxOps,
39  common::{
40    arena::SymHashMap, dimension::Dimension, error::*, numeric_ops::NumericOps, object::Object,
41  },
42  digested::Digested,
43  document::{Document, get_node_qname, with_node_qname},
44  gullet::{self, ExpansionLevel},
45  mouth::{Mouth, MouthOptions},
46  state::*,
47  stomach::*,
48  token::Catcode,
49  tokens::Tokens,
50};
51
52/// The alignment property of an alignment that is a display by itself in TeX, `$$\halign…$$`: amsmath's align and
53/// gather families (amsmath.sty `\start@align`, `\start@gather`), latex.ltx's `eqnarray` and IEEEtrantools'
54/// `IEEEeqnarray` (IEEEtrantools.sty:2013). Not cases.sty's `numcases`, whose `\halign` is inside a `\vbox`
55/// (cases.sty:73-75). amsmath's `multline` is a display too but is not marked: its material is kept in the formula
56/// (TeX: "Improper \halign inside $$'s"), the safe direction. Set by the bindings (`latexml_engine::tex_tables`).
57pub const ALIGNMENT_IS_DISPLAY: &str = "display";
58
59/// The colour of the horizontal rule being drawn, as colortbl's `\CT@arc@` gives it (colortbl.sty:166-192): set by
60/// the binding in the rule's group, taken by [`Alignment::add_line`].
61pub const RULE_COLOR: &str = "lx@alignment@rule@color";
62
63/// Takes the colour [`RULE_COLOR`] holds for the rule being drawn (`None`: the default ink).
64pub fn take_rule_color() -> Option<String> {
65  let Some(Stored::String(color)) = lookup_value(RULE_COLOR) else {
66    return None;
67  };
68  assign_value(RULE_COLOR, Stored::None, Some(Scope::Local));
69  Some(crate::common::arena::with(color, str::to_string))
70}
71
72/// token-locators: source span of an alignment cell (its content's locator).
73/// `tabular`/`tr`/`td` are opened before their content's `box_to_absorb` is set,
74/// so the absorb explicitly stamps each with its cell/row/table span via
75/// `Document::set_current_box_locator`. See docs/performance/SOURCE_PROVENANCE.md §3.1.3.
76#[cfg(feature = "token-locators")]
77fn cell_loc(cell: &Cell) -> Option<crate::common::locator::Locator> {
78  cell
79    .boxes
80    .as_ref()
81    .and_then(|b| b.get_locator())
82    .filter(|l| l.from_line != 0)
83}
84
85/// Union (first `from` → last `to`) of a row's cell spans.
86#[cfg(feature = "token-locators")]
87fn row_span(row: &Row) -> Option<crate::common::locator::Locator> {
88  row
89    .get_columns()
90    .iter()
91    .filter_map(cell_loc)
92    .reduce(|a, b| crate::common::locator::Locator::new_range(a, b).unwrap_or(a))
93}
94use std::{
95  borrow::Cow,
96  collections::VecDeque,
97  fmt::{self, Debug, Display},
98  rc::Rc,
99};
100
101use regex::Regex;
102use rustc_hash::FxHashMap as HashMap;
103
104//DebuggableFeature('alignment', "Debug guessing headers of alignments/tables");
105pub type OpenContainerFn =
106  Rc<dyn Fn(&mut Document, HashMap<String, String>) -> Result<Option<Node>>>;
107pub type CloseContainerFn = Rc<dyn Fn(&mut Document) -> Result<Option<Node>>>;
108pub type OpenRowFn = Rc<dyn Fn(&mut Document, HashMap<String, Stored>) -> Result<()>>;
109pub type CloseRowFn = Rc<dyn Fn(&mut Document) -> Result<Option<Node>>>;
110pub type OpenColumnFn = Rc<dyn Fn(&mut Document, HashMap<String, String>) -> Result<Option<Node>>>;
111pub type CloseColumnFn = Rc<dyn Fn(&mut Document) -> Result<Option<Node>>>;
112
113static SINGLE_PUNCT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*[\.,;]\s*$").unwrap());
114
115pub struct AlignmentConfig {
116  pub template:        Option<Template>,
117  pub open_container:  OpenContainerFn,
118  pub close_container: CloseContainerFn,
119  pub open_row:        OpenRowFn,
120  pub close_row:       CloseRowFn,
121  pub open_column:     OpenColumnFn,
122  pub close_column:    CloseColumnFn,
123  pub properties:      SymHashMap<Stored>,
124  pub xml_attributes:  HashMap<String, String>,
125  pub is_math:         bool,
126}
127
128/// What becomes of the row being built at its end, asked by a binding from inside the row (longtable's `\kill`, its
129/// `\caption`'s row); the alignment carries it so a nested one cannot take it.
130#[derive(Clone, Copy, Debug)]
131pub enum RowDisposition {
132  /// Removed at its end.
133  Drop,
134  /// Removed at its end and handed to the function; a column ended after the request (`&`) withdraws it, the row
135  /// being more than the requesting cell.
136  Route(fn(&Row)),
137}
138
139#[derive(Clone)]
140pub struct Alignment {
141  in_column:         bool,
142  in_row:            bool,
143  in_tabular_head:   bool,
144  is_math:           bool,
145  is_normalized:     bool,
146  /// True for \halign templates
147  pub is_halign:     bool,
148  current_column:    usize,
149  /// The open cell's `alignmentStartColumn` and `IN_MATH` as its frame holds them, which a cell's end reads there
150  /// (TeX_Tables.pool.ltxml:470-471): kept for a cell a Fatal leaves, whose frame is no longer the innermost (OD #251).
151  cell_start_column: usize,
152  cell_in_math:      bool,
153  current_row:       Option<usize>,
154  reversion:         Option<Tokens>,
155  content_reversion: Option<Tokens>,
156  rows:              VecDeque<Row>,
157  properties:        SymHashMap<Stored>,
158  xml_attributes:    HashMap<String, String>,
159  template:          Template,
160  open_container:    OpenContainerFn,
161  close_container:   CloseContainerFn,
162  open_row:          OpenRowFn,
163  close_row:         CloseRowFn,
164  open_column:       OpenColumnFn,
165  close_column:      CloseColumnFn,
166  cached_width:      Option<Dimension>,
167  cached_height:     Option<Dimension>,
168  cached_depth:      Option<Dimension>,
169  column_widths:     Vec<Dimension>,
170  row_heights:       Vec<Dimension>,
171  row_depths:        Vec<Dimension>,
172  // Longtable: stored head/foot rows for reinsertion
173  pub head_rows:     Vec<Row>,
174  pub foot_rows:     Vec<Row>,
175  row_disposition:   Option<RowDisposition>,
176}
177impl Alignment {
178  /// Create a new Alignment.
179  /// `config` can contain:
180  ///   - template: an Alignment::Template object
181  ///   - openContainer: creates the container element with given attributes
182  ///   - closeContainer = sub($doc); closes the container
183  ///   - openRow        = sub($doc,%attrib); creates the row element with given attributes
184  ///   - closeRow       = closes the row
185  ///   - openColumn     = sub($doc,%attrib); creates the column element with given attributes
186  ///   - closeColumn    = closes the column
187  ///   - properties     = hashmap containing extra attributes for the container element.
188  ///   - xml_attributes = hashmap containing attributes for the main XML node
189  pub fn new(config: AlignmentConfig) -> Self {
190    let template = config.template.unwrap_or_default();
191    // Perl Alignment.pm: Copy width/height/depth from XML attributes to main properties,
192    // but REMOVE them from XML attributes so they don't appear on the element.
193    let mut xml_attributes = config.xml_attributes;
194    for key in ["width", "height", "depth"] {
195      xml_attributes.remove(key);
196    }
197    Alignment {
198      template,
199      current_row: None,
200      reversion: None,
201      content_reversion: None,
202      cached_width: None,
203      cached_height: None,
204      cached_depth: None,
205      open_container: config.open_container,
206      close_container: config.close_container,
207      open_row: config.open_row,
208      close_row: config.close_row,
209      open_column: config.open_column,
210      close_column: config.close_column,
211      current_column: 0,
212      cell_start_column: 0,
213      cell_in_math: false,
214      is_math: config.is_math,
215      in_row: false,
216      in_column: false,
217      in_tabular_head: false,
218      is_normalized: false,
219      is_halign: false,
220      properties: config.properties,
221      xml_attributes,
222      rows: VecDeque::new(),
223      column_widths: Vec::new(),
224      row_heights: Vec::new(),
225      row_depths: Vec::new(),
226      head_rows: Vec::new(),
227      foot_rows: Vec::new(),
228      row_disposition: None,
229    }
230  }
231
232  pub fn get_template(&self) -> &Template { &self.template }
233  pub fn get_template_mut(&mut self) -> &mut Template { &mut self.template }
234
235  pub fn current_row(&self) -> Option<&Row> {
236    match self.current_row {
237      Some(idx) => self.rows.get(idx),
238      None => None,
239    }
240  }
241  pub fn current_row_mut(&mut self) -> Option<&mut Row> {
242    match self.current_row {
243      Some(idx) => self.rows.get_mut(idx),
244      None => None,
245    }
246  }
247
248  pub fn new_row(&mut self) -> Option<&Row> {
249    let row = self.template.clone();
250    self.current_row = Some(self.rows.len());
251    self.rows.push_back(row);
252    self.current_column = 0;
253    self.rows.back()
254  }
255
256  pub fn remove_row(&mut self) -> Option<Row> { self.rows.pop_back() }
257
258  /// Ask for the current row's disposition at its end ([`RowDisposition`]).
259  pub fn set_row_disposition(&mut self, disposition: RowDisposition) {
260    self.row_disposition = Some(disposition);
261  }
262
263  /// A column ended (`&`): a [`RowDisposition::Route`] is withdrawn.
264  pub fn column_ended(&mut self) {
265    if matches!(self.row_disposition, Some(RowDisposition::Route(_))) {
266      self.row_disposition = None;
267    }
268  }
269
270  /// The row just ended, removed if its disposition says so.
271  pub fn dispose_ended_row(&mut self) {
272    match self.row_disposition.take() {
273      Some(RowDisposition::Drop) => {
274        self.remove_row();
275      },
276      Some(RowDisposition::Route(to)) => {
277        if let Some(row) = self.remove_row() {
278          to(&row);
279        }
280      },
281      None => {},
282    }
283  }
284
285  pub fn prepend_rows(&mut self, new_rows: Vec<Row>) {
286    for new_row in new_rows.into_iter().rev() {
287      self.rows.push_front(new_row)
288    }
289  }
290
291  pub fn append_rows(&mut self, new_rows: Vec<Row>) {
292    for new_row in new_rows.into_iter() {
293      self.rows.push_back(new_row)
294    }
295  }
296
297  pub fn rows(&self) -> &VecDeque<Row> { &self.rows }
298  pub fn rows_mut(&mut self) -> &mut VecDeque<Row> { &mut self.rows }
299
300  /// Turns the rows read into the table's columns: `\valign`'s body is read as `\halign`'s is, but each line its `\cr`
301  /// ends is a column of the table, its `&`-separated entries stacked from the top (tex.web §768, §785), and a span
302  /// covers rows. A column shorter than the longest ends in empty cells; the material a `\noalign` put between
303  /// columns opens the first row.
304  pub fn transpose(&mut self) {
305    let columns: Vec<Row> = self.rows.drain(..).collect();
306    let height = columns
307      .iter()
308      .map(|column| column.get_columns().len())
309      .max()
310      .unwrap_or(0);
311    let mut rows: Vec<Row> = (0..height)
312      .map(|_| {
313        let mut row = self.template.clone();
314        row.get_columns_mut().clear();
315        row
316      })
317      .collect();
318    for mut column in columns {
319      if let Some(first) = rows.first_mut() {
320        first.before.append(&mut column.before);
321        first.before.append(&mut column.after);
322      }
323      let mut cells = std::mem::take(column.get_columns_mut()).into_iter();
324      for row in &mut rows {
325        let mut cell = cells
326          .next()
327          .unwrap_or_else(|| Cell { empty: true, ..Cell::default() });
328        std::mem::swap(&mut cell.colspan, &mut cell.rowspan);
329        std::mem::swap(&mut cell.colspanned, &mut cell.rowspanned);
330        row.get_columns_mut().push(cell);
331      }
332    }
333    self.rows = rows.into();
334  }
335  pub fn get_cached_height(&self) -> Option<Dimension> { self.cached_height }
336  pub fn get_cached_depth(&self) -> Option<Dimension> { self.cached_depth }
337  pub fn get_row_heights(&self) -> &[Dimension] { &self.row_heights }
338  pub fn get_row_depths(&self) -> &[Dimension] { &self.row_depths }
339  pub fn get_column_widths(&self) -> &[Dimension] { &self.column_widths }
340  /// Run normalization (cell sizes, spans, pruning, positioning).
341  /// Perl: $alignment->normalizeAlignment
342  pub fn normalize(&mut self) -> Result<()> { normalize_alignment(self) }
343
344  pub fn add_line(&mut self, border: &str, cols: Vec<usize>) { self.add_rule(border, cols, false) }
345
346  /// [`Self::add_line`] for a dashed rule (arydshln's `\hdashline`, `\cdashline`): the sides it borders are dashed.
347  pub fn add_dashed_line(&mut self, border: &str, cols: Vec<usize>) {
348    self.add_rule(border, cols, true)
349  }
350
351  fn add_rule(&mut self, border: &str, cols: Vec<usize>, dashed: bool) {
352    let color = take_rule_color();
353    if let Some(row_idx) = self.current_row {
354      let Some(row) = self.rows.get_mut(row_idx) else {
355        return;
356      };
357      self.current_column = 1;
358      if !cols.is_empty() {
359        // Perl Alignment.pm:128-130 — `$row->column($c)` returns undef
360        // for out-of-range column index and autovivifies a discarded
361        // temp hash, so the assignment silently no-ops. Match that
362        // here: skip indices that don't map to a real column instead
363        // of panicking on `.unwrap()`. Witness: 0708.2784 with a
364        // `\hline`/`\cline`-style line referencing a column past the
365        // tabular's column count.
366        for c in cols {
367          if let Some(colspec) = row.get_column_mut(c) {
368            colspec.add_border(border, color.as_deref(), dashed);
369          }
370        }
371      } else {
372        for colspec in row.get_columns_mut() {
373          colspec.add_border(border, color.as_deref(), dashed)
374        }
375      }
376    }
377  }
378
379  pub fn next_column(&mut self) -> Result<Option<&mut Cell>> {
380    if self.current_row.is_none() {
381      return Ok(None);
382    }
383    self.current_column += 1;
384    // `current_row` index is Some (guarded above), but it can point past
385    // `self.rows` if that row was never materialised — degrade to "no next
386    // column" instead of panicking, LOUDLY (the sibling extra-& path errors
387    // too; fail-toward-flagging). Witness: 1809.10756.
388    let Some(current_row) = self.rows.get_mut(self.current_row.unwrap()) else {
389      Error!(
390        "unexpected",
391        "alignment_row",
392        "Alignment row index points past the materialised rows; dropping the cell"
393      );
394      return Ok(None);
395    };
396    if current_row.get_column_mut(self.current_column).is_some() {
397      Ok(current_row.get_column_mut(self.current_column))
398    } else {
399      // Perl: Error then add fallback column with align=center
400      Error!("unexpected", "&", "Extra alignment tab '&'");
401      let fallback = Cell {
402        align: Some(Align::Center),
403        ..Cell::default()
404      };
405      current_row.add_column(fallback);
406      Ok(current_row.get_column_mut(self.current_column))
407    }
408  }
409
410  pub fn last_column(&mut self) -> Option<&mut Cell> {
411    if let Some(row_idx) = self.current_row {
412      if let Some(row) = self.rows.get_mut(row_idx) {
413        self.current_column = row.get_columns().len();
414        row.get_column_mut(self.current_column)
415      } else {
416        None
417      }
418    } else {
419      None
420    }
421  }
422
423  pub fn current_column_number(&self) -> usize { self.current_column }
424  /// The open cell's `alignmentStartColumn`, as its `start_column` bound it.
425  pub fn cell_start_column(&self) -> usize { self.cell_start_column }
426  /// The open cell's `IN_MATH`, as its frame holds it (a formula in the cell is a group nested in it).
427  pub fn cell_in_math(&self) -> bool { self.cell_in_math }
428
429  /// Set a property on the current row (for attributes like backgroundcolor from \rowcolor)
430  pub fn set_row_property(&mut self, key: &str, value: String) {
431    if let Some(row_idx) = self.current_row
432      && let Some(row) = self.rows.get_mut(row_idx)
433    {
434      row.properties.insert(key.to_string(), Stored::from(value));
435    }
436  }
437
438  pub fn current_row_number(&self) -> usize {
439    self.rows.iter().filter(|row| !row.is_pseudo()).count()
440  }
441
442  /// The alignment's `name` XML attribute (e.g. `multline`, `gathered`), set
443  /// via the container bindings. Perl reads `$$alignment{properties}{attributes}
444  /// {name}`; here it lives in `xml_attributes`. Used by amsmath's `\shove*`.
445  pub fn get_name(&self) -> Option<&str> { self.xml_attributes.get("name").map(String::as_str) }
446
447  pub fn current_column(&mut self) -> Option<&mut Cell> {
448    self
449      .current_row
450      .and_then(|cw| self.rows.get_mut(cw)?.get_column_mut(self.current_column))
451  }
452
453  pub fn get_column(&mut self, n: usize) -> Option<&mut Cell> {
454    // TODO: do we need an immutable variant? For now alias the mutable one
455    self.get_column_mut(n)
456  }
457
458  pub fn get_column_mut(&mut self, n: usize) -> Option<&mut Cell> {
459    self
460      .current_row
461      .and_then(|cw| self.rows.get_mut(cw)?.get_column_mut(n))
462  }
463
464  // Ugh... these take boxes; adding before/after columns takes tokens!
465  pub fn add_before_row(&mut self, boxes: Vec<Digested>) {
466    if let Some(cw) = self.current_row
467      && let Some(current_row) = self.rows.get_mut(cw)
468    {
469      current_row.before.extend(boxes);
470    }
471  }
472
473  pub fn add_after_row(&mut self, boxes: Vec<Digested>) {
474    if let Some(cw) = self.current_row
475      && let Some(current_row) = self.rows.get_mut(cw)
476    {
477      current_row.after.extend(boxes);
478    }
479  }
480
481  pub fn omit_column(&mut self) {
482    if let Some(column) = self.current_column() {
483      column.omitted = true;
484    }
485  }
486
487  pub fn omit_next_column(&mut self) {
488    if let Some(cw) = self.current_row
489      && let Some(row) = self.rows.get_mut(cw)
490      && let Some(column) = row.get_column_mut(self.current_column + 1)
491    {
492      column.omitted = true;
493    }
494  }
495
496  /// [`Self::omit_next_column`], the cell's material boxed as text ([`Cell::omit_text_box`]).
497  pub fn omit_next_column_as_text(&mut self) {
498    if let Some(cw) = self.current_row
499      && let Some(row) = self.rows.get_mut(cw)
500      && let Some(column) = row.get_column_mut(self.current_column + 1)
501    {
502      column.omitted = true;
503      column.omit_text_box = true;
504    }
505  }
506
507  pub fn get_column_before(&mut self) -> Tokens {
508    if let Some(column) = self.current_column() {
509      if !column.omitted {
510        Tokens!(
511          T_CS!("\\lx@alignment@column@before"),
512          column.before.clone().unwrap_or_default().unlist()
513        )
514      } else if column.omit_text_box {
515        // the cell's own group, explicit braces: the before-column marker that follows resets the ledger; its leading
516        // and trailing fills are the cell's (tex_tables.rs `hoist_omit_text_box_fills`)
517        Tokens!(T_CS!("\\hbox"), T_BEGIN!())
518      } else {
519        Tokens!()
520      }
521    } else {
522      Tokens!()
523    }
524  }
525
526  pub fn get_column_after(&mut self) -> Tokens {
527    if let Some(column) = self.current_column() {
528      if !column.omitted {
529        // Possible \lx@column@trimright ??? (if LaTeX style???)
530        Tokens!(
531          column.after.clone().unwrap_or_default().unlist(),
532          T_CS!("\\lx@alignment@column@after")
533        )
534      } else if column.omit_text_box {
535        Tokens!(T_END!())
536      } else {
537        Tokens!()
538      }
539    } else {
540      Tokens!()
541    }
542  }
543
544  pub fn revert(&self) -> Result<Tokens> { Ok(self.reversion.clone().unwrap_or_default()) }
545
546  pub fn set_reversion(&mut self, rev: Tokens) { self.reversion = Some(rev); }
547  pub fn set_content_reversion(&mut self, rev: Tokens) { self.content_reversion = Some(rev); }
548
549  //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
550  // Support for building an alignment's Rows & Columns
551  pub fn is_in_row(&self) -> bool { self.in_row }
552
553  /// A math alignment (`array`, amsmath's environments), not a text one (`tabular`).
554  pub fn is_math(&self) -> bool { self.is_math }
555  pub fn is_in_column(&self) -> bool { self.in_column }
556  pub fn start_row(&mut self, pseudorow: bool) -> Result<()> {
557    self.new_row();
558    bgroup(); // Grouping around ROW!
559    if pseudorow {
560      self.current_row_mut().unwrap().set_pseudo()
561    } else {
562      // Store row number before digest — row hooks may need it (e.g. \rowcolors)
563      // and cannot re-borrow the alignment which is already mutably borrowed.
564      let row_num = self.current_row_number();
565      assign_value("alignmentRowNumber", row_num as i32, None);
566      let row_before = digest(T_CS!("\\lx@alignment@row@before"))?;
567      push_box_list(row_before);
568    }
569    self.in_row = true;
570    assign_value("alignmentStartColumn", 0, None); // ???
571    Ok(())
572  }
573
574  pub fn end_row(&mut self) -> Result<()> {
575    if self.in_row {
576      if self.in_column {
577        self.end_column()?;
578      }
579      egroup()?; // Grouping around ROW!
580      self.in_row = false;
581    }
582    Ok(()) //  Digest(T_CS('\lx@alignment@row@after'));
583  }
584
585  pub fn start_column(&mut self, pseudorow: bool) -> Result<()> {
586    if !self.in_row {
587      self.start_row(pseudorow)?;
588    } else if pseudorow {
589      self.current_row_mut().unwrap().set_pseudo();
590    }
591    bgroup(); // Grouping around CELL!
592    // Note: a VERY round-about way of tracking the column spanning!
593    assign_value("alignmentStartColumn", self.current_column_number(), None);
594    self.cell_start_column = self.current_column_number();
595    self.cell_in_math = lookup_bool("IN_MATH");
596    // Propagate `?` so a TooManyErrors Fatal (e.g. from a runaway
597    // `&` storm in a malformed alignment, paper 1112.6246) actually
598    // aborts rather than getting silently swallowed by `let _ =`.
599    let _colspec = self.next_column()?;
600    // Mark the cell frame: its `\aftergroup` tokens are run at the cell's
601    // end (see `end_column`).
602    assign_frame_value_sym(crate::pin!("alignCellGroup"), true);
603    // The cell frame is the template's brace pair (latex.ltx:16666 `\@tabclassz`'s `\@preamble{…\@sharp…}`, see
604    // `end_column`), so it carries the template-brace mark: a cell's stray `}` closes that `{` and leaves the frame
605    // (`stomach::close_template_brace`); the column end then meets the count −1 (tex.web §1127 `align_error`, "Missing {
606    // inserted"), and the inserted `{` is closed at the cell's end as the template's `}` would close it. Before, the `}`
607    // popped the cell frame and the column bookkeeping bound in it, and a `{a & b}` or `a & b}` row lost its first cell
608    // to a spanning second one (`colspan="2"`). Guard
609    // `perfect_kernel_batch70b::tabular_stray_close_brace_keeps_its_cells`.
610    assign_value(TEMPLATE_BRACE_OPEN, true, None);
611    set_align_group_count(1000000);
612    self.in_column = true;
613    Ok(())
614  }
615
616  pub fn end_column(&mut self) -> Result<()> {
617    if self.in_column {
618      // The template's `}` (see `start_column`): when the cell's own `}` closed the template's `{` and a `{` was
619      // inserted after it (tex.web §1127 `align_error`), that `{` is the group open at the cell's end, and this `}`
620      // closes it. Then the cell frame is popped as itself, never taken for a template brace again.
621      if !is_value_bound("alignCellGroup", Some(0))
622        && !lookup_bool(TEMPLATE_BRACE_OPEN)
623        && off_save_closer().is_some_and(|closer| closer == T_END!())
624      {
625        egroup()?;
626      }
627      if is_value_bound("alignCellGroup", Some(0)) {
628        assign_value(TEMPLATE_BRACE_OPEN, false, None);
629      }
630      // `\aftergroup` IN A CELL FIRES INSIDE THE CELL. LaTeX's tabular/array
631      // entry template wraps every entry in a brace group (latex.ltx
632      // `\@classz`: `{\hfil\hskip1sp\ignorespaces\@sharp\unskip\hfil}`), so an
633      // `\aftergroup` in the entry binds to THAT group and its tokens run at
634      // the entry's `}` — while the cell is still open, before `&`/`\cr` is
635      // acted on (tex.web §282 `unsave` back-inputs them; a bare `\halign`
636      // has no such group and the tokens would start the next cell/row).
637      // The cell frame here is that group, but `egroup` unread its tokens
638      // AFTER the column had ended, so they were read as the NEXT cell — and
639      // after the last cell they opened a spurious one: babel.def:738-742
640      // `\selectlanguage` = `\aftergroup\bbl@pop@language…` in a tabular
641      // cell (uantwerpenexam.cls:426 `\engdut`, uantwerpenexam-example2 41;
642      // derivative 101; Perl identical) ended with "`\@end@tabular` Attempt
643      // to close boxing group". So run the cell frame's `\aftergroup` list
644      // now, inside the cell. Guard:
645      // `perfect_kernel_batch54::aftergroup_in_a_tabular_cell_fires_inside_the_cell`.
646      if is_value_bound("alignCellGroup", Some(0))
647        && let Some(Stored::VecDequeStored(after)) = lookup_value("afterGroup")
648        && !after.is_empty()
649      {
650        assign_value(
651          "afterGroup",
652          Stored::VecDequeStored(VecDeque::new()),
653          Some(Scope::Local),
654        );
655        let mut toks: Vec<crate::token::Token> = Vec::new();
656        for entry in after {
657          match entry {
658            Stored::Tokens(t) => toks.extend(t.unlist()),
659            Stored::Token(t) => toks.push(t),
660            _ => {},
661          }
662        }
663        let digested = digest(Tokens::new(toks))?;
664        push_box_list(digested);
665      }
666      egroup()?; // Grouping around CELL!
667      self.in_column = false;
668    }
669    Ok(())
670  }
671
672  pub fn set_in_tabular_head(&mut self) { self.in_tabular_head = true; }
673  pub fn unset_in_tabular_head(&mut self) { self.in_tabular_head = false; }
674  pub fn is_in_tabular_head(&self) -> bool { self.in_tabular_head }
675
676  pub fn get_properties_mut(&mut self) -> &mut SymHashMap<Stored> { &mut self.properties }
677  pub fn get_xml_attributes_mut(&mut self) -> &mut HashMap<String, String> {
678    &mut self.xml_attributes
679  }
680}
681
682//======================================================================
683// Constructing the XML for the alignment.
684
685impl Object for Alignment {}
686impl BoxOps for Alignment {
687  fn get_properties(&self) -> &SymHashMap<Stored> { &self.properties }
688  fn with_properties<R, FnR>(&self, caller: FnR) -> R
689  where FnR: FnOnce(&SymHashMap<Stored>) -> R {
690    caller(&self.properties)
691  }
692  fn get_property(&self, key: &str) -> Option<Cow<'_, Stored>> {
693    self.properties.get(key).map(Cow::Borrowed)
694  }
695  fn get_properties_mut(&mut self) -> &mut SymHashMap<Stored> { &mut self.properties }
696
697  fn compute_size(
698    &self,
699    _options: SymHashMap<Stored>,
700  ) -> Result<(Dimension, Dimension, Dimension)> {
701    Ok((
702      Dimension::default(),
703      Dimension::default(),
704      Dimension::default(),
705    ))
706  }
707  fn get_font(&self) -> Result<Option<Rc<crate::common::font::Font>>> { Ok(None) }
708  fn get_string(&self) -> Result<Cow<'_, str>> { Ok(Cow::Borrowed("")) }
709
710  fn compute_size_and_cache(
711    &mut self,
712    _options: SymHashMap<Stored>,
713  ) -> Result<(Dimension, Dimension, Dimension)> {
714    normalize_alignment(self)?;
715    let w = self.cached_width.unwrap();
716    let h = self.cached_height.unwrap();
717    let d = self.cached_depth.unwrap();
718    // Store in properties so get_size()'s has_property("cached_width") check works
719    self.properties.insert("cached_width", Stored::Dimension(w));
720    self
721      .properties
722      .insert("cached_height", Stored::Dimension(h));
723    self.properties.insert("cached_depth", Stored::Dimension(d));
724    Ok((w, h, d))
725  }
726
727  fn be_absorbed(&self, _document: &mut Document) -> Result<Vec<Node>> {
728    // Alignments must be absorbed via `be_absorbed_mut` because
729    // `normalize_alignment` mutates the carrier (rearranging rows,
730    // applying border specs, etc). The `Digested::be_absorbed` dispatch
731    // for `DigestedData::Alignment` correctly calls `be_absorbed_mut`;
732    // this immutable path should never be reached in practice. Surface
733    // a meaningful error rather than a bare `todo!()` panic if an
734    // unexpected caller lands here.
735    fatal!(
736      Internal,
737      Misdefined,
738      "Alignment::be_absorbed called — use be_absorbed_mut instead \
739       (alignment rearrangement requires &mut self)"
740    );
741  }
742  fn be_absorbed_mut(&mut self, document: &mut Document) -> Result<Vec<Node>> {
743    let ismath = self.is_math;
744    normalize_alignment(self)?;
745    // token-locators: the whole table's span (union of all cell spans), stamped
746    // on the `tabular` element below. Computed before the mutable `rows` borrow.
747    #[cfg(feature = "token-locators")]
748    let table_span = self
749      .rows
750      .iter()
751      .filter_map(row_span)
752      .reduce(|a, b| crate::common::locator::Locator::new_range(a, b).unwrap_or(a));
753    let rows = &mut self.rows;
754    if rows.is_empty() {
755      return Ok(Vec::new());
756    }
757
758    // Guard via the absorb limit to avoid infinite loops (Perl L478-483);
759    // the counter and its limit are typed State fields (`State::absorb_count`).
760    let absorb_limit = absorb_limit();
761    if absorb_limit > 0 {
762      let absorb_count = next_absorb_id();
763      if absorb_count > absorb_limit {
764        fatal!(
765          Timeout,
766          Convert,
767          s!(
768            "Whatsit absorb limit of {} exceeded, infinite loop?",
769            absorb_limit
770          )
771        );
772      }
773    }
774
775    // We _should_ attach boxes to the alignment and rows,
776    // but (ATM) we"ve only got sensible boxes for the cells.
777    let mut attrs = HashMap::default();
778    std::mem::swap(&mut attrs, &mut self.xml_attributes);
779    // Perl Alignment.pm L311-316: pass dimension data to openContainer callback
780    // Serialized as px-value strings for callbacks that need positioning (tikz matrices).
781    if let Some(w) = self.cached_width {
782      attrs.insert("cwidth".to_string(), format!("{}", w.px_value(None)));
783    }
784    if let Some(h) = self.cached_height {
785      attrs.insert("cheight".to_string(), format!("{}", h.px_value(None)));
786    }
787    if let Some(d) = self.cached_depth {
788      attrs.insert("cdepth".to_string(), format!("{}", d.px_value(None)));
789    }
790    // Perl Alignment.pm L321-323: rowheights / rowdepths / columnwidths, as comma-separated px
791    // values (openTikzAlignment reads the last row depth).
792    for (key, dims) in [
793      ("rowheights", &self.row_heights),
794      ("rowdepths", &self.row_depths),
795      ("columnwidths", &self.column_widths),
796    ] {
797      if !dims.is_empty() {
798        let px: Vec<String> = dims
799          .iter()
800          .map(|d| format!("{}", d.px_value(None)))
801          .collect();
802        attrs.insert(key.to_string(), px.join(","));
803      }
804    }
805    let open_container_fn = &self.open_container;
806    // token-locators: stamp the `tabular` with the table span before it opens.
807    #[cfg(feature = "token-locators")]
808    document.set_current_box_locator(table_span);
809    // an alignment is a TeX box: the container it opens is marked, its cells' text no body text for a field's print
810    // outside it (OXIDIZED_DESIGN #715)
811    document.arm_field_box();
812    let opened = open_container_fn(document, attrs);
813    document.disarm_field_box();
814    opened?;
815
816    for row in rows {
817      // token-locators: stamp this `tr` with the row's span before it opens.
818      #[cfg(feature = "token-locators")]
819      document.set_current_box_locator(row_span(row));
820      let vpad_opt = row.get_padding().copied();
821      // Perl Alignment.pm L319-324: pass position/size to openRow callback
822      let mut open_row_attrs = HashMap::default();
823      for (k, v) in &row.properties {
824        open_row_attrs.insert(k.clone(), v.clone());
825      }
826      if row.has_explicit_tags() {
827        open_row_attrs.insert(
828          template::TAGGED_ROW_ATTRIBUTE.to_string(),
829          Stored::from("true"),
830        );
831      }
832      if let Some(x) = row.x {
833        open_row_attrs.insert("x".to_string(), Stored::Dimension(x));
834      }
835      if let Some(y) = row.y {
836        open_row_attrs.insert("y".to_string(), Stored::Dimension(y));
837      }
838      if let Some(w) = row.cached_width {
839        open_row_attrs.insert("cwidth".to_string(), Stored::Dimension(w));
840      }
841      if let Some(h) = row.cached_height {
842        open_row_attrs.insert("cheight".to_string(), Stored::Dimension(h));
843      }
844      if let Some(d) = row.cached_depth {
845        open_row_attrs.insert("cdepth".to_string(), Stored::Dimension(d));
846      }
847      let open_row_fn = &self.open_row;
848      open_row_fn(document, open_row_attrs)?;
849      for before in row.before.iter() {
850        document.absorb(before, None)?;
851      }
852      for cell in row.get_columns_mut().iter_mut() {
853        if cell.skipped {
854          continue;
855        }
856        // Normalize the border attribute
857        // Perl: join(' ', sort(map { split(/ */, $_) } $$cell{border}));
858        //       $border =~ s/(.) \1/$1$1/g;
859        let mut border_chars: Vec<char> =
860          cell.border.chars().filter(|c| !c.is_whitespace()).collect();
861        border_chars.sort_unstable();
862        let mut border = String::new();
863        for (idx, &c) in border_chars.iter().enumerate() {
864          border.push(c);
865          // Space between different consecutive chars, no space between same chars
866          if idx + 1 < border_chars.len() && border_chars[idx + 1] != c {
867            border.push(' ');
868          }
869        }
870        let open_column_fn = &self.open_column;
871        let mut cell_attrs = HashMap::default();
872        // Perl Alignment.pm L358-359: pass position/size to openColumn callback
873        if let Some(x) = cell.x {
874          cell_attrs.insert("x".to_string(), format!("{}", x.px_value(None)));
875        }
876        if let Some(y) = cell.y {
877          cell_attrs.insert("y".to_string(), format!("{}", y.px_value(None)));
878        }
879        if let Some(w) = cell.cached_width {
880          cell_attrs.insert("cwidth".to_string(), format!("{}", w.px_value(None)));
881        }
882        if let Some(h) = cell.cached_height {
883          cell_attrs.insert("cheight".to_string(), format!("{}", h.px_value(None)));
884        }
885        if let Some(d) = cell.cached_depth {
886          cell_attrs.insert("cdepth".to_string(), format!("{}", d.px_value(None)));
887        }
888        // Perl: always passes align attribute (Alignment.pm L350).
889        // A paragraph column (p/m/b/tabularx-X/tabulary — all `Align::Justify`)
890        // gets `align="left"` on the `<td>` in Perl, regardless of any `>{}`
891        // alignment prefix (the prefix's `\centering`/`\raggedleft` goes on the
892        // INNER `<inline-block>`/`<p>`, not the cell). Map the Justify marker
893        // (kept for `is_pcol` detection in `\lx@alignment@multicolumn`) to the
894        // Perl-faithful `"left"` here on the cell attribute only (cluster-B Kind-B).
895        if let Some(ref align) = cell.align {
896          let td_align = if *align == Align::Justify {
897            "left".to_string()
898          } else {
899            align.name()
900          };
901          cell_attrs.insert(String::from("align"), td_align);
902        }
903        if let Some(ref vattach) = cell.vattach {
904          cell_attrs.insert(String::from("vattach"), vattach.clone());
905        }
906        if let Some(w) = cell.width {
907          cell_attrs.insert(String::from("width"), w.to_attribute());
908        }
909        let mut cssstyle: Vec<String> = vpad_opt
910          .map(|vpad| s!("padding-bottom: {vpad}"))
911          .into_iter()
912          .collect();
913        cssstyle.extend(cell.border_color_style());
914        if !cssstyle.is_empty() {
915          cell_attrs.insert(String::from("cssstyle"), cssstyle.join(";"));
916        }
917        // colortbl: backgroundcolor from \columncolor/\cellcolor
918        if let Some(ref bg) = cell.backgroundcolor {
919          cell_attrs.insert(String::from("backgroundcolor"), bg.clone());
920        }
921        // Perl: colspan/rowspan attributes for spanning cells
922        if cell.colspan.unwrap_or(1) != 1 {
923          cell_attrs.insert(String::from("colspan"), cell.colspan.unwrap().to_string());
924        }
925        if cell.rowspan.unwrap_or(1) != 1 {
926          cell_attrs.insert(String::from("rowspan"), cell.rowspan.unwrap().to_string());
927        }
928        if !border.is_empty() {
929          cell_attrs.insert(String::from("border"), border);
930        }
931        if cell.thead_in_column || cell.thead_in_row {
932          let mut thead = String::new();
933          if cell.thead_in_column {
934            thead.push_str(Axis::Column.name());
935            if cell.thead_in_row {
936              thead.push(' ');
937            }
938          }
939          if cell.thead_in_row {
940            thead.push_str(Axis::Row.name());
941          }
942          if !thead.is_empty() {
943            cell_attrs.insert(String::from("thead"), thead);
944          }
945        }
946        // Perl Alignment.pm L332-347: ltx_nopad_l/ltx_nopad_r CSS classes
947        // Based on lspaces/rspaces width relative to 0.2em threshold
948        let mut classes: Vec<String> = Vec::new();
949        let empty = cell.empty;
950        // Perl: $$cell{boxes} — truthy when boxes field is defined (even if empty List)
951        let has_boxes = cell.boxes.is_some();
952        let mut pre_absorb: Option<Digested> = None;
953        let mut post_absorb: Option<Digested> = None;
954        if !ismath {
955          // 0.2em ≈ 131072 scaled points; 1.5em ≈ 983040 scaled points (at 10pt font)
956          let threshold_02em: i64 = 131072;
957          let threshold_15em: i64 = 983040;
958          // Perl: $lpad = ($$cell{lspaces} ? $$cell{lspaces}->getWidth->valueOf : 0)
959          // Note: In Perl, lspaces is populated from \lx@intercol (isSpace, width=tabcolsep)
960          // during cell content extraction. Rust doesn't populate lspaces, so we approximate:
961          // - If template has \lx@intercol → there IS intercolumn padding (assume 0.2em)
962          // - Else if template has \hfil/\hfill → centering fill, treat as padding (prevents
963          //   incorrect ltx_nopad_l for regular centered/right-aligned columns)
964          // - Else → no padding (assume 0, enables ltx_nopad_l)
965          // Perl L338-339: lpad/rpad from extracted lspaces/rspaces width.
966          // When lspaces/rspaces are populated (from cell extraction), use their
967          // actual width. When None, use template heuristic as fallback.
968          // Perl L338-339: lpad/rpad from lspaces/rspaces width.
969          // In Perl, lspaces is populated from the left-scan of digested cell boxes.
970          // The left-scan encounters template-injected boxes (vrules, intercol spaces,
971          // fills) and extracts spacing. When lspaces is undef, Perl returns 0.
972          // In Rust, lspaces is not always populated by extraction (extraction stores
973          // None for empty lspaces). We use intercol_reachable_in_before to distinguish:
974          // - Regular columns (|l|): \vrule then \lx@intercol → reachable → threshold
975          // - @{text} columns: text then \lx@intercol → NOT reachable → 0
976          //
977          // KNOWN LIMITATION: this fallback over-reports padding for some
978          // numprint cells (`\lx@intercol\nprt@begin\ignorespaces`-style
979          // before): Perl's extracted lspaces would be undef there → lpad=0 →
980          // ltx_nopad_l added; our heuristic returns threshold_02em → no nopad_l.
981          // Naively removing the heuristic regresses 21 other tabular tests
982          // because Rust's extraction doesn't always populate lspaces for
983          // cases where Perl's would (`|l|`, `|c|`, `|r|`, p/m/X, etc.). The
984          // proper fix is to make lspaces extraction reliable to match Perl's
985          // left-scan; until then, this heuristic is load-bearing.
986          let lpad = cell
987            .lspaces
988            .as_ref()
989            .and_then(|ls| ls.get_width(None).ok().flatten())
990            .map(|rv| rv.value_of())
991            .unwrap_or_else(|| {
992              if intercol_reachable_in_before(&cell.before) || template_has_fill(&cell.before) {
993                threshold_02em
994              } else {
995                0
996              }
997            });
998          let rpad = cell
999            .rspaces
1000            .as_ref()
1001            .and_then(|rs| rs.get_width(None).ok().flatten())
1002            .map(|rv| rv.value_of())
1003            .unwrap_or_else(|| {
1004              // Perl: rpad from rspaces. When not extracted, use template.
1005              // Only the after tokens determine right padding.
1006              if template_has_intercol(&cell.after) {
1007                threshold_02em
1008              } else {
1009                0
1010              }
1011            });
1012          // Perl L340-341: ltx_nopad_l, unless math mode (Perl: `unless $ismath`)
1013          if !ismath && (!empty || has_boxes) && lpad < threshold_02em {
1014            classes.push("ltx_nopad_l".to_string());
1015          } else if lpad < threshold_15em {
1016            // In math mode, absorb named spacing (like \quad) as XMHint content
1017            // even when below the 1.5em threshold. This preserves XMHint for
1018            // the math parser to convert to lpadding.
1019            if ismath && cell.lspaces.is_some() {
1020              pre_absorb = cell.lspaces.take();
1021            }
1022          } else {
1023            pre_absorb = cell.lspaces.take();
1024          }
1025          // Perl L344-345: ltx_nopad_r, unless math mode (Perl: `unless $ismath`)
1026          if !ismath && (!empty || has_boxes) && rpad < threshold_02em {
1027            classes.push("ltx_nopad_r".to_string());
1028          } else if rpad < threshold_15em {
1029            // do nothing — use CSS default padding
1030          } else {
1031            post_absorb = cell.rspaces.take();
1032          }
1033        }
1034        classes.splice(0..0, cell.border_dashed_classes());
1035        if let Some(ref cell_class) = cell.class {
1036          classes.insert(0, cell_class.clone());
1037        }
1038        let class_str: String = classes
1039          .into_iter()
1040          .filter(|s| !s.is_empty())
1041          .collect::<Vec<_>>()
1042          .join(" ");
1043        if !class_str.is_empty() {
1044          cell_attrs.insert(String::from("class"), class_str);
1045        }
1046        //       # Which properties do we expose to the constructor?
1047        //       x      => $$cell{x}, y => $$cell{y},
1048        //       cached_width => $$cell{cached_width}, cached_height => $$cell{cached_height},
1049        // cached_depth => $$cell{cached_depth})
1050        // token-locators: stamp this `td` with the cell's content span before it
1051        // opens (its content's box_to_absorb is set just below, after the open).
1052        #[cfg(feature = "token-locators")]
1053        document.set_current_box_locator(cell_loc(cell));
1054        cell.cell = open_column_fn(document, cell_attrs)?;
1055        // Perl L362: absorb cell content only if !skippable (not just !empty)
1056        if !cell.skippable {
1057          let box_ref = cell.boxes.as_ref().unwrap();
1058          // local $LaTeXML::BOX
1059          document.set_box_to_absorb(Some(box_ref.clone()));
1060          // Perl wraps cell content in XMArg for math alignments, but NOT for _Capture_ columns
1061          // (_Capture_ is not in the schema, so Perl's openElement validation prevents XMArg there)
1062          let cur_qname = get_node_qname(document.get_node());
1063          let wrap_xmarg =
1064            ismath && !crate::common::arena::with(cur_qname, |s| s.ends_with("_Capture_"));
1065          if wrap_xmarg {
1066            // Hacky! Perl Alignment.pm:372 `rule => 'Anything,'`: the trailing comma lets
1067            // parse_single set a cell's closing punctuation aside as presentation.
1068            document.open_element("ltx:XMArg", Some(string_map!("rule" => "Anything,")), None)?;
1069          }
1070          // Perl L365: absorb pre-spacing (lspaces > 1.5em)
1071          if let Some(ref pre) = pre_absorb {
1072            document.absorb(pre, None)?;
1073          }
1074          // In math mode, absorb lspaces as content (creates XMHint for \quad etc.)
1075          // This is needed for the math parser to convert XMHint → lpadding.
1076          if ismath
1077            && pre_absorb.is_none()
1078            && let Some(ref lsp) = cell.lspaces
1079          {
1080            document.absorb(lsp, None)?;
1081          }
1082          document.absorb(box_ref, None)?;
1083          // Perl L367: absorb post-spacing (rspaces > 1.5em)
1084          if let Some(ref post) = post_absorb {
1085            document.absorb(post, None)?;
1086          }
1087          if wrap_xmarg {
1088            // Hacky!
1089            document.close_element("ltx:XMArg")?;
1090          }
1091          // expire local $LaTeXML::BOX
1092          document.expire_box_to_absorb();
1093        } else if let Some(ref boxes) = cell.boxes {
1094          // Cell is skippable but may contain preserved boxes (e.g. \label wrapped
1095          // in \lx@hidden@noalign with alignmentPreserve=true). These boxes need
1096          // to be absorbed so their constructors run (e.g. \label sets labels= on
1097          // the parent equation element via float_to_label).
1098          // In Perl, \hfil from the template contributes cell width, making such
1099          // cells non-skippable. In Rust, \hfil doesn't contribute width.
1100          for item in boxes.unlist() {
1101            if item.get_property_bool("alignmentPreserve") {
1102              document.absorb(&item, None)?;
1103            }
1104          }
1105        }
1106        let close_column_fn = &self.close_column;
1107        close_column_fn(document)?;
1108      }
1109      for after in row.after.iter() {
1110        document.absorb(after, None)?;
1111      }
1112      let close_row_fn = &self.close_row;
1113      close_row_fn(document)?;
1114    }
1115    let close_container_fn = &self.close_container;
1116    let node_opt = close_container_fn(document)?;
1117
1118    // If we're not nested inside another tabular
1119    // [This should be an afterConstruct somewhere?]
1120    // If requested to guess headers & we're not nested inside another tabular
1121    if let Some(mut node) = node_opt {
1122      if document
1123        .findnodes("ancestor::ltx:tabular", Some(&node))
1124        .is_empty()
1125      {
1126        let hashead = !document
1127          .findnodes("descendant::ltx:td[@thead]", Some(&node))
1128          .is_empty();
1129        // If requested && no cells are already marked as being thead, apply heuristic
1130        let guess_headers = self
1131          .properties
1132          .get("guess_headers")
1133          .map(|v| !matches!(v, Stored::Bool(false)))
1134          .unwrap_or(false);
1135        if guess_headers && !hashead {
1136          guess_alignment_headers(document, &mut node, self)?;
1137        }
1138        // Otherwise, if not a math array, group thead & tbody rows
1139        // TODO: Re-design asking the outer Whatsit about "!body->isMath"
1140        else if hashead && !ismath {
1141          // in case already marked w/thead|tbody
1142          alignment_regroup_rows(document, &node)?;
1143        }
1144      }
1145      Ok(vec![node])
1146    } else {
1147      Ok(Vec::new())
1148    }
1149  }
1150}
1151
1152impl Debug for Alignment {
1153  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1154    write!(
1155      f,
1156      "Alignment{{template:{:?}, properties:{:?}, rows:{:?} }}",
1157      self.template, self.properties, self.rows
1158    )
1159  }
1160}
1161
1162impl Display for Alignment {
1163  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{self:?}") }
1164}
1165impl PartialEq for Alignment {
1166  fn eq(&self, other: &Alignment) -> bool {
1167    // TODO: Is it enough to compare the owned template?
1168    self.template == other.template
1169  }
1170}
1171
1172//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1173// Dealing with templates
1174
1175// newcolumntype
1176//  defines \NC@rewrite@<char>
1177//    As macro
1178//    or "constructor" (or just sub that creates a column)
1179
1180/// a reader for the Template parameter type
1181pub fn read_alignment_template() -> Result<Template> {
1182  gullet::skip_spaces()?;
1183  local_build_template(Template::default());
1184  let mut tokens = vec![T_BEGIN!()];
1185  // The template is its argument: a balanced group (latex.ltx `\@mkpream`
1186  // takes `#1`; tex.web's preamble ends at its `}`), or a single token,
1187  // parsed in a mouth of its own. A column type that takes an argument at
1188  // the template's end (`{cp}`, `{c@}`) then finds that end, not the document
1189  // after it (Perl reads the template from the document, Alignment.pm:895-921,
1190  // KNOWN_PERL_ERRORS #292; pdflatex "Missing p-arg in array arg"). Repro
1191  // `kernel-alignment/tabular_template_missing_argument.tex`.
1192  let template = match gullet::read_token()? {
1193    Some(open) if open.get_catcode() == Catcode::BEGIN => {
1194      gullet::read_balanced(ExpansionLevel::Off, false, false)?
1195    },
1196    Some(single) => Tokens::new(vec![single]),
1197    None => Tokens::default(),
1198  };
1199  // A sourceless mouth, which the locator walk passes over (Perl getLocator
1200  // skips a mouth with no source, Gullet.pm:150-157), so the template's
1201  // diagnostics point into the document. The template's braces, read above,
1202  // still enclose it: TeX scans the preamble as a macro argument inside
1203  // `\@mkpream`'s `\edef` (latex.ltx:16632), so an `&` in it never ends an
1204  // enclosing alignment's cell.
1205  empty_column_rewrite_accumulator()?;
1206  increment_align_group_count();
1207  let parsed = gullet::reading_from_mouth(Mouth::create("", MouthOptions::default())?, || {
1208    gullet::unread(template);
1209    parse_alignment_template_tokens()
1210  });
1211  decrement_align_group_count();
1212  parsed?;
1213  tokens.push(T_END!());
1214  with_current_build_template(|template_opt| {
1215    let t = template_opt.unwrap();
1216    t.set_reversion(Tokens::new(tokens));
1217    // Perl Alignment.pm:923: $BUILD_TEMPLATE->finish
1218    t.finish();
1219  });
1220  Ok(take_build_template().unwrap())
1221}
1222
1223/// Empties `\@temptokena`, the accumulator array.sty's column-type search
1224/// rewrites the preamble into: `\NC@do` empties it before every search
1225/// (array.sty:361), `\NC@` appends the preamble read before the column type
1226/// (array.sty:351-352), and a package's own `\NC@rewrite@<c>` reads it back
1227/// (rccol.sty `\rc@rewrite@@@`: `\edef…{\the\@temptokena>{…}c<{…}}`). This
1228/// reader has already taken that prefix as columns, so the faithful value is
1229/// empty — not what a package left there at load time: natbib's `\appdef`
1230/// (natbib.sty:163-166) leaves its last argument, which `\the\@temptokena`
1231/// spliced into rccol's `R` column, its `\@bibibid@` swallowing the `>` and the
1232/// cell code then expanded here until `Fatal:Timeout:PushbackLimit` (1101.1265,
1233/// 0812.2309, 2609.37147). A local assignment: the environment's group bounds
1234/// it, as `\@mkpream`'s `\@temptokena{#1}` (array.sty:393) is bounded.
1235fn empty_column_rewrite_accumulator() -> Result<()> {
1236  let cs = T_CS!("\\@temptokena");
1237  if let Some(defn) = lookup_definition(&cs)?
1238    && defn.is_register()
1239    && matches!(defn.value_of(Vec::new()), Some(crate::definition::register::RegisterValue::Tokens(ref toks)) if !toks.is_empty())
1240  {
1241    defn.set_value(
1242      crate::definition::register::RegisterValue::Tokens(Tokens::default()),
1243      None,
1244      Vec::new(),
1245    )?;
1246  }
1247  Ok(())
1248}
1249
1250/// The column-type loop of [`read_alignment_template`], reading the template
1251/// from the mouth it was given until that mouth is empty.
1252fn parse_alignment_template_tokens() -> Result<()> {
1253  while let Some(op) = gullet::read_token()? {
1254    let cc = op.get_catcode();
1255    if cc == Catcode::SPACE || cc == Catcode::END {
1256    } else {
1257      match lookup_expandable(&T_CS!(s!("\\NC@rewrite@{op}")), None)? {
1258        Some(defn) if takes_required_argument(defn.as_ref()) && template_is_exhausted()? => {
1259          // The template ended where the column type wanted its argument:
1260          // latex.ltx `\@mkpream` ends on class 2/3, "Missing @-exp/p-arg in
1261          // array arg" (latex.ltx:16643-16644, `\@preamerr` 8997-9003); array
1262          // "Missing arg: token ignored" (array.sty:331, 414). The column is
1263          // dropped, as array drops it.
1264          Error!(
1265            "expected",
1266            op,
1267            s!(
1268              "Missing argument of the column type '{op}' at the end of the tabular template; token ignored"
1269            )
1270          );
1271        },
1272        Some(defn) => {
1273          let invoked =
1274            crate::parameter::dropping_argument_tails(crate::parameter::IN_EVERY_CELL, || {
1275              defn.invoke(true)
1276            })?;
1277          gullet::unread(invoked);
1278        },
1279        _ => {
1280          if cc == Catcode::BEGIN {
1281            let balanced_arg = gullet::read_balanced(ExpansionLevel::Off, false, false)?;
1282            if !balanced_arg.is_empty() {
1283              gullet::unread(balanced_arg);
1284            }
1285          } else if cc.is_active_or_cs()
1286            && let Some(defn) = lookup_expandable(&op, Some(false))?
1287            // Everything `\edef` expands, EXCEPT the three that reorder or
1288            // scan for a terminator: a `\csname`/`\expandafter`/`\noexpand`
1289            // reached here is almost always the "safety valve" below having
1290            // over-read past an unknown column's `{arg}` (Perl Alignment.pm:906
1291            // shares the over-read); invoking `\csname` then scanned for an
1292            // `\endcsname` far outside the template (its own mouth now ends
1293            // the scan there) — nicematrix/nicematrix
1294            // 109 → 1002 errors + Fatal (`V{3cm}` before the binding
1295            // registered `V`). Bounded primitives (`\string`, `\number`,
1296            // `\romannumeral`, `\the`, `\meaning`) are what a class's
1297            // `\edef\pt@format{\string#1}` (aguplus.cls:314) relies on.
1298            && !op.with_str(|s| matches!(s, "\\csname" | "\\expandafter" | "\\noexpand"))
1299          {
1300            // Macro-valued column specs: real `\@mkpream` FULLY edef-expands
1301            // the preamble before classification (latex.ltx L16610-16644,
1302            // `\@xexpast`'s `\edef\reserved@a{#1}` under
1303            // `\let\protect\@unexpandable@protect`), so
1304            // `\begin{tabular}{|l|\mycol|}` with `\def\mycol{c|}` is valid
1305            // LaTeX. `Some(false)` filters protected defs — the exact
1306            // analogue of the `\@unexpandable@protect` shield. Perl's
1307            // ReadAlignmentTemplate (Alignment.pm L895-921) reads unexpanded
1308            // and drops the CS (shared failure; pdflatex clean). Witness:
1309            // dijkstra-fr `\dijk_last_col_type` (noexpand-protected by
1310            // design in dijkstra.sty's `\edef\dijk_tab`, L245-258) — 7
1311            // extra-`&` errors. Iterated re-read = full edef semantics.
1312            gullet::unread(defn.invoke(true)?);
1313          } else {
1314            Warn!("unexpected", op, s!("Unrecognized tabular template {op:?}"));
1315          }
1316        },
1317      }
1318    }
1319  }
1320  Ok(())
1321}
1322
1323/// Whether `defn` reads an argument it cannot do without (any parameter that
1324/// is neither optional nor valueless).
1325fn takes_required_argument(defn: &dyn crate::definition::Definition) -> bool {
1326  defn.get_parameters().is_some_and(|params| {
1327    params
1328      .get_parameters()
1329      .iter()
1330      .any(|p| !p.optional && !p.novalue)
1331  })
1332}
1333
1334/// Whether the template's mouth has nothing left but spaces (which a template
1335/// ignores).
1336fn template_is_exhausted() -> Result<bool> {
1337  match gullet::read_non_space()? {
1338    Some(token) => {
1339      gullet::unread_one(token);
1340      Ok(false)
1341    },
1342    None => Ok(true),
1343  }
1344}
1345
1346pub fn parse_alignment_template(spec: &str) -> Result<Template> {
1347  let reader_mouth = Mouth::new(&s!("{{{spec}}}"), None)?;
1348  gullet::reading_from_mouth(reader_mouth, read_alignment_template)
1349}
1350
1351pub fn matrix_template() -> Template {
1352  Template::new(TemplateConfig {
1353    repeated: vec![Cell {
1354      before: Some(Tokens!(T_CS!("\\hfil"))),
1355      after: Some(Tokens!(T_CS!("\\hfil"))),
1356      ..Cell::default()
1357    }],
1358    ..TemplateConfig::default()
1359  })
1360}
1361
1362//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1363// Experimental alignment heading heuristications.
1364//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1365// We attempt to recognize patterns of rows/columns that indicate which might be headers.
1366// We'll characterize the cells by alignment, content and borders.
1367// Then, assuming that headers will be first and be noticably `different' from data lines,
1368// and also that the data lines will have similar structure,  we'll attempt to
1369// recognize groups of header lines and groups data lines, possibly alternating.
1370
1371/// Check whether a template token list contains fill/spacing commands
1372/// like \hfil, \hfill, \hskip, \lx@intercol. Previously used as fallback
1373/// for lpad/rpad; now superseded by template_has_intercol for better @{} handling.
1374#[allow(dead_code)]
1375fn template_has_fill(tokens: &Option<Tokens>) -> bool {
1376  if let Some(toks) = tokens {
1377    for tok in toks.unlist_ref() {
1378      let s = tok.to_string();
1379      if s == "\\hfil" || s == "\\hfill" || s == "\\hskip" {
1380        return true;
1381      }
1382    }
1383  }
1384  false
1385}
1386
1387/// The mapping of the template tokens a binding's column rule puts between the columns besides `\vrule` (colortbl's
1388/// paint, arydshln's `\lx@adl@vdashrule`), filled by [`declare_column_rule_token`].
1389const COLUMN_RULE_TOKENS: &str = "COLUMN_RULE_TOKENS";
1390
1391/// Declares `cs` a token of a column rule, which the template scans skip as they skip `\vrule`.
1392pub fn declare_column_rule_token(cs: &str) { assign_mapping(COLUMN_RULE_TOKENS, cs, Some(true)); }
1393
1394/// Whether a column template token draws (or paints) a column rule the cell-edge scan strips: `\vrule` or a token a
1395/// binding declared ([`declare_column_rule_token`]).
1396pub fn is_column_rule_token(name: &str) -> bool {
1397  name == "\\vrule" || lookup_mapping_sym(crate::pin!("COLUMN_RULE_TOKENS"), name).is_some()
1398}
1399
1400/// Check if \lx@intercol in the before tokens is reachable by the left-scan.
1401/// The left-scan skips: isVerticalRule (\vrule), \relax, isFill (\hfil/\hfill),
1402/// isSpace, isHorizontalRule, alignmentSkippable, Comment.
1403/// It STOPS at real content (like text from @{text}).
1404/// For `\vrule\relax\lx@intercol\hfil`: reachable (vrule is skippable).
1405/// For `@{1}\lx@intercol\hfil`: NOT reachable ("1" blocks the scan).
1406fn intercol_reachable_in_before(tokens: &Option<Tokens>) -> bool {
1407  if let Some(toks) = tokens {
1408    for tok in toks.unlist_ref() {
1409      let s = tok.to_string();
1410      if s == "\\lx@intercol" || s.contains("intercol") {
1411        return true;
1412      }
1413      // These are skippable by the left-scan in Perl's extractAlignmentColumn
1414      if s == "\\relax"
1415        || s == "\\hfil"
1416        || s == "\\hfill"
1417        || s == "\\hskip"
1418        || s == "\\lx@column@trimright"
1419        || is_column_rule_token(&s)
1420      {
1421        continue;
1422      }
1423      // Any other token blocks the scan
1424      return false;
1425    }
1426  }
1427  false
1428}
1429
1430/// Check if template tokens contain \lx@intercol (intercolumn spacing).
1431/// Unlike template_has_fill, this ignores \hfil/\hfill which are alignment fill.
1432/// \lx@intercol indicates actual intercolumn padding; \hfil is just centering.
1433/// For @{}c@{} columns, \lx@intercol is disabled but \hfil remains.
1434fn template_has_intercol(tokens: &Option<Tokens>) -> bool {
1435  if let Some(toks) = tokens {
1436    for tok in toks.unlist_ref() {
1437      let s = tok.to_string();
1438      if s == "\\lx@intercol" || s.contains("intercol") {
1439        return true;
1440      }
1441    }
1442  }
1443  false
1444}
1445
1446fn guess_alignment_headers(
1447  document: &mut Document,
1448  table: &mut Node,
1449  alignment: &mut Alignment,
1450) -> Result<()> {
1451  // Assume that headers don't make sense for nested tables.
1452  // OR Maybe we should only do this within table environments???
1453  if !document
1454    .findnodes("ancestor::ltx:tabular", Some(table))
1455    .is_empty()
1456  {
1457    return Ok(());
1458  }
1459  let tag = get_node_qname(table);
1460  // TODO
1461  //   Debug(('=' x 50) . "\nGuessing alignment headers for "
1462  //       . (($x = $document->findnode('ancestor-or-self::*[@xml:id]', $table)) ?
1463  // $x->getAttribute('xml:id') : $tag))     if $LaTeXML::DEBUG{alignment};
1464
1465  let ismath = tag == crate::pin!("ltx:XMArray");
1466  let reversed = false;
1467  // Attempt to recognize header lines.
1468  // Build a view of the table by extracting the rows, collecting & characterizing each cell.
1469  classify_alignment_rows(alignment);
1470
1471  {
1472    let mut rows = collect_alignment_rows(alignment);
1473    if rows.is_empty() {
1474      return Ok(());
1475    }
1476    alignment_characterize_lines(document, Axis::Row, false, rows.as_mut_slice())?;
1477  }
1478  // Flip the rows around to produce a column view.
1479  {
1480    let mut cols = collect_alignment_columns(alignment);
1481    if cols.is_empty() {
1482      return Ok(());
1483    }
1484    // This usually does something unpleasant
1485    alignment_characterize_lines(document, Axis::Column, false, cols.as_mut_slice())?;
1486  }
1487
1488  // Did we go overboard?
1489  let rows = collect_alignment_rows(alignment);
1490  let mut n_h = 0;
1491  let mut n_d = 0;
1492  for r in rows.iter() {
1493    for c in r {
1494      match c.cell_type {
1495        Some('h') => n_h += 1,
1496        Some('d') => n_d += 1,
1497        Some(other) => panic!("unexpected cell_type {}", other),
1498        None => {},
1499      }
1500    }
1501  }
1502  // dbg!((n_h, n_d));
1503  //   Debug("$n{h} header, $n{d} data cells") if $LaTeXML::DEBUG{alignment};
1504  if n_d == 1 {
1505    // Or any other heuristic?
1506    n_h = 0;
1507    for r in rows {
1508      for c in r {
1509        c.cell_type = Some('d');
1510        if let Some(ref mut cell) = c.cell {
1511          cell.remove_attribute("thead")?;
1512        }
1513      }
1514    }
1515  }
1516  // Regroup the rows into thead & tbody elements.
1517  // But not if it's a math array, or if reversed (since browsers get confused?)
1518  if !ismath && !reversed {
1519    alignment_regroup_rows(document, table)?;
1520  }
1521  if n_h > 0 {
1522    // Found some headers?
1523    document.add_class(table, "ltx_guessed_headers")?;
1524  }
1525
1526  //   # Debugging report!
1527  //   summarize_alignment([@rows], [@cols]) if $LaTeXML::DEBUG{alignment};
1528  Ok(())
1529}
1530
1531//======================================================================
1532// Regroup the rows into thead, tbody & tfoot
1533// Any leading rows, all of whose cells have attribute thead should be in thead.
1534// UNLESS any of them have a rowspan that extends PAST the end of the thead!!!!
1535// trailing rows marked as thead go into tfoot.
1536fn alignment_regroup_rows(document: &mut Document, table: &Node) -> Result<()> {
1537  let mut rows = document.findnodes("ltx:tr", Some(table));
1538  // `heads` is bounded by the initial thead-candidate rows; pre-size
1539  // to `rows.len()` as a conservative upper bound.
1540  let mut heads = Vec::with_capacity(rows.len());
1541  let mut maxreach = 0;
1542  // Scan initial rows as potential thead
1543  while !rows.is_empty() {
1544    let cells = document.findnodes("ltx:td", Some(&rows[0]));
1545    // Non header cells, done.
1546    if cells
1547      .iter()
1548      .any(|cell| cell.get_attribute("thead").is_none())
1549    {
1550      break;
1551    }
1552    let line = heads.len();
1553    heads.push(rows.remove(0));
1554    for cell in cells {
1555      // Malformed/non-numeric rowspan silently degrades to 0 — matches Perl's
1556      // lax numeric coercion and prevents crashes on unusual input XML.
1557      let this_rowspan = cell
1558        .get_attribute("rowspan")
1559        .and_then(|v| v.parse::<usize>().ok())
1560        .unwrap_or(0)
1561        + line;
1562      if this_rowspan > maxreach {
1563        maxreach = this_rowspan;
1564      }
1565    }
1566  }
1567  if maxreach > heads.len() {
1568    // rowspan crossed over thead boundary! Put head rows back at the FRONT of body rows.
1569    heads.append(&mut rows);
1570    rows = std::mem::take(&mut heads);
1571  }
1572  // scan trailing rows as potential tfoot
1573  let mut foots = VecDeque::new();
1574  while !rows.is_empty() {
1575    let cells = document.findnodes("ltx:td", Some(rows.last().unwrap()));
1576    // Non header cells, done.
1577    if cells
1578      .iter()
1579      .any(|cell| cell.get_attribute("thead").is_none())
1580    {
1581      break;
1582    }
1583    foots.push_front(rows.pop().unwrap())
1584  }
1585  if !heads.is_empty() {
1586    document.wrap_nodes("ltx:thead", heads)?;
1587  }
1588  if !rows.is_empty() {
1589    document.wrap_nodes("ltx:tbody", rows)?;
1590  }
1591  if !foots.is_empty() {
1592    document.wrap_nodes("ltx:tfoot", foots.into_iter().collect())?;
1593  }
1594  Ok(())
1595}
1596
1597//======================================================================
1598/// Setup a View of the alignment, with characterized cells, for analysis -- modifying it in place.
1599fn classify_alignment_rows(alignment: &mut Alignment) {
1600  let mut ncols = 0;
1601  for arow in &mut alignment.rows {
1602    let n = arow.get_columns().len();
1603    if n > ncols {
1604      ncols = n;
1605    }
1606  }
1607  // eprintln!("classify_alignment_rows: {} rows, max {} cols", alignment.rows.len(), ncols);
1608  let (mut h, mut v) = (false, false);
1609  for arow in alignment.rows.iter_mut() {
1610    let cols = arow.get_columns_mut();
1611    let this_row_len = cols.len();
1612    // eprintln!("  row {_ri}: {this_row_len} cols");
1613    for col in cols.iter_mut() {
1614      col.cell_type = Some('d');
1615      col.content_class = Some(
1616        // Assume mixed content for any justified cell???
1617        if col.align == Some(Align::Justify) {
1618          ColumnSpec::MathAltText
1619        } else if col.cell.is_some() {
1620          classify_alignment_cell(col.cell.as_ref().unwrap())
1621        } else {
1622          ColumnSpec::Unknown
1623        },
1624      );
1625      // eprintln!("    cell: cell={}, class={:?}, border='{}'", col.cell.is_some(),
1626      // col.content_class, col.border);
1627      col.content_length = Some(if col.content_class == Some(ColumnSpec::Graphics) {
1628        1000
1629      } else if col.cell.is_some() {
1630        col.cell.as_ref().unwrap().get_content().chars().count()
1631      } else {
1632        0
1633      });
1634      let (mut border_top, mut border_bottom, mut border_left, mut border_right) = (0, 0, 0, 0);
1635      for c in col.border.chars() {
1636        match c {
1637          'l' | 'L' => border_left += 1,
1638          'r' | 'R' => border_right += 1,
1639          't' | 'T' => border_top += 1,
1640          'b' | 'B' => border_bottom += 1,
1641          _ => {}, // spaces etc.
1642        }
1643      }
1644      // Note: once h and v are set as true on any row, they remain globally true.
1645      if (border_top > 0) || (border_bottom > 0) {
1646        h = true;
1647      }
1648      if (border_right > 0) || (border_left > 0) {
1649        v = true;
1650      }
1651      col.border_top = Some(border_top);
1652      col.border_bottom = Some(border_bottom);
1653      col.border_left = Some(border_left);
1654      col.border_right = Some(border_right);
1655    }
1656    // pad the columns out.
1657    let to_pad = ncols - this_row_len;
1658    if to_pad > 0 {
1659      for _ in 0..to_pad {
1660        let col = Cell {
1661          align: Some(Align::Center),
1662          cell_type: Some('d'),
1663          content_class: Some(ColumnSpec::Empty),
1664          content_length: Some(0),
1665          ..Cell::default()
1666        };
1667        cols.push(col);
1668      }
1669    }
1670  }
1671  // Copy the characterizations to spanned cells, and move the outer borders of
1672  // span-origin cells onto their last spanned column/row.
1673  // Perl: collect_alignment_rows (Alignment.pm L1070-1093). This MUST run
1674  // in-place and sequentially: Perl mutates the shared row array as it scans,
1675  // so when it reaches a colspan-covered cell it reads the right border that
1676  // the spanning cell just wrote (and writes it back), keeping the bar on the
1677  // span boundary. An earlier Rust port DEFERRED these assignments (collected
1678  // them, applied after the loop) to sidestep cross-row borrow conflicts —
1679  // which broke that read-after-write chain: a `\multicolumn` lost the vertical
1680  // bar on its spanned-over neighbor, and the following cell lost the matching
1681  // left border. That inflated the row-difference score in alignment_compare
1682  // and defeated guess_alignment_headers on the common "header row over a
1683  // \multicolumn data row" table. Index-based single-cell access keeps each
1684  // &mut borrow scoped to one statement, so we can update in place faithfully.
1685  // Out-of-bounds spans (malformed rowspan/colspan past the table edge) are
1686  // skipped rather than auto-vivified as Perl would.
1687  let nrows_pre = alignment.rows.len();
1688  for r in 0..nrows_pre {
1689    let row_len = alignment.rows[r].get_columns().len();
1690    for c in 0..row_len {
1691      let (rs, cs, ca, cc, cl, rb, bb) = {
1692        let cell = &mut alignment.rows[r].get_columns_mut()[c];
1693        let rs = cell.rowspan.unwrap_or(1);
1694        let cs = cell.colspan.unwrap_or(1);
1695        let ca = cell.align.clone();
1696        let cc = cell.content_class;
1697        let cl = cell.content_length;
1698        let rb = cell.border_right;
1699        cell.border_right = Some(0);
1700        let bb = cell.border_bottom;
1701        cell.border_bottom = Some(0);
1702        (rs, cs, ca, cc, cl, rb, bb)
1703      };
1704      // colspan: copy characterizations to spanned-over cells in this row
1705      for sc in 1..cs {
1706        if let Some(cell) = alignment.rows[r].get_columns_mut().get_mut(c + sc) {
1707          cell.align = ca.clone();
1708          cell.content_class = cc;
1709          cell.content_length = cl;
1710        }
1711      }
1712      // rowspan: copy characterizations to cells covered in the rows below
1713      for sr in 1..rs {
1714        if r + sr >= nrows_pre {
1715          break;
1716        }
1717        for sc in 0..cs {
1718          if let Some(cell) = alignment.rows[r + sr].get_columns_mut().get_mut(c + sc) {
1719            cell.align = ca.clone();
1720            cell.content_class = cc;
1721            cell.content_length = cl;
1722          }
1723        }
1724      }
1725      // move the outer right border onto the last spanned column (every spanned row)
1726      for sr in 0..rs {
1727        if r + sr >= nrows_pre {
1728          break;
1729        }
1730        if let Some(cell) = alignment.rows[r + sr].get_columns_mut().get_mut(c + cs - 1) {
1731          cell.border_right = rb;
1732        }
1733      }
1734      // move the outer bottom border onto the last spanned row (every spanned column)
1735      if r + rs - 1 < nrows_pre {
1736        for sc in 0..cs {
1737          if let Some(cell) = alignment.rows[r + rs - 1].get_columns_mut().get_mut(c + sc) {
1738            cell.border_bottom = bb;
1739          }
1740        }
1741      }
1742    }
1743  }
1744  // Now, do some border massaging...
1745  // Empty-alignment guard: if ncols==0 (no columns in any row), there are no
1746  // borders to massage. Skip the whole block to avoid out-of-bounds panics on
1747  // `cols[0]` (witness: astro-ph0006087, garmire.tex deluxetable input).
1748  if ncols == 0 {
1749    return;
1750  }
1751  for row in alignment.rows.iter_mut() {
1752    let cols = row.get_columns_mut();
1753    cols[0].border_left = Some(if v { 1 } else { 0 });
1754    if ncols > 1 {
1755      if cols[1].border_left.unwrap_or(0) > 0 {
1756        cols[0].border_right = cols[1].border_left;
1757      }
1758      if cols[ncols - 2].border_right.unwrap_or(0) > 0 {
1759        cols[ncols - 1].border_left = cols[ncols - 2].border_right;
1760      }
1761    }
1762    cols[ncols - 1].border_right = Some(if v { 1 } else { 0 });
1763  }
1764  let nrows = alignment.rows.len();
1765  for c in 0..ncols {
1766    alignment.rows[0].get_columns_mut()[c].border_top = Some(if h { 1 } else { 0 });
1767    if nrows > 1 {
1768      if let Some(bt) = alignment.rows[1].get_columns_mut()[c].border_top
1769        && bt > 0
1770      {
1771        // only set if border is inked
1772        alignment.rows[0].get_columns_mut()[c].border_bottom = Some(bt);
1773      }
1774      if let Some(bb) = alignment.rows[nrows - 2].get_columns_mut()[c].border_bottom
1775        && bb > 0
1776      {
1777        // only set if border is inked
1778        alignment.rows[nrows - 1].get_columns_mut()[c].border_top = Some(bb);
1779      }
1780    }
1781    alignment.rows[nrows - 1].get_columns_mut()[c].border_bottom = Some(if h { 1 } else { 0 });
1782  }
1783  // Perl Alignment.pm L1106-1112: propagate inked interior borders between
1784  // adjacent interior cells (top←above.bottom, bottom←below.top,
1785  // left←left.right, right←right.left). Edge rows/cols are excluded (loop
1786  // bounds 1..n-1), matching Perl; their outer borders were handled above.
1787  for r in 1..nrows - 1 {
1788    for c in 1..ncols - 1 {
1789      if let Some(bb) = alignment.rows[r - 1].get_columns_mut()[c].border_bottom
1790        && bb > 0
1791      {
1792        // only set if border is inked
1793        alignment.rows[r].get_columns_mut()[c].border_top = Some(bb);
1794      }
1795      if let Some(bt) = alignment.rows[r + 1].get_columns_mut()[c].border_top
1796        && bt > 0
1797      {
1798        // only set if border is inked
1799        alignment.rows[r].get_columns_mut()[c].border_bottom = Some(bt);
1800      }
1801      if let Some(br) = alignment.rows[r].get_columns_mut()[c - 1].border_right
1802        && br > 0
1803      {
1804        // only set if border is inked
1805        alignment.rows[r].get_columns_mut()[c].border_left = Some(br);
1806      }
1807      if let Some(bl) = alignment.rows[r].get_columns_mut()[c + 1].border_left
1808        && bl > 0
1809      {
1810        // only set if border is inked
1811        alignment.rows[r].get_columns_mut()[c].border_right = Some(bl);
1812      }
1813    }
1814  }
1815  // debug info
1816  // eprintln!("Cell characterizations:");
1817  // for (row_index,row) in alignment.rows.iter().enumerate() {
1818  //   for (col_index, cell) in row.get_columns().iter().enumerate() {
1819  //     eprintln!("[{row_index},{col_index}]=>{}{}{} {} {} => {}{}{}{}",
1820  //       cell.cell_type.as_ref().unwrap_or(&'?'),
1821  //       cell.align.as_ref().map(|a| a.char_code()).unwrap_or(' '),
1822  //       cell.content_class.map(|a| a.to_string()).unwrap_or_else(|| String::from("?")),
1823  //       cell.content_length.unwrap_or(0),
1824  //       cell.border,
1825  //       if cell.border_top.unwrap_or(0) > 0 { "t" } else { "" },
1826  //       if cell.border_right.unwrap_or(0) > 0  { "r" } else { "" },
1827  //       if cell.border_bottom.unwrap_or(0) > 0 { "b" } else { "" },
1828  //       if cell.border_left.unwrap_or(0) > 0 { "l" } else {""}
1829  //     );
1830  //   }
1831  // }
1832}
1833
1834fn collect_alignment_rows(alignment: &mut Alignment) -> Vec<Vec<&mut Cell>> {
1835  alignment
1836    .rows
1837    .iter_mut()
1838    .map(|x| x.get_columns_mut().iter_mut().collect())
1839    .collect()
1840}
1841
1842fn collect_alignment_columns(alignment: &mut Alignment) -> Vec<Vec<&mut Cell>> {
1843  let mut row_cells: Vec<_> = alignment
1844    .rows
1845    .iter_mut()
1846    .map(|r| r.get_columns_mut().iter_mut())
1847    .collect();
1848  let n_cols = row_cells[0].len();
1849  let n_rows = row_cells.len();
1850  let mut columns = Vec::with_capacity(n_cols);
1851  for _ in 0..n_cols {
1852    let mut column = Vec::with_capacity(n_rows);
1853    for row_iter in row_cells.iter_mut() {
1854      column.push(row_iter.next().unwrap());
1855    }
1856    columns.push(column);
1857  }
1858  columns
1859}
1860
1861/// Return one of: i(nteger), t(ext), m(ath), ? (unknown) or '_' (empty) (or some combination)
1862///  or 'mx' for alternating text & math.
1863fn classify_alignment_cell(xcell: &Node) -> ColumnSpec {
1864  let content = xcell.get_content();
1865  let mut inferred_classes: Vec<ColumnSpec> = Vec::new();
1866  // Perl L1123: /^[\s\d]+$/ — Perl \d is ASCII-only (0-9).
1867  // Also include mathematical double-struck digits (U+1D7D8-U+1D7E1, 𝟘-𝟡) since these
1868  // are font-decoded equivalents of ASCII 0-9 in blackboard bold fonts. In Perl, these
1869  // appear as ASCII digits with font attributes; in Rust they're Unicode codepoints.
1870  // Exclude circled/enclosed numerals (❶❷❸ U+2776-, ①②③ U+2460-) which are symbols.
1871  if !content.is_empty()
1872    && content
1873      .chars()
1874      .all(|c| c.is_whitespace() || c.is_ascii_digit() || ('\u{1D7D8}'..='\u{1D7E1}').contains(&c))
1875  {
1876    inferred_classes.push(ColumnSpec::Integer);
1877  } else {
1878    let mut nodes = xcell.get_child_nodes();
1879    while !nodes.is_empty() {
1880      let ch = nodes.remove(0);
1881      match ch.get_type() {
1882        Some(NodeType::TextNode) => {
1883          let text = ch.get_content();
1884          if !(text.chars().all(|c| c.is_whitespace())
1885            || (inferred_classes.first() == Some(&ColumnSpec::Math)
1886              && SINGLE_PUNCT.is_match(&text)))
1887          {
1888            inferred_classes.push(ColumnSpec::Text);
1889          }
1890        },
1891        Some(NodeType::ElementNode) => {
1892          with_node_qname(&ch, |chtag| match chtag {
1893            "ltx:text" => {
1894              // Perl L1136-1137: $class .= 't' unless $class eq 't'
1895              // Only skip if the LAST class was also Text (not just first).
1896              // This preserves "tt" for cells with two text elements.
1897              if inferred_classes.last() != Some(&ColumnSpec::Text) {
1898                inferred_classes.push(ColumnSpec::Text);
1899              }
1900            },
1901            "ltx:graphics" => {
1902              if inferred_classes.first() != Some(&ColumnSpec::Graphics) {
1903                inferred_classes.push(ColumnSpec::Graphics);
1904              }
1905            },
1906            "ltx:Math" => {
1907              if inferred_classes.first() != Some(&ColumnSpec::Math) {
1908                inferred_classes.push(ColumnSpec::Math);
1909              }
1910            },
1911            "ltx:XMText" => {
1912              if inferred_classes.first() != Some(&ColumnSpec::Text) {
1913                inferred_classes.push(ColumnSpec::Text);
1914              }
1915            },
1916            "ltx:XMArg" | "ltx:inline-block" | "ltx:p" => {
1917              // Transparent containers: look through to classify children.
1918              // Perl's beAbsorbed creates <text> directly in td; Rust wraps in
1919              // <inline-block><p> from {turn}/{rotate}. Treat these as transparent
1920              // so the classification matches Perl's view of the cell content.
1921              let mut children = ch.get_child_nodes();
1922              children.append(&mut nodes);
1923              nodes = children;
1924            },
1925            other if other.starts_with("ltx:XM") => {
1926              if inferred_classes.first() != Some(&ColumnSpec::Math) {
1927                inferred_classes.push(ColumnSpec::Math);
1928              }
1929            },
1930            _ => {
1931              if inferred_classes.is_empty() {
1932                inferred_classes.push(ColumnSpec::Unknown);
1933              }
1934            },
1935          })
1936        },
1937        _ => {},
1938      }
1939    }
1940  }
1941
1942  // check if we have alternating math-and-text or text-and-math (only if 2+ classes)
1943  if inferred_classes.len() > 1 {
1944    let mut alt_peekable = inferred_classes.iter().peekable();
1945    let mut is_alternating = true;
1946    while let Some(c) = alt_peekable.next() {
1947      match c {
1948        ColumnSpec::Math | ColumnSpec::Integer => {
1949          if let Some(peek) = alt_peekable.peek()
1950            && !matches!(peek, ColumnSpec::Text)
1951          {
1952            is_alternating = false;
1953            break;
1954          }
1955        },
1956        ColumnSpec::Text => {
1957          if let Some(peek) = alt_peekable.peek()
1958            && !matches!(peek, ColumnSpec::Math | ColumnSpec::Integer)
1959          {
1960            is_alternating = false;
1961            break;
1962          }
1963        },
1964        _ => {
1965          is_alternating = false;
1966          break;
1967        },
1968      }
1969    }
1970    if is_alternating {
1971      inferred_classes = vec![ColumnSpec::MathAltText];
1972    }
1973  }
1974  // Default to empty and return
1975  if inferred_classes.is_empty() {
1976    ColumnSpec::Empty
1977  } else if inferred_classes.len() == 1 {
1978    inferred_classes[0]
1979  } else {
1980    // Perl L1151: multi-class detection.
1981    // "tt" (all Text) → MultiText, mixed math+text → MathAltText
1982    let all_text = inferred_classes
1983      .iter()
1984      .all(|c| matches!(c, ColumnSpec::Text));
1985    if all_text {
1986      ColumnSpec::MultiText
1987    } else {
1988      ColumnSpec::Unknown
1989    }
1990  }
1991}
1992
1993//======================================================================
1994// Scan pairs of rows/columns attempting to recognize differences that
1995// might indicate which are headers and which are data.
1996// Warning: This section is full of "magic numbers"
1997// guessed by sampling various test cases.
1998
1999const MIN_ALIGNMENT_DATA_LINES: usize = 1; //  (or 2?) [CONSTANT]
2000const MAX_ALIGNMENT_HEADER_LINES: usize = 4; // [CONSTANT]
2001
2002// We expect to find header lines at the beginning, noticably different from the eventual data
2003// lines. Both header lines and data lines can consist of several neighboring lines.
2004// Check that header lines are `similar' to each other.  So, the strategy is to look
2005// for a `hump' in the line differences and consider blocks containing these lines to be potential
2006// headers.
2007
2008fn alignment_characterize_lines(
2009  document: &mut Document,
2010  axis: Axis,
2011  reversed: bool,
2012  lines: &mut [Vec<&mut Cell>],
2013) -> Result<()> {
2014  let n = lines.len();
2015  if n < 2 {
2016    return Ok(());
2017  }
2018  // eprintln!("Characterizing {n} {}", if axis == Axis::Row {"rows"} else {"columns"});
2019
2020  // Establish a scale of differences for the table.
2021  let (mut max_diff, mut min_diff, _avg_diff) = (0.0, 99999999.0, 0.0);
2022  for l in 0..n - 1 {
2023    let d = alignment_compare(axis, true, reversed, l, l + 1, lines);
2024    // eprintln!("  compare({l},{}) = {d}", l + 1);
2025    // avg_diff += d;
2026    if d > max_diff {
2027      max_diff = d;
2028    }
2029    if d < min_diff {
2030      min_diff = d;
2031    }
2032  }
2033  // avg_diff = avg_diff / (n - 1) as f64;
2034  if max_diff < 0.05 {
2035    // virtually no differences.
2036    return Ok(());
2037  }
2038  if (n > 2) && ((max_diff - min_diff) < max_diff * 0.5) {
2039    // differences too similar to establish pattern
2040    return Ok(());
2041  }
2042  let tab_threshold = min_diff + 0.3 * (max_diff - min_diff);
2043
2044  // eprintln!("Differences {min_diff} -- {max_diff} => threshold = {tab_threshold}");
2045  // Find the first hump in differences. These are candidates for header lines.
2046  // eprintln!("Scanning for headers");
2047  let (minh, mut maxh) = (1, 1);
2048  let mut diff;
2049  loop {
2050    diff = alignment_compare(axis, true, reversed, maxh - 1, maxh, lines);
2051    if diff >= tab_threshold {
2052      break;
2053    }
2054    maxh += 1;
2055  }
2056  if maxh > MAX_ALIGNMENT_HEADER_LINES {
2057    // too many before even finding diffs? give up!
2058    return Ok(());
2059  }
2060  while alignment_compare(axis, true, reversed, maxh, maxh + 1, lines) > tab_threshold {
2061    maxh += 1;
2062  }
2063  if maxh > MAX_ALIGNMENT_HEADER_LINES {
2064    maxh = MAX_ALIGNMENT_HEADER_LINES;
2065  }
2066  // eprintln!("Found from {minh}--{maxh} potential headers");
2067
2068  let nn = lines[0].len() - 1;
2069  // The sets of lines 1--$minh, .. 1--$maxh are potential headers.
2070  for nh in (minh..=maxh).rev() {
2071    // Check whether the set 1..$nh is plausable.
2072    let heads = alignment_test_headers(nh, tab_threshold, axis, lines);
2073    if !heads.is_empty() {
2074      // Now, change all cells marked as header from td => th.
2075      for h in heads {
2076        for (i, cell) in lines[h].iter_mut().enumerate() {
2077          cell.cell_type = Some('h');
2078          if let Some(ref mut xcell) = cell.cell {
2079            // But NOT empty cells on outer edges.
2080            // Perl: !$$cell{l} is falsy for both undef AND 0.
2081            if (cell.content_class == Some(ColumnSpec::Empty))
2082              && ((i == 0
2083                && (if axis == Axis::Row {
2084                  cell.border_left.unwrap_or(0) == 0
2085                } else {
2086                  cell.border_top.unwrap_or(0) == 0
2087                }))
2088                || (i == nn
2089                  && (if axis == Axis::Row {
2090                    cell.border_right.unwrap_or(0) == 0
2091                  } else {
2092                    cell.border_bottom.unwrap_or(0) == 0
2093                  })))
2094            {
2095            } else {
2096              document.add_ss_values(xcell, "thead", axis.marker_name())?;
2097            }
2098          }
2099        }
2100      }
2101      return Ok(());
2102    }
2103  }
2104  Ok(())
2105}
2106
2107/// Test whether `nhead` lines makes a good fit for the headers
2108fn alignment_test_headers(
2109  nhead: usize,
2110  tab_threshold: f64,
2111  axis: Axis,
2112  lines: &[Vec<&mut Cell>],
2113) -> Vec<usize> {
2114  // eprintln!("Testing {nhead} headers with threshold {tab_threshold} for axis {:?}", axis);
2115  let mut heads: Vec<usize> = (0..nhead).collect(); // The indices of heading lines.
2116  let mut head_length = alignment_max_content_length(0, 0, nhead - 1, lines);
2117  let mut next_line = nhead; // Start from the end of the proposed headings.
2118
2119  // Watch out for the assumed header being really data that is a repeated pattern.
2120  let nrep = lines.len() / nhead;
2121  if nhead > 1 {
2122    //   Debug("Check for apparent header repeated $nrep times") if $LaTeXML::DEBUG{alignment};
2123    let mut matched = true;
2124    for r in 1..nrep {
2125      matched =
2126        matched && alignment_match_head(0, r * nhead, nhead, tab_threshold, axis, lines) > 0;
2127    }
2128    //   Debug("Repeated headers: " . ($matched ? "Matched=> Fail" : "Nomatch => Succeed"))
2129    //     if $LaTeXML::DEBUG{alignment};
2130    // eprintln!("  repeated pattern check: matched={matched}");
2131    if matched {
2132      return Vec::new();
2133    }
2134  }
2135
2136  // And find a following grouping of data lines.
2137  let ndata = alignment_skip_data(next_line, tab_threshold, axis, lines);
2138  // eprintln!("  ndata={ndata} from next_line={next_line}");
2139  if ndata < nhead {
2140    // ???? Well, maybe if _really_ convincing???
2141    return Vec::new();
2142  }
2143  if (ndata < nhead) && (ndata < 2) {
2144    return Vec::new();
2145  }
2146  // Check that the content of the headers isn't dramatically larger than the content in the data
2147  let mut data_length = alignment_max_content_length(0, next_line, next_line + ndata - 1, lines);
2148  next_line += ndata;
2149
2150  let mut nd;
2151  // If there are more lines, they should match either the previous data block, or the head/data
2152  // pattern.
2153  while next_line < lines.len() {
2154    // First try to match a repeat of the 1st data block;
2155    // This would be the case when groups of data have borders around them.
2156    // Could want to match a variable number of datalines, but they should be similar!!!??!?!?
2157    nd = if ndata > 1 {
2158      alignment_match_data(nhead, next_line, ndata, tab_threshold, axis, lines)
2159    } else {
2160      0
2161    };
2162    // eprintln!("  while: next_line={next_line}, nd={nd}");
2163    if nd > 0 {
2164      data_length = alignment_max_content_length(data_length, next_line, next_line + nd - 1, lines);
2165      next_line += nd;
2166    }
2167    // Else, try to match the first header block; less common.
2168    else if alignment_match_head(0, next_line, nhead, tab_threshold, axis, lines) > 0 {
2169      // eprintln!("  matched head at next_line={next_line}");
2170      for idx in next_line..next_line + nhead {
2171        heads.push(idx);
2172      }
2173      head_length =
2174        alignment_max_content_length(head_length, next_line, next_line + nhead - 1, lines);
2175      next_line += nhead;
2176      nd = alignment_match_data(nhead, next_line, ndata, tab_threshold, axis, lines);
2177      if nd == 0 {
2178        return Vec::new();
2179      }
2180      data_length = alignment_max_content_length(data_length, next_line, next_line + nd - 1, lines);
2181      next_line += nd;
2182    } else {
2183      // eprintln!("  no match at next_line={next_line} => fail");
2184      return Vec::new();
2185    }
2186  }
2187  // Header content seems too large relative to data?
2188  // eprintln!("  header content = {head_length}; data content = {data_length}");
2189  if (head_length > 10) && (head_length > 4 * data_length) {
2190    //   Debug("header content too much longer than data content")
2191    //     if $LaTeXML::DEBUG{alignment};
2192    return Vec::new();
2193  }
2194  // Or if a header cell has "large" content?
2195  if head_length >= 1000 {
2196    // Or if a header cell has "large" content?
2197    //   Debug("header content too large")
2198    //     if $LaTeXML::DEBUG{alignment};
2199    return Vec::new();
2200  }
2201
2202  // eprintln!("  Succeeded with {nhead} headers: {heads:?}");
2203  heads
2204}
2205
2206fn alignment_match_head(
2207  p1: usize,
2208  p2: usize,
2209  nhead: usize,
2210  tab_threshold: f64,
2211  axis: Axis,
2212  tablines: &[Vec<&mut Cell>],
2213) -> usize {
2214  let nh = alignment_match_lines(p1, p2, nhead, tab_threshold, axis, tablines);
2215  let ok = nhead == nh;
2216  // Debug("Matched $nh header lines => " . ($ok ? "Succeed" : "Failed")) if
2217  // $LaTeXML::DEBUG{alignment};
2218  if ok { nhead } else { 0 }
2219}
2220
2221fn alignment_match_data(
2222  p1: usize,
2223  p2: usize,
2224  n: usize,
2225  tab_threshold: f64,
2226  axis: Axis,
2227  tablines: &[Vec<&mut Cell>],
2228) -> usize {
2229  let nd = alignment_match_lines(p1, p2, n, tab_threshold, axis, tablines);
2230  let ok = (nd as f64 * 1.0) / n as f64 > 0.66;
2231  //   Debug("Matched $nd data lines => " . ($ok ? "Succeed" : "Failed"))
2232  //     if $LaTeXML::DEBUG{alignment};
2233  if ok { nd } else { 0 }
2234}
2235
2236// Match the $n lines starting at $i2 to those starting at $i1.
2237fn alignment_match_lines(
2238  p1: usize,
2239  p2: usize,
2240  n: usize,
2241  tab_threshold: f64,
2242  axis: Axis,
2243  tablines: &[Vec<&mut Cell>],
2244) -> usize {
2245  let max_n = tablines.len();
2246  for i in 0..n {
2247    if (p1 + i >= max_n)
2248      || (p2 + i >= max_n)
2249      || alignment_compare(axis, false, false, p1 + i, p2 + i, tablines) >= tab_threshold
2250    {
2251      return i;
2252    }
2253  }
2254  n
2255}
2256
2257/// Skip through a block of lines starting at $i that appear to be data, returning the number of
2258/// lines. We'll assume the 1st line is data, compare it to following lines,
2259/// but also accept `continuation' data lines.
2260///
2261/// Note: Perl's continuation-line logic (L1336-1339) is effectively dead code:
2262/// `scalar($::TABLINES[0])` evaluates to an array ref's memory address (huge number),
2263/// making `0.4 * huge` very large, so `count_empty <= huge` is always true.
2264/// The condition `($n < 2) || true` = true, so the `last if` simplifies to just
2265/// `last if diff >= threshold`. We match this behavior.
2266fn alignment_skip_data(
2267  i: usize,
2268  tab_threshold: f64,
2269  axis: Axis,
2270  tablines: &[Vec<&mut Cell>],
2271) -> usize {
2272  let tab_lines_length = tablines.len();
2273  if i >= tab_lines_length {
2274    return 0;
2275  }
2276  let _header_width = if !tablines.is_empty() {
2277    tablines[0].len()
2278  } else {
2279    1
2280  };
2281  let mut n = 1;
2282  while i + n < tab_lines_length {
2283    if alignment_compare(axis, true, false, i + n - 1, i + n, tablines) >= tab_threshold {
2284      // TODO: Perl Alignment.pm L1337-1339 has continuation line check here.
2285      // Applying it changes behavior for fonts/bbold tables (false positive headers).
2286      // Need to investigate further.
2287      break;
2288    }
2289    n += 1;
2290  }
2291  if n >= MIN_ALIGNMENT_DATA_LINES { n } else { 0 }
2292}
2293
2294/// Return the maximum "content length" for lines from $from to $to.
2295fn alignment_max_content_length(
2296  mut length: usize,
2297  from: usize,
2298  to: usize,
2299  tablines: &[Vec<&mut Cell>],
2300) -> usize {
2301  for item in tablines.iter().take(to + 1).skip(from) {
2302    let mut l = 0;
2303    for cell in item.iter() {
2304      l += cell.content_length.unwrap_or(0);
2305    }
2306    if l > length {
2307      length = l;
2308    }
2309  }
2310  length
2311}
2312
2313//======================================================================
2314
2315/// Compare two lines along `Axis` (0=row,1=column), returning a measure of the difference.
2316/// The borders are compared differently if
2317///  `for_adjacency`: we adjacent lines that might belong to the same block,
2318///  otherwise    : comparing two lines that ought to have identical patterns (eg. in a repeated
2319/// block)
2320fn alignment_compare(
2321  axis: Axis,
2322  for_adjacency: bool,
2323  reversed: bool,
2324  p1: usize,
2325  p2: usize,
2326  lines: &[Vec<&mut Cell>],
2327) -> f64 {
2328  let max_guard = lines.len();
2329  if p1 >= max_guard || p2 >= max_guard {
2330    return 0.0;
2331  }
2332  let line1 = &lines[p1];
2333  let line2 = &lines[p2];
2334  if line1.is_empty() && line2.is_empty() {
2335    return 0.0;
2336  } else if line1.is_empty() || line2.is_empty() {
2337    return 99999.0;
2338  }
2339  let ncells = line1.len();
2340  let mut diff = 0.0;
2341
2342  for (cell1, cell2) in line1.iter().zip(line2.iter()) {
2343    // Annoying test avoids warnings if cells inconsistent; likely due to incorrect row/col spans
2344    if cell1.content_class.is_none()
2345      || cell2.content_class.is_none()
2346      || cell1.border_left.is_none()
2347      || cell2.border_left.is_none()
2348      || cell1.border_right.is_none()
2349      || cell2.border_right.is_none()
2350      || cell1.border_bottom.is_none()
2351      || cell2.border_bottom.is_none()
2352      || cell1.border_top.is_none()
2353      || cell2.border_top.is_none()
2354    {
2355      continue;
2356    }
2357    if cell1.align != cell2.align
2358      && cell1.content_class != Some(ColumnSpec::Empty)
2359      && cell2.content_class != Some(ColumnSpec::Empty)
2360    {
2361      diff += 0.75;
2362    }
2363    let d = cell1
2364      .content_class
2365      .as_ref()
2366      .unwrap()
2367      .difference_heuristic(cell2.content_class.as_ref().unwrap());
2368    if d > 0.0 {
2369      diff += d;
2370    }
2371    // compare certain edges
2372    if for_adjacency {
2373      // Compare edges for adjacent rows of potentially different purpose
2374      let mut inner_diffs = 0.0;
2375      if axis == Axis::Row {
2376        if cell1.border_right != cell2.border_right {
2377          inner_diffs += 1.0;
2378        }
2379        if cell1.border_left != cell2.border_left {
2380          inner_diffs += 1.0;
2381        }
2382      } else {
2383        if cell1.border_top != cell2.border_top {
2384          inner_diffs += 1.0;
2385        }
2386        if cell1.border_bottom != cell2.border_bottom {
2387          inner_diffs += 1.0;
2388        }
2389      };
2390      diff += 0.3 * inner_diffs;
2391      // Penalty for apparent divider between.
2392      let pedge = if axis == Axis::Row {
2393        if reversed {
2394          BorderSpec::Top
2395        } else {
2396          BorderSpec::Bottom
2397        }
2398      } else if reversed {
2399        BorderSpec::Left
2400      } else {
2401        BorderSpec::Right
2402      };
2403      let border1_pedge = cell1.border_at(pedge);
2404      let border2_pedge = cell2.border_at(pedge);
2405      if let Some(b1p) = border1_pedge
2406        && b1p > 0
2407        && (border1_pedge != border2_pedge)
2408      {
2409        diff += (b1p as i64 - border2_pedge.unwrap_or(0) as i64).abs() as f64;
2410      }
2411    } else {
2412      // Compare edges for rows from diff places for potential similarity
2413      let mut inner_diffs = 0.0;
2414      if cell1.border_right != cell2.border_right {
2415        inner_diffs += 1.0;
2416      }
2417      if cell1.border_left != cell2.border_left {
2418        inner_diffs += 1.0;
2419      }
2420      if cell1.border_top != cell2.border_top {
2421        inner_diffs += 1.0;
2422      }
2423      if cell1.border_bottom != cell2.border_bottom {
2424        inner_diffs += 1.0;
2425      }
2426      diff += 0.3 * inner_diffs;
2427    }
2428  }
2429  diff /= ncells as f64;
2430  // eprintln!("alignment_compare: {p1} - {p2} => {diff};");
2431  // Debug("$p1-$p2 => $diff; ") if $LaTeXML::DEBUG{alignment};
2432  diff
2433}