From 5a9571f79266c2bc5c3fde4696f12097cf081caa Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 20 Oct 2026 19:01:33 +0800 Subject: [PATCH] Preserve math spaces as control-word terminators and text spaces --- crates/texrra-tex-core/src/math.rs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/texrra-tex-core/src/math.rs b/crates/texrra-tex-core/src/math.rs index fcb1330..2a63471 100755 --- a/crates/texrra-tex-core/src/math.rs +++ b/crates/texrra-tex-core/src/math.rs @@ -431,7 +431,10 @@ pub fn layout_math(atom: &MathAtom, font: &Cmr10Metrics) -> MathBox { /// `\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 = input.chars().filter(|ch| !ch.is_whitespace()).collect(); + let chars: Vec = input + .chars() + .map(|ch| if ch.is_whitespace() { '\u{0}' } else { ch }) + .collect(); let (atom, _) = parse_sequence(&chars, 0, false, false); atom } @@ -526,6 +529,10 @@ fn parse_sequence( } 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); }; @@ -843,7 +850,10 @@ fn parse_atom(chars: &[char], index: usize) -> (MathAtom, usize) { while after < chars.len() && chars[after] != '}' { after += 1; } - let text: String = chars[start..after].iter().collect(); + let text: String = chars[start..after] + .iter() + .map(|ch| if *ch == '\u{0}' { ' ' } else { *ch }) + .collect(); if after < chars.len() { after += 1; } @@ -1213,11 +1223,18 @@ mod tests { assert_eq!(under.height, plain.height); } + #[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); + let styled = layout_math(&parse_math(r"\displaystyle x"), &font); assert_eq!(plain.width, styled.width); assert_eq!(plain.height, styled.height); }