Lay out matrix and array environments as grids
This commit is contained in:
1 parent
971190df26
commit
59b6ca571b
6 files changed
+283
-62
No files matched your search
@@ -18,6 +18,14 @@ pub enum MathAlphabet {
|
||||
Fraktur,
|
||||
}
|
||||
|
||||
/// Horizontal alignment of a matrix/array column.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MathColumnAlign {
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MathAtom {
|
||||
Symbol(char),
|
||||
@@ -88,9 +96,12 @@ pub enum MathAtom {
|
||||
},
|
||||
/// A `\middle` delimiter; TeX sizes it with the enclosing `\left`/`\right`.
|
||||
Middle(char),
|
||||
/// A `cases` environment: each row holds the cells split on `&`.
|
||||
Cases {
|
||||
/// A matrix-like environment: rows of cells with per-column alignment.
|
||||
Matrix {
|
||||
rows: Vec<Vec<MathAtom>>,
|
||||
align: Vec<MathColumnAlign>,
|
||||
left: Option<char>,
|
||||
right: Option<char>,
|
||||
},
|
||||
/// Rows of an `align` (column-aligned) or `gather` (centred) display.
|
||||
Aligned {
|
||||
@@ -540,21 +551,30 @@ pub fn italic_correction(atom: &MathAtom, font: &Cmr10Metrics) -> i64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Geometry shared by the layout and painter of a `cases` environment.
|
||||
pub(crate) struct CasesLayout {
|
||||
/// Geometry shared by the layout and painter of a matrix-like environment.
|
||||
pub(crate) struct MatrixLayout {
|
||||
pub boxes: Vec<Vec<MathBox>>,
|
||||
pub column_widths: Vec<i64>,
|
||||
pub column_starts: Vec<i64>,
|
||||
pub baselines: Vec<i64>,
|
||||
pub first_height: i64,
|
||||
pub brace: (i64, i64, i64),
|
||||
pub left: Option<(char, i64, i64, i64)>,
|
||||
pub right: Option<(char, i64, i64, i64)>,
|
||||
pub body_width: i64,
|
||||
pub border: i64,
|
||||
pub width: i64,
|
||||
pub height: i64,
|
||||
pub depth: i64,
|
||||
}
|
||||
|
||||
/// Lay out the rows of a `cases` environment and the brace beside them.
|
||||
pub(crate) fn cases_layout(rows: &[Vec<MathAtom>], font: &Cmr10Metrics) -> CasesLayout {
|
||||
/// Lay out the rows of a matrix/array and the delimiters around them.
|
||||
pub(crate) fn matrix_layout(
|
||||
rows: &[Vec<MathAtom>],
|
||||
font: &Cmr10Metrics,
|
||||
_align: &[MathColumnAlign],
|
||||
left: Option<char>,
|
||||
right: Option<char>,
|
||||
) -> MatrixLayout {
|
||||
let boxes: Vec<Vec<MathBox>> = rows
|
||||
.iter()
|
||||
.map(|row| row.iter().map(|cell| layout_math(cell, font)).collect())
|
||||
@@ -592,17 +612,42 @@ pub(crate) fn cases_layout(rows: &[Vec<MathAtom>], font: &Cmr10Metrics) -> Cases
|
||||
let last_depth = row_depths.last().copied().unwrap_or(0);
|
||||
let extent = first_height + last_baseline + last_depth;
|
||||
let axis = 2 * 65_536 + 32_768;
|
||||
let brace = select_delimiter(*font, '{', extent);
|
||||
CasesLayout {
|
||||
let left_metrics = left.map(|delimiter| {
|
||||
let (width, height, depth) = select_delimiter(*font, delimiter, extent);
|
||||
(delimiter, width, height, depth)
|
||||
});
|
||||
let right_metrics = right.map(|delimiter| {
|
||||
let (width, height, depth) = select_delimiter(*font, delimiter, extent);
|
||||
(delimiter, width, height, depth)
|
||||
});
|
||||
let border = if left_metrics.is_some() || right_metrics.is_some() {
|
||||
32_768
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let left_width = left_metrics.map(|(_, width, _, _)| width).unwrap_or(0);
|
||||
let right_width = right_metrics.map(|(_, width, _, _)| width).unwrap_or(0);
|
||||
let mut height = extent / 2 + axis;
|
||||
let mut depth = (extent / 2 - axis).max(0);
|
||||
for (_, _, delimiter_height, delimiter_depth) in
|
||||
[left_metrics, right_metrics].into_iter().flatten()
|
||||
{
|
||||
height = height.max(delimiter_height);
|
||||
depth = depth.max(delimiter_depth);
|
||||
}
|
||||
MatrixLayout {
|
||||
boxes,
|
||||
column_widths,
|
||||
column_starts,
|
||||
baselines,
|
||||
first_height,
|
||||
brace,
|
||||
width: brace.0 + 3 * 65_536 + body_width,
|
||||
height: (extent / 2 + axis).max(brace.1),
|
||||
depth: (extent / 2 - axis).max(0).max(brace.2),
|
||||
left: left_metrics,
|
||||
right: right_metrics,
|
||||
body_width,
|
||||
border,
|
||||
width: left_width + border + body_width + border + right_width,
|
||||
height,
|
||||
depth,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -711,27 +756,64 @@ fn math_environment(chars: &[char], index: usize) -> Option<(MathAtom, usize)> {
|
||||
return None;
|
||||
}
|
||||
cursor += 1;
|
||||
let (inner, end) = read_environment(chars, cursor, &name)?;
|
||||
match name.as_str() {
|
||||
"cases" => {
|
||||
let rows = split_environment_rows(&inner)
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
row.into_iter()
|
||||
.map(|cell| {
|
||||
if cell.is_empty() {
|
||||
MathAtom::Row(Vec::new())
|
||||
} else {
|
||||
parse_math(&cell)
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
Some((MathAtom::Cases { rows }, end))
|
||||
let mut align = Vec::new();
|
||||
if name == "array" && chars.get(cursor) == Some(&'{') {
|
||||
cursor += 1;
|
||||
while let Some(&character) = chars.get(cursor) {
|
||||
if character == '}' {
|
||||
cursor += 1;
|
||||
break;
|
||||
}
|
||||
match character {
|
||||
'l' => align.push(MathColumnAlign::Left),
|
||||
'c' => align.push(MathColumnAlign::Center),
|
||||
'r' => align.push(MathColumnAlign::Right),
|
||||
_ => {}
|
||||
}
|
||||
cursor += 1;
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
let (inner, end) = read_environment(chars, cursor, &name)?;
|
||||
let rows: Vec<Vec<MathAtom>> = split_environment_rows(&inner)
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
row.into_iter()
|
||||
.map(|cell| {
|
||||
if cell.is_empty() {
|
||||
MathAtom::Row(Vec::new())
|
||||
} else {
|
||||
parse_math(&cell)
|
||||
}
|
||||
})
|
||||
.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),
|
||||
_ => return None,
|
||||
};
|
||||
let columns = rows.iter().map(|row| row.len()).max().unwrap_or(0);
|
||||
let align = if align.is_empty() {
|
||||
vec![default_align; columns]
|
||||
} else {
|
||||
align
|
||||
};
|
||||
Some((
|
||||
MathAtom::Matrix {
|
||||
rows,
|
||||
align,
|
||||
left,
|
||||
right,
|
||||
},
|
||||
end,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
|
||||
@@ -825,8 +907,13 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
|
||||
depth: body_box.depth.max(left_box.2).max(right_box.2),
|
||||
}
|
||||
}
|
||||
MathAtom::Cases { rows } => {
|
||||
let layout = cases_layout(rows, font);
|
||||
MathAtom::Matrix {
|
||||
rows,
|
||||
align,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
let layout = matrix_layout(rows, font, align, *left, *right);
|
||||
MathBox {
|
||||
width: layout.width,
|
||||
height: layout.height,
|
||||
@@ -2489,21 +2576,100 @@ mod tests {
|
||||
let atom = match atom {
|
||||
MathAtom::Row(atoms) => atoms
|
||||
.into_iter()
|
||||
.find(|atom| matches!(atom, MathAtom::Cases { .. }))
|
||||
.find(|atom| matches!(atom, MathAtom::Matrix { .. }))
|
||||
.expect("cases atom in the row"),
|
||||
other => other,
|
||||
};
|
||||
let MathAtom::Cases { rows } = atom else {
|
||||
panic!("expected a cases atom");
|
||||
let MathAtom::Matrix {
|
||||
rows,
|
||||
align,
|
||||
left,
|
||||
right,
|
||||
} = atom
|
||||
else {
|
||||
panic!("expected a cases matrix");
|
||||
};
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(rows[0].len(), 2);
|
||||
assert_eq!(rows[1].len(), 2);
|
||||
let box_ = layout_math(&MathAtom::Cases { rows }, &Cmr10Metrics::default());
|
||||
assert_eq!(left, Some('{'));
|
||||
assert_eq!(right, None);
|
||||
assert_eq!(align[0], MathColumnAlign::Left);
|
||||
let box_ = layout_math(
|
||||
&MathAtom::Matrix {
|
||||
rows,
|
||||
align,
|
||||
left: Some('{'),
|
||||
right: None,
|
||||
},
|
||||
&Cmr10Metrics::default(),
|
||||
);
|
||||
assert!(box_.width > 3 * 65_536);
|
||||
assert!(box_.height > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix_environments_wrap_their_grid() {
|
||||
let atom = parse_math("\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}");
|
||||
let atom = match atom {
|
||||
MathAtom::Row(atoms) => atoms
|
||||
.into_iter()
|
||||
.find(|atom| matches!(atom, MathAtom::Matrix { .. }))
|
||||
.expect("matrix atom in the row"),
|
||||
other => other,
|
||||
};
|
||||
let MathAtom::Matrix {
|
||||
rows,
|
||||
align,
|
||||
left,
|
||||
right,
|
||||
} = atom
|
||||
else {
|
||||
panic!("expected a matrix atom");
|
||||
};
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(rows[0].len(), 2);
|
||||
assert_eq!(left, Some('('));
|
||||
assert_eq!(right, Some(')'));
|
||||
assert_eq!(align[0], MathColumnAlign::Center);
|
||||
let box_ = layout_math(
|
||||
&MathAtom::Matrix {
|
||||
rows,
|
||||
align,
|
||||
left: Some('('),
|
||||
right: Some(')'),
|
||||
},
|
||||
&Cmr10Metrics::default(),
|
||||
);
|
||||
assert!(box_.width > 0);
|
||||
assert!(box_.height > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_environments_use_their_column_spec() {
|
||||
let atom = parse_math("\\begin{array}{lr} a & b \\\\ c & d \\end{array}");
|
||||
let atom = match atom {
|
||||
MathAtom::Row(atoms) => atoms
|
||||
.into_iter()
|
||||
.find(|atom| matches!(atom, MathAtom::Matrix { .. }))
|
||||
.expect("array atom in the row"),
|
||||
other => other,
|
||||
};
|
||||
let MathAtom::Matrix {
|
||||
rows,
|
||||
align,
|
||||
left,
|
||||
right,
|
||||
} = atom
|
||||
else {
|
||||
panic!("expected an array matrix");
|
||||
};
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(left, None);
|
||||
assert_eq!(right, None);
|
||||
assert_eq!(align, vec![MathColumnAlign::Left, MathColumnAlign::Right]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_delimiters_allow_math_spaces() {
|
||||
let font = Cmr10Metrics::default();
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! wired up.
|
||||
|
||||
use crate::cmr10::Cmr10Metrics;
|
||||
use crate::math::{self, MathAtom};
|
||||
use crate::math::{self, MathAtom, MathColumnAlign};
|
||||
use crate::paragraph::ParagraphFont;
|
||||
use crate::{CellAlignment, Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem};
|
||||
|
||||
@@ -1026,32 +1026,70 @@ impl Page {
|
||||
});
|
||||
}
|
||||
}
|
||||
MathAtom::Cases { rows } => {
|
||||
let layout = math::cases_layout(rows, font);
|
||||
let base_extent = font.height('{') + font.depth('{');
|
||||
let scale = if base_extent > 0 {
|
||||
(layout.brace.1 + layout.brace.2) as f64 / base_extent as f64
|
||||
} else {
|
||||
1.0
|
||||
MathAtom::Matrix {
|
||||
rows,
|
||||
align,
|
||||
left,
|
||||
right,
|
||||
} => {
|
||||
let layout = math::matrix_layout(rows, font, align, *left, *right);
|
||||
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);
|
||||
let scale = if base > 0 {
|
||||
(metrics.2 + metrics.3) as f64 / base as f64
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let glyph_size = (size as f64 * scale) as i64;
|
||||
let shift = ((glyph_size - size) as f64 * 0.35) as i64;
|
||||
(glyph_size, shift)
|
||||
};
|
||||
let glyph_size = (size as f64 * scale) as i64;
|
||||
let shift = ((glyph_size - size) as f64 * 0.35) as i64;
|
||||
list.push(DisplayItem::Text {
|
||||
font: FontFace::Roman,
|
||||
x,
|
||||
y: baseline + shift,
|
||||
size: glyph_size,
|
||||
text: "{".to_string(),
|
||||
});
|
||||
let start_x = x + layout.brace.0 + 3 * 65_536;
|
||||
let left_width = layout.left.map(|(_, width, _, _)| width).unwrap_or(0);
|
||||
if let Some(metrics) = layout.left {
|
||||
let (glyph_size, shift) = scaled(metrics);
|
||||
list.push(DisplayItem::Text {
|
||||
font: FontFace::Roman,
|
||||
x,
|
||||
y: baseline + shift,
|
||||
size: glyph_size,
|
||||
text: metrics.0.to_string(),
|
||||
});
|
||||
}
|
||||
let body_x = x + left_width + layout.border;
|
||||
let first_baseline = baseline - layout.height + layout.first_height;
|
||||
for (row_index, cells) in rows.iter().enumerate() {
|
||||
let row_baseline = first_baseline + layout.baselines[row_index];
|
||||
for (column, cell) in cells.iter().enumerate() {
|
||||
let cell_x = start_x + layout.column_starts[column];
|
||||
let offset = match align
|
||||
.get(column)
|
||||
.copied()
|
||||
.unwrap_or(MathColumnAlign::Center)
|
||||
{
|
||||
MathColumnAlign::Left => 0,
|
||||
MathColumnAlign::Center => {
|
||||
(layout.column_widths[column]
|
||||
- layout.boxes[row_index][column].width)
|
||||
/ 2
|
||||
}
|
||||
MathColumnAlign::Right => {
|
||||
layout.column_widths[column] - layout.boxes[row_index][column].width
|
||||
}
|
||||
};
|
||||
let cell_x = body_x + layout.column_starts[column] + offset;
|
||||
Self::paint_math(cell, font, cell_x, row_baseline, size, list);
|
||||
}
|
||||
}
|
||||
if let Some(metrics) = layout.right {
|
||||
let (glyph_size, shift) = scaled(metrics);
|
||||
list.push(DisplayItem::Text {
|
||||
font: FontFace::Roman,
|
||||
x: body_x + layout.body_width + layout.border,
|
||||
y: baseline + shift,
|
||||
size: glyph_size,
|
||||
text: metrics.0.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
MathAtom::Accent { accent, base } => {
|
||||
let base_box = math::layout_math(base, font);
|
||||
|
||||
Reference in new issue
Block a user