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).
This commit is contained in:
texrra committed 2026-10-24 12:28:33 +08:00
1 parent cb40cc4634
commit 8c42f2de2f
10 files changed
+499 -72

No files matched your search

+257 -7
View File
@@ -15,6 +15,7 @@ pub enum MathAlphabet {
Mono,
Calligraphic,
Blackboard,
Fraktur,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -85,6 +86,8 @@ pub enum MathAtom {
delimiter: char,
size: u8,
},
/// A `\middle` delimiter; TeX sizes it with the enclosing `\left`/`\right`.
Middle(char),
StackLines(Vec<MathAtom>),
Stack {
top: Box<MathAtom>,
@@ -107,9 +110,16 @@ pub enum 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)
@@ -127,6 +137,7 @@ impl MathAtom {
Self::Fraction {
numerator: Box::new(numerator),
denominator: Box::new(denominator),
bar: true,
}
}
}
@@ -309,6 +320,7 @@ pub(crate) fn alphabet_metrics(font: Cmr10Metrics, alphabet: MathAlphabet) -> Cm
}
MathAlphabet::Calligraphic => Cmr10Metrics::MathCalligraphic,
MathAlphabet::Blackboard => Cmr10Metrics::MathBlackboard,
MathAlphabet::Fraktur => Cmr10Metrics::MathFraktur,
}
}
@@ -566,6 +578,7 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
}
}
}
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 {
@@ -672,6 +685,7 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox {
MathAtom::Fraction {
numerator,
denominator,
..
} => {
let numerator_box = layout_math(numerator, font);
let denominator_box = layout_math(denominator, font);
@@ -702,6 +716,97 @@ pub fn parse_math(input: &str) -> MathAtom {
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')
@@ -762,6 +867,30 @@ fn parse_sequence(
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;
@@ -1151,10 +1280,7 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
"bigg" | "biggl" | "biggr" => 3,
_ => 4,
};
let mut after = next;
while after < chars.len() && chars[after].is_whitespace() {
after += 1;
}
let after = skip_math_space(chars, next);
let (delimiter, after) = parse_delimiter(chars, after);
(MathAtom::SizedDelimiter { delimiter, size }, after)
}
@@ -1319,8 +1445,9 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
)
}
"middle" => {
let (delimiter, after) = parse_delimiter(chars, next);
(MathAtom::Symbol(delimiter), after)
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" => {
@@ -1350,6 +1477,7 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
"mathtt" => Some(MathAlphabet::Mono),
"mathcal" => Some(MathAlphabet::Calligraphic),
"mathbb" => Some(MathAlphabet::Blackboard),
"mathfrak" => Some(MathAlphabet::Fraktur),
_ => None,
};
match alphabet {
@@ -1433,8 +1561,11 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) {
(MathAtom::Text(text), after)
}
"left" => {
let (left, body_start) = parse_delimiter(chars, next);
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) {
@@ -1586,6 +1717,25 @@ mod tests {
);
}
#[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();
@@ -1686,6 +1836,49 @@ mod tests {
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();
@@ -2082,6 +2275,63 @@ mod tests {
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}");