Check matrix and cases positions against pdfLaTeX

This commit is contained in:
gloamxun committed 2026-10-26 00:53:40 +08:00
1 parent e926bc9eb3
commit 52a74755f7
5 files changed
+183 -21

No files matched your search

+36 -11
View File
@@ -26,6 +26,10 @@ pub enum MathColumnAlign {
Right,
}
fn default_matrix_row_lead() -> i64 {
12 * 65_536
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum MathAtom {
Symbol(char),
@@ -102,6 +106,8 @@ pub enum MathAtom {
align: Vec<MathColumnAlign>,
left: Option<char>,
right: Option<char>,
#[serde(default = "default_matrix_row_lead")]
row_lead: i64,
},
/// Rows of a `multline`: first flush left, last flush right, middle centred.
Multline {
@@ -635,6 +641,7 @@ pub(crate) fn matrix_layout(
_align: &[MathColumnAlign],
left: Option<char>,
right: Option<char>,
row_lead: i64,
) -> MatrixLayout {
let boxes: Vec<Vec<MathBox>> = rows
.iter()
@@ -665,7 +672,7 @@ pub(crate) fn matrix_layout(
.collect();
let mut baselines = vec![0_i64; boxes.len()];
for index in 1..boxes.len() {
let advance = (row_depths[index - 1] + row_heights[index] + 2 * 65_536).max(655_360);
let advance = (row_depths[index - 1] + row_heights[index] + 2 * 65_536).max(row_lead);
baselines[index] = baselines[index - 1] + advance;
}
let first_height = row_heights.first().copied().unwrap_or(0);
@@ -849,15 +856,26 @@ fn math_environment(chars: &[char], index: usize) -> Option<(MathAtom, usize)> {
.collect()
})
.collect();
let (left, right, default_align) = match name.as_str() {
"cases" => (Some('{'), None, MathColumnAlign::Left),
"matrix" => (None, None, MathColumnAlign::Center),
"pmatrix" => (Some('('), Some(')'), MathColumnAlign::Center),
"bmatrix" => (Some('['), Some(']'), MathColumnAlign::Center),
"Bmatrix" => (Some('{'), Some('}'), MathColumnAlign::Center),
"vmatrix" => (Some('|'), Some('|'), MathColumnAlign::Center),
"Vmatrix" => (Some('\u{2016}'), Some('\u{2016}'), MathColumnAlign::Center),
"array" => (None, None, MathColumnAlign::Center),
let (left, right, default_align, row_lead) = match name.as_str() {
"cases" => (
Some('{'),
None,
MathColumnAlign::Left,
// amsmath applies \arraystretch{1.2} inside cases.
943_718,
),
"matrix" => (None, None, MathColumnAlign::Center, 12 * 65_536),
"pmatrix" => (Some('('), Some(')'), MathColumnAlign::Center, 12 * 65_536),
"bmatrix" => (Some('['), Some(']'), MathColumnAlign::Center, 12 * 65_536),
"Bmatrix" => (Some('{'), Some('}'), MathColumnAlign::Center, 12 * 65_536),
"vmatrix" => (Some('|'), Some('|'), MathColumnAlign::Center, 12 * 65_536),
"Vmatrix" => (
Some('\u{2016}'),
Some('\u{2016}'),
MathColumnAlign::Center,
12 * 65_536,
),
"array" => (None, None, MathColumnAlign::Center, 12 * 65_536),
_ => return None,
};
let columns = rows.iter().map(|row| row.len()).max().unwrap_or(0);
@@ -872,6 +890,7 @@ fn math_environment(chars: &[char], index: usize) -> Option<(MathAtom, usize)> {
align,
left,
right,
row_lead,
},
end,
))
@@ -973,8 +992,9 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
align,
left,
right,
row_lead,
} => {
let layout = matrix_layout(rows, font, align, *left, *right);
let layout = matrix_layout(rows, font, align, *left, *right, *row_lead);
MathBox {
width: layout.width,
height: layout.height,
@@ -2687,6 +2707,7 @@ mod tests {
align,
left,
right,
..
} = atom
else {
panic!("expected a cases matrix");
@@ -2703,6 +2724,7 @@ mod tests {
align,
left: Some('{'),
right: None,
row_lead: 943_718,
},
&Cmr10Metrics::default(),
);
@@ -2745,6 +2767,7 @@ mod tests {
align,
left,
right,
..
} = atom
else {
panic!("expected a matrix atom");
@@ -2760,6 +2783,7 @@ mod tests {
align,
left: Some('('),
right: Some(')'),
row_lead: 12 * 65_536,
},
&Cmr10Metrics::default(),
);
@@ -2782,6 +2806,7 @@ mod tests {
align,
left,
right,
..
} = atom
else {
panic!("expected an array matrix");
+2 -1
View File
@@ -1031,8 +1031,9 @@ impl Page {
align,
left,
right,
row_lead,
} => {
let layout = math::matrix_layout(rows, font, align, *left, *right);
let layout = math::matrix_layout(rows, font, align, *left, *right, *row_lead);
let base_extent = |delimiter: char| font.height(delimiter) + font.depth(delimiter);
let scaled = |metrics: (char, i64, i64, i64)| -> (i64, i64) {
let base = base_extent(metrics.0);
+141 -5
View File
@@ -22,6 +22,12 @@ struct Word {
text: String,
/// Offset from the start of its line, in TeX points.
x: f64,
/// Absolute left edge on the page, in TeX points.
#[allow(dead_code)]
abs_x: f64,
/// Absolute top edge on the page, in TeX points.
#[allow(dead_code)]
abs_y: f64,
}
#[derive(Clone, Debug)]
@@ -121,11 +127,12 @@ fn parse_bbox(xhtml: &str) -> Vec<Line> {
});
current_y = y_min;
}
lines
.last_mut()
.expect("line")
.words
.push(Word { text, x: x_min });
lines.last_mut().expect("line").words.push(Word {
text,
x: x_min,
abs_x: x_min * BP_TO_PT,
abs_y: y_min * BP_TO_PT,
});
rest = &rest[close + "</word>".len()..];
}
for line in &mut lines {
@@ -138,6 +145,18 @@ fn parse_bbox(xhtml: &str) -> Vec<Line> {
lines
}
/// Flatten pdfLaTeX word boxes into absolute page positions.
fn tex_word_positions(source: &str) -> Option<Vec<(String, f64, f64)>> {
let lines = pdftex_lines(source)?;
Some(
lines
.into_iter()
.flat_map(|line| line.words)
.map(|word| (word.text, word.abs_x, word.abs_y))
.collect(),
)
}
/// Lay out a paragraph after applying paragraph-register overrides.
fn route_d_lines_with(
text: &str,
@@ -189,6 +208,8 @@ fn route_d_lines_with(
words.push(Word {
text: std::mem::take(&mut word),
x: word_x,
abs_x: 0.0,
abs_y: 0.0,
});
}
x += *width as f64 / PT as f64;
@@ -200,6 +221,8 @@ fn route_d_lines_with(
words.push(Word {
text: word,
x: word_x,
abs_x: 0.0,
abs_y: 0.0,
});
}
let start = words.first().map(|word| word.x).unwrap_or(0.0);
@@ -1237,3 +1260,116 @@ fn hfill_matches_pdftex() {
fn hfill_and_hfil_match_pdftex() {
compare_fixture_with("alpha \\hfil beta \\hfill gamma", 150, "", |_| {});
}
#[test]
fn pmatrix_word_positions_match_pdftex() {
let source = r"\documentclass[10pt]{article}
\usepackage{amsmath}
\pagestyle{empty}
\begin{document}
\[ \begin{pmatrix} a & b \\ c & d \end{pmatrix} \]
\end{document}
";
let Some(tex) = tex_word_positions(source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let tex = |letter: &str| {
tex.iter()
.find(|(text, _, _)| text == letter)
.map(|(_, x, y)| (*x, *y))
.unwrap_or_else(|| panic!("pdfLaTeX produced no `{letter}`"))
};
let atom = texrra_tex_core::math::parse_math(r"\begin{pmatrix} a & b \\ c & d \end{pmatrix}");
let font = texrra_tex_core::cmr10::Cmr10Metrics::default();
let unit = Unit::math(1, atom, &font);
let document = Document::new(700 * PT, vec![unit]);
let engine = Engine::layout(&document);
let page = engine.pages().first().expect("one page");
let display = page.display_list();
let ours = |letter: &str| {
display
.items
.iter()
.find_map(|item| match item {
texrra_tex_core::render::DisplayItem::Text { text, x, y, .. } if text == letter => {
Some((*x as f64 / PT as f64, *y as f64 / PT as f64))
}
_ => None,
})
.unwrap_or_else(|| panic!("route-D produced no `{letter}`"))
};
let (origin_x, origin_y) = ours("a");
let (tex_x, tex_y) = tex("a");
let mut max_dx = 0.0_f64;
let mut max_dy = 0.0_f64;
for letter in ["b", "c", "d"] {
let (x, y) = ours(letter);
let (reference_x, reference_y) = tex(letter);
let dx = (x - origin_x) - (reference_x - tex_x);
let dy = (y - origin_y) - (reference_y - tex_y);
max_dx = max_dx.max(dx.abs());
max_dy = max_dy.max(dy.abs());
}
eprintln!("pmatrix maximum offsets: ({max_dx:.2}, {max_dy:.2}) pt");
assert!(
max_dx <= 1.0 && max_dy <= 1.0,
"pmatrix words are off by up to ({max_dx:.2}, {max_dy:.2}) pt"
);
}
#[test]
fn cases_row_spacing_matches_pdftex() {
let source = r"\documentclass[10pt]{article}
\usepackage{amsmath}
\pagestyle{empty}
\begin{document}
\[ \begin{cases} a & x>0 \\ b & y<0 \end{cases} \]
\end{document}
";
let Some(tex) = tex_word_positions(source) else {
eprintln!("skipping: pdflatex/pdftotext are not installed");
return;
};
let tex = |word: &str| {
tex.iter()
.find(|(text, _, _)| text == word || text.starts_with(word))
.map(|(_, x, y)| (*x, *y))
.unwrap_or_else(|| panic!("pdfLaTeX produced no `{word}`"))
};
let atom = texrra_tex_core::math::parse_math(r"\begin{cases} a & x>0 \\ b & y<0 \end{cases}");
let font = texrra_tex_core::cmr10::Cmr10Metrics::default();
let unit = Unit::math(1, atom, &font);
let document = Document::new(700 * PT, vec![unit]);
let engine = Engine::layout(&document);
let page = engine.pages().first().expect("one page");
let display = page.display_list();
let ours = |letter: &str| {
display
.items
.iter()
.find_map(|item| match item {
texrra_tex_core::render::DisplayItem::Text { text, x, y, .. } if text == letter => {
Some((*x as f64 / PT as f64, *y as f64 / PT as f64))
}
_ => None,
})
.unwrap_or_else(|| panic!("route-D produced no `{letter}`"))
};
let (origin_x, origin_y) = ours("a");
let (tex_x, tex_y) = tex("a");
for word in ["b", "x"] {
let (x, y) = ours(word);
let (reference_x, reference_y) = tex(word);
let dx = (x - origin_x) - (reference_x - tex_x);
let dy = (y - origin_y) - (reference_y - tex_y);
assert!(
dx.abs() <= 1.5 && dy.abs() <= 1.5,
"`{word}` is off by ({dx:.2}, {dy:.2}) pt"
);
}
}