1pub 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
52pub const ALIGNMENT_IS_DISPLAY: &str = "display";
58
59pub const RULE_COLOR: &str = "lx@alignment@rule@color";
62
63pub 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#[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#[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
104pub 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#[derive(Clone, Copy, Debug)]
131pub enum RowDisposition {
132 Drop,
134 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 pub is_halign: bool,
148 current_column: usize,
149 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 pub head_rows: Vec<Row>,
174 pub foot_rows: Vec<Row>,
175 row_disposition: Option<RowDisposition>,
176}
177impl Alignment {
178 pub fn new(config: AlignmentConfig) -> Self {
190 let template = config.template.unwrap_or_default();
191 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 pub fn set_row_disposition(&mut self, disposition: RowDisposition) {
260 self.row_disposition = Some(disposition);
261 }
262
263 pub fn column_ended(&mut self) {
265 if matches!(self.row_disposition, Some(RowDisposition::Route(_))) {
266 self.row_disposition = None;
267 }
268 }
269
270 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 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 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 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 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 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 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 pub fn cell_start_column(&self) -> usize { self.cell_start_column }
426 pub fn cell_in_math(&self) -> bool { self.cell_in_math }
428
429 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 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 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 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 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 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 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 pub fn is_in_row(&self) -> bool { self.in_row }
552
553 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(); if pseudorow {
560 self.current_row_mut().unwrap().set_pseudo()
561 } else {
562 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); 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()?; self.in_row = false;
581 }
582 Ok(()) }
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(); 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 let _colspec = self.next_column()?;
600 assign_frame_value_sym(crate::pin!("alignCellGroup"), true);
603 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 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 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()?; 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
682impl 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 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 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 #[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 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 let mut attrs = HashMap::default();
778 std::mem::swap(&mut attrs, &mut self.xml_attributes);
779 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 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 #[cfg(feature = "token-locators")]
808 document.set_current_box_locator(table_span);
809 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 #[cfg(feature = "token-locators")]
819 document.set_current_box_locator(row_span(row));
820 let vpad_opt = row.get_padding().copied();
821 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 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 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 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 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 if let Some(ref bg) = cell.backgroundcolor {
919 cell_attrs.insert(String::from("backgroundcolor"), bg.clone());
920 }
921 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 let mut classes: Vec<String> = Vec::new();
949 let empty = cell.empty;
950 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 let threshold_02em: i64 = 131072;
957 let threshold_15em: i64 = 983040;
958 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 if template_has_intercol(&cell.after) {
1007 threshold_02em
1008 } else {
1009 0
1010 }
1011 });
1012 if !ismath && (!empty || has_boxes) && lpad < threshold_02em {
1014 classes.push("ltx_nopad_l".to_string());
1015 } else if lpad < threshold_15em {
1016 if ismath && cell.lspaces.is_some() {
1020 pre_absorb = cell.lspaces.take();
1021 }
1022 } else {
1023 pre_absorb = cell.lspaces.take();
1024 }
1025 if !ismath && (!empty || has_boxes) && rpad < threshold_02em {
1027 classes.push("ltx_nopad_r".to_string());
1028 } else if rpad < threshold_15em {
1029 } 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 #[cfg(feature = "token-locators")]
1053 document.set_current_box_locator(cell_loc(cell));
1054 cell.cell = open_column_fn(document, cell_attrs)?;
1055 if !cell.skippable {
1057 let box_ref = cell.boxes.as_ref().unwrap();
1058 document.set_box_to_absorb(Some(box_ref.clone()));
1060 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 document.open_element("ltx:XMArg", Some(string_map!("rule" => "Anything,")), None)?;
1069 }
1070 if let Some(ref pre) = pre_absorb {
1072 document.absorb(pre, None)?;
1073 }
1074 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 if let Some(ref post) = post_absorb {
1085 document.absorb(post, None)?;
1086 }
1087 if wrap_xmarg {
1088 document.close_element("ltx:XMArg")?;
1090 }
1091 document.expire_box_to_absorb();
1093 } else if let Some(ref boxes) = cell.boxes {
1094 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 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 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 else if hashead && !ismath {
1141 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 self.template == other.template
1169 }
1170}
1171
1172pub fn read_alignment_template() -> Result<Template> {
1182 gullet::skip_spaces()?;
1183 local_build_template(Template::default());
1184 let mut tokens = vec![T_BEGIN!()];
1185 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 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 t.finish();
1219 });
1220 Ok(take_build_template().unwrap())
1221}
1222
1223fn 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
1250fn 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 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 && !op.with_str(|s| matches!(s, "\\csname" | "\\expandafter" | "\\noexpand"))
1299 {
1300 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
1323fn 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
1334fn 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#[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
1387const COLUMN_RULE_TOKENS: &str = "COLUMN_RULE_TOKENS";
1390
1391pub fn declare_column_rule_token(cs: &str) { assign_mapping(COLUMN_RULE_TOKENS, cs, Some(true)); }
1393
1394pub fn is_column_rule_token(name: &str) -> bool {
1397 name == "\\vrule" || lookup_mapping_sym(crate::pin!("COLUMN_RULE_TOKENS"), name).is_some()
1398}
1399
1400fn 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 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 return false;
1425 }
1426 }
1427 false
1428}
1429
1430fn 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 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 let ismath = tag == crate::pin!("ltx:XMArray");
1466 let reversed = false;
1467 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 {
1480 let mut cols = collect_alignment_columns(alignment);
1481 if cols.is_empty() {
1482 return Ok(());
1483 }
1484 alignment_characterize_lines(document, Axis::Column, false, cols.as_mut_slice())?;
1486 }
1487
1488 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 if n_d == 1 {
1505 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 if !ismath && !reversed {
1519 alignment_regroup_rows(document, table)?;
1520 }
1521 if n_h > 0 {
1522 document.add_class(table, "ltx_guessed_headers")?;
1524 }
1525
1526 Ok(())
1529}
1530
1531fn alignment_regroup_rows(document: &mut Document, table: &Node) -> Result<()> {
1537 let mut rows = document.findnodes("ltx:tr", Some(table));
1538 let mut heads = Vec::with_capacity(rows.len());
1541 let mut maxreach = 0;
1542 while !rows.is_empty() {
1544 let cells = document.findnodes("ltx:td", Some(&rows[0]));
1545 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 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 heads.append(&mut rows);
1570 rows = std::mem::take(&mut heads);
1571 }
1572 let mut foots = VecDeque::new();
1574 while !rows.is_empty() {
1575 let cells = document.findnodes("ltx:td", Some(rows.last().unwrap()));
1576 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
1597fn 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 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 for col in cols.iter_mut() {
1614 col.cell_type = Some('d');
1615 col.content_class = Some(
1616 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 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 _ => {}, }
1643 }
1644 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 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 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 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 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 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 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 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 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 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 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 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 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 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 alignment.rows[r].get_columns_mut()[c].border_right = Some(bl);
1812 }
1813 }
1814 }
1815 }
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
1861fn classify_alignment_cell(xcell: &Node) -> ColumnSpec {
1864 let content = xcell.get_content();
1865 let mut inferred_classes: Vec<ColumnSpec> = Vec::new();
1866 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 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 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 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 if inferred_classes.is_empty() {
1976 ColumnSpec::Empty
1977 } else if inferred_classes.len() == 1 {
1978 inferred_classes[0]
1979 } else {
1980 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
1993const MIN_ALIGNMENT_DATA_LINES: usize = 1; const MAX_ALIGNMENT_HEADER_LINES: usize = 4; fn 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 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 if d > max_diff {
2027 max_diff = d;
2028 }
2029 if d < min_diff {
2030 min_diff = d;
2031 }
2032 }
2033 if max_diff < 0.05 {
2035 return Ok(());
2037 }
2038 if (n > 2) && ((max_diff - min_diff) < max_diff * 0.5) {
2039 return Ok(());
2041 }
2042 let tab_threshold = min_diff + 0.3 * (max_diff - min_diff);
2043
2044 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 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 let nn = lines[0].len() - 1;
2069 for nh in (minh..=maxh).rev() {
2071 let heads = alignment_test_headers(nh, tab_threshold, axis, lines);
2073 if !heads.is_empty() {
2074 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 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
2107fn alignment_test_headers(
2109 nhead: usize,
2110 tab_threshold: f64,
2111 axis: Axis,
2112 lines: &[Vec<&mut Cell>],
2113) -> Vec<usize> {
2114 let mut heads: Vec<usize> = (0..nhead).collect(); let mut head_length = alignment_max_content_length(0, 0, nhead - 1, lines);
2117 let mut next_line = nhead; let nrep = lines.len() / nhead;
2121 if nhead > 1 {
2122 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 if matched {
2132 return Vec::new();
2133 }
2134 }
2135
2136 let ndata = alignment_skip_data(next_line, tab_threshold, axis, lines);
2138 if ndata < nhead {
2140 return Vec::new();
2142 }
2143 if (ndata < nhead) && (ndata < 2) {
2144 return Vec::new();
2145 }
2146 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 while next_line < lines.len() {
2154 nd = if ndata > 1 {
2158 alignment_match_data(nhead, next_line, ndata, tab_threshold, axis, lines)
2159 } else {
2160 0
2161 };
2162 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 if alignment_match_head(0, next_line, nhead, tab_threshold, axis, lines) > 0 {
2169 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 return Vec::new();
2185 }
2186 }
2187 if (head_length > 10) && (head_length > 4 * data_length) {
2190 return Vec::new();
2193 }
2194 if head_length >= 1000 {
2196 return Vec::new();
2200 }
2201
2202 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 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 if ok { nd } else { 0 }
2234}
2235
2236fn 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
2257fn 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 break;
2288 }
2289 n += 1;
2290 }
2291 if n >= MIN_ALIGNMENT_DATA_LINES { n } else { 0 }
2292}
2293
2294fn 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
2313fn 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 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 if for_adjacency {
2373 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 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 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 diff
2433}