craft-math: review fixes: number bases, a comma after a script, whitespace in kept OMML

From the review of this series:

- A base that is one number by the parser's rule (1,000 as well as 2.5 and .5) is written bare,
  1,000^2 rather than 〖1,000〗^2. lin_base tested numbers with digits and points only, so a
  comma made it a multi-letter base. The rule is now is_number, the parser's number_len over the
  whole text; simple_operand, which fractions share, is unchanged.
- A bare script followed by a comma and a digit is ended with a space: x^2 then ,3 was written
  x^2,3, and the number script read the ,3 back into the exponent. Only a comma before a digit
  gets one; x^2, y is written as before.
- Kept OMML whose element name is followed by a tab, carriage return or line feed (all XML
  whitespace) is written back like one followed by a space, instead of from the nodes.

Each new test fails without its fix.
This commit is contained in:
kiwi4boy
2026-11-12 22:36:13 -05:00
parent fd4a95d261
commit ae00359d2b
4 changed files with 64 additions and 5 deletions
+11
View File
@@ -49,6 +49,17 @@ fn well_formed_kept_omml_is_written_back_unchanged() {
assert_eq!(texts(&back), vec!["KEPT".to_string()]);
}
#[test]
fn xml_whitespace_after_the_element_name_is_kept() {
// XML allows any of space, tab, carriage return and line feed between a name and `>`.
for ws in [" ", "\t", "\r", "\n", "\r\n "] {
let kept = format!("<m:oMath{ws}><m:r><m:t>KEPT</m:t></m:r></m:oMath>");
let (xml, back) = save(&kept, false);
assert!(xml.contains(&kept), "{ws:?}: {xml}");
assert_eq!(texts(&back), vec!["KEPT".to_string()], "{ws:?}");
}
}
#[test]
fn malformed_kept_omml_is_written_from_the_nodes() {
for kept in [
+20 -4
View File
@@ -499,7 +499,12 @@ fn lin_arg(a: &[MNode], s: &mut String, depth: usize) {
// A bare script or limit ends at a space: a letter, digit or period after it is its own item.
if matches!(n, MNode::Script { kind, .. } if *kind != ScriptKind::Pre) || matches!(n, MNode::Lim { .. }) {
let ends_bare = s.chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '.');
if ends_bare && a.get(i + 1).and_then(first_lin_char).is_some_and(|c| c.is_alphanumeric() || c == '.') {
// So does a `,` before a digit: a number script reads it as part of the number (`x^2,3`).
let comma_digit = || {
let mut cs = a[i + 1..].iter().map_while(|n| if let MNode::Run(r) = n { Some(r.text.chars()) } else { None }).flatten();
cs.next() == Some(',') && cs.next().is_some_and(|c| c.is_ascii_digit())
};
if ends_bare && (a.get(i + 1).and_then(first_lin_char).is_some_and(|c| c.is_alphanumeric() || c == '.') || comma_digit()) {
s.push(' ');
}
}
@@ -518,6 +523,16 @@ fn first_lin_char(n: &MNode) -> Option<char> {
}
}
/// Whether `t` is one number as the linear-format parser reads it (`number_len`): digits, where a
/// `.` or `,` continues it only before a digit (`2.5`, `1,000`), and a leading `.` before a digit
/// starts one (`.5`). `2.` isn't one: the parser leaves the point out.
fn is_number(t: &str) -> bool {
let c: Vec<char> = t.chars().collect();
let digit = |k: usize| c.get(k).is_some_and(|c| c.is_ascii_digit());
(digit(0) || (c.first() == Some(&'.') && digit(1)))
&& c.iter().enumerate().all(|(k, &ch)| ch.is_ascii_digit() || (matches!(ch, '.' | ',') && digit(k + 1)))
}
/// Whether `a` is written bare as an operand: a single simple atom.
fn simple_operand(a: &[MNode]) -> bool {
match a {
@@ -560,10 +575,11 @@ fn lin_base(a: &[MNode], s: &mut String, depth: usize) {
lin_arg(a, &mut inner, depth);
let invisible = matches!(a, [MNode::Delim { beg: None, end: None, elems, .. }] if elems.len() == 1);
let operator = matches!(a, [MNode::Run(r)] if r.text.chars().all(crate::math_linear::is_boundary));
let number = |t: &str| t.chars().all(|c| c.is_ascii_digit() || c == '.');
let name = |r: &MRun| r.sty == Some(MSty::Plain) && crate::math_linear::FUNCTION_NAMES.contains(&r.text.as_str());
let letters = matches!(a, [MNode::Run(r)] if r.text.chars().nth(1).is_some() && !number(&r.text) && !name(r));
if simple_operand(a) && !inner.is_empty() && !invisible && !operator && !letters {
// A number by the parser's rule (`1,000`, `2.5`, `.5`) is one item, so it stays bare too.
let number = matches!(a, [MNode::Run(r)] if is_number(&r.text));
let letters = matches!(a, [MNode::Run(r)] if r.text.chars().nth(1).is_some() && !number && !name(r));
if (simple_operand(a) || number) && !inner.is_empty() && !invisible && !operator && !letters {
s.push_str(&inner);
} else {
s.push('〖');
+4 -1
View File
@@ -72,7 +72,10 @@ fn parse_kept(xml: &str) -> Option<El> {
/// document's root declares them): any other prefix is undeclared there. The element must be
/// `m:oMath` by namespace, so an `m:` bound to another URI isn't one.
fn is_well_formed(xml: &str) -> bool {
if !(xml.starts_with("<m:oMath>") || xml.starts_with("<m:oMath ")) || Options::default().strict().parse(xml.as_bytes()).is_err() {
// The name ends at `>` or XML whitespace (XML 1.0 §2.3 S), not at `/>` (an empty equation) or
// a longer name (`m:oMathPara`).
let named = xml.strip_prefix("<m:oMath").and_then(|r| r.chars().next()).is_some_and(|c| matches!(c, '>' | ' ' | '\t' | '\r' | '\n'));
if !named || Options::default().strict().parse(xml.as_bytes()).is_err() {
return false;
}
let wrapped = format!("<x xmlns:m=\"{MATH_NS}\" xmlns:w=\"{W_NS}\" xmlns:mc=\"{MC_NS}\">{xml}</x>");
+29
View File
@@ -92,3 +92,32 @@ fn a_comma_between_digits_in_brackets_joins_them() {
assert_eq!(f.text, "f");
assert_eq!(elems, &vec![vec![sup("1,2", "3")]]);
}
/// Linear text and back: the same tree.
#[track_caller]
fn prints_back(t: Vec<MNode>, want: &str) {
let lin = craft_math::math::to_linear(&t);
assert_eq!(lin, want);
assert_eq!(parse_linear(&lin), t, "{lin}");
}
#[test]
fn a_number_base_prints_bare() {
// A number the parser reads as one item needs no brackets as a base, with a comma too.
for (base, want) in [("10", "10^2"), ("2.5", "2.5^2"), (".5", ".5^2"), ("1,000", "1,000^2")] {
prints_back(vec![sup(base, "2")], want);
}
}
#[test]
fn a_comma_before_a_digit_after_a_script_stays_outside_it() {
// `x^2,3` would read `,3` into the number script, so a space ends the script first.
prints_back(vec![sup("x", "2"), r(",3")], "x^2 ,3");
prints_back(vec![sup("x", "a"), r(",3")], "x^a ,3");
// Also when the comma and the digit are separate runs (read back as one).
let lin = craft_math::math::to_linear(&[sup("x", "2"), r(","), r("3")]);
assert_eq!(lin, "x^2 ,3");
assert_eq!(parse_linear(&lin), vec![sup("x", "2"), r(",3")]);
// A comma before anything else ends the script on its own: no space is added.
assert_eq!(craft_math::math::to_linear(&[sup("x", "2"), r(", y")]), "x^2, y");
}