Files
texrra-engine/crates/texrra-tex-core/src/math.rs
T
texrra 8c42f2de2f Add Fraktur letters, infix fractions and middle delimiters
- bundle eufm10 (TFM + Type1), add the MathFraktur face and map \mathfrak
  onto it, including PDF embedding and width lookup;
- parse TeX's infix fractions (\over, \atop, \choose, \brace,
  \brack, \overwithdelims, \atopwithdelims): the rest of the current
  row becomes the denominator, ar records whether a rule is drawn, and the
  painter no longer emits parentheses (a \frac painter bug) and only draws
  the bar for \over forms;
- add MathAtom::Middle, size top-level middle delimiters with the enclosing
  \left/\right group through the CMEX size classes, and paint
  SizedDelimiter at its selected size instead of the base glyph;
- skip the parser's '\u{0}' math spaces before \big, \middle,
  \left and the withdelims delimiters, so \big ( parses like \big(.

560 workspace tests (381 route-D unit).
2026-10-24 12:28:33 +08:00

2513 lines
87 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,
}
#[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),
StackLines(Vec<MathAtom>),
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,
},
}
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,
}
}
/// Width of one math unit at 10pt (TeX's `\thinmuskip` is 3mu).
const THIN_MU: i64 = 3 * 65_536 / 18;
/// Width of `\medmuskip` (4mu plus 2mu minus 4mu at 10pt).
const MED_MU: i64 = 4 * 65_536 / 18;
/// Width of `\thickmuskip` (5mu plus 5mu at 10pt).
const THICK_MU: i64 = 5 * 65_536 / 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::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,
}
}
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::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| layout_math(atom, font));
let sup = sup.as_ref().map(|atom| 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 + 65_536),
depth: base.depth + sub.as_ref().map_or(0, |item| item.height + 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::StackLines(rows) => {
let boxes: Vec<MathBox> = rows.iter().map(|atom| layout_math(atom, font)).collect();
MathBox {
width: boxes.iter().map(|b| b.width).max().unwrap_or(0),
height: boxes.iter().map(|b| b.height).sum(),
depth: boxes.last().map_or(0, |b| b.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 parse_limits(chars: &[char], next: usize, base: MathAtom) -> (MathAtom, usize) {
let mut after = next;
let mut sub = None;
let mut sup = None;
loop {
let mut cursor = after;
while cursor < chars.len() && chars[cursor].is_whitespace() {
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,
}
}
if sub.is_none() && sup.is_none() {
(base, 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)
}
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() {
"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)
}
"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,
)
}
"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,
)
}
"operatorname" => {
let mut after = next;
let starred = chars.get(after) == Some(&'*');
if starred {
after += 1;
}
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 atom = MathAtom::Text(text);
if starred {
parse_limits(chars, after, atom)
} else {
(atom, 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 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 > plain.height);
}
#[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 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 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, 3 * 65_536 / 18);
}
#[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 * (4 * 65_536 / 18));
let relation = font.width('x') + font.width('=') + font.width('y');
assert_eq!(width("x=y") - relation, 2 * (5 * 65_536 / 18));
}
#[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'), 3 * 65_536 / 18);
}
}
#[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));
}
}