//! Equations as MathML (W3C MathML Core / Presentation MathML): written into HTML export and the
//! HTML a copy puts on the system clipboard, so programs that read MathML can get a formatted
//! equation instead of its linear text (#816); for a copy of one equation alone, the text of the
//! platform's MathML clipboard formats, which Word reads first when it pastes math (#1297;
//! pasting into Word and LibreOffice not yet verified); and read back from pasted or opened HTML.
//!
//! The writer walks the equation tree ([`MNode`]) and wraps it in `` with the linear
//! format as an `application/x-unicodemath` annotation, which renderers ignore and WordCraft reads
//! back exactly. The reader takes that annotation when present, else a TeX annotation, else
//! builds the tree from the presentation elements (fractions, scripts, radicals, under/over
//! limits, tables, fences); both bound their nesting and size.
use crate::math::{
Arg, ColJc, FracKind, LimLoc, MAX_DEPTH, MClass, MNode, MRun, MScr, MSty, ScriptKind, is_integral, is_nary_char, math_alnum, math_class,
to_linear,
};
use crate::math_linear::FUNCTION_NAMES;
/// Escape text for HTML or XML content and attribute values.
fn esc(s: &str) -> String {
let mut o = String::with_capacity(s.len() + 8);
for c in s.chars() {
match c {
'&' => o.push_str("&"),
'<' => o.push_str("<"),
'>' => o.push_str(">"),
'"' => o.push_str("""),
'\u{000C}' | '\u{000E}' => {}
_ => o.push(c),
}
}
o
}
/// The MathML namespace.
pub const NS: &str = "http://www.w3.org/1998/Math/MathML";
/// The annotation encoding carrying the linear format (UnicodeMath).
pub const UNICODEMATH: &str = "application/x-unicodemath";
// ---------------------------------------------------------------------------------------------
// Writer
/// An equation as a `
")), vec![(linear.to_string(), display)], "{xml}");
}
}
#[test]
fn foreign_mathml_is_read_from_its_elements() {
let cases = [
("y=2xs", "y=2x_s"),
("ab+1", "a/(b+1)"),
("x", "√x"),
("∑k=1nk", "∑_(k=1)^n▒k"),
("ex", "e^x"),
// A TeX annotation is used when the presentation is empty.
("\\frac{1}{2}", "1/2"),
];
for (html, want) in cases {
let got = pasted(html);
assert_eq!(got.first().map(|g| g.0.as_str()), Some(want), "{html}");
}
assert!(pasted("x").first().is_some_and(|g| g.1));
// An unclosed element ends with the input.
assert!(!pasted("x").is_empty());
// Hostile nesting is bounded.
let deep = format!("{}x{}", "".repeat(5000), "".repeat(5000));
assert!(pasted(&deep).len() <= 1);
}
#[test]
fn math_over_the_node_cap_keeps_the_first_elements() {
let xml = format!("{}z", "y".repeat(MAX_NODES * 2));
let el = parse(&xml).unwrap();
assert_eq!(el.children.len(), MAX_NODES);
assert!(read(&el).is_some_and(|(l, _)| !l.contains('z')));
// Not XML, or no math element: nothing.
assert!(parse("").is_none() && parse("no math
").is_none() && parse("\u{0}<<").is_none());
}
#[test]
fn function_names_apply_without_the_invisible_operator() {
let cases = [
("sinx", "sin\u{2061}x"),
("logab", "log\u{2061}ab"),
("cos\u{2061}x", "cos\u{2061}x"),
("abx", "abx"),
];
for (html, want) in cases {
assert_eq!(pasted(html).first().map(|g| g.0.as_str()), Some(want), "{html}");
}
let tree = to_tree(&El {
name: "math".into(),
attrs: vec![],
children: vec![
Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("sin".into())] }),
Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("x".into())] }),
],
});
assert!(matches!(tree.as_slice(), [MNode::Func { .. }]), "{tree:?}");
}
#[test]
fn one_column_tables_are_column_vectors_unless_marked() {
let tree = |html: &str| {
let linear = pasted(html).first().map(|g| g.0.clone()).unwrap_or_default();
crate::math::parse_linear(&linear)
};
let vector = tree("ab");
assert!(matches!(vector.as_slice(), [MNode::Matrix { rows, .. }] if rows.len() == 2), "{vector:?}");
for marked in [
"ab",
"a=1b",
] {
let t = tree(marked);
assert!(matches!(t.as_slice(), [MNode::EqArr { rows }] if rows.len() == 2), "{marked}: {t:?}");
}
// Our own equation arrays read back as equation arrays from their elements alone.
let ml = to_mathml(&[MNode::EqArr { rows: vec![parse_linear("x=1"), parse_linear("y=2")] }], false, "");
let ml = ml.replace("application/x-unicodemath", "x-ignored");
let t = tree(&ml);
assert!(matches!(t.as_slice(), [MNode::EqArr { .. }]), "{ml}: {t:?}");
}
#[test]
fn mmultiscripts_and_borderbox_round_trip() {
let html = "X12";
let p = pasted(html);
assert!(!p.is_empty(), "should parse mmultiscripts with pre and post scripts");
let html_box = "x";
let p_box = pasted(html_box);
assert!(!p_box.is_empty(), "should parse menclose");
let html_tbl = "ab";
let p_tbl = pasted(html_tbl);
assert!(!p_tbl.is_empty(), "should parse mtable with columnalign");
let html_pad = "z";
let p_pad = pasted(html_pad);
assert!(!p_pad.is_empty(), "should parse mpadded phantom");
}
#[test]
fn deep_nesting_is_bounded() {
let mut n = parse_linear("x");
for _ in 0..500 {
n = vec![MNode::Frac { kind: FracKind::Bar, num: n, den: parse_linear("y") }];
}
let m = to_mathml(&n, false, "z");
assert!(m.ends_with(""));
}
#[test]
fn test_mfrac_linethickness_none_and_menclose_notations() {
let el_frac = El {
name: "mfrac".into(),
attrs: vec![("linethickness".into(), "none".into())],
children: vec![
Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("n".into())] }),
Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("k".into())] }),
],
};
let mut budget = MAX_NODES;
let tree_frac = elem(&el_frac, 0, &mut budget);
assert!(matches!(tree_frac.as_slice(), [MNode::Frac { kind: FracKind::NoBar, .. }]), "{tree_frac:?}");
let el_strike = El {
name: "menclose".into(),
attrs: vec![("notation".into(), "horizontalstrike".into())],
children: vec![Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("x".into())] })],
};
let mut budget = MAX_NODES;
let tree_strike = elem(&el_strike, 0, &mut budget);
assert!(matches!(tree_strike.as_slice(), [MNode::BorderBox { strike: [true, false, false, false], .. }]), "{tree_strike:?}");
let el_cross = El {
name: "menclose".into(),
attrs: vec![("notation".into(), "cross".into())],
children: vec![Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("x".into())] })],
};
let mut budget = MAX_NODES;
let tree_cross = elem(&el_cross, 0, &mut budget);
assert!(matches!(tree_cross.as_slice(), [MNode::BorderBox { strike: [false, false, true, true], .. }]), "{tree_cross:?}");
let el_rad = El {
name: "menclose".into(),
attrs: vec![("notation".into(), "radical".into())],
children: vec![Item::El(El { name: "mi".into(), attrs: vec![], children: vec![Item::Text("x".into())] })],
};
let mut budget = MAX_NODES;
let tree_rad = elem(&el_rad, 0, &mut budget);
assert!(matches!(tree_rad.as_slice(), [MNode::Rad { deg_hide: true, .. }]), "{tree_rad:?}");
}
}