3754 lines
128 KiB
Rust
Executable File
3754 lines
128 KiB
Rust
Executable File
//! M4 math list model: symbols, scripts and fractions expressed as boxes.
|
|
//!
|
|
//! This is deliberately independent of v1's math renderer. It provides the
|
|
//! geometry the route-D page builder needs; token-to-atom conversion and the
|
|
//! final painter arrive in later M4 slices.
|
|
|
|
use crate::cmr10::{Cmr10Metrics, cmex_delimiter};
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub enum MathAlphabet {
|
|
Roman,
|
|
Bold,
|
|
Italic,
|
|
Sans,
|
|
Mono,
|
|
Calligraphic,
|
|
Blackboard,
|
|
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,
|
|
}
|
|
|
|
fn default_matrix_row_lead() -> i64 {
|
|
12 * 65_536
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub enum MathAtom {
|
|
Symbol(char),
|
|
Space(i64),
|
|
Row(Vec<MathAtom>),
|
|
Sqrt {
|
|
radicand: Box<MathAtom>,
|
|
degree: Option<Box<MathAtom>>,
|
|
},
|
|
Text(String),
|
|
Alphabet {
|
|
text: String,
|
|
alphabet: MathAlphabet,
|
|
},
|
|
Delimited {
|
|
left: char,
|
|
right: char,
|
|
body: Box<MathAtom>,
|
|
},
|
|
Accent {
|
|
accent: char,
|
|
base: Box<MathAtom>,
|
|
},
|
|
Underline {
|
|
base: Box<MathAtom>,
|
|
},
|
|
Negated {
|
|
base: Box<MathAtom>,
|
|
},
|
|
Cancel {
|
|
base: Box<MathAtom>,
|
|
forward: bool,
|
|
backward: bool,
|
|
},
|
|
Boxed {
|
|
body: Box<MathAtom>,
|
|
},
|
|
BigOperator {
|
|
name: String,
|
|
},
|
|
Smash {
|
|
body: Box<MathAtom>,
|
|
top: bool,
|
|
bottom: bool,
|
|
},
|
|
Phantom {
|
|
body: Box<MathAtom>,
|
|
horizontal: bool,
|
|
vertical: bool,
|
|
},
|
|
Strut,
|
|
Tagged {
|
|
body: Box<MathAtom>,
|
|
tag: String,
|
|
},
|
|
Limits {
|
|
base: Box<MathAtom>,
|
|
sub: Option<Box<MathAtom>>,
|
|
sup: Option<Box<MathAtom>>,
|
|
},
|
|
Classed {
|
|
class: MathClass,
|
|
body: Box<MathAtom>,
|
|
},
|
|
SizedDelimiter {
|
|
delimiter: char,
|
|
size: u8,
|
|
},
|
|
/// A `\middle` delimiter; TeX sizes it with the enclosing `\left`/`\right`.
|
|
Middle(char),
|
|
/// 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>,
|
|
#[serde(default = "default_matrix_row_lead")]
|
|
row_lead: i64,
|
|
},
|
|
/// Rows of a `multline`: first flush left, last flush right, middle centred.
|
|
Multline {
|
|
rows: Vec<MathAtom>,
|
|
tag: Option<String>,
|
|
},
|
|
/// Rows of an `align` (column-aligned) or `gather` (centred) display.
|
|
Aligned {
|
|
rows: Vec<AlignedRow>,
|
|
centered: bool,
|
|
},
|
|
StackLines(Vec<MathAtom>),
|
|
/// An `\operatorname` name, with optional default limits.
|
|
OperatorName {
|
|
name: String,
|
|
limits: bool,
|
|
},
|
|
Stack {
|
|
top: Box<MathAtom>,
|
|
base: Box<MathAtom>,
|
|
above: bool,
|
|
},
|
|
Brace {
|
|
base: Box<MathAtom>,
|
|
above: bool,
|
|
},
|
|
Binomial {
|
|
numerator: Box<MathAtom>,
|
|
denominator: Box<MathAtom>,
|
|
},
|
|
Script {
|
|
base: Box<MathAtom>,
|
|
sub: Option<Box<MathAtom>>,
|
|
sup: Option<Box<MathAtom>>,
|
|
},
|
|
Fraction {
|
|
numerator: Box<MathAtom>,
|
|
denominator: Box<MathAtom>,
|
|
/// Whether TeX draws the fraction bar (`\over` vs `\atop`).
|
|
#[serde(default = "fraction_bar_default")]
|
|
bar: bool,
|
|
},
|
|
}
|
|
|
|
/// One row of an `align`/`gather` display.
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct AlignedRow {
|
|
/// The cells between `&`; `gather` rows carry a single cell.
|
|
pub cells: Vec<MathAtom>,
|
|
/// The equation number rendered at the row's right edge.
|
|
pub tag: Option<String>,
|
|
}
|
|
|
|
impl AlignedRow {
|
|
pub fn new(cells: Vec<MathAtom>, tag: Option<String>) -> Self {
|
|
Self { cells, tag }
|
|
}
|
|
}
|
|
|
|
/// Geometry shared by the layout and painter of an `align`/`gather` display.
|
|
pub(crate) struct AlignedLayout {
|
|
pub boxes: Vec<Vec<MathBox>>,
|
|
pub column_widths: Vec<i64>,
|
|
pub column_starts: Vec<i64>,
|
|
pub tag_widths: Vec<i64>,
|
|
pub body_width: i64,
|
|
pub total_width: i64,
|
|
pub baselines: Vec<i64>,
|
|
pub first_height: i64,
|
|
pub height: i64,
|
|
pub depth: i64,
|
|
}
|
|
|
|
pub(crate) struct StackLayout {
|
|
pub(crate) boxes: Vec<MathBox>,
|
|
pub(crate) offsets: Vec<i64>,
|
|
pub(crate) width: i64,
|
|
pub(crate) height: i64,
|
|
pub(crate) depth: i64,
|
|
}
|
|
|
|
pub(crate) fn stack_layout(rows: &[MathAtom], font: &Cmr10Metrics) -> StackLayout {
|
|
if rows.is_empty() {
|
|
return StackLayout {
|
|
boxes: Vec::new(),
|
|
offsets: Vec::new(),
|
|
width: 0,
|
|
height: 0,
|
|
depth: 0,
|
|
};
|
|
}
|
|
let boxes: Vec<MathBox> = rows.iter().map(|row| layout_math(row, font)).collect();
|
|
let width = boxes.iter().map(|box_| box_.width).max().unwrap_or(0);
|
|
let mut offsets = vec![0_i64; boxes.len()];
|
|
let mut offset = 0_i64;
|
|
for index in 1..boxes.len() {
|
|
offset += boxes[index - 1].depth + boxes[index].height + 65_536;
|
|
offsets[index] = offset;
|
|
}
|
|
let height = boxes[0].height;
|
|
let depth = *offsets.last().unwrap_or(&0) + boxes.last().map_or(0, |box_| box_.depth);
|
|
StackLayout {
|
|
boxes,
|
|
offsets,
|
|
width,
|
|
height,
|
|
depth,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn layout_aligned(
|
|
rows: &[AlignedRow],
|
|
centered: bool,
|
|
font: &Cmr10Metrics,
|
|
) -> AlignedLayout {
|
|
if rows.is_empty() {
|
|
return AlignedLayout {
|
|
boxes: Vec::new(),
|
|
column_widths: Vec::new(),
|
|
column_starts: Vec::new(),
|
|
tag_widths: Vec::new(),
|
|
body_width: 0,
|
|
total_width: 0,
|
|
baselines: Vec::new(),
|
|
first_height: 0,
|
|
height: 0,
|
|
depth: 0,
|
|
};
|
|
}
|
|
let boxes: Vec<Vec<MathBox>> = rows
|
|
.iter()
|
|
.map(|row| {
|
|
row.cells
|
|
.iter()
|
|
.map(|cell| layout_math(cell, font))
|
|
.collect()
|
|
})
|
|
.collect();
|
|
let columns = boxes.iter().map(Vec::len).max().unwrap_or(0);
|
|
let mut column_widths = vec![0i64; columns];
|
|
for row in &boxes {
|
|
for (index, cell) in row.iter().enumerate() {
|
|
column_widths[index] = column_widths[index].max(cell.width);
|
|
}
|
|
}
|
|
let mut column_starts = Vec::with_capacity(columns);
|
|
let mut pen = 0i64;
|
|
for width in &column_widths {
|
|
column_starts.push(pen);
|
|
pen += width;
|
|
}
|
|
let body_width = if centered {
|
|
boxes
|
|
.iter()
|
|
.flat_map(|row| row.iter())
|
|
.map(|cell| cell.width)
|
|
.max()
|
|
.unwrap_or(0)
|
|
} else {
|
|
pen
|
|
};
|
|
let tag_widths: Vec<i64> = rows
|
|
.iter()
|
|
.map(|row| {
|
|
row.tag
|
|
.as_ref()
|
|
.map(|tag| {
|
|
tag.chars()
|
|
.map(|character| Cmr10Metrics::Roman.width(character))
|
|
.sum()
|
|
})
|
|
.unwrap_or(0)
|
|
})
|
|
.collect();
|
|
let total_width = body_width.max(tag_widths.iter().copied().max().unwrap_or(0));
|
|
let row_heights: Vec<i64> = boxes
|
|
.iter()
|
|
.map(|row| row.iter().map(|cell| cell.height).max().unwrap_or(0))
|
|
.collect();
|
|
let row_depths: Vec<i64> = boxes
|
|
.iter()
|
|
.map(|row| row.iter().map(|cell| cell.depth).max().unwrap_or(0))
|
|
.collect();
|
|
let mut baselines = vec![0i64; rows.len()];
|
|
for index in 1..rows.len() {
|
|
let minimum = 12 * 65_536;
|
|
let touching = row_depths[index - 1] + row_heights[index] + 65_536;
|
|
baselines[index] = baselines[index - 1] + minimum.max(touching);
|
|
}
|
|
let first_height = row_heights.first().copied().unwrap_or(0);
|
|
let below = baselines.last().copied().unwrap_or(0) + row_depths.last().copied().unwrap_or(0);
|
|
let extent = first_height + below;
|
|
let axis = 2 * 65_536 + 32_768;
|
|
AlignedLayout {
|
|
boxes,
|
|
column_widths,
|
|
column_starts,
|
|
tag_widths,
|
|
body_width,
|
|
total_width,
|
|
baselines,
|
|
first_height,
|
|
height: extent / 2 + axis,
|
|
depth: (extent / 2 - axis).max(0),
|
|
}
|
|
}
|
|
|
|
fn fraction_bar_default() -> bool {
|
|
true
|
|
}
|
|
|
|
impl MathAtom {
|
|
pub fn symbol(character: char) -> Self {
|
|
Self::Symbol(character)
|
|
}
|
|
|
|
pub fn script(base: MathAtom, sub: Option<MathAtom>, sup: Option<MathAtom>) -> Self {
|
|
Self::Script {
|
|
base: Box::new(base),
|
|
sub: sub.map(Box::new),
|
|
sup: sup.map(Box::new),
|
|
}
|
|
}
|
|
|
|
pub fn fraction(numerator: MathAtom, denominator: MathAtom) -> Self {
|
|
Self::Fraction {
|
|
numerator: Box::new(numerator),
|
|
denominator: Box::new(denominator),
|
|
bar: true,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Geometry of a math atom in scaled points, measured from its baseline.
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct MathBox {
|
|
pub width: i64,
|
|
pub height: i64,
|
|
pub depth: i64,
|
|
}
|
|
|
|
/// TeX math atom classes used for inter-atom spacing.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub enum MathClass {
|
|
Ordinary,
|
|
Binary,
|
|
Relation,
|
|
Open,
|
|
Close,
|
|
Punctuation,
|
|
Inner,
|
|
Op,
|
|
}
|
|
|
|
pub fn math_class(character: char) -> MathClass {
|
|
match character {
|
|
'+' | '-' | '*' | '/' => MathClass::Binary,
|
|
'=' | '<' | '>' | ':' => MathClass::Relation,
|
|
'(' | '[' | '{' => MathClass::Open,
|
|
')' | ']' | '}' => MathClass::Close,
|
|
',' | ';' => MathClass::Punctuation,
|
|
_ => MathClass::Ordinary,
|
|
}
|
|
}
|
|
|
|
/// TeX's `\thinmuskip` at 10pt: `3mu`, where `1mu` is `1/18em` and `1em`
|
|
/// is 10pt (so one mu is 36,408.9sp).
|
|
const THIN_MU: i64 = 3 * 655_360 / 18;
|
|
/// Width of `\medmuskip` (4mu plus 2mu minus 4mu at 10pt).
|
|
const MED_MU: i64 = 4 * 655_360 / 18;
|
|
/// Width of `\thickmuskip` (5mu plus 5mu at 10pt).
|
|
const THICK_MU: i64 = 5 * 655_360 / 18;
|
|
|
|
/// TeX's inter-atom spacing table.
|
|
///
|
|
/// The result is the number of math units (0, thin, medium or thick) inserted
|
|
/// between two atoms of the given classes. Entries that TeX marks as
|
|
/// impossible cannot occur after `row_classes` normalises binary operators.
|
|
fn spacing_level(left: MathClass, right: MathClass) -> i64 {
|
|
use MathClass::*;
|
|
match (left, right) {
|
|
(Ordinary, Ordinary) | (Ordinary, Open) | (Ordinary, Close) | (Ordinary, Punctuation) => 0,
|
|
(Ordinary, Op) | (Ordinary, Inner) => 1,
|
|
(Ordinary, Binary) => 2,
|
|
(Ordinary, Relation) => 3,
|
|
(Op, Ordinary) | (Op, Op) | (Op, Inner) => 1,
|
|
(Op, Binary) => 2,
|
|
(Op, Relation) => 3,
|
|
(Op, Open) | (Op, Close) | (Op, Punctuation) => 0,
|
|
(Binary, Ordinary) | (Binary, Op) | (Binary, Open) | (Binary, Inner) => 2,
|
|
(Binary, Binary) | (Binary, Relation) | (Binary, Close) | (Binary, Punctuation) => 0,
|
|
(Relation, Ordinary) | (Relation, Op) | (Relation, Open) | (Relation, Inner) => 3,
|
|
(Relation, Binary) | (Relation, Relation) | (Relation, Close) | (Relation, Punctuation) => {
|
|
0
|
|
}
|
|
(Open, Ordinary)
|
|
| (Open, Op)
|
|
| (Open, Binary)
|
|
| (Open, Relation)
|
|
| (Open, Open)
|
|
| (Open, Close)
|
|
| (Open, Punctuation)
|
|
| (Open, Inner) => 0,
|
|
(Close, Ordinary) | (Close, Open) | (Close, Close) | (Close, Punctuation) => 0,
|
|
(Close, Op) | (Close, Inner) => 1,
|
|
(Close, Binary) => 2,
|
|
(Close, Relation) => 3,
|
|
(Punctuation, Ordinary)
|
|
| (Punctuation, Op)
|
|
| (Punctuation, Binary)
|
|
| (Punctuation, Relation)
|
|
| (Punctuation, Open)
|
|
| (Punctuation, Close)
|
|
| (Punctuation, Punctuation)
|
|
| (Punctuation, Inner) => 1,
|
|
(Inner, Ordinary) | (Inner, Op) | (Inner, Open) | (Inner, Punctuation) => 1,
|
|
(Inner, Binary) => 2,
|
|
(Inner, Relation) | (Inner, Inner) => 3,
|
|
(Inner, Close) => 0,
|
|
}
|
|
}
|
|
|
|
fn spacing_width(left: MathClass, right: MathClass) -> i64 {
|
|
match spacing_level(left, right) {
|
|
1 => THIN_MU,
|
|
2 => MED_MU,
|
|
3 => THICK_MU,
|
|
_ => 0,
|
|
}
|
|
}
|
|
|
|
/// Classify the atoms of one math list and apply TeX's binary-operator
|
|
/// normalisation: a `\mathbin` that starts the list, follows an operator-like
|
|
/// atom, or precedes a relation/close/punctuation becomes ordinary.
|
|
fn row_classes(atoms: &[MathAtom]) -> Vec<MathClass> {
|
|
use MathClass::*;
|
|
let original: Vec<MathClass> = atoms.iter().map(atom_class).collect();
|
|
let mut classes = original.clone();
|
|
for (index, class) in original.iter().enumerate() {
|
|
if *class != Binary {
|
|
continue;
|
|
}
|
|
let previous_is_operand = index > 0;
|
|
let previous_forbids = index == 0
|
|
|| matches!(
|
|
original[index - 1],
|
|
Binary | Op | Relation | Open | Punctuation
|
|
);
|
|
let next_forbids = index + 1 == original.len()
|
|
|| matches!(original[index + 1], Relation | Close | Punctuation);
|
|
if previous_forbids || next_forbids {
|
|
classes[index] = Ordinary;
|
|
}
|
|
let _ = previous_is_operand;
|
|
}
|
|
classes
|
|
}
|
|
|
|
fn scaled(value: i64, factor: f64) -> i64 {
|
|
(value as f64 * factor).round() as i64
|
|
}
|
|
|
|
/// Split a display formula into lines that fit `max_width`.
|
|
///
|
|
/// TeX itself never breaks display math automatically; this mirrors the
|
|
/// explicit `\\split`/`align` behaviour by breaking after a top-level
|
|
/// binary or relation operator once the line would overflow.
|
|
pub fn split_math_lines(atom: &MathAtom, font: &Cmr10Metrics, max_width: i64) -> Vec<MathAtom> {
|
|
let atoms = match atom {
|
|
MathAtom::Row(items) => items.clone(),
|
|
other => vec![other.clone()],
|
|
};
|
|
if layout_math(atom, font).width <= max_width {
|
|
return vec![atom.clone()];
|
|
}
|
|
let mut lines: Vec<Vec<MathAtom>> = Vec::new();
|
|
let mut current: Vec<MathAtom> = Vec::new();
|
|
for item in atoms {
|
|
let mut candidate = current.clone();
|
|
candidate.push(item.clone());
|
|
let candidate_width = layout_math(&MathAtom::Row(candidate.clone()), font).width;
|
|
if !current.is_empty() && candidate_width > max_width {
|
|
lines.push(std::mem::take(&mut current));
|
|
}
|
|
current.push(item);
|
|
}
|
|
if !current.is_empty() {
|
|
lines.push(current);
|
|
}
|
|
lines.into_iter().map(MathAtom::Row).collect()
|
|
}
|
|
|
|
/// Metrics for the built-in math alphabets.
|
|
///
|
|
/// Mathematical italic letters are the default math face (`cmmi10`); the
|
|
/// upright faces reuse the paragraph TFMs so `\mathbf`, `\mathsf` and
|
|
/// `\mathtt` get the same advances as their text counterparts.
|
|
pub(crate) fn alphabet_metrics(font: Cmr10Metrics, alphabet: MathAlphabet) -> Cmr10Metrics {
|
|
match alphabet {
|
|
MathAlphabet::Roman => font,
|
|
MathAlphabet::Italic => Cmr10Metrics::Math,
|
|
MathAlphabet::Bold => {
|
|
Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Bold)
|
|
}
|
|
MathAlphabet::Sans => {
|
|
Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Sans)
|
|
}
|
|
MathAlphabet::Mono => {
|
|
Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Mono)
|
|
}
|
|
MathAlphabet::Calligraphic => Cmr10Metrics::MathCalligraphic,
|
|
MathAlphabet::Blackboard => Cmr10Metrics::MathBlackboard,
|
|
MathAlphabet::Fraktur => Cmr10Metrics::MathFraktur,
|
|
}
|
|
}
|
|
|
|
fn atom_class(atom: &MathAtom) -> MathClass {
|
|
match atom {
|
|
MathAtom::Symbol(character) => math_class(*character),
|
|
MathAtom::Classed { class, .. } => *class,
|
|
MathAtom::Row(atoms) => atoms.last().map(atom_class).unwrap_or(MathClass::Ordinary),
|
|
MathAtom::Negated { base } => atom_class(base),
|
|
MathAtom::Cancel { base, .. } => atom_class(base),
|
|
MathAtom::BigOperator { .. } => MathClass::Op,
|
|
MathAtom::OperatorName { .. } => MathClass::Op,
|
|
MathAtom::Limits { base, .. } => atom_class(base),
|
|
MathAtom::Fraction { .. } | MathAtom::Binomial { .. } | MathAtom::Delimited { .. } => {
|
|
MathClass::Inner
|
|
}
|
|
_ => MathClass::Ordinary,
|
|
}
|
|
}
|
|
|
|
/// TeX grows delimiters with the enclosed formula; this is a simple 1x-3x
|
|
/// approximation of that rule.
|
|
/// Pick the delimiter glyph TeX would use for a body of `delta` extent.
|
|
///
|
|
/// The ordinary glyph is used while it is tall enough; otherwise the smallest
|
|
/// CMEX size variant whose extent covers the requirement wins, and oversized
|
|
/// bodies scale the largest variant further.
|
|
pub(crate) fn select_delimiter(font: Cmr10Metrics, delimiter: char, delta: i64) -> (i64, i64, i64) {
|
|
if delimiter == '.' {
|
|
return (0, 0, 0);
|
|
}
|
|
let base = (
|
|
font.width(delimiter),
|
|
font.height(delimiter),
|
|
font.depth(delimiter),
|
|
);
|
|
let need = ((delta * 901) / 1000).max(delta - 5 * 65_536).max(0);
|
|
if base.1 + base.2 >= need && base.1 + base.2 > 0 {
|
|
return base;
|
|
}
|
|
for size in 1..=4 {
|
|
if let Some(metrics) = cmex_delimiter(delimiter, size) {
|
|
if metrics.1 + metrics.2 >= need {
|
|
return metrics;
|
|
}
|
|
}
|
|
}
|
|
if let Some(metrics) = cmex_delimiter(delimiter, 4) {
|
|
let extent = metrics.1 + metrics.2;
|
|
if extent > 0 && need > extent {
|
|
let factor = need as f64 / extent as f64;
|
|
return (
|
|
(metrics.0 as f64 * factor) as i64,
|
|
(metrics.1 as f64 * factor) as i64,
|
|
(metrics.2 as f64 * factor) as i64,
|
|
);
|
|
}
|
|
return metrics;
|
|
}
|
|
base
|
|
}
|
|
|
|
pub fn delimiter_scale(body: &MathBox) -> f64 {
|
|
let extent = (body.height + body.depth) as f64 / 65_536.0;
|
|
(extent / 9.0).clamp(1.0, 3.0)
|
|
}
|
|
|
|
/// Lay out a math atom at the current style size.
|
|
/// TeX italic correction of the rightmost glyph of an atom. It is added
|
|
/// before a superscript/subscript so italic bases do not collide with scripts.
|
|
pub fn italic_correction(atom: &MathAtom, font: &Cmr10Metrics) -> i64 {
|
|
match atom {
|
|
MathAtom::Symbol(character) => font.italic(*character),
|
|
MathAtom::Row(atoms) => atoms
|
|
.iter()
|
|
.rev()
|
|
.map(|atom| italic_correction(atom, font))
|
|
.find(|correction| *correction != 0)
|
|
.unwrap_or(0),
|
|
MathAtom::Script { base, .. } => italic_correction(base, font),
|
|
_ => 0,
|
|
}
|
|
}
|
|
|
|
/// 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 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,
|
|
}
|
|
|
|
/// Geometry shared by the layout and painter of a `multline` environment.
|
|
pub(crate) struct MultlineLayout {
|
|
pub offsets: Vec<i64>,
|
|
pub body_width: i64,
|
|
pub width: i64,
|
|
pub baselines: Vec<i64>,
|
|
pub first_height: i64,
|
|
pub height: i64,
|
|
pub depth: i64,
|
|
}
|
|
|
|
/// Lay out the rows of a `multline`, with the last row flush right.
|
|
pub(crate) fn multline_layout(
|
|
rows: &[MathAtom],
|
|
tag: Option<&str>,
|
|
font: &Cmr10Metrics,
|
|
) -> MultlineLayout {
|
|
let boxes: Vec<MathBox> = rows.iter().map(|row| layout_math(row, font)).collect();
|
|
let body_width = boxes.iter().map(|row| row.width).max().unwrap_or(0);
|
|
let tag_width = tag
|
|
.map(|text| text.chars().map(|ch| Cmr10Metrics::Roman.width(ch)).sum())
|
|
.unwrap_or(0);
|
|
let mut baselines = vec![0_i64; boxes.len()];
|
|
for index in 1..boxes.len() {
|
|
let advance = (boxes[index - 1].depth + boxes[index].height + 2 * 65_536).max(655_360);
|
|
baselines[index] = baselines[index - 1] + advance;
|
|
}
|
|
let first_height = boxes.first().map(|row| row.height).unwrap_or(0);
|
|
let last_baseline = baselines.last().copied().unwrap_or(0);
|
|
let last_depth = boxes.last().map(|row| row.depth).unwrap_or(0);
|
|
let extent = first_height + last_baseline + last_depth;
|
|
let axis = 2 * 65_536 + 32_768;
|
|
let offsets: Vec<i64> = boxes
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(index, row)| {
|
|
if index == 0 {
|
|
0
|
|
} else if index + 1 == boxes.len() {
|
|
body_width - row.width
|
|
} else {
|
|
(body_width - row.width) / 2
|
|
}
|
|
})
|
|
.collect();
|
|
MultlineLayout {
|
|
offsets,
|
|
body_width,
|
|
width: body_width + tag_width,
|
|
baselines,
|
|
first_height,
|
|
height: extent / 2 + axis,
|
|
depth: (extent / 2 - axis).max(0),
|
|
}
|
|
}
|
|
|
|
/// 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>,
|
|
row_lead: i64,
|
|
) -> MatrixLayout {
|
|
let boxes: Vec<Vec<MathBox>> = rows
|
|
.iter()
|
|
.map(|row| row.iter().map(|cell| layout_math(cell, font)).collect())
|
|
.collect();
|
|
let columns = boxes.iter().map(|row| row.len()).max().unwrap_or(0);
|
|
let mut column_widths = vec![0_i64; columns];
|
|
for row in &boxes {
|
|
for (column, cell) in row.iter().enumerate() {
|
|
column_widths[column] = column_widths[column].max(cell.width);
|
|
}
|
|
}
|
|
let gap = 655_360;
|
|
let mut column_starts = vec![0_i64; columns];
|
|
let mut cursor = 0_i64;
|
|
for (column, width) in column_widths.iter().enumerate() {
|
|
column_starts[column] = cursor;
|
|
cursor += *width + if column + 1 < columns { gap } else { 0 };
|
|
}
|
|
let body_width = cursor;
|
|
let row_heights: Vec<i64> = boxes
|
|
.iter()
|
|
.map(|row| row.iter().map(|cell| cell.height).max().unwrap_or(0))
|
|
.collect();
|
|
let row_depths: Vec<i64> = boxes
|
|
.iter()
|
|
.map(|row| row.iter().map(|cell| cell.depth).max().unwrap_or(0))
|
|
.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(row_lead);
|
|
baselines[index] = baselines[index - 1] + advance;
|
|
}
|
|
let first_height = row_heights.first().copied().unwrap_or(0);
|
|
let last_baseline = baselines.last().copied().unwrap_or(0);
|
|
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 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,
|
|
left: left_metrics,
|
|
right: right_metrics,
|
|
body_width,
|
|
border,
|
|
width: left_width + border + body_width + border + right_width,
|
|
height,
|
|
depth,
|
|
}
|
|
}
|
|
|
|
/// Read the body of `\begin{name}` up to its matching `\end{name}`.
|
|
fn read_environment(chars: &[char], index: usize, name: &str) -> Option<(String, usize)> {
|
|
let pattern: Vec<char> = format!("\\end{{{name}}}").chars().collect();
|
|
let mut cursor = index;
|
|
let mut depth = 0_i32;
|
|
while cursor < chars.len() {
|
|
match chars[cursor] {
|
|
'{' => depth += 1,
|
|
'}' => depth -= 1,
|
|
_ => {}
|
|
}
|
|
if depth == 0
|
|
&& cursor + pattern.len() <= chars.len()
|
|
&& chars[cursor..cursor + pattern.len()] == pattern[..]
|
|
{
|
|
let inner: String = chars[index..cursor].iter().collect();
|
|
return Some((inner, cursor + pattern.len()));
|
|
}
|
|
cursor += 1;
|
|
}
|
|
None
|
|
}
|
|
|
|
/// Split an environment body into rows on `\\` and cells on `&`.
|
|
pub(crate) fn split_environment_rows(inner: &str) -> Vec<Vec<String>> {
|
|
fn cells(row: &str) -> Vec<String> {
|
|
let mut cells = Vec::new();
|
|
let mut cell = String::new();
|
|
let mut depth = 0_i32;
|
|
for character in row.chars() {
|
|
match character {
|
|
'{' => {
|
|
depth += 1;
|
|
cell.push(character);
|
|
}
|
|
'}' => {
|
|
depth -= 1;
|
|
cell.push(character);
|
|
}
|
|
'&' if depth == 0 => {
|
|
cells.push(cell.trim().to_string());
|
|
cell.clear();
|
|
}
|
|
_ => cell.push(character),
|
|
}
|
|
}
|
|
cells.push(cell.trim().to_string());
|
|
cells
|
|
}
|
|
|
|
let mut rows = Vec::new();
|
|
let mut row = String::new();
|
|
let mut depth = 0_i32;
|
|
let mut characters = inner.chars().peekable();
|
|
while let Some(character) = characters.next() {
|
|
match character {
|
|
'{' => {
|
|
depth += 1;
|
|
row.push(character);
|
|
}
|
|
'}' => {
|
|
depth -= 1;
|
|
row.push(character);
|
|
}
|
|
'\\' if depth == 0 => {
|
|
if characters.peek() == Some(&'\\') {
|
|
characters.next();
|
|
rows.push(cells(&row));
|
|
row.clear();
|
|
} else {
|
|
row.push(character);
|
|
}
|
|
}
|
|
_ => row.push(character),
|
|
}
|
|
}
|
|
let last = cells(&row);
|
|
if !(last.len() == 1 && last[0].is_empty()) {
|
|
rows.push(last);
|
|
}
|
|
rows
|
|
}
|
|
|
|
/// Parse a `\begin{env}...\end{env}` math environment.
|
|
fn math_environment(chars: &[char], index: usize) -> Option<(MathAtom, usize)> {
|
|
let mut cursor = index;
|
|
while chars.get(cursor) == Some(&'\u{0}') {
|
|
cursor += 1;
|
|
}
|
|
if chars.get(cursor) != Some(&'{') {
|
|
return None;
|
|
}
|
|
cursor += 1;
|
|
let mut name = String::new();
|
|
while let Some(&character) = chars.get(cursor) {
|
|
if character == '}' {
|
|
break;
|
|
}
|
|
name.push(character);
|
|
cursor += 1;
|
|
}
|
|
if chars.get(cursor) != Some(&'}') {
|
|
return None;
|
|
}
|
|
cursor += 1;
|
|
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;
|
|
}
|
|
}
|
|
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, 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);
|
|
let align = if align.is_empty() {
|
|
vec![default_align; columns]
|
|
} else {
|
|
align
|
|
};
|
|
Some((
|
|
MathAtom::Matrix {
|
|
rows,
|
|
align,
|
|
left,
|
|
right,
|
|
row_lead,
|
|
},
|
|
end,
|
|
))
|
|
}
|
|
|
|
/// Scale a math box to TeX's 70% script size.
|
|
pub(crate) fn script_metrics(box_: MathBox) -> MathBox {
|
|
MathBox {
|
|
width: box_.width * 7 / 10,
|
|
height: box_.height * 7 / 10,
|
|
depth: box_.depth * 7 / 10,
|
|
}
|
|
}
|
|
|
|
/// The glyph depth TeX would use for a base, without the 2pt floor that
|
|
/// ordinary math boxes apply for visual spacing.
|
|
pub(crate) fn intrinsic_depth(atom: &MathAtom, font: &Cmr10Metrics) -> i64 {
|
|
match atom {
|
|
MathAtom::Symbol(character) => font.depth(*character).max(0),
|
|
MathAtom::Row(atoms) => atoms
|
|
.iter()
|
|
.rev()
|
|
.map(|atom| intrinsic_depth(atom, font))
|
|
.find(|depth| *depth > 0)
|
|
.unwrap_or(0),
|
|
MathAtom::Classed { body, .. } => intrinsic_depth(body, font),
|
|
MathAtom::Script { base, .. } => intrinsic_depth(base, font),
|
|
MathAtom::Limits { base, .. } => intrinsic_depth(base, font),
|
|
_ => layout_math(atom, font).depth,
|
|
}
|
|
}
|
|
|
|
pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
|
|
match atom {
|
|
MathAtom::Symbol(character) => {
|
|
let height = font.height(*character);
|
|
let depth = font.depth(*character);
|
|
MathBox {
|
|
width: font.width(*character),
|
|
height: if height > 0 { height } else { 7 * 65_536 },
|
|
depth: if depth > 0 { depth } else { 2 * 65_536 },
|
|
}
|
|
}
|
|
MathAtom::Space(width) => MathBox {
|
|
width: *width,
|
|
height: 0,
|
|
depth: 0,
|
|
},
|
|
MathAtom::Row(atoms) => {
|
|
let mut width = 0;
|
|
let mut height = 0;
|
|
let mut depth = 0;
|
|
let classes = row_classes(atoms);
|
|
for (index, atom) in atoms.iter().enumerate() {
|
|
let boxed = layout_math(atom, font);
|
|
if index > 0 {
|
|
width += spacing_width(classes[index - 1], classes[index]);
|
|
}
|
|
width += boxed.width;
|
|
height = height.max(boxed.height);
|
|
depth = depth.max(boxed.depth);
|
|
}
|
|
MathBox {
|
|
width,
|
|
height,
|
|
depth,
|
|
}
|
|
}
|
|
MathAtom::Sqrt { radicand, degree } => {
|
|
let boxed = layout_math(radicand, font);
|
|
let degree_box = degree.as_deref().map(|atom| layout_math(atom, font));
|
|
MathBox {
|
|
width: boxed.width
|
|
+ 4 * 65_536
|
|
+ degree_box.as_ref().map_or(0, |boxed| boxed.width),
|
|
height: boxed.height
|
|
+ 2 * 65_536
|
|
+ degree_box.as_ref().map_or(0, |boxed| boxed.height),
|
|
depth: boxed.depth,
|
|
}
|
|
}
|
|
MathAtom::Text(text) => MathBox {
|
|
width: text
|
|
.chars()
|
|
.map(|character| {
|
|
if character == ' ' {
|
|
font.space()
|
|
} else {
|
|
font.width(character)
|
|
}
|
|
})
|
|
.sum(),
|
|
height: 6 * 65_536,
|
|
depth: 2 * 65_536,
|
|
},
|
|
MathAtom::Alphabet { text, alphabet } => {
|
|
let metrics = alphabet_metrics(*font, *alphabet);
|
|
MathBox {
|
|
width: text
|
|
.chars()
|
|
.map(|character| {
|
|
if character == ' ' {
|
|
metrics.space()
|
|
} else {
|
|
metrics.width(character)
|
|
}
|
|
})
|
|
.sum(),
|
|
height: 6 * 65_536,
|
|
depth: 2 * 65_536,
|
|
}
|
|
}
|
|
MathAtom::Delimited { left, right, body } => {
|
|
let body_box = layout_math(body, font);
|
|
let delta = body_box.height + body_box.depth;
|
|
let left_box = select_delimiter(*font, *left, delta);
|
|
let right_box = select_delimiter(*font, *right, delta);
|
|
MathBox {
|
|
width: left_box.0 + body_box.width + right_box.0,
|
|
height: body_box.height.max(left_box.1).max(right_box.1),
|
|
depth: body_box.depth.max(left_box.2).max(right_box.2),
|
|
}
|
|
}
|
|
MathAtom::Matrix {
|
|
rows,
|
|
align,
|
|
left,
|
|
right,
|
|
row_lead,
|
|
} => {
|
|
let layout = matrix_layout(rows, font, align, *left, *right, *row_lead);
|
|
MathBox {
|
|
width: layout.width,
|
|
height: layout.height,
|
|
depth: layout.depth,
|
|
}
|
|
}
|
|
MathAtom::Multline { rows, tag } => {
|
|
let layout = multline_layout(rows, tag.as_deref(), font);
|
|
MathBox {
|
|
width: layout.width,
|
|
height: layout.height,
|
|
depth: layout.depth,
|
|
}
|
|
}
|
|
MathAtom::Accent { base, .. } => {
|
|
let base_box = layout_math(base, font);
|
|
MathBox {
|
|
width: base_box.width,
|
|
height: base_box.height + 2 * 65_536,
|
|
depth: base_box.depth,
|
|
}
|
|
}
|
|
MathAtom::Smash { body, top, bottom } => {
|
|
let body = layout_math(body, font);
|
|
MathBox {
|
|
width: body.width,
|
|
height: if *top { 0 } else { body.height },
|
|
depth: if *bottom { 0 } else { body.depth },
|
|
}
|
|
}
|
|
MathAtom::Strut => MathBox {
|
|
width: 0,
|
|
height: 7 * 65_536,
|
|
depth: 2 * 65_536,
|
|
},
|
|
MathAtom::Phantom {
|
|
body,
|
|
horizontal,
|
|
vertical,
|
|
} => {
|
|
let body = layout_math(body, font);
|
|
MathBox {
|
|
width: if *horizontal { body.width } else { 0 },
|
|
height: if *vertical { body.height } else { 0 },
|
|
depth: if *vertical { body.depth } else { 0 },
|
|
}
|
|
}
|
|
MathAtom::BigOperator { name } => {
|
|
let (width, height, depth) =
|
|
crate::cmr10::cmex_operator(name).unwrap_or((12 * 65_536, 8 * 65_536, 3 * 65_536));
|
|
MathBox {
|
|
width,
|
|
height,
|
|
depth,
|
|
}
|
|
}
|
|
MathAtom::Limits { base, sub, sup } => {
|
|
let base = layout_math(base, font);
|
|
let sub = sub
|
|
.as_ref()
|
|
.map(|atom| script_metrics(layout_math(atom, font)));
|
|
let sup = sup
|
|
.as_ref()
|
|
.map(|atom| script_metrics(layout_math(atom, font)));
|
|
MathBox {
|
|
width: base
|
|
.width
|
|
.max(sub.as_ref().map_or(0, |item| item.width))
|
|
.max(sup.as_ref().map_or(0, |item| item.width)),
|
|
height: base.height
|
|
+ sup
|
|
.as_ref()
|
|
.map_or(0, |item| item.height + item.depth + 65_536),
|
|
depth: base.depth
|
|
+ sub
|
|
.as_ref()
|
|
.map_or(0, |item| item.height + item.depth + 65_536),
|
|
}
|
|
}
|
|
MathAtom::Classed { body, .. } => layout_math(body, font),
|
|
MathAtom::SizedDelimiter { delimiter, size } => {
|
|
if *delimiter == '.' {
|
|
MathBox {
|
|
width: 0,
|
|
height: 0,
|
|
depth: 0,
|
|
}
|
|
} else if let Some((width, height, depth)) = cmex_delimiter(*delimiter, *size) {
|
|
MathBox {
|
|
width,
|
|
height,
|
|
depth,
|
|
}
|
|
} else {
|
|
let extent = match *size {
|
|
1 => 8 * 65_536,
|
|
2 => 11 * 65_536,
|
|
3 => 14 * 65_536,
|
|
_ => 17 * 65_536,
|
|
};
|
|
MathBox {
|
|
width: (extent as f64 * 0.35) as i64,
|
|
height: extent,
|
|
depth: 2 * 65_536,
|
|
}
|
|
}
|
|
}
|
|
MathAtom::Middle(delimiter) => layout_math(&MathAtom::Symbol(*delimiter), font),
|
|
MathAtom::Aligned { rows, centered } => {
|
|
let layout = layout_aligned(rows, *centered, font);
|
|
MathBox {
|
|
width: layout.total_width,
|
|
height: layout.height,
|
|
depth: layout.depth,
|
|
}
|
|
}
|
|
MathAtom::StackLines(rows) => {
|
|
let layout = stack_layout(rows, font);
|
|
MathBox {
|
|
width: layout.width,
|
|
height: layout.height,
|
|
depth: layout.depth,
|
|
}
|
|
}
|
|
MathAtom::OperatorName { name, .. } => {
|
|
let roman = Cmr10Metrics::Roman;
|
|
let mut width = 0;
|
|
let mut height = 0;
|
|
let mut depth = 0;
|
|
for character in name.chars() {
|
|
if character == ' ' {
|
|
width += roman.space();
|
|
continue;
|
|
}
|
|
width += roman.width(character);
|
|
height = height.max(roman.height(character));
|
|
depth = depth.max(roman.depth(character));
|
|
}
|
|
MathBox {
|
|
width: width.max(1),
|
|
height: height.max(8 * 65_536),
|
|
depth,
|
|
}
|
|
}
|
|
MathAtom::Stack { top, base, above } => {
|
|
let top = layout_math(top, font);
|
|
let base = layout_math(base, font);
|
|
MathBox {
|
|
width: top.width.max(base.width),
|
|
height: base.height + if *above { top.height + 65_536 } else { 0 },
|
|
depth: base.depth + if *above { 0 } else { top.height + 65_536 },
|
|
}
|
|
}
|
|
MathAtom::Brace { base, above } => {
|
|
let base_box = layout_math(base, font);
|
|
MathBox {
|
|
width: base_box.width.max(4 * 65_536),
|
|
height: base_box.height + if *above { 2 * 65_536 } else { 0 },
|
|
depth: base_box.depth + if *above { 0 } else { 2 * 65_536 },
|
|
}
|
|
}
|
|
MathAtom::Binomial {
|
|
numerator,
|
|
denominator,
|
|
} => {
|
|
let numerator = layout_math(numerator, font);
|
|
let denominator = layout_math(denominator, font);
|
|
MathBox {
|
|
width: numerator.width.max(denominator.width) + 4 * 65_536,
|
|
height: numerator.height + denominator.height + 2 * 65_536,
|
|
depth: denominator.depth,
|
|
}
|
|
}
|
|
MathAtom::Boxed { body } => {
|
|
let inner = layout_math(body, font);
|
|
MathBox {
|
|
width: inner.width + 6 * 65_536,
|
|
height: inner.height + 3 * 65_536,
|
|
depth: inner.depth + 3 * 65_536,
|
|
}
|
|
}
|
|
MathAtom::Negated { base } => {
|
|
let inner = layout_math(base, font);
|
|
MathBox {
|
|
width: inner.width,
|
|
height: inner.height,
|
|
depth: inner.depth,
|
|
}
|
|
}
|
|
MathAtom::Cancel { base, .. } => {
|
|
let inner = layout_math(base, font);
|
|
MathBox {
|
|
width: inner.width,
|
|
height: inner.height,
|
|
depth: inner.depth,
|
|
}
|
|
}
|
|
MathAtom::Underline { base } => {
|
|
let base_box = layout_math(base, font);
|
|
MathBox {
|
|
width: base_box.width,
|
|
height: base_box.height,
|
|
depth: base_box.depth + 2 * 65_536,
|
|
}
|
|
}
|
|
MathAtom::Tagged { body, tag } => {
|
|
let body_box = layout_math(body, font);
|
|
let tag_width: i64 = tag
|
|
.chars()
|
|
.map(|character| Cmr10Metrics::Roman.width(character))
|
|
.sum();
|
|
MathBox {
|
|
width: body_box.width.max(tag_width),
|
|
height: body_box.height.max(7 * 65_536),
|
|
depth: body_box.depth.max(2 * 65_536),
|
|
}
|
|
}
|
|
MathAtom::Script { base, sub, sup } => {
|
|
let base_box = layout_math(base, font);
|
|
let sub_box = sub.as_deref().map(|atom| layout_math(atom, font));
|
|
let sup_box = sup.as_deref().map(|atom| layout_math(atom, font));
|
|
let script_width = sub_box
|
|
.as_ref()
|
|
.map(|boxed| boxed.width)
|
|
.unwrap_or(0)
|
|
.max(sup_box.as_ref().map(|boxed| boxed.width).unwrap_or(0));
|
|
let sup_height = sup_box.as_ref().map_or(0, |boxed| boxed.height);
|
|
let sub_depth = sub_box.as_ref().map_or(0, |boxed| boxed.depth);
|
|
let italic = italic_correction(base, font);
|
|
MathBox {
|
|
width: base_box.width + italic + scaled(script_width, 0.7),
|
|
height: base_box
|
|
.height
|
|
.max(scaled(base_box.height, 0.6) + scaled(sup_height, 0.7)),
|
|
depth: base_box
|
|
.depth
|
|
.max(scaled(base_box.depth, 0.5) + scaled(sub_depth, 0.7)),
|
|
}
|
|
}
|
|
MathAtom::Fraction {
|
|
numerator,
|
|
denominator,
|
|
..
|
|
} => {
|
|
let numerator_box = layout_math(numerator, font);
|
|
let denominator_box = layout_math(denominator, font);
|
|
let width = numerator_box
|
|
.width
|
|
.max(denominator_box.width)
|
|
.saturating_add(2 * 65_536);
|
|
MathBox {
|
|
width,
|
|
height: scaled(numerator_box.height + numerator_box.depth, 0.7) + 2 * 65_536,
|
|
depth: scaled(denominator_box.height + denominator_box.depth, 0.7) + 2 * 65_536,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Parse a small TeX math subset into a [`MathAtom`] row.
|
|
///
|
|
/// Supported: plain symbols, `{}` groups, `_`/`^` scripts, `\frac{a}{b}` and
|
|
/// `\sqrt{x}`. Whitespace is ignored. Unknown control words become `?` so a
|
|
/// later M4 parser can replace them.
|
|
pub fn parse_math(input: &str) -> MathAtom {
|
|
let chars: Vec<char> = input
|
|
.chars()
|
|
.map(|ch| if ch.is_whitespace() { '\u{0}' } else { ch })
|
|
.collect();
|
|
let (atom, _) = parse_sequence(&chars, 0, false, false);
|
|
atom
|
|
}
|
|
|
|
/// An infix fraction command such as `\over`, `\atop` or `\choose`.
|
|
///
|
|
/// Returns the fraction bar flag, optional delimiters and the index after the
|
|
/// command (and its delimiters).
|
|
fn infix_fraction(chars: &[char], index: usize) -> Option<(bool, Option<(char, char)>, usize)> {
|
|
if chars.get(index) != Some(&'\\') {
|
|
return None;
|
|
}
|
|
let mut cursor = index + 1;
|
|
let mut command = String::new();
|
|
while let Some(&ch) = chars.get(cursor) {
|
|
if ch.is_ascii_alphabetic() {
|
|
command.push(ch);
|
|
cursor += 1;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
match command.as_str() {
|
|
"over" => Some((true, None, cursor)),
|
|
"atop" => Some((false, None, cursor)),
|
|
"choose" => Some((false, Some(('(', ')')), cursor)),
|
|
"brace" => Some((false, Some(('{', '}')), cursor)),
|
|
"brack" => Some((false, Some(('[', ']')), cursor)),
|
|
"overwithdelims" | "atopwithdelims" => {
|
|
while chars.get(cursor) == Some(&'\u{0}') {
|
|
cursor += 1;
|
|
}
|
|
let (left, after_left) = parse_delimiter(chars, cursor);
|
|
let mut cursor = after_left;
|
|
while chars.get(cursor) == Some(&'\u{0}') {
|
|
cursor += 1;
|
|
}
|
|
let (right, after_right) = parse_delimiter(chars, cursor);
|
|
Some((
|
|
command == "overwithdelims",
|
|
Some((left, right)),
|
|
after_right,
|
|
))
|
|
}
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
fn skip_math_space(chars: &[char], mut index: usize) -> usize {
|
|
while chars.get(index) == Some(&'\u{0}') {
|
|
index += 1;
|
|
}
|
|
index
|
|
}
|
|
|
|
/// The `cmex10` size class (0 for the base glyph) that covers `delta`.
|
|
pub(crate) fn delimiter_size(delimiter: char, delta: i64) -> u8 {
|
|
if delimiter == '.' {
|
|
return 0;
|
|
}
|
|
let font = Cmr10Metrics::default();
|
|
let base = font.height(delimiter) + font.depth(delimiter);
|
|
let need = ((delta * 901) / 1000).max(delta - 5 * 65_536).max(0);
|
|
if base >= need && base > 0 {
|
|
return 0;
|
|
}
|
|
for size in 1..=4 {
|
|
if let Some(metrics) = cmex_delimiter(delimiter, size) {
|
|
if metrics.1 + metrics.2 >= need {
|
|
return size;
|
|
}
|
|
}
|
|
}
|
|
4
|
|
}
|
|
|
|
/// Replace top-level `\middle` atoms with sized delimiters.
|
|
fn size_middle_delimiters(body: MathAtom, delta: i64) -> MathAtom {
|
|
match body {
|
|
MathAtom::Row(atoms) => MathAtom::Row(
|
|
atoms
|
|
.into_iter()
|
|
.map(|atom| match atom {
|
|
MathAtom::Middle(delimiter) => MathAtom::SizedDelimiter {
|
|
delimiter,
|
|
size: delimiter_size(delimiter, delta),
|
|
},
|
|
other => other,
|
|
})
|
|
.collect(),
|
|
),
|
|
other => other,
|
|
}
|
|
}
|
|
|
|
fn is_right_command(chars: &[char], index: usize) -> bool {
|
|
chars.get(index) == Some(&'\\')
|
|
&& chars.get(index + 1) == Some(&'r')
|
|
&& chars.get(index + 2) == Some(&'i')
|
|
&& chars.get(index + 3) == Some(&'g')
|
|
&& chars.get(index + 4) == Some(&'h')
|
|
&& chars.get(index + 5) == Some(&'t')
|
|
}
|
|
|
|
fn limits_override(chars: &[char], index: usize) -> Option<(bool, usize)> {
|
|
let mut cursor = index;
|
|
while cursor < chars.len() && (chars[cursor] == '\u{0}' || chars[cursor].is_whitespace()) {
|
|
cursor += 1;
|
|
}
|
|
let rest = chars.get(cursor..)?;
|
|
for (word, forced) in [("\\limits", true), ("\\nolimits", false)] {
|
|
let letters: Vec<char> = word.chars().collect();
|
|
if rest.starts_with(&letters)
|
|
&& !rest
|
|
.get(letters.len())
|
|
.is_some_and(|character| character.is_ascii_alphabetic())
|
|
{
|
|
return Some((forced, cursor + letters.len()));
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
/// TeX puts scripts beside an integral unless `\limits` asks otherwise,
|
|
/// while sums, products and operator-name operators stack them by default.
|
|
fn operator_default_limits(base: &MathAtom) -> bool {
|
|
match base {
|
|
MathAtom::BigOperator { name } => name != "int",
|
|
MathAtom::OperatorName { limits, .. } => *limits,
|
|
_ => true,
|
|
}
|
|
}
|
|
|
|
fn read_braced_text(chars: &[char], mut index: usize) -> Option<(String, usize)> {
|
|
while index < chars.len() && (chars[index].is_whitespace() || chars[index] == '\u{0}') {
|
|
index += 1;
|
|
}
|
|
if chars.get(index) != Some(&'{') {
|
|
return None;
|
|
}
|
|
let start = index + 1;
|
|
let mut depth = 1_usize;
|
|
index = start;
|
|
while index < chars.len() {
|
|
match chars[index] {
|
|
'{' => depth += 1,
|
|
'}' => {
|
|
depth -= 1;
|
|
if depth == 0 {
|
|
let text: String = chars[start..index].iter().collect();
|
|
return Some((text, index + 1));
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
index += 1;
|
|
}
|
|
None
|
|
}
|
|
|
|
fn delimiter_from_text(text: &str) -> Option<char> {
|
|
let chars: Vec<char> = text.trim().chars().collect();
|
|
if chars.is_empty() {
|
|
return None;
|
|
}
|
|
let (delimiter, end) = parse_delimiter(&chars, 0);
|
|
if end != chars.len() {
|
|
return None;
|
|
}
|
|
Some(delimiter)
|
|
}
|
|
|
|
fn parse_limits(chars: &[char], next: usize, base: MathAtom) -> (MathAtom, usize) {
|
|
let mut after = next;
|
|
let mut forced = None;
|
|
while let Some((value, end)) = limits_override(chars, after) {
|
|
forced = Some(value);
|
|
after = end;
|
|
}
|
|
let mut sub = None;
|
|
let mut sup = None;
|
|
loop {
|
|
let mut cursor = after;
|
|
while cursor < chars.len() && (chars[cursor].is_whitespace() || chars[cursor] == '\u{0}') {
|
|
cursor += 1;
|
|
}
|
|
match chars.get(cursor) {
|
|
Some('_') => {
|
|
let (atom, end) = parse_atom(chars, cursor + 1);
|
|
sub = Some(Box::new(atom));
|
|
after = end;
|
|
}
|
|
Some('^') => {
|
|
let (atom, end) = parse_atom(chars, cursor + 1);
|
|
sup = Some(Box::new(atom));
|
|
after = end;
|
|
}
|
|
_ => break,
|
|
}
|
|
}
|
|
let stacked = forced.unwrap_or_else(|| operator_default_limits(&base));
|
|
if sub.is_none() && sup.is_none() {
|
|
(base, after)
|
|
} else if !stacked {
|
|
(
|
|
MathAtom::Script {
|
|
base: Box::new(base),
|
|
sub,
|
|
sup,
|
|
},
|
|
after,
|
|
)
|
|
} else {
|
|
(
|
|
MathAtom::Limits {
|
|
base: Box::new(base),
|
|
sub,
|
|
sup,
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
}
|
|
|
|
fn parse_sequence(
|
|
chars: &[char],
|
|
mut index: usize,
|
|
stop_at_brace: bool,
|
|
stop_at_right: bool,
|
|
) -> (MathAtom, usize) {
|
|
let mut atoms = Vec::new();
|
|
while index < chars.len() {
|
|
if stop_at_brace && chars[index] == '}' {
|
|
break;
|
|
}
|
|
if stop_at_right && is_right_command(chars, index) {
|
|
break;
|
|
}
|
|
let mut probe = index;
|
|
while chars.get(probe) == Some(&'\u{0}') {
|
|
probe += 1;
|
|
}
|
|
if let Some((bar, delimiters, after)) = infix_fraction(chars, probe) {
|
|
// TeX's infix fractions consume everything collected so far in the
|
|
// current group; the rest of the group becomes the denominator.
|
|
let numerator = MathAtom::Row(std::mem::take(&mut atoms));
|
|
let (denominator, end) = parse_sequence(chars, after, stop_at_brace, stop_at_right);
|
|
let fraction = MathAtom::Fraction {
|
|
numerator: Box::new(numerator),
|
|
denominator: Box::new(denominator),
|
|
bar,
|
|
};
|
|
let atom = match delimiters {
|
|
Some((left, right)) => MathAtom::Delimited {
|
|
left,
|
|
right,
|
|
body: Box::new(fraction),
|
|
},
|
|
None => fraction,
|
|
};
|
|
return (MathAtom::Row(vec![atom]), end);
|
|
}
|
|
let (mut atom, mut next) = parse_atom(chars, index);
|
|
let mut sub = None;
|
|
let mut sup = None;
|
|
loop {
|
|
if next < chars.len() && chars[next] == '_' && sub.is_none() {
|
|
let (script, after) = parse_script(chars, next + 1);
|
|
sub = Some(Box::new(script));
|
|
next = after;
|
|
} else if next < chars.len() && chars[next] == '^' && sup.is_none() {
|
|
let (script, after) = parse_script(chars, next + 1);
|
|
sup = Some(Box::new(script));
|
|
next = after;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
if sub.is_some() || sup.is_some() {
|
|
atom = MathAtom::Script {
|
|
base: Box::new(atom),
|
|
sub,
|
|
sup,
|
|
};
|
|
}
|
|
atoms.push(atom);
|
|
index = next;
|
|
}
|
|
(MathAtom::Row(atoms), index)
|
|
}
|
|
|
|
fn accent_atom(chars: &[char], next: usize, accent: char) -> (MathAtom, usize) {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Accent {
|
|
accent,
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
|
|
fn parse_delimiter(chars: &[char], index: usize) -> (char, usize) {
|
|
let Some(&character) = chars.get(index) else {
|
|
return ('(', index);
|
|
};
|
|
if character != '\\' {
|
|
return (character, index + 1);
|
|
}
|
|
let mut next = index + 1;
|
|
let mut command = String::new();
|
|
while let Some(&ch) = chars.get(next) {
|
|
if ch.is_ascii_alphabetic() {
|
|
command.push(ch);
|
|
next += 1;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
if command.is_empty() {
|
|
let delimiter = chars.get(next).copied().unwrap_or('.');
|
|
(delimiter, (next + 1).min(chars.len()))
|
|
} else {
|
|
let delimiter = match command.as_str() {
|
|
"lbrace" | "rbrace" => '{',
|
|
"lVert" | "rVert" | "Vert" => '\u{2016}',
|
|
"vert" | "lvert" | "rvert" => '|',
|
|
"langle" => '\u{27E8}',
|
|
"rangle" => '\u{27E9}',
|
|
"lfloor" => '\u{230A}',
|
|
"rfloor" => '\u{230B}',
|
|
"lceil" => '\u{2308}',
|
|
"rceil" => '\u{2309}',
|
|
_ => '.',
|
|
};
|
|
(delimiter, next)
|
|
}
|
|
}
|
|
|
|
/// Unicode n-ary operator for a `\sum`-style big operator name.
|
|
pub(crate) fn big_operator_character(name: &str) -> Option<char> {
|
|
let character = match name {
|
|
"sum" => '\u{2211}',
|
|
"prod" => '\u{220F}',
|
|
"coprod" => '\u{2210}',
|
|
"int" => '\u{222B}',
|
|
"oint" => '\u{222E}',
|
|
"bigcap" => '\u{22C2}',
|
|
"bigcup" => '\u{22C3}',
|
|
"bigsqcup" => '\u{2A06}',
|
|
"bigvee" => '\u{22C1}',
|
|
"bigwedge" => '\u{22C0}',
|
|
"bigodot" => '\u{2A00}',
|
|
"bigotimes" => '\u{2A02}',
|
|
"bigoplus" => '\u{2A01}',
|
|
_ => return None,
|
|
};
|
|
Some(character)
|
|
}
|
|
|
|
fn math_symbol_command(name: &str) -> Option<char> {
|
|
let character = match name {
|
|
"cdot" => '\u{00B7}',
|
|
"times" => '\u{00D7}',
|
|
"div" => '\u{00F7}',
|
|
"pm" => '\u{00B1}',
|
|
"mp" => '\u{2213}',
|
|
"oplus" => '\u{2295}',
|
|
"ominus" => '\u{2296}',
|
|
"otimes" => '\u{2297}',
|
|
"oslash" => '\u{2298}',
|
|
"odot" => '\u{2299}',
|
|
"asymp" => '\u{224D}',
|
|
"equiv" => '\u{2261}',
|
|
"subseteq" => '\u{2286}',
|
|
"supseteq" => '\u{2287}',
|
|
"leq" | "le" => '\u{2264}',
|
|
"geq" | "ge" => '\u{2265}',
|
|
"preceq" => '\u{2AAF}',
|
|
"succeq" => '\u{2AB0}',
|
|
"sim" => '\u{223C}',
|
|
"approx" => '\u{2248}',
|
|
"subset" => '\u{2282}',
|
|
"supset" => '\u{2283}',
|
|
"ll" => '\u{226A}',
|
|
"gg" => '\u{226B}',
|
|
"prec" => '\u{227A}',
|
|
"succ" => '\u{227B}',
|
|
"leftarrow" | "gets" => '\u{2190}',
|
|
"rightarrow" | "to" => '\u{2192}',
|
|
"uparrow" => '\u{2191}',
|
|
"downarrow" => '\u{2193}',
|
|
"leftrightarrow" => '\u{2194}',
|
|
"nearrow" => '\u{2197}',
|
|
"searrow" => '\u{2198}',
|
|
"simeq" => '\u{2243}',
|
|
"Leftarrow" => '\u{21D0}',
|
|
"Rightarrow" => '\u{21D2}',
|
|
"Uparrow" => '\u{21D1}',
|
|
"Downarrow" => '\u{21D3}',
|
|
"Leftrightarrow" => '\u{21D4}',
|
|
"nwarrow" => '\u{2196}',
|
|
"swarrow" => '\u{2199}',
|
|
"propto" => '\u{221D}',
|
|
"prime" => '\u{2032}',
|
|
"infty" => '\u{221E}',
|
|
"in" => '\u{2208}',
|
|
"ni" => '\u{220B}',
|
|
"triangle" => '\u{25B3}',
|
|
"triangledown" => '\u{25BD}',
|
|
"mapsto" => '\u{21A6}',
|
|
"forall" => '\u{2200}',
|
|
"exists" => '\u{2203}',
|
|
"neg" | "lnot" => '\u{00AC}',
|
|
"emptyset" | "varnothing" => '\u{2205}',
|
|
"Re" => '\u{211C}',
|
|
"Im" => '\u{2111}',
|
|
"top" => '\u{22A4}',
|
|
"bot" => '\u{22A5}',
|
|
"aleph" => '\u{2135}',
|
|
"cup" => '\u{222A}',
|
|
"cap" => '\u{2229}',
|
|
"uplus" => '\u{228E}',
|
|
"wedge" | "land" => '\u{2227}',
|
|
"vee" | "lor" => '\u{2228}',
|
|
"vdash" => '\u{22A2}',
|
|
"dashv" => '\u{22A3}',
|
|
"updownarrow" => '\u{2195}',
|
|
"Updownarrow" => '\u{21D5}',
|
|
"wr" => '\u{2240}',
|
|
"coprod" => '\u{2210}',
|
|
"nabla" => '\u{2207}',
|
|
"sqcup" => '\u{2294}',
|
|
"sqcap" => '\u{2293}',
|
|
"S" => '\u{00A7}',
|
|
"dagger" => '\u{2020}',
|
|
"ddagger" => '\u{2021}',
|
|
"P" => '\u{00B6}',
|
|
"clubsuit" => '\u{2663}',
|
|
"diamondsuit" => '\u{2662}',
|
|
"heartsuit" => '\u{2661}',
|
|
"spadesuit" => '\u{2660}',
|
|
_ => return None,
|
|
};
|
|
Some(character)
|
|
}
|
|
|
|
/// Scan a TeX dimension at `index`, returning scaled points and the next index.
|
|
///
|
|
/// `muskip` makes a unitless value a math unit, which is what `\mskip` and
|
|
/// `\mkern` require.
|
|
fn scan_math_dimension(chars: &[char], index: usize, muskip: bool) -> Option<(i64, usize)> {
|
|
let mut at = skip_math_space(chars, index);
|
|
let mut negative = false;
|
|
if chars.get(at) == Some(&'-') {
|
|
negative = true;
|
|
at += 1;
|
|
} else if chars.get(at) == Some(&'+') {
|
|
at += 1;
|
|
}
|
|
let mut whole = 0i64;
|
|
let mut digits = 0u32;
|
|
while let Some(digit) = chars.get(at).and_then(|ch| ch.to_digit(10)) {
|
|
whole = whole.saturating_mul(10).saturating_add(digit as i64);
|
|
at += 1;
|
|
digits += 1;
|
|
}
|
|
let mut fraction = 0i64;
|
|
if chars.get(at) == Some(&'.') {
|
|
at += 1;
|
|
let mut scale = 65_536i64;
|
|
while let Some(digit) = chars.get(at).and_then(|ch| ch.to_digit(10)) {
|
|
scale /= 10;
|
|
fraction += digit as i64 * scale;
|
|
at += 1;
|
|
digits += 1;
|
|
}
|
|
}
|
|
if digits == 0 {
|
|
return None;
|
|
}
|
|
let mut unit = String::new();
|
|
while let Some(ch) = chars.get(at) {
|
|
if ch.is_ascii_alphabetic() {
|
|
unit.push(*ch);
|
|
at += 1;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
let (numerator, denominator) = match unit.as_str() {
|
|
"mu" => (10, 18),
|
|
"pt" => (1, 1),
|
|
"bp" => (7227, 7200),
|
|
"in" => (4_736_286, 65_536),
|
|
"cm" => (1_864_679, 65_536),
|
|
"mm" => (186_468, 65_536),
|
|
"pc" => (786_432, 65_536),
|
|
"dd" => (70_124, 65_536),
|
|
"cc" => (841_489, 65_536),
|
|
"em" => (10, 1),
|
|
"ex" => (5, 1),
|
|
"sp" => (1, 65_536),
|
|
"" if muskip => (10, 18),
|
|
"" => (1, 1),
|
|
_ => return None,
|
|
};
|
|
let total = whole.saturating_mul(65_536).saturating_add(fraction);
|
|
let value = total.saturating_mul(numerator) / denominator;
|
|
Some((if negative { -value } else { value }, at))
|
|
}
|
|
|
|
/// Match a word after skipping math spaces; rejects longer identifiers.
|
|
fn math_keyword(chars: &[char], index: usize, word: &str) -> Option<usize> {
|
|
let at = skip_math_space(chars, index);
|
|
let mut cursor = at;
|
|
for expected in word.chars() {
|
|
if chars.get(cursor) != Some(&expected) {
|
|
return None;
|
|
}
|
|
cursor += 1;
|
|
}
|
|
if chars
|
|
.get(cursor)
|
|
.is_some_and(|character| character.is_ascii_alphabetic())
|
|
{
|
|
return None;
|
|
}
|
|
Some(cursor)
|
|
}
|
|
|
|
/// Scan `\mskip`-style dimensions, consuming any `plus`/`minus` parts.
|
|
///
|
|
/// Only the natural width participates in the layout: math boxes are not
|
|
/// glue lists, so stretch and shrink are accepted but not distributed.
|
|
fn unbraced_math_space(chars: &[char], index: usize, muskip: bool) -> Option<(i64, usize)> {
|
|
let (value, mut at) = scan_math_dimension(chars, index, muskip)?;
|
|
let mut seen_plus = false;
|
|
let mut seen_minus = false;
|
|
loop {
|
|
if !seen_plus {
|
|
if let Some(after) = math_keyword(chars, at, "plus") {
|
|
if let Some((_, next)) = scan_math_dimension(chars, after, muskip) {
|
|
at = next;
|
|
seen_plus = true;
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
if !seen_minus {
|
|
if let Some(after) = math_keyword(chars, at, "minus") {
|
|
if let Some((_, next)) = scan_math_dimension(chars, after, muskip) {
|
|
at = next;
|
|
seen_minus = true;
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
Some((value, at))
|
|
}
|
|
|
|
/// Scan a braced dimension such as `\mspace{18mu}`.
|
|
fn braced_math_space(chars: &[char], index: usize, muskip: bool) -> Option<(i64, usize)> {
|
|
let at = skip_math_space(chars, index);
|
|
if chars.get(at) != Some(&'{') {
|
|
return None;
|
|
}
|
|
let mut depth = 0i64;
|
|
let mut end = at;
|
|
while end < chars.len() {
|
|
match chars[end] {
|
|
'{' => depth += 1,
|
|
'}' => {
|
|
depth -= 1;
|
|
if depth == 0 {
|
|
break;
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
end += 1;
|
|
}
|
|
if depth != 0 {
|
|
return None;
|
|
}
|
|
let (value, _) = scan_math_dimension(&chars[at + 1..end], 0, muskip)?;
|
|
Some((value, end + 1))
|
|
}
|
|
|
|
/// Read a math-space command argument, allowing an optional star.
|
|
fn math_space_argument(
|
|
chars: &[char],
|
|
index: usize,
|
|
muskip: bool,
|
|
braced: bool,
|
|
) -> Option<(i64, usize)> {
|
|
let at = skip_math_space(chars, index);
|
|
let at = if chars.get(at) == Some(&'*') {
|
|
skip_math_space(chars, at + 1)
|
|
} else {
|
|
at
|
|
};
|
|
if braced {
|
|
braced_math_space(chars, at, muskip)
|
|
} else {
|
|
unbraced_math_space(chars, at, muskip)
|
|
}
|
|
}
|
|
|
|
fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
|
|
let mut index = index;
|
|
while chars.get(index) == Some(&'\u{0}') {
|
|
index += 1;
|
|
}
|
|
let Some(&character) = chars.get(index) else {
|
|
return (MathAtom::Row(Vec::new()), index);
|
|
};
|
|
if character == '{' {
|
|
let (atom, next) = parse_sequence(chars, index + 1, true, false);
|
|
let next = if chars.get(next) == Some(&'}') {
|
|
next + 1
|
|
} else {
|
|
next
|
|
};
|
|
return (atom, next);
|
|
}
|
|
if character == '\\' {
|
|
let mut next = index + 1;
|
|
let mut command = String::new();
|
|
while let Some(&ch) = chars.get(next) {
|
|
if ch.is_ascii_alphabetic() {
|
|
command.push(ch);
|
|
next += 1;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
if command.is_empty() {
|
|
let width = match chars.get(next) {
|
|
Some(',') => 109_227,
|
|
Some(':') | Some('>') => 218_454,
|
|
Some(';') => 327_680,
|
|
Some('!') => -109_227,
|
|
Some(' ') => 0,
|
|
_ => 0,
|
|
};
|
|
if matches!(
|
|
chars.get(next),
|
|
Some(',') | Some(':') | Some('>') | Some(';') | Some('!')
|
|
) {
|
|
return (MathAtom::Space(width), next + 1);
|
|
}
|
|
}
|
|
return match command.as_str() {
|
|
"mid" => (
|
|
MathAtom::Classed {
|
|
class: MathClass::Relation,
|
|
body: Box::new(MathAtom::Symbol('|')),
|
|
},
|
|
next,
|
|
),
|
|
"colon" => (
|
|
MathAtom::Classed {
|
|
class: MathClass::Punctuation,
|
|
body: Box::new(MathAtom::Symbol(':')),
|
|
},
|
|
next,
|
|
),
|
|
"mskip" | "mkern" => match math_space_argument(chars, next, true, false) {
|
|
Some((width, after)) => (MathAtom::Space(width), after),
|
|
None => (MathAtom::Symbol('?'), next),
|
|
},
|
|
"mspace" => match math_space_argument(chars, next, true, true) {
|
|
Some((width, after)) => (MathAtom::Space(width), after),
|
|
None => (MathAtom::Symbol('?'), next),
|
|
},
|
|
"hskip" | "kern" => match math_space_argument(chars, next, false, false) {
|
|
Some((width, after)) => (MathAtom::Space(width), after),
|
|
None => (MathAtom::Symbol('?'), next),
|
|
},
|
|
"hspace" => match math_space_argument(chars, next, false, true) {
|
|
Some((width, after)) => (MathAtom::Space(width), after),
|
|
None => (MathAtom::Symbol('?'), next),
|
|
},
|
|
"quad" => (MathAtom::Space(655_360), next),
|
|
"qquad" => (MathAtom::Space(1_310_720), next),
|
|
"lvert" | "rvert" | "vert" => (MathAtom::Symbol('|'), next),
|
|
"lVert" | "rVert" | "Vert" => (MathAtom::Symbol('\u{2016}'), next),
|
|
"lbrace" => (MathAtom::Symbol('{'), next),
|
|
"rbrace" => (MathAtom::Symbol('}'), next),
|
|
"langle" => (MathAtom::Symbol('\u{27E8}'), next),
|
|
"rangle" => (MathAtom::Symbol('\u{27E9}'), next),
|
|
"lfloor" => (MathAtom::Symbol('\u{230A}'), next),
|
|
"rfloor" => (MathAtom::Symbol('\u{230B}'), next),
|
|
"lceil" => (MathAtom::Symbol('\u{2308}'), next),
|
|
"rceil" => (MathAtom::Symbol('\u{2309}'), next),
|
|
"displaystyle" | "textstyle" | "scriptstyle" | "scriptscriptstyle" | "nonumber"
|
|
| "notag" | "limits" | "nolimits" | "displaylimits" => {
|
|
let mut after = next;
|
|
while chars.get(after).is_some_and(|ch| ch.is_whitespace()) {
|
|
after += 1;
|
|
}
|
|
parse_atom(chars, after)
|
|
}
|
|
"begin" => match math_environment(chars, next) {
|
|
Some((atom, after)) => (atom, after),
|
|
None => (MathAtom::Symbol('?'), next),
|
|
},
|
|
"genfrac" => {
|
|
let mut cursor = next;
|
|
let mut fields = Vec::new();
|
|
for _ in 0..6 {
|
|
let (text, after) = match read_braced_text(chars, cursor) {
|
|
Some(parsed) => parsed,
|
|
None => return (MathAtom::Symbol('?'), cursor),
|
|
};
|
|
fields.push(text);
|
|
cursor = after;
|
|
}
|
|
let left = delimiter_from_text(&fields[0]);
|
|
let right = delimiter_from_text(&fields[1]);
|
|
let thickness = fields[2].trim();
|
|
let bar = !thickness.is_empty() && thickness != "0pt";
|
|
let numerator = parse_math(&fields[4]);
|
|
let denominator = parse_math(&fields[5]);
|
|
let mut atom = MathAtom::Fraction {
|
|
numerator: Box::new(numerator),
|
|
denominator: Box::new(denominator),
|
|
bar,
|
|
};
|
|
if left.is_some() || right.is_some() {
|
|
atom = MathAtom::Delimited {
|
|
left: left.unwrap_or('.'),
|
|
right: right.unwrap_or('.'),
|
|
body: Box::new(atom),
|
|
};
|
|
}
|
|
(atom, cursor)
|
|
}
|
|
"frac" | "tfrac" | "dfrac" | "cfrac" => {
|
|
let (numerator, after) = parse_atom(chars, next);
|
|
let (denominator, after) = parse_atom(chars, after);
|
|
(MathAtom::fraction(numerator, denominator), after)
|
|
}
|
|
"sqrt" => {
|
|
let mut after = next;
|
|
let mut degree = None;
|
|
if chars.get(after) == Some(&'[') {
|
|
let mut close = after + 1;
|
|
while close < chars.len() && chars[close] != ']' {
|
|
close += 1;
|
|
}
|
|
let degree_chars = &chars[after + 1..close.min(chars.len())];
|
|
let (atom, _) = parse_sequence(degree_chars, 0, false, false);
|
|
degree = Some(Box::new(atom));
|
|
after = if close < chars.len() {
|
|
close + 1
|
|
} else {
|
|
close
|
|
};
|
|
}
|
|
let (radicand, after) = parse_atom(chars, after);
|
|
(
|
|
MathAtom::Sqrt {
|
|
radicand: Box::new(radicand),
|
|
degree,
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"hat" | "widehat" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Accent {
|
|
accent: '\u{0302}',
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"tilde" | "widetilde" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Accent {
|
|
accent: '\u{0303}',
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"smash" => {
|
|
let mut cursor = next;
|
|
while cursor < chars.len() && chars[cursor].is_whitespace() {
|
|
cursor += 1;
|
|
}
|
|
let mut top = true;
|
|
let mut bottom = true;
|
|
if chars.get(cursor) == Some(&'[') {
|
|
let mut end = cursor + 1;
|
|
while end < chars.len() && chars[end] != ']' {
|
|
match chars[end] {
|
|
't' => {
|
|
top = true;
|
|
bottom = false;
|
|
}
|
|
'b' => {
|
|
top = false;
|
|
bottom = true;
|
|
}
|
|
_ => {}
|
|
}
|
|
end += 1;
|
|
}
|
|
cursor = (end + 1).min(chars.len());
|
|
}
|
|
let (body, after) = parse_atom(chars, cursor);
|
|
(
|
|
MathAtom::Smash {
|
|
body: Box::new(body),
|
|
top,
|
|
bottom,
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"mathstrut" => (MathAtom::Strut, next),
|
|
"phantom" | "hphantom" | "vphantom" => {
|
|
let (body, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Phantom {
|
|
body: Box::new(body),
|
|
horizontal: command != "vphantom",
|
|
vertical: command != "hphantom",
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"operatorname" => {
|
|
let mut after = next;
|
|
while chars.get(after) == Some(&'\u{0}')
|
|
|| chars.get(after).is_some_and(|c| c.is_whitespace())
|
|
{
|
|
after += 1;
|
|
}
|
|
let (limits, after) = if chars.get(after) == Some(&'*') {
|
|
(true, after + 1)
|
|
} else {
|
|
(false, after)
|
|
};
|
|
if let Some((name, after)) = read_braced_text(chars, after) {
|
|
let base = MathAtom::OperatorName {
|
|
name: name.trim().to_string(),
|
|
limits,
|
|
};
|
|
parse_limits(chars, after, base)
|
|
} else {
|
|
(MathAtom::Symbol('?'), after)
|
|
}
|
|
}
|
|
"sum" | "prod" | "int" => {
|
|
let base = MathAtom::BigOperator {
|
|
name: command.clone(),
|
|
};
|
|
parse_limits(chars, next, base)
|
|
}
|
|
"lim" | "sup" | "inf" => {
|
|
let base = MathAtom::Text(command.clone());
|
|
parse_limits(chars, next, base)
|
|
}
|
|
"mathord" | "mathop" | "mathbin" | "mathrel" | "mathopen" | "mathclose"
|
|
| "mathpunct" | "mathinner" => {
|
|
let (body, after) = parse_atom(chars, next);
|
|
let class = match command.as_str() {
|
|
"mathop" => MathClass::Op,
|
|
"mathbin" => MathClass::Binary,
|
|
"mathrel" => MathClass::Relation,
|
|
"mathopen" => MathClass::Open,
|
|
"mathclose" => MathClass::Close,
|
|
"mathpunct" => MathClass::Punctuation,
|
|
"mathinner" => MathClass::Inner,
|
|
_ => MathClass::Ordinary,
|
|
};
|
|
let atom = MathAtom::Classed {
|
|
class,
|
|
body: Box::new(body),
|
|
};
|
|
if command == "mathop" {
|
|
parse_limits(chars, after, atom)
|
|
} else {
|
|
(atom, after)
|
|
}
|
|
}
|
|
"big" | "bigl" | "bigr" | "Big" | "Bigl" | "Bigr" | "bigg" | "biggl" | "biggr"
|
|
| "Bigg" | "Biggl" | "Biggr" => {
|
|
let size = match command.as_str() {
|
|
"big" | "bigl" | "bigr" => 1,
|
|
"Big" | "Bigl" | "Bigr" => 2,
|
|
"bigg" | "biggl" | "biggr" => 3,
|
|
_ => 4,
|
|
};
|
|
let after = skip_math_space(chars, next);
|
|
let (delimiter, after) = parse_delimiter(chars, after);
|
|
(MathAtom::SizedDelimiter { delimiter, size }, after)
|
|
}
|
|
"substack" => {
|
|
let mut after = next;
|
|
if chars.get(after) == Some(&'{') {
|
|
after += 1;
|
|
}
|
|
let start = after;
|
|
while after < chars.len() && chars[after] != '}' {
|
|
after += 1;
|
|
}
|
|
let content: String = chars[start..after].iter().collect();
|
|
let rows = content.split("\\\\").map(parse_math).collect();
|
|
(MathAtom::StackLines(rows), (after + 1).min(chars.len()))
|
|
}
|
|
"overset" | "underset" | "stackrel" => {
|
|
let (top, after) = parse_atom(chars, next);
|
|
let (base, after) = parse_atom(chars, after);
|
|
(
|
|
MathAtom::Stack {
|
|
top: Box::new(top),
|
|
base: Box::new(base),
|
|
above: command != "underset",
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"overbrace" | "underbrace" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
parse_limits(
|
|
chars,
|
|
after,
|
|
MathAtom::Brace {
|
|
base: Box::new(base),
|
|
above: command == "overbrace",
|
|
},
|
|
)
|
|
}
|
|
"binom" | "dbinom" | "tbinom" => {
|
|
let (numerator, after) = parse_atom(chars, next);
|
|
let (denominator, after) = parse_atom(chars, after);
|
|
(
|
|
MathAtom::Binomial {
|
|
numerator: Box::new(numerator),
|
|
denominator: Box::new(denominator),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"underline" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Underline {
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"cancel" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Cancel {
|
|
base: Box::new(base),
|
|
forward: true,
|
|
backward: false,
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"bcancel" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Cancel {
|
|
base: Box::new(base),
|
|
forward: false,
|
|
backward: true,
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"xcancel" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Cancel {
|
|
base: Box::new(base),
|
|
forward: true,
|
|
backward: true,
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"dot" => accent_atom(chars, next, '\u{0307}'),
|
|
"ddot" => accent_atom(chars, next, '\u{0308}'),
|
|
"check" => accent_atom(chars, next, '\u{030C}'),
|
|
"breve" => accent_atom(chars, next, '\u{0306}'),
|
|
"acute" => accent_atom(chars, next, '\u{0301}'),
|
|
"grave" => accent_atom(chars, next, '\u{0300}'),
|
|
"bar" | "overline" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Accent {
|
|
accent: '\u{0305}',
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"overrightarrow" | "overleftarrow" | "overleftrightarrow" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
let accent = match command.as_str() {
|
|
"overrightarrow" => '\u{20D7}',
|
|
"overleftarrow" => '\u{20D6}',
|
|
_ => '\u{20E1}',
|
|
};
|
|
(
|
|
MathAtom::Accent {
|
|
accent,
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"mathring" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Accent {
|
|
accent: '\u{030A}',
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"widecheck" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Accent {
|
|
accent: '\u{030C}',
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"dddot" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Accent {
|
|
accent: '\u{20DB}',
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"vec" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Accent {
|
|
accent: '\u{20D7}',
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"middle" => {
|
|
let after = skip_math_space(chars, next);
|
|
let (delimiter, after) = parse_delimiter(chars, after);
|
|
(MathAtom::Middle(delimiter), after)
|
|
}
|
|
"max" | "min" | "log" | "ln" | "sin" | "cos" | "tan" | "cot" | "sec" | "csc"
|
|
| "exp" | "det" | "dim" | "ker" | "hom" | "arg" | "deg" | "gcd" => {
|
|
(MathAtom::Text(command.clone()), next)
|
|
}
|
|
"mathcal" | "mathbb" | "mathbf" | "mathit" | "mathsf" | "mathtt" | "mathfrak"
|
|
| "mathnormal" => {
|
|
let mut after = next;
|
|
if chars.get(after) == Some(&'{') {
|
|
after += 1;
|
|
}
|
|
let start = after;
|
|
while after < chars.len() && chars[after] != '}' {
|
|
after += 1;
|
|
}
|
|
let text: String = chars[start..after]
|
|
.iter()
|
|
.map(|ch| if *ch == '\u{0}' { ' ' } else { *ch })
|
|
.collect();
|
|
if after < chars.len() {
|
|
after += 1;
|
|
}
|
|
let alphabet = match command.as_str() {
|
|
"mathbf" => Some(MathAlphabet::Bold),
|
|
"mathit" => Some(MathAlphabet::Italic),
|
|
"mathsf" => Some(MathAlphabet::Sans),
|
|
"mathtt" => Some(MathAlphabet::Mono),
|
|
"mathcal" => Some(MathAlphabet::Calligraphic),
|
|
"mathbb" => Some(MathAlphabet::Blackboard),
|
|
"mathfrak" => Some(MathAlphabet::Fraktur),
|
|
_ => None,
|
|
};
|
|
match alphabet {
|
|
Some(alphabet) => (MathAtom::Alphabet { text, alphabet }, after),
|
|
None => (MathAtom::Text(text), after),
|
|
}
|
|
}
|
|
"not" => {
|
|
let (base, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Negated {
|
|
base: Box::new(base),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"bmod" => (MathAtom::Text("mod".to_owned()), next),
|
|
"pmod" => {
|
|
let (inner, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Classed {
|
|
class: MathClass::Relation,
|
|
body: Box::new(MathAtom::Row(vec![
|
|
MathAtom::Text("(mod ".to_owned()),
|
|
inner,
|
|
MathAtom::Text(")".to_owned()),
|
|
])),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"boxed" => {
|
|
let (body, after) = parse_atom(chars, next);
|
|
(
|
|
MathAtom::Boxed {
|
|
body: Box::new(body),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
"text" | "mathrm" => {
|
|
let mut after = next;
|
|
if chars.get(after) == Some(&'{') {
|
|
after += 1;
|
|
}
|
|
let start = after;
|
|
while after < chars.len() && chars[after] != '}' {
|
|
after += 1;
|
|
}
|
|
let text: String = chars[start..after].iter().collect();
|
|
if after < chars.len() {
|
|
after += 1;
|
|
}
|
|
(MathAtom::Text(text), after)
|
|
}
|
|
"left" => {
|
|
let body_start = skip_math_space(chars, next);
|
|
let (left, body_start) = parse_delimiter(chars, body_start);
|
|
let (body, after) = parse_sequence(chars, body_start, false, true);
|
|
let body_box = layout_math(&body, &Cmr10Metrics::default());
|
|
let body = size_middle_delimiters(body, body_box.height + body_box.depth);
|
|
let mut after = after;
|
|
// Consume `\right` and its delimiter.
|
|
if is_right_command(chars, after) {
|
|
after += 6;
|
|
}
|
|
let (right, after) = parse_delimiter(chars, after);
|
|
(
|
|
MathAtom::Delimited {
|
|
left,
|
|
right,
|
|
body: Box::new(body),
|
|
},
|
|
after,
|
|
)
|
|
}
|
|
other => match math_symbol_command(other) {
|
|
Some(character) => (MathAtom::Symbol(character), next),
|
|
None => (MathAtom::Symbol('?'), next),
|
|
},
|
|
};
|
|
}
|
|
(MathAtom::Symbol(character), index + 1)
|
|
}
|
|
|
|
fn parse_script(chars: &[char], index: usize) -> (MathAtom, usize) {
|
|
if chars.get(index) == Some(&'{') {
|
|
parse_atom(chars, index)
|
|
} else if chars.get(index) == Some(&'\\') {
|
|
parse_atom(chars, index)
|
|
} else if let Some(&character) = chars.get(index) {
|
|
(MathAtom::Symbol(character), index + 1)
|
|
} else {
|
|
(MathAtom::Row(Vec::new()), index)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn italic_base_offsets_scripts() {
|
|
let font = Cmr10Metrics::default();
|
|
let base = parse_math("f");
|
|
let scripted = parse_math("f^2");
|
|
let italic = italic_correction(&base, &font);
|
|
assert!(italic > 0);
|
|
let base_box = layout_math(&base, &font);
|
|
let scripted_box = layout_math(&scripted, &font);
|
|
assert!(scripted_box.width >= base_box.width + italic);
|
|
}
|
|
#[test]
|
|
fn math_symbol_uses_font_width() {
|
|
let font = Cmr10Metrics::default();
|
|
let boxed = layout_math(&MathAtom::symbol('x'), &font);
|
|
assert_eq!(boxed.width, font.width('x'));
|
|
assert!(boxed.height > 0);
|
|
assert!(boxed.depth > 0);
|
|
}
|
|
|
|
#[test]
|
|
fn script_stacks_above_and_below_the_base() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&MathAtom::symbol('x'), &font);
|
|
let scripted = layout_math(
|
|
&MathAtom::script(
|
|
MathAtom::symbol('x'),
|
|
Some(MathAtom::symbol('i')),
|
|
Some(MathAtom::symbol('2')),
|
|
),
|
|
&font,
|
|
);
|
|
assert!(scripted.width > plain.width);
|
|
assert!(scripted.height > plain.height);
|
|
assert!(scripted.depth >= plain.depth);
|
|
}
|
|
|
|
#[test]
|
|
fn fraction_is_wider_than_its_parts() {
|
|
let font = Cmr10Metrics::default();
|
|
let numerator = layout_math(&MathAtom::symbol('a'), &font);
|
|
let fraction = layout_math(
|
|
&MathAtom::fraction(MathAtom::symbol('a'), MathAtom::symbol('b')),
|
|
&font,
|
|
);
|
|
assert!(fraction.width > numerator.width);
|
|
assert!(fraction.height > numerator.height);
|
|
assert!(fraction.depth > 0);
|
|
}
|
|
|
|
#[test]
|
|
fn sqrt_degree_is_wider_than_a_plain_root() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("\\sqrt{x}"), &font);
|
|
let indexed = layout_math(&parse_math("\\sqrt[3]{x}"), &font);
|
|
assert!(indexed.width > plain.width);
|
|
assert!(indexed.height > plain.height);
|
|
}
|
|
|
|
#[test]
|
|
fn math_bold_letters_use_bold_metrics() {
|
|
let font = Cmr10Metrics::Math;
|
|
let plain = layout_math(&parse_math("\\mathrm{x}"), &font);
|
|
let bold = layout_math(&parse_math("\\mathbf{x}"), &font);
|
|
let bold_metrics = Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Bold);
|
|
assert_eq!(bold.width, bold_metrics.width('x'));
|
|
assert_ne!(bold.width, plain.width);
|
|
}
|
|
|
|
#[test]
|
|
fn math_italic_letters_use_the_math_face() {
|
|
let font = Cmr10Metrics::Math;
|
|
let italic = layout_math(&parse_math("\\mathit{x}"), &font);
|
|
assert_eq!(italic.width, Cmr10Metrics::Math.width('x'));
|
|
}
|
|
|
|
#[test]
|
|
fn math_sans_and_typewriter_use_their_metrics() {
|
|
let font = Cmr10Metrics::Math;
|
|
let sans = layout_math(&parse_math("\\mathsf{x}"), &font);
|
|
let mono = layout_math(&parse_math("\\mathtt{x}"), &font);
|
|
let sans_metrics = Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Sans);
|
|
let mono_metrics = Cmr10Metrics::for_paragraph_font(crate::paragraph::ParagraphFont::Mono);
|
|
assert_eq!(sans.width, sans_metrics.width('x'));
|
|
assert_eq!(mono.width, mono_metrics.width('x'));
|
|
}
|
|
|
|
#[test]
|
|
fn mathcal_uses_calligraphic_widths() {
|
|
let font = Cmr10Metrics::default();
|
|
let calligraphic = layout_math(&parse_math("\\mathcal{N}"), &font);
|
|
let upright = layout_math(&parse_math("\\mathrm{N}"), &font);
|
|
assert_ne!(calligraphic.width, upright.width);
|
|
assert_eq!(
|
|
calligraphic.width,
|
|
crate::cmr10::math_symbol_width('N').expect("cmsy has calligraphic capitals")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn mathbb_uses_blackboard_widths() {
|
|
let font = Cmr10Metrics::default();
|
|
let blackboard = layout_math(&parse_math("\\mathbb{A}"), &font);
|
|
let upright = layout_math(&parse_math("\\mathrm{A}"), &font);
|
|
assert_ne!(blackboard.width, upright.width);
|
|
assert_eq!(
|
|
blackboard.width,
|
|
crate::cmr10::math_blackboard_width('A').expect("msbm has blackboard capitals")
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn mathfrak_uses_fraktur_widths() {
|
|
let font = Cmr10Metrics::default();
|
|
let fraktur = layout_math(&parse_math("\\mathfrak{A}"), &font);
|
|
let upright = layout_math(&parse_math("\\mathrm{A}"), &font);
|
|
let blackboard = layout_math(&parse_math("\\mathbb{A}"), &font);
|
|
assert_ne!(fraktur.width, upright.width);
|
|
assert_eq!(
|
|
fraktur.width,
|
|
crate::cmr10::math_fraktur_width('A').expect("eufm has Fraktur capitals")
|
|
);
|
|
let lower = layout_math(&parse_math("\\mathfrak{a}"), &font);
|
|
assert_eq!(
|
|
lower.width,
|
|
crate::cmr10::math_fraktur_width('a').expect("eufm has Fraktur lowercase")
|
|
);
|
|
assert_ne!(fraktur.width, blackboard.width);
|
|
}
|
|
|
|
#[test]
|
|
fn smash_can_target_only_the_top_or_bottom() {
|
|
let font = Cmr10Metrics::default();
|
|
let top = layout_math(&parse_math("\\smash[t]{x}"), &font);
|
|
let bottom = layout_math(&parse_math("\\smash[b]{x}"), &font);
|
|
assert_eq!(top.height, 0);
|
|
assert!(top.depth > 0);
|
|
assert!(bottom.height > 0);
|
|
assert_eq!(bottom.depth, 0);
|
|
}
|
|
#[test]
|
|
fn smash_removes_height_but_keeps_width() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
let smashed = layout_math(&parse_math("\\smash{x}"), &font);
|
|
assert_eq!(smashed.width, plain.width);
|
|
assert_eq!(smashed.height, 0);
|
|
assert_eq!(smashed.depth, 0);
|
|
}
|
|
|
|
#[test]
|
|
fn mathstrut_has_zero_width_and_math_height() {
|
|
let font = Cmr10Metrics::default();
|
|
let box_ = layout_math(&parse_math(r"\mathstrut"), &font);
|
|
assert_eq!(box_.width, 0);
|
|
assert_eq!(box_.height, 7 * 65_536);
|
|
assert_eq!(box_.depth, 2 * 65_536);
|
|
}
|
|
|
|
#[test]
|
|
fn phantoms_keep_only_selected_dimensions() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
let horizontal = layout_math(&parse_math("\\hphantom{x}"), &font);
|
|
let vertical = layout_math(&parse_math("\\vphantom{x}"), &font);
|
|
assert_eq!(horizontal.width, plain.width);
|
|
assert_eq!(horizontal.height, 0);
|
|
assert_eq!(vertical.width, 0);
|
|
assert_eq!(vertical.height, plain.height);
|
|
}
|
|
#[test]
|
|
fn big_operators_are_wider_than_letters() {
|
|
let font = Cmr10Metrics::default();
|
|
let sum = layout_math(&parse_math("\\sum"), &font);
|
|
let letter = layout_math(&parse_math("s"), &font);
|
|
assert!(sum.width > letter.width);
|
|
assert!(sum.depth > letter.depth);
|
|
}
|
|
#[test]
|
|
fn sum_places_scripts_above_and_below() {
|
|
let font = Cmr10Metrics::default();
|
|
let sum = layout_math(&parse_math("\\sum_{i=1}^{n}"), &font);
|
|
let plain = layout_math(&parse_math("sum"), &font);
|
|
assert!(sum.height > 0);
|
|
assert!(sum.width > 600_000);
|
|
assert!(sum.depth > plain.depth);
|
|
}
|
|
|
|
#[test]
|
|
fn boxed_pads_its_body_on_all_sides() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
let boxed = layout_math(&parse_math(r"\boxed{x}"), &font);
|
|
assert_eq!(boxed.width, plain.width + 6 * 65_536);
|
|
assert_eq!(boxed.height, plain.height + 3 * 65_536);
|
|
assert_eq!(boxed.depth, plain.depth + 3 * 65_536);
|
|
}
|
|
|
|
#[test]
|
|
fn mathop_uses_the_operator_spacing_class() {
|
|
let MathAtom::Row(atoms) = parse_math(r"\mathop{x}") else {
|
|
panic!("expected row")
|
|
};
|
|
let MathAtom::Classed { class, .. } = &atoms[0] else {
|
|
panic!("expected classed")
|
|
};
|
|
assert_eq!(*class, MathClass::Op);
|
|
}
|
|
#[test]
|
|
fn mathinner_adds_three_mu_on_both_sides() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("axb"), &font);
|
|
let inner = layout_math(&parse_math(r"a\mathinner{x}b"), &font);
|
|
assert!(inner.width > plain.width + 10_000);
|
|
}
|
|
#[test]
|
|
fn mathrel_wrapper_forces_relation_spacing() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("a+b"), &font);
|
|
let relation = layout_math(&parse_math("a \\mathrel{+} b"), &font);
|
|
assert!(relation.width > plain.width);
|
|
}
|
|
#[test]
|
|
fn big_delimiters_get_progressively_taller() {
|
|
let font = Cmr10Metrics::default();
|
|
let big = layout_math(&parse_math("\\big("), &font);
|
|
let bigg = layout_math(&parse_math("\\Bigg("), &font);
|
|
assert!(bigg.height > big.height);
|
|
assert!(bigg.width > big.width);
|
|
}
|
|
#[test]
|
|
fn middle_delimiters_follow_the_group_extent() {
|
|
let atom = parse_math("\\left( \\frac{\\frac{a}{b}}{\\frac{c}{d}} \\middle\\{ c \\right)");
|
|
let MathAtom::Row(atoms) = &atom else {
|
|
panic!("expected a row");
|
|
};
|
|
let MathAtom::Delimited { body, .. } = &atoms[0] else {
|
|
panic!("expected a delimited group, got {:?}", atoms[0]);
|
|
};
|
|
let MathAtom::Row(parts) = &**body else {
|
|
panic!("expected a row");
|
|
};
|
|
let middle = parts
|
|
.iter()
|
|
.find_map(|atom| match atom {
|
|
MathAtom::SizedDelimiter { delimiter, size } if *delimiter == '{' => Some(*size),
|
|
_ => None,
|
|
})
|
|
.expect("middle delimiter should have been sized");
|
|
assert!(middle >= 1, "expected a CMEX variant, got size {middle}");
|
|
}
|
|
|
|
#[test]
|
|
fn middle_outside_left_right_stays_a_plain_delimiter() {
|
|
let atom = parse_math("a \\middle| b");
|
|
let MathAtom::Row(atoms) = &atom else {
|
|
panic!("expected a row");
|
|
};
|
|
assert!(
|
|
atoms
|
|
.iter()
|
|
.any(|atom| matches!(atom, MathAtom::Middle('|')))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn aligned_rows_share_their_column_widths() {
|
|
let font = Cmr10Metrics::default();
|
|
let rows = vec![
|
|
AlignedRow::new(
|
|
vec![
|
|
MathAtom::Text("a".to_string()),
|
|
MathAtom::Text("= x".to_string()),
|
|
],
|
|
None,
|
|
),
|
|
AlignedRow::new(
|
|
vec![
|
|
MathAtom::Text("long".to_string()),
|
|
MathAtom::Text("= y".to_string()),
|
|
],
|
|
None,
|
|
),
|
|
];
|
|
let layout = layout_aligned(&rows, false, &font);
|
|
assert_eq!(layout.column_widths.len(), 2);
|
|
assert_eq!(
|
|
layout.column_widths[0],
|
|
layout_math(&MathAtom::Text("long".to_string()), &font).width
|
|
);
|
|
assert_eq!(layout.body_width, layout.column_widths.iter().sum::<i64>());
|
|
assert!(layout.baselines.len() == 2 && layout.baselines[1] > 0);
|
|
}
|
|
|
|
#[test]
|
|
fn gather_rows_centre_their_cells() {
|
|
let font = Cmr10Metrics::default();
|
|
let rows = vec![
|
|
AlignedRow::new(vec![MathAtom::Text("a".to_string())], None),
|
|
AlignedRow::new(vec![MathAtom::Text("wide row".to_string())], None),
|
|
];
|
|
let layout = layout_aligned(&rows, true, &font);
|
|
assert_eq!(
|
|
layout.body_width,
|
|
layout_math(&MathAtom::Text("wide row".to_string()), &font).width
|
|
);
|
|
assert_eq!(layout.column_widths.len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn aligned_rows_are_centred_on_the_math_axis() {
|
|
let font = Cmr10Metrics::default();
|
|
let single = layout_math(
|
|
&MathAtom::Aligned {
|
|
rows: vec![AlignedRow::new(vec![MathAtom::Text("a".to_string())], None)],
|
|
centered: false,
|
|
},
|
|
&font,
|
|
);
|
|
let two = layout_math(
|
|
&MathAtom::Aligned {
|
|
rows: vec![
|
|
AlignedRow::new(vec![MathAtom::Text("a".to_string())], None),
|
|
AlignedRow::new(vec![MathAtom::Text("b".to_string())], None),
|
|
],
|
|
centered: false,
|
|
},
|
|
&font,
|
|
);
|
|
assert!(two.height > single.height);
|
|
assert!(two.depth > single.depth);
|
|
}
|
|
|
|
#[test]
|
|
fn cases_environment_lays_out_its_rows() {
|
|
let atom = parse_math("\\begin{cases} x & x>0 \\\\ 0 & \\text{else} \\end{cases}");
|
|
let atom = match atom {
|
|
MathAtom::Row(atoms) => atoms
|
|
.into_iter()
|
|
.find(|atom| matches!(atom, MathAtom::Matrix { .. }))
|
|
.expect("cases atom in the row"),
|
|
other => other,
|
|
};
|
|
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);
|
|
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,
|
|
row_lead: 943_718,
|
|
},
|
|
&Cmr10Metrics::default(),
|
|
);
|
|
assert!(box_.width > 3 * 65_536);
|
|
assert!(box_.height > 0);
|
|
}
|
|
|
|
#[test]
|
|
fn multline_rows_flush_to_the_edges() {
|
|
let font = Cmr10Metrics::default();
|
|
let rows = vec![
|
|
MathAtom::Symbol('a'),
|
|
MathAtom::Symbol('b'),
|
|
MathAtom::Row(vec![MathAtom::Symbol('c'), MathAtom::Symbol('d')]),
|
|
];
|
|
let layout = multline_layout(&rows, Some("(1)"), &font);
|
|
assert_eq!(layout.offsets[0], 0);
|
|
assert_eq!(
|
|
layout.offsets[2],
|
|
layout.body_width - layout_math(&rows[2], &font).width
|
|
);
|
|
assert_eq!(layout.offsets[2], 0);
|
|
assert!(layout.offsets[1] > 0);
|
|
let plain = multline_layout(&rows, None, &font);
|
|
assert!(layout.width > plain.width);
|
|
}
|
|
|
|
#[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(')'),
|
|
row_lead: 12 * 65_536,
|
|
},
|
|
&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();
|
|
let spaced = layout_math(&parse_math("\\big ("), &font);
|
|
let compact = layout_math(&parse_math("\\big("), &font);
|
|
assert_eq!(spaced, compact);
|
|
}
|
|
|
|
#[test]
|
|
fn tall_delimiters_grow_with_their_body() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("\\left(a\\right)"), &font);
|
|
let tall = layout_math(&parse_math("\\left(\\frac{a}{b}\\right)"), &font);
|
|
assert!(tall.height > plain.height);
|
|
assert!(tall.width > plain.width);
|
|
}
|
|
|
|
#[test]
|
|
fn overleftrightarrow_uses_the_double_arrow_accent() {
|
|
let MathAtom::Row(atoms) = parse_math(r"\overleftrightarrow{AB}") else {
|
|
panic!("expected row")
|
|
};
|
|
assert!(matches!(
|
|
&atoms[0],
|
|
MathAtom::Accent {
|
|
accent: '\u{20E1}',
|
|
..
|
|
}
|
|
));
|
|
}
|
|
#[test]
|
|
fn mathring_uses_the_ring_accent() {
|
|
let MathAtom::Row(atoms) = parse_math(r"\mathring{x}") else {
|
|
panic!("expected row")
|
|
};
|
|
assert!(matches!(
|
|
&atoms[0],
|
|
MathAtom::Accent {
|
|
accent: '\u{030A}',
|
|
..
|
|
}
|
|
));
|
|
}
|
|
#[test]
|
|
fn substack_stacks_multiple_rows() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("a"), &font);
|
|
let stacked = layout_math(&parse_math(r"\substack{a\\b}"), &font);
|
|
assert!(stacked.height + stacked.depth > plain.height + plain.depth);
|
|
}
|
|
#[test]
|
|
fn overbrace_accepts_a_superscript_label() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math(r"\overbrace{x}"), &font);
|
|
let labeled = layout_math(&parse_math(r"\overbrace{x}^{n}"), &font);
|
|
assert!(labeled.height > plain.height);
|
|
}
|
|
#[test]
|
|
fn widecheck_and_dddot_use_their_accent_codepoints() {
|
|
let MathAtom::Row(check) = parse_math(r"\widecheck{x}") else {
|
|
panic!("expected row")
|
|
};
|
|
assert!(matches!(
|
|
&check[0],
|
|
MathAtom::Accent {
|
|
accent: '\u{030C}',
|
|
..
|
|
}
|
|
));
|
|
let MathAtom::Row(dots) = parse_math(r"\dddot{x}") else {
|
|
panic!("expected row")
|
|
};
|
|
assert!(matches!(
|
|
&dots[0],
|
|
MathAtom::Accent {
|
|
accent: '\u{20DB}',
|
|
..
|
|
}
|
|
));
|
|
}
|
|
#[test]
|
|
fn overrightarrow_uses_the_arrow_accent() {
|
|
let parsed = parse_math(r"\overrightarrow{AB}");
|
|
let MathAtom::Row(atoms) = parsed else {
|
|
panic!("expected row")
|
|
};
|
|
assert!(matches!(
|
|
&atoms[0],
|
|
MathAtom::Accent {
|
|
accent: '\u{20D7}',
|
|
..
|
|
}
|
|
));
|
|
}
|
|
#[test]
|
|
fn stackrel_places_its_first_argument_above_the_relation() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("="), &font);
|
|
let stacked = layout_math(&parse_math(r"\stackrel{def}{=}"), &font);
|
|
assert!(stacked.height > plain.height);
|
|
}
|
|
#[test]
|
|
fn overset_and_underset_stack_their_arguments() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
let over = layout_math(&parse_math("\\overset{a}{x}"), &font);
|
|
let under = layout_math(&parse_math("\\underset{a}{x}"), &font);
|
|
assert!(over.height > plain.height);
|
|
assert_eq!(over.depth, plain.depth);
|
|
assert!(under.depth > plain.depth);
|
|
assert_eq!(under.height, plain.height);
|
|
}
|
|
#[test]
|
|
fn braces_add_height_or_depth() {
|
|
let font = Cmr10Metrics::default();
|
|
let over = layout_math(&parse_math("\\overbrace{x+y}"), &font);
|
|
let under = layout_math(&parse_math("\\underbrace{x+y}"), &font);
|
|
let plain = layout_math(&parse_math("x+y"), &font);
|
|
assert!(over.height > plain.height);
|
|
assert_eq!(over.depth, plain.depth);
|
|
assert!(under.depth > plain.depth);
|
|
assert_eq!(under.height, plain.height);
|
|
}
|
|
|
|
#[test]
|
|
fn numbering_control_words_are_transparent() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("x+y"), &font);
|
|
let numbered = layout_math(&parse_math(r"x\nonumber+y"), &font);
|
|
assert_eq!(plain.width, numbered.width);
|
|
assert_eq!(plain.height, numbered.height);
|
|
}
|
|
|
|
#[test]
|
|
fn cancel_commands_keep_the_base_box() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
for command in [r"\cancel{x}", r"\bcancel{x}", r"\xcancel{x}"] {
|
|
let cancelled = layout_math(&parse_math(command), &font);
|
|
assert_eq!(cancelled.width, plain.width);
|
|
assert_eq!(cancelled.height, plain.height);
|
|
}
|
|
}
|
|
#[test]
|
|
fn dot_and_check_accents_raise_the_math_box() {
|
|
let font = Cmr10Metrics::default();
|
|
for command in [r"\dot{x}", r"\ddot{x}", r"\check{x}", r"\breve{x}"] {
|
|
let accented = layout_math(&parse_math(command), &font);
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
assert!(accented.height > plain.height);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn big_delimiters_accept_control_sequences() {
|
|
let font = Cmr10Metrics::default();
|
|
let brace = layout_math(&parse_math(r"\big{"), &font);
|
|
let escaped = layout_math(&parse_math(r"\big\{"), &font);
|
|
assert_eq!(brace.width, escaped.width);
|
|
}
|
|
#[test]
|
|
fn middle_accepts_control_sequence_delimiters() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math(r"\left(a\right)"), &font);
|
|
let middle = layout_math(&parse_math(r"\left(a\middle\{b\right)"), &font);
|
|
assert!(middle.width > plain.width);
|
|
}
|
|
|
|
#[test]
|
|
fn left_right_delimiters_scale_with_the_body() {
|
|
let font = Cmr10Metrics::default();
|
|
let short = layout_math(&parse_math(r"\left(a\right)"), &font);
|
|
let tall = layout_math(&parse_math(r"\left(\frac{a}{b}\right)"), &font);
|
|
assert!(tall.height > short.height);
|
|
assert!(tall.width > short.width);
|
|
}
|
|
#[test]
|
|
fn left_right_accept_control_sequence_delimiters() {
|
|
let font = Cmr10Metrics::default();
|
|
let escaped = layout_math(&parse_math(r"\left\{x\right\}"), &font);
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
assert!(escaped.width > plain.width);
|
|
let empty = layout_math(&parse_math(r"\left.x\right."), &font);
|
|
assert_eq!(empty.width, plain.width);
|
|
}
|
|
#[test]
|
|
fn fence_delimiters_have_widths() {
|
|
let font = Cmr10Metrics::default();
|
|
for source in [r"\lvert x \rvert", r"\lfloor x \rfloor", r"\lceil x \rceil"] {
|
|
let boxed = layout_math(&parse_math(source), &font);
|
|
assert!(boxed.width > layout_math(&parse_math(r"x"), &font).width);
|
|
}
|
|
}
|
|
#[test]
|
|
fn pmod_wraps_the_argument_and_bmod_stays_inline() {
|
|
let font = Cmr10Metrics::default();
|
|
let pmod = layout_math(&parse_math(r"a\pmod{m}"), &font);
|
|
assert!(pmod.width > layout_math(&parse_math(r"a"), &font).width);
|
|
assert!(matches!(
|
|
&parse_math(r"\bmod"),
|
|
MathAtom::Row(atoms) if matches!(&atoms[0], MathAtom::Text(text) if text == "mod")
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn mathop_takes_limits_below() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math(r"\mathop{argmax}"), &font);
|
|
let limited = layout_math(&parse_math(r"\mathop{argmax}_{x}"), &font);
|
|
assert!(limited.depth > plain.depth);
|
|
}
|
|
#[test]
|
|
fn operator_names_are_upright_and_stack_when_starred() {
|
|
let font = Cmr10Metrics::default();
|
|
let upright = layout_math(&parse_math("\\operatorname{Tr}"), &font);
|
|
let italic = layout_math(&parse_math("\\mathit{Tr}"), &font);
|
|
assert_ne!(upright.width, italic.width);
|
|
let stacked = layout_math(&parse_math("\\operatorname*{arg}_{x}"), &font);
|
|
let beside = layout_math(&parse_math("\\operatorname{arg}_{x}"), &font);
|
|
assert!(stacked.width < beside.width);
|
|
assert!(stacked.height + stacked.depth > beside.height + beside.depth);
|
|
}
|
|
|
|
#[test]
|
|
fn substack_rows_stack_downward() {
|
|
let atom = parse_math(r"\substack{a \\ b}");
|
|
let MathAtom::Row(mut atoms) = atom else {
|
|
panic!("expected a row");
|
|
};
|
|
assert_eq!(atoms.len(), 1);
|
|
let MathAtom::StackLines(rows) = atoms.remove(0) else {
|
|
panic!("expected StackLines");
|
|
};
|
|
assert_eq!(rows.len(), 2);
|
|
let box_ = layout_math(&MathAtom::StackLines(rows), &Cmr10Metrics::default());
|
|
assert!(box_.width > 0);
|
|
assert!(
|
|
box_.depth > box_.height,
|
|
"second row should sit below the baseline"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn genfrac_builds_fractions_with_optional_delimiters() {
|
|
let font = Cmr10Metrics::default();
|
|
fn only(atom: MathAtom) -> MathAtom {
|
|
match atom {
|
|
MathAtom::Row(mut atoms) if atoms.len() == 1 => atoms.remove(0),
|
|
other => other,
|
|
}
|
|
}
|
|
let plain = only(parse_math(r"\genfrac{}{}{0pt}{}{a}{b}"));
|
|
let MathAtom::Fraction { bar, .. } = &plain else {
|
|
panic!("expected a bare fraction");
|
|
};
|
|
assert!(!bar, "an empty or 0pt thickness suppresses the rule");
|
|
let framed = only(parse_math(r"\genfrac{[}{]}{0.4pt}{}{a}{b}"));
|
|
let MathAtom::Delimited { left, right, body } = &framed else {
|
|
panic!("expected a delimited fraction");
|
|
};
|
|
assert_eq!((*left, *right), ('[', ']'));
|
|
assert!(matches!(**body, MathAtom::Fraction { bar: true, .. }));
|
|
assert!(layout_math(&framed, &font).width > layout_math(&plain, &font).width);
|
|
}
|
|
|
|
#[test]
|
|
fn integrals_keep_scripts_beside_them_by_default() {
|
|
let font = Cmr10Metrics::default();
|
|
let integral = layout_math(&parse_math(r"\int_0^1"), &font);
|
|
let sum = layout_math(&parse_math(r"\sum_0^1"), &font);
|
|
assert!(
|
|
integral.height < sum.height,
|
|
"int scripts should sit beside it"
|
|
);
|
|
let forced = layout_math(&parse_math(r"\int\limits_0^1"), &font);
|
|
assert!(
|
|
forced.height > integral.height,
|
|
r"\limits should stack int scripts"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn nolimits_moves_scripts_beside_the_operator() {
|
|
let font = Cmr10Metrics::default();
|
|
let stacked = layout_math(&parse_math(r"\sum_{i}^{n}"), &font);
|
|
let beside = layout_math(&parse_math(r"\sum\nolimits_{i}^{n}"), &font);
|
|
assert!(beside.width > stacked.width);
|
|
assert!(beside.height < stacked.height);
|
|
let MathAtom::Row(atoms) = parse_math(r"\int\limits_{0}^{1}") else {
|
|
panic!("expected a row");
|
|
};
|
|
assert!(matches!(&atoms[0], MathAtom::Limits { .. }));
|
|
let MathAtom::Row(nolimits) = parse_math(r"\sum\nolimits_{i}") else {
|
|
panic!("expected a row");
|
|
};
|
|
assert!(matches!(&nolimits[0], MathAtom::Script { .. }));
|
|
}
|
|
#[test]
|
|
fn starred_operatorname_takes_limits_below() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math(r"\operatorname*{argmax}"), &font);
|
|
let limited = layout_math(&parse_math(r"\operatorname*{argmax}_{x}"), &font);
|
|
assert!(limited.depth > plain.depth);
|
|
assert!(limited.width >= plain.width);
|
|
}
|
|
#[test]
|
|
fn operatorname_star_does_not_emit_a_symbol() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math(r"\operatorname{argmax}"), &font);
|
|
let starred = layout_math(&parse_math(r"\operatorname*{argmax}"), &font);
|
|
assert_eq!(plain.width, starred.width);
|
|
assert_eq!(plain.height, starred.height);
|
|
}
|
|
#[test]
|
|
fn operatorname_becomes_upright_text() {
|
|
let font = Cmr10Metrics::default();
|
|
let long = layout_math(&parse_math(r"\operatorname{argmax}"), &font);
|
|
let short = layout_math(&parse_math(r"\operatorname{arg}"), &font);
|
|
assert!(long.width > short.width);
|
|
}
|
|
#[test]
|
|
fn fraction_style_aliases_match_frac() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math(r"\frac{a}{b}"), &font);
|
|
for command in ["tfrac", "dfrac", "cfrac"] {
|
|
let source = format!(r"\{command}{{a}}{{b}}");
|
|
let boxed = layout_math(&parse_math(&source), &font);
|
|
assert_eq!(plain.width, boxed.width);
|
|
assert_eq!(plain.height, boxed.height);
|
|
}
|
|
}
|
|
#[test]
|
|
fn math_spacing_commands_have_expected_widths() {
|
|
let font = Cmr10Metrics::default();
|
|
let thin = layout_math(&parse_math(r"a\,b"), &font);
|
|
let medium = layout_math(&parse_math(r"a\;b"), &font);
|
|
let quad = layout_math(&parse_math(r"a\quad b"), &font);
|
|
let double = layout_math(&parse_math(r"a\qquad b"), &font);
|
|
let plain = layout_math(&parse_math("ab"), &font);
|
|
assert!(thin.width > plain.width);
|
|
assert!(medium.width > thin.width);
|
|
assert!(quad.width > medium.width);
|
|
assert!(double.width > quad.width);
|
|
}
|
|
#[test]
|
|
fn explicit_math_skips_have_their_natural_width() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("ab"), &font).width;
|
|
let thin = layout_math(&parse_math(r"a\mskip 3mu b"), &font).width;
|
|
let mspace = layout_math(&parse_math(r"a\mspace{18mu}b"), &font).width;
|
|
let em = layout_math(&parse_math(r"a\hspace{1em}b"), &font).width;
|
|
assert_eq!(thin - plain, THIN_MU);
|
|
assert_eq!(mspace - plain, 655_360);
|
|
assert_eq!(em - plain, 655_360);
|
|
}
|
|
|
|
#[test]
|
|
fn math_skips_accept_plus_minus_and_negative_values() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("ab"), &font).width;
|
|
let stretchy = layout_math(&parse_math(r"a\mskip 3mu plus 1mu minus 1mu b"), &font).width;
|
|
let tight = layout_math(&parse_math(r"a\mkern-2mu b"), &font).width;
|
|
assert_eq!(stretchy - plain, THIN_MU);
|
|
assert_eq!(plain - tight, 2 * 655_360 / 18);
|
|
}
|
|
|
|
#[test]
|
|
fn mid_spaces_like_a_relation() {
|
|
let font = Cmr10Metrics::default();
|
|
let mid = layout_math(&parse_math(r"a\mid b"), &font).width;
|
|
let bar = layout_math(&parse_math("a|b"), &font).width;
|
|
assert_eq!(mid - bar, 2 * THICK_MU);
|
|
let colon = layout_math(&parse_math(r"a\colon b"), &font).width;
|
|
let relation = layout_math(&parse_math("a:b"), &font).width;
|
|
assert!(colon < relation, "\\colon is punctuation, not a relation");
|
|
}
|
|
|
|
#[test]
|
|
fn math_text_preserves_internal_spaces() {
|
|
let font = Cmr10Metrics::default();
|
|
let spaced = layout_math(&parse_math(r"\text{a b}"), &font);
|
|
let joined = layout_math(&parse_math(r"\text{ab}"), &font);
|
|
assert!(spaced.width > joined.width);
|
|
}
|
|
#[test]
|
|
fn math_style_commands_are_transparent() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
let styled = layout_math(&parse_math(r"\displaystyle x"), &font);
|
|
assert_eq!(plain.width, styled.width);
|
|
assert_eq!(plain.height, styled.height);
|
|
}
|
|
#[test]
|
|
fn binom_stacks_two_arguments() {
|
|
let font = Cmr10Metrics::default();
|
|
let binom = layout_math(&parse_math("\\binom{n}{k}"), &font);
|
|
let single = layout_math(&parse_math("n"), &font);
|
|
assert!(binom.width >= single.width);
|
|
assert!(binom.height > single.height);
|
|
assert!(binom.depth > 0);
|
|
}
|
|
#[test]
|
|
fn named_operators_use_upright_text_widths() {
|
|
let font = Cmr10Metrics::default();
|
|
let max = layout_math(&parse_math("\\max"), &font);
|
|
let single = layout_math(&parse_math("m"), &font);
|
|
assert!(max.width > single.width);
|
|
assert!(matches!(
|
|
&parse_math("\\max"),
|
|
MathAtom::Row(atoms) if matches!(&atoms[0], MathAtom::Text(text) if text == "max")
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn pmod_wraps_its_argument_in_a_mod_row() {
|
|
let parsed = parse_math(r"\pmod{n}");
|
|
let MathAtom::Row(atoms) = parsed else {
|
|
panic!("expected row")
|
|
};
|
|
assert!(matches!(
|
|
&atoms[0],
|
|
MathAtom::Classed {
|
|
class: MathClass::Relation,
|
|
..
|
|
}
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn negated_atom_keeps_its_base_geometry() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("="), &font);
|
|
let negated = layout_math(&parse_math("\\not="), &font);
|
|
assert_eq!(negated.width, plain.width);
|
|
assert!(matches!(
|
|
&parse_math("\\not="),
|
|
MathAtom::Row(atoms) if matches!(&atoms[0], MathAtom::Negated { .. })
|
|
));
|
|
}
|
|
#[test]
|
|
fn underline_adds_depth_without_changing_width() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
let underlined = layout_math(&parse_math("\\underline{x}"), &font);
|
|
assert_eq!(underlined.width, plain.width);
|
|
assert!(underlined.depth > plain.depth);
|
|
assert_eq!(underlined.height, plain.height);
|
|
}
|
|
|
|
#[test]
|
|
fn glyph_height_comes_from_the_tfm() {
|
|
let font = Cmr10Metrics::default();
|
|
let box_ = layout_math(&parse_math("A"), &font);
|
|
assert_eq!(box_.height, font.height('A'));
|
|
let g = layout_math(&parse_math("g"), &font);
|
|
assert_eq!(g.depth, font.depth('g'));
|
|
}
|
|
#[test]
|
|
fn math_text_uses_upright_character_widths() {
|
|
let font = Cmr10Metrics::default();
|
|
let atom = parse_math("\\text{PSNR}");
|
|
let MathAtom::Row(atoms) = &atom else {
|
|
panic!("expected a row");
|
|
};
|
|
let MathAtom::Text(text) = &atoms[0] else {
|
|
panic!("expected a text atom");
|
|
};
|
|
assert_eq!(text, "PSNR");
|
|
let text_box = layout_math(&atom, &font);
|
|
let symbol = layout_math(&parse_math("P"), &font);
|
|
assert!(text_box.width > symbol.width);
|
|
assert!(text_box.height > 0);
|
|
}
|
|
|
|
#[test]
|
|
fn middle_delimiter_adds_a_symbol() {
|
|
let font = Cmr10Metrics::default();
|
|
let without = layout_math(&parse_math("\\left(ab\\right)"), &font);
|
|
let with = layout_math(&parse_math("\\left(a\\middle|b\\right)"), &font);
|
|
assert!(with.width > without.width);
|
|
}
|
|
#[test]
|
|
fn empty_left_delimiter_has_no_width() {
|
|
let font = Cmr10Metrics::default();
|
|
let dotted = layout_math(&parse_math("\\left.x\\right|"), &font);
|
|
let bare = layout_math(&parse_math("x|"), &font);
|
|
assert_eq!(dotted.width, bare.width);
|
|
}
|
|
#[test]
|
|
fn accents_add_height_without_changing_width() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("x"), &font);
|
|
let accented = layout_math(&parse_math("\\hat{x}"), &font);
|
|
assert_eq!(accented.width, plain.width);
|
|
assert!(accented.height > plain.height);
|
|
}
|
|
#[test]
|
|
fn left_right_delimiters_grow_with_their_body() {
|
|
let font = Cmr10Metrics::default();
|
|
let atom = parse_math("\\left(\\frac{a}{b}\\right)");
|
|
let boxed = layout_math(&atom, &font);
|
|
let plain = layout_math(&parse_math("(a)"), &font);
|
|
assert!(matches!(atom, MathAtom::Row(_)));
|
|
assert!(boxed.height > plain.height);
|
|
}
|
|
#[test]
|
|
fn operator_spacing_separates_binary_and_relation_atoms() {
|
|
let font = Cmr10Metrics::default();
|
|
let plain = layout_math(&parse_math("xy"), &font);
|
|
let binary = layout_math(&parse_math("x+y"), &font);
|
|
let relation = layout_math(&parse_math("x=y"), &font);
|
|
assert!(binary.width > plain.width);
|
|
assert!(relation.width > binary.width);
|
|
}
|
|
#[test]
|
|
fn parse_script_attaches_to_the_previous_atom() {
|
|
let atom = parse_math("x^2");
|
|
let MathAtom::Row(atoms) = atom else {
|
|
panic!("expected a row");
|
|
};
|
|
assert!(matches!(&atoms[0], MathAtom::Script { sup: Some(_), .. }));
|
|
}
|
|
|
|
#[test]
|
|
fn infix_fractions_consume_the_current_row() {
|
|
let atom = parse_math("a + b \\over c + d");
|
|
let MathAtom::Row(atoms) = atom else {
|
|
panic!("expected a row");
|
|
};
|
|
assert_eq!(atoms.len(), 1);
|
|
let MathAtom::Fraction {
|
|
numerator,
|
|
denominator,
|
|
bar,
|
|
} = &atoms[0]
|
|
else {
|
|
panic!("expected a fraction, got {:?}", atoms[0]);
|
|
};
|
|
assert!(*bar);
|
|
assert!(matches!(**numerator, MathAtom::Row(ref row) if row.len() == 3));
|
|
assert!(matches!(**denominator, MathAtom::Row(ref row) if row.len() == 3));
|
|
}
|
|
|
|
#[test]
|
|
fn atop_and_choose_use_their_own_forms() {
|
|
let atom = parse_math("a \\atop b");
|
|
let MathAtom::Row(atoms) = &atom else {
|
|
panic!("expected a row");
|
|
};
|
|
assert!(matches!(&atoms[0], MathAtom::Fraction { bar: false, .. }));
|
|
let choose = parse_math("n \\choose k");
|
|
let MathAtom::Row(atoms) = &choose else {
|
|
panic!("expected a row");
|
|
};
|
|
assert!(matches!(
|
|
&atoms[0],
|
|
MathAtom::Delimited {
|
|
left: '(',
|
|
right: ')',
|
|
body,
|
|
} if matches!(**body, MathAtom::Fraction { bar: false, .. })
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn over_with_delims_keeps_the_requested_delimiters() {
|
|
let atom = parse_math("a \\overwithdelims [ ] b");
|
|
let MathAtom::Row(atoms) = &atom else {
|
|
panic!("expected a row");
|
|
};
|
|
assert!(matches!(
|
|
&atoms[0],
|
|
MathAtom::Delimited {
|
|
left: '[',
|
|
right: ']',
|
|
body,
|
|
} if matches!(**body, MathAtom::Fraction { bar: true, .. })
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn parse_fraction_and_sqrt() {
|
|
let atom = parse_math("\\frac{a}{b} + \\sqrt{x}");
|
|
let MathAtom::Row(atoms) = atom else {
|
|
panic!("expected a row");
|
|
};
|
|
assert!(matches!(&atoms[0], MathAtom::Fraction { .. }));
|
|
assert!(matches!(&atoms[2], MathAtom::Sqrt { .. }));
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod cmsy_symbol_tests {
|
|
use super::*;
|
|
use crate::cmr10::Cmr10Metrics;
|
|
|
|
#[test]
|
|
fn symbol_commands_use_cmsy_metrics() {
|
|
let font = Cmr10Metrics::Math;
|
|
let atom = parse_math(r"\times");
|
|
let MathAtom::Row(row) = &atom else {
|
|
panic!("atom: {atom:?}");
|
|
};
|
|
assert!(
|
|
matches!(row.first(), Some(MathAtom::Symbol('\u{00D7}'))),
|
|
"row: {row:?}"
|
|
);
|
|
let laid_out = layout_math(&atom, &font);
|
|
assert_eq!(laid_out.width, font.width('\u{00D7}'));
|
|
assert!(laid_out.width > 0);
|
|
assert_ne!(laid_out.width, Cmr10Metrics::Roman.width('\u{00D7}'));
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod cmex_size_tests {
|
|
use super::*;
|
|
use crate::cmr10::{Cmr10Metrics, cmex_delimiter};
|
|
|
|
#[test]
|
|
fn big_delimiters_use_cmex_metrics() {
|
|
let font = Cmr10Metrics::Math;
|
|
let big = layout_math(&parse_math(r"\big("), &font);
|
|
let (width, height, depth) = cmex_delimiter('(', 1).expect("cmex big paren");
|
|
assert_eq!(big.width, width);
|
|
assert_eq!(big.height, height);
|
|
assert_eq!(big.depth, depth);
|
|
let plain = layout_math(&parse_math("("), &font);
|
|
assert!(big.height > plain.height);
|
|
}
|
|
|
|
#[test]
|
|
fn bigger_delimiters_pick_larger_cmex_variants() {
|
|
let font = Cmr10Metrics::Math;
|
|
let big = layout_math(&parse_math(r"\Big["), &font);
|
|
let bigg = layout_math(&parse_math(r"\bigg["), &font);
|
|
let slot_big = cmex_delimiter('[', 2).expect("cmex Big bracket");
|
|
let slot_bigg = cmex_delimiter('[', 3).expect("cmex bigg bracket");
|
|
assert_eq!(big.width, slot_big.0);
|
|
assert_eq!(bigg.width, slot_bigg.0);
|
|
assert!(bigg.height > big.height);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod delimiter_selection_tests {
|
|
use super::*;
|
|
use crate::cmr10::{Cmr10Metrics, cmex_delimiter};
|
|
|
|
#[test]
|
|
fn selector_keeps_the_ordinary_glyph_for_small_bodies() {
|
|
let font = Cmr10Metrics::Math;
|
|
let small = select_delimiter(font, '(', 7 * 65_536);
|
|
assert_eq!(small.0, font.width('('));
|
|
assert_eq!(small.1, font.height('('));
|
|
assert_eq!(small.2, font.depth('('));
|
|
let empty = select_delimiter(font, '.', 30 * 65_536);
|
|
assert_eq!(empty, (0, 0, 0));
|
|
}
|
|
|
|
#[test]
|
|
fn selector_grows_to_cmex_variants_for_tall_bodies() {
|
|
let font = Cmr10Metrics::Math;
|
|
let tall = select_delimiter(font, '(', 30 * 65_536);
|
|
let bigg_bigg = cmex_delimiter('(', 4).expect("cmex Bigg paren");
|
|
assert_eq!(tall, bigg_bigg);
|
|
let medium = select_delimiter(font, '(', 15 * 65_536);
|
|
let mut matched = false;
|
|
for size in 1..=4 {
|
|
if let Some(metrics) = cmex_delimiter('(', size) {
|
|
if metrics == medium {
|
|
matched = true;
|
|
}
|
|
}
|
|
}
|
|
assert!(matched, "medium selection {medium:?} is not a cmex variant");
|
|
}
|
|
|
|
#[test]
|
|
fn delimited_layout_uses_selected_delimiters() {
|
|
let font = Cmr10Metrics::Math;
|
|
let plain = layout_math(&parse_math(r"\left(a\right)"), &font);
|
|
let tall = layout_math(&parse_math(r"\left(\frac{a}{b}\right)"), &font);
|
|
assert!(tall.height + tall.depth > plain.height + plain.depth);
|
|
assert!(tall.width > plain.width);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod spacing_class_tests {
|
|
use super::*;
|
|
use crate::cmr10::Cmr10Metrics;
|
|
|
|
fn width(source: &str) -> i64 {
|
|
layout_math(&parse_math(source), &Cmr10Metrics::Math).width
|
|
}
|
|
|
|
#[test]
|
|
fn punctuation_gets_a_thin_space() {
|
|
let font = Cmr10Metrics::Math;
|
|
let packed = font.width('a') + font.width(',') + font.width('b');
|
|
assert_eq!(width("a,b") - packed, THIN_MU);
|
|
}
|
|
|
|
#[test]
|
|
fn binary_operators_at_list_edges_become_ordinary() {
|
|
let font = Cmr10Metrics::Math;
|
|
let plus = font.width('+');
|
|
let a = font.width('a');
|
|
assert_eq!(width("+a"), plus + a);
|
|
assert_eq!(width("a+"), a + plus);
|
|
}
|
|
|
|
#[test]
|
|
fn relation_and_binary_spacing_stay_distinct() {
|
|
let font = Cmr10Metrics::Math;
|
|
let base = font.width('x') + font.width('+') + font.width('y');
|
|
assert_eq!(width("x+y") - base, 2 * MED_MU);
|
|
let relation = font.width('x') + font.width('=') + font.width('y');
|
|
assert_eq!(width("x=y") - relation, 2 * THICK_MU);
|
|
}
|
|
|
|
#[test]
|
|
fn big_operators_are_operator_atoms() {
|
|
let font = Cmr10Metrics::Math;
|
|
let sum = width(r"\sum");
|
|
assert_eq!(width(r"\sum x") - sum - font.width('x'), THIN_MU);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tagged_equation_tests {
|
|
use super::*;
|
|
use crate::cmr10::Cmr10Metrics;
|
|
|
|
fn roman_width(text: &str) -> i64 {
|
|
text.chars()
|
|
.map(|character| Cmr10Metrics::Roman.width(character))
|
|
.sum()
|
|
}
|
|
|
|
#[test]
|
|
fn tagged_formula_reserves_room_for_the_tag() {
|
|
let font = Cmr10Metrics::Math;
|
|
let body = parse_math("x");
|
|
let plain = layout_math(&body, &font);
|
|
let tagged = layout_math(
|
|
&MathAtom::Tagged {
|
|
body: Box::new(body),
|
|
tag: "(12)".to_string(),
|
|
},
|
|
&font,
|
|
);
|
|
assert_eq!(tagged.width, plain.width.max(roman_width("(12)")));
|
|
assert_eq!(tagged.height, plain.height.max(7 * 65_536));
|
|
assert_eq!(tagged.depth, plain.depth.max(2 * 65_536));
|
|
}
|
|
}
|