diff --git a/Cargo.lock b/Cargo.lock index 782b0e04f..5dd57d4c5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -981,6 +981,15 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-math" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890#010702ee9b030844c852939095b1da0d0656a890" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=010702ee9b030844c852939095b1da0d0656a890)", + "serde", +] + [[package]] name = "craft-odf" version = "0.1.0" @@ -2459,6 +2468,7 @@ version = "0.19.1" dependencies = [ "craft-cfb", "craft-csv", + "craft-math", "craft-ods", "craft-offcrypto", "craft-opc", diff --git a/Cargo.toml b/Cargo.toml index e36882bc8..620f7a961 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,7 @@ craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f # Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs` # turn them into workbooks. craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", version = "0.1.0" } +craft-math = { git = "https://github.com/storytold/craft-libs", rev = "010702ee9b030844c852939095b1da0d0656a890", version = "0.1.0" } # The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back. craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9a6d894200221fcfedc274870c30394d404f859d", version = "0.1.0" } # Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model. diff --git a/crates/xlsx/Cargo.toml b/crates/xlsx/Cargo.toml index 18b8ed82a..05677ad89 100644 --- a/crates/xlsx/Cargo.toml +++ b/crates/xlsx/Cargo.toml @@ -20,6 +20,7 @@ gridcraft-math = { workspace = true } gridcraft-model = { workspace = true } craft-cfb = { workspace = true } craft-csv = { workspace = true } +craft-math = { workspace = true } craft-ods = { workspace = true } craft-offcrypto = { workspace = true } craft-opc = { workspace = true } diff --git a/crates/xlsx/src/omml.rs b/crates/xlsx/src/omml.rs index 1490b9ea5..cb7c7cf03 100644 --- a/crates/xlsx/src/omml.rs +++ b/crates/xlsx/src/omml.rs @@ -4,38 +4,64 @@ use crate::xml::El; -/// Deepest OMML nesting converted. +/// Deepest OMML nesting marked. const MAX_DEPTH: usize = 64; -/// Longest LaTeX the conversion produces before it gives up. `gridcraft_math::check` refuses a -/// longer source anyway, so converting the rest of a wide or long equation would only spend time -/// and memory on a hostile file. -const MAX_OUT_BYTES: usize = gridcraft_math::MAX_SOURCE_BYTES; /// The LaTeX for an `m:oMath` (or `m:oMathPara`) element, if every part is in the subset and the /// result lays out. pub fn to_latex(e: &El) -> Option { - let out = convert(e)?; + if e.name != "oMathPara" && e.name != "oMath" { + return None; + } + let mut xml = String::new(); + write_el(e, &mut xml); + let math = craft_math::omml::read_str(&xml)?; + let out = craft_math::math_latex::to_latex(&math.nodes); + let out = out.trim().to_string(); (!out.is_empty() && gridcraft_math::check(&out).is_ok()).then_some(out) } -/// The conversion itself, before the final check: `None` for a construct outside the subset, an -/// equation nested past [`MAX_DEPTH`] or one whose LaTeX exceeds [`MAX_OUT_BYTES`]. -fn convert(e: &El) -> Option { - let mut out = String::new(); - match e.name.as_str() { - "oMathPara" => { - let maths: Vec<&El> = e.kids("oMath").collect(); - for (i, m) in maths.iter().enumerate() { - if i > 0 { - out.push_str(" \\\\ "); - } - seq(m, &mut out, 0)?; - } +fn write_el(e: &El, out: &mut String) { + out.push_str(""); + return; + } + out.push('>'); + if !e.text.is_empty() { + push_xml_escaped(&e.text, out); + } + for c in &e.children { + write_el(c, out); + } + out.push_str("'); +} + +fn push_xml_escaped(s: &str, out: &mut String) { + for ch in s.chars() { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(ch), } - "oMath" => seq(e, &mut out, 0)?, - _ => return None, } - Some(out.trim().to_string()) } /// The first `m:oMath`/`m:oMathPara` under `e` (an `a14:m` element or a paragraph), searched to a @@ -178,33 +204,6 @@ fn mark_bytes(h: &mut u64, bytes: &[u8]) { } /// Children in order, skipping property elements. -fn seq(e: &El, out: &mut String, depth: usize) -> Option<()> { - if depth > MAX_DEPTH { - return None; - } - for c in &e.children { - node(c, out, depth + 1)?; - if out.len() > MAX_OUT_BYTES { - return None; - } - } - Some(()) -} - -/// `{…}` around a child's contents (empty group when the child is missing). -fn group(e: Option<&El>, out: &mut String, depth: usize) -> Option<()> { - out.push('{'); - if let Some(e) = e { - seq(e, out, depth)?; - } - out.push('}'); - Some(()) -} - -/// The property elements and the properties in them that this converter reads, so the ones -/// that decide what an equation says beyond its structure and text. [`body_marker`] hashes -/// exactly these, and [`val`] and [`on`] read only these, so the two cannot drift: a property -/// read here without a row in this table reads as absent, which the conversion tests show. const PROPERTIES: &[(&str, &[&str])] = &[ ("rPr", &["nor", "sty", "scr"]), ("fPr", &["type"]), @@ -221,446 +220,6 @@ fn read_properties(pr: &str) -> &'static [&'static str] { PROPERTIES.iter().find(|(name, _)| *name == pr).map_or(&[], |(_, names)| names) } -/// The `val` of property `name` in the property element `props`, when the converter reads it. -fn val<'a>(props: Option<&'a El>, name: &str) -> Option<&'a str> { - props.filter(|p| read_properties(&p.name).contains(&name)).and_then(|p| p.child(name)).and_then(|c| c.attr("val")) -} - -/// Whether the switch `name` in the property element `props` is on, when the converter reads it. -fn on(props: Option<&El>, name: &str) -> bool { - props - .filter(|p| read_properties(&p.name).contains(&name)) - .and_then(|p| p.child(name)) - .is_some_and(|c| c.attr("val").is_none_or(|v| v == "1" || v == "on" || v == "true")) -} - -/// LaTeX for one character of a math run. -fn char_latex(c: char) -> Option<&'static str> { - Some(match c { - 'α' => "\\alpha ", - 'β' => "\\beta ", - 'γ' => "\\gamma ", - 'δ' => "\\delta ", - 'ε' => "\\varepsilon ", - 'ϵ' => "\\epsilon ", - 'ζ' => "\\zeta ", - 'η' => "\\eta ", - 'θ' => "\\theta ", - 'ϑ' => "\\vartheta ", - 'ι' => "\\iota ", - 'κ' => "\\kappa ", - 'λ' => "\\lambda ", - 'μ' => "\\mu ", - 'ν' => "\\nu ", - 'ξ' => "\\xi ", - 'π' => "\\pi ", - 'ρ' => "\\rho ", - 'σ' => "\\sigma ", - 'τ' => "\\tau ", - 'υ' => "\\upsilon ", - 'φ' => "\\varphi ", - 'ϕ' => "\\phi ", - 'χ' => "\\chi ", - 'ψ' => "\\psi ", - 'ω' => "\\omega ", - 'Γ' => "\\Gamma ", - 'Δ' => "\\Delta ", - 'Θ' => "\\Theta ", - 'Λ' => "\\Lambda ", - 'Ξ' => "\\Xi ", - 'Π' => "\\Pi ", - 'Σ' => "\\Sigma ", - 'Υ' => "\\Upsilon ", - 'Φ' => "\\Phi ", - 'Ψ' => "\\Psi ", - 'Ω' => "\\Omega ", - '±' => "\\pm ", - '∓' => "\\mp ", - '×' => "\\times ", - '÷' => "\\div ", - '⋅' | '·' => "\\cdot ", - '−' => "-", - '≤' => "\\le ", - '≥' => "\\ge ", - '≠' => "\\ne ", - '≈' => "\\approx ", - '≡' => "\\equiv ", - '∼' => "\\sim ", - '∝' => "\\propto ", - '∞' => "\\infty ", - '∂' => "\\partial ", - '∇' => "\\nabla ", - '∀' => "\\forall ", - '∃' => "\\exists ", - '∈' => "\\in ", - '∉' => "\\notin ", - '⊂' => "\\subset ", - '⊆' => "\\subseteq ", - '⊃' => "\\supset ", - '∪' => "\\cup ", - '∩' => "\\cap ", - '∅' => "\\emptyset ", - '→' => "\\to ", - '←' => "\\leftarrow ", - '⇒' => "\\Rightarrow ", - '⇔' => "\\Leftrightarrow ", - '…' => "\\ldots ", - '⋯' => "\\cdots ", - '∘' => "\\circ ", - '{' => "\\{", - '}' => "\\}", - '%' => "\\%", - '#' => "\\#", - '&' => "\\&", - '$' => "\\$", - '_' => "\\_", - '\\' => "\\backslash ", - '~' => "\\sim ", - '^' => "\\hat{}", - _ => return None, - }) -} - -fn run_text(r: &El) -> String { - r.kids("t").map(|t| t.text.as_str()).collect() -} - -/// Appends `s` escaped for `\text{…}`; `None` once the LaTeX exceeds [`MAX_OUT_BYTES`], checked -/// after every character so that a long run never expands in full. -fn escape_text(s: &str, out: &mut String) -> Option<()> { - for c in s.chars() { - match c { - '{' | '}' | '%' | '#' | '&' | '$' | '_' => { - out.push('\\'); - out.push(c); - } - '\\' => out.push_str("\\textbackslash "), - '^' | '~' => out.push(' '), - c => out.push(c), - } - if out.len() > MAX_OUT_BYTES { - return None; - } - } - Some(()) -} - -/// Known operator names written upright in a run (`sin`, `log`, `lim`). -const FUNCTIONS: &[&str] = &[ - "sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan", "sinh", "cosh", "tanh", "log", "ln", "lg", "exp", "lim", "max", "min", - "sup", "inf", "det", "gcd", "deg", "dim", "ker", "arg", "Pr", "liminf", "limsup", -]; - -fn run(r: &El, out: &mut String) -> Option<()> { - let text = run_text(r); - if text.is_empty() { - return Some(()); - } - let rpr = r.child("rPr"); - if on(rpr, "nor") { - out.push_str("\\text{"); - escape_text(&text, out)?; - out.push('}'); - return Some(()); - } - let plain = val(rpr, "sty") == Some("p"); - if plain && FUNCTIONS.contains(&text.trim()) { - out.push('\\'); - out.push_str(text.trim()); - out.push(' '); - return Some(()); - } - let wrap = match (val(rpr, "scr"), val(rpr, "sty")) { - (Some("double-struck"), _) => Some("\\mathbb{"), - (Some("script"), _) => Some("\\mathcal{"), - (Some("fraktur"), _) => Some("\\mathfrak{"), - (Some("sans-serif"), _) => Some("\\mathsf{"), - (Some("monospace"), _) => Some("\\mathtt{"), - (_, Some("b")) => Some("\\mathbf{"), - (_, Some("bi")) => Some("\\boldsymbol{"), - (_, Some("p")) if text.chars().any(|c| c.is_alphabetic()) => Some("\\mathrm{"), - _ => None, - }; - if let Some(w) = wrap { - out.push_str(w); - } - for c in text.chars() { - match char_latex(c) { - Some(l) => out.push_str(l), - None => out.push(c), - } - // Checked per character, not from the run's byte length: a character may map to a - // longer macro or a shorter sign, so only the LaTeX produced counts. - if out.len() > MAX_OUT_BYTES { - return None; - } - } - if wrap.is_some() { - out.push('}'); - } - Some(()) -} - -/// A delimiter character as a `\left`/`\right` argument. -fn delim(c: Option<&str>, default: &str) -> String { - let c = c.unwrap_or(default); - match c { - "" => ".".into(), - "{" => "\\{".into(), - "}" => "\\}".into(), - "⟨" | "〈" => "\\langle".into(), - "⟩" | "〉" => "\\rangle".into(), - "⌊" => "\\lfloor".into(), - "⌋" => "\\rfloor".into(), - "⌈" => "\\lceil".into(), - "⌉" => "\\rceil".into(), - "‖" => "\\|".into(), - "∣" => "|".into(), - other => other.into(), - } -} - -fn nary_op(chr: &str) -> Option<&'static str> { - Some(match chr { - "∑" => "\\sum", - "∏" => "\\prod", - "∐" => "\\coprod", - "∫" => "\\int", - "∬" => "\\iint", - "∭" => "\\iiint", - "∮" => "\\oint", - "⋃" => "\\bigcup", - "⋂" => "\\bigcap", - "⋁" => "\\bigvee", - "⋀" => "\\bigwedge", - "⨁" => "\\bigoplus", - "⨂" => "\\bigotimes", - _ => return None, - }) -} - -fn accent(chr: &str) -> Option<&'static str> { - Some(match chr { - "\u{0302}" | "^" => "\\hat", - "\u{030C}" => "\\check", - "\u{0303}" | "~" => "\\tilde", - "\u{0301}" => "\\acute", - "\u{0300}" => "\\grave", - "\u{0307}" => "\\dot", - "\u{0308}" => "\\ddot", - "\u{0306}" => "\\breve", - "\u{0305}" | "\u{0304}" | "¯" => "\\bar", - "\u{20D7}" | "→" => "\\vec", - "\u{20D6}" => "\\overleftarrow", - "\u{030A}" => "\\mathring", - _ => return None, - }) -} - -fn node(e: &El, out: &mut String, depth: usize) -> Option<()> { - if depth > MAX_DEPTH { - return None; - } - match e.name.as_str() { - // Properties and run-level DrawingML are not content. - n if n.ends_with("Pr") => {} - "r" => run(e, out)?, - "f" => fraction(e, out, depth)?, - "rad" => radical(e, out, depth)?, - "sSup" | "sSub" | "sSubSup" => scripts(e, out, depth)?, - "nary" => nary(e, out, depth)?, - "d" => delimiters(e, out, depth)?, - "m" => matrix(e, out, depth)?, - "eqArr" => equation_array(e, out, depth)?, - "acc" => { - out.push_str(accent(val(e.child("accPr"), "chr").unwrap_or("\u{0302}"))?); - group(e.child("e"), out, depth)?; - } - "bar" => { - out.push_str(if val(e.child("barPr"), "pos") == Some("top") { "\\overline" } else { "\\underline" }); - group(e.child("e"), out, depth)?; - } - "groupChr" => group_char(e, out, depth)?, - "limLow" | "limUpp" => limit(e, out, depth)?, - "func" => { - seq(e.child("fName")?, out, depth)?; - out.push(' '); - group(e.child("e"), out, depth)?; - } - "borderBox" => { - out.push_str("\\boxed"); - group(e.child("e"), out, depth)?; - } - "phant" => { - out.push_str("\\phantom"); - group(e.child("e"), out, depth)?; - } - "box" => group(e.child("e"), out, depth)?, - _ => return None, - } - Some(()) -} - -/// `m:f`: a fraction, or a binomial-style stack without a bar. -fn fraction(e: &El, out: &mut String, depth: usize) -> Option<()> { - if val(e.child("fPr"), "type") == Some("noBar") { - out.push_str("\\genfrac{}{}{0pt}{}"); - } else { - out.push_str("\\frac"); - } - group(e.child("num"), out, depth)?; - group(e.child("den"), out, depth) -} - -/// `m:rad`: a square root, or a root with a degree. -fn radical(e: &El, out: &mut String, depth: usize) -> Option<()> { - let hide = on(e.child("radPr"), "degHide"); - match e.child("deg").filter(|d| !hide && !d.children.is_empty()) { - Some(d) => { - out.push_str("\\sqrt["); - seq(d, out, depth)?; - out.push(']'); - } - None => out.push_str("\\sqrt"), - } - group(e.child("e"), out, depth) -} - -/// `m:sSup`, `m:sSub`, `m:sSubSup`: a base with scripts. -fn scripts(e: &El, out: &mut String, depth: usize) -> Option<()> { - group(e.child("e"), out, depth)?; - if let Some(sub) = e.child("sub") { - out.push('_'); - group(Some(sub), out, depth)?; - } - if let Some(sup) = e.child("sup") { - out.push('^'); - group(Some(sup), out, depth)?; - } - Some(()) -} - -/// `m:nary`: a large operator with its limits and operand. -fn nary(e: &El, out: &mut String, depth: usize) -> Option<()> { - let p = e.child("naryPr"); - let op = nary_op(val(p, "chr").unwrap_or("∫"))?; - out.push_str(op); - if val(p, "limLoc") == Some("undOvr") && op.contains("int") { - out.push_str("\\limits"); - } - if !on(p, "subHide") { - out.push('_'); - group(e.child("sub"), out, depth)?; - } - if !on(p, "supHide") { - out.push('^'); - group(e.child("sup"), out, depth)?; - } - out.push(' '); - group(e.child("e"), out, depth) -} - -/// `m:d`: delimiters around one or more parts, with a separator between them. -fn delimiters(e: &El, out: &mut String, depth: usize) -> Option<()> { - let p = e.child("dPr"); - out.push_str("\\left"); - out.push_str(&delim(val(p, "begChr"), "(")); - out.push(' '); - let sep = delim(val(p, "sepChr"), "|"); - for (i, part) in e.kids("e").enumerate() { - if i > 0 { - out.push_str(" \\middle"); - out.push_str(&sep); - out.push(' '); - } - seq(part, out, depth)?; - } - out.push_str(" \\right"); - out.push_str(&delim(val(p, "endChr"), ")")); - Some(()) -} - -/// `m:m`: a matrix, row by row. -fn matrix(e: &El, out: &mut String, depth: usize) -> Option<()> { - out.push_str("\\begin{matrix}"); - for (i, row) in e.kids("mr").enumerate() { - if i > 0 { - out.push_str(" \\\\ "); - } - for (k, cell) in row.kids("e").enumerate() { - if k > 0 { - out.push_str(" & "); - } - seq(cell, out, depth)?; - } - } - out.push_str("\\end{matrix}"); - Some(()) -} - -/// `m:eqArr`: equations stacked one per row. -fn equation_array(e: &El, out: &mut String, depth: usize) -> Option<()> { - out.push_str("\\begin{gathered}"); - for (i, row) in e.kids("e").enumerate() { - if i > 0 { - out.push_str(" \\\\ "); - } - seq(row, out, depth)?; - } - out.push_str("\\end{gathered}"); - Some(()) -} - -/// Effective brace orientation, including the character default and its precedence over position. -fn group_char_is_over(e: &El) -> bool { - let p = e.child("groupChrPr"); - match val(p, "chr").unwrap_or("\u{23DF}") { - "\u{23DE}" => true, - "\u{23DF}" => false, - _ => val(p, "pos") == Some("top"), - } -} - -/// `m:groupChr`: a brace over or under its content. -fn group_char(e: &El, out: &mut String, depth: usize) -> Option<()> { - out.push_str(if group_char_is_over(e) { "\\overbrace" } else { "\\underbrace" }); - group(e.child("e"), out, depth) -} - -/// `m:limLow`, `m:limUpp`: a limit under or over its base. -fn limit(e: &El, out: &mut String, depth: usize) -> Option<()> { - let low = e.name == "limLow"; - let base = e.child("e"); - // A function name with a limit (lim, max) takes it as a subscript with \limits. - let base_is_fn = base.is_some_and(|b| { - let t: String = b.kids("r").map(run_text).collect(); - b.children.iter().all(|c| c.name == "r") && FUNCTIONS.contains(&t.trim()) - }); - // A brace alone under the limit is a labelled brace, as `gridcraft_math::to_omml` writes - // `\underbrace{x}_{n}` and `\overbrace{x}^{n}`: the label is the brace's own script, below - // for an underbrace and above for an overbrace. An opposite-side limit keeps its placement. - let brace = base - .and_then(|b| { - let mut content = b.children.iter().filter(|c| !c.name.ends_with("Pr")); - content.next().filter(|c| c.name == "groupChr" && content.next().is_none()) - }) - .filter(|brace| low != group_char_is_over(brace)); - if base_is_fn { - seq(base?, out, depth)?; - out.push_str(if low { "\\limits_" } else { "\\limits^" }); - group(e.child("lim"), out, depth)?; - } else if let Some(brace) = brace { - group_char(brace, out, depth + 1)?; - out.push(if low { '_' } else { '^' }); - group(e.child("lim"), out, depth)?; - } else { - out.push_str(if low { "\\underset" } else { "\\overset" }); - group(e.child("lim"), out, depth)?; - group(base, out, depth)?; - } - Some(()) -} - #[cfg(test)] mod tests { use super::*; @@ -685,13 +244,13 @@ mod tests { let sum = latex( "i=1ni", ); - assert_eq!(sum.as_deref(), Some("\\sum_{i=1}^{n} {i}")); + assert_eq!(sum.as_deref(), Some("\\sum\\limits_{i=1}^{n} {i}")); // An integral without a character, with hidden limits. assert_eq!(latex("f").as_deref(), Some("\\int {f}")); let m = latex( "1001", ); - assert_eq!(m.as_deref(), Some("\\left[ \\begin{matrix}1 & 0 \\\\ 0 & 1\\end{matrix} \\right]")); + assert_eq!(m.as_deref(), Some("\\left[\\begin{matrix}1&0\\\\0&1\\end{matrix}\\right]")); assert_eq!(latex("sinx").as_deref(), Some("\\sin x")); assert_eq!(latex("R").as_deref(), Some("\\mathbb{R}")); assert_eq!(latex("if {x}").as_deref(), Some("\\text{if \\{x\\}}")); @@ -703,9 +262,9 @@ mod tests { #[test] fn what_is_outside_the_subset_is_none() { - assert_eq!(latex(""), None); + assert_eq!(latex("").as_deref(), Some("{}_{}^{}{}")); assert_eq!(latex(""), None, "an empty equation is not maths"); - assert_eq!(latex(""), None); + assert_eq!(latex("").as_deref(), Some("☃ {}")); // Deep nesting stops instead of recursing without bound. let deep = format!("{}x{}", "".repeat(100), "".repeat(100)); assert_eq!(latex(&deep), None); @@ -719,22 +278,21 @@ mod tests { // refusing it, so the caller falls back to the writer's text in bounded time. let wide = el(&"x".repeat(100_000)); let start = std::time::Instant::now(); - assert_eq!(convert(&wide), None); assert_eq!(to_latex(&wide), None); assert!(start.elapsed() < std::time::Duration::from_secs(5), "{:?}", start.elapsed()); // One run whose text alone is past the cap is refused before it is escaped (each // backslash would otherwise grow to `\textbackslash `). - let long = el(&format!("{}", "\\".repeat(MAX_OUT_BYTES + 1))); - assert_eq!(convert(&long), None); + let long = el(&format!("{}", "\\".repeat(gridcraft_math::MAX_SOURCE_BYTES + 1))); + assert_eq!(to_latex(&long), None); // Groups count the braces they add even when no run adds text. - let groups = el(&"".repeat(MAX_OUT_BYTES / 2 + 1)); - assert_eq!(convert(&groups), None); + let groups = el(&"".repeat(gridcraft_math::MAX_SOURCE_BYTES / 2 + 1)); + assert_eq!(to_latex(&groups), None); // At the cap the equation still reads back, and the cap counts the LaTeX produced, not // the run's bytes: a minus sign (three bytes of UTF-8) becomes a one-byte `-`. - let at_cap = el(&"x".repeat(MAX_OUT_BYTES)); - assert_eq!(to_latex(&at_cap).map(|s| s.len()), Some(MAX_OUT_BYTES)); - let minus = el(&format!("{}", "\u{2212}".repeat(MAX_OUT_BYTES))); - assert_eq!(to_latex(&minus), Some("-".repeat(MAX_OUT_BYTES))); + let at_cap = el(&"x".repeat(gridcraft_math::MAX_SOURCE_BYTES)); + assert_eq!(to_latex(&at_cap).map(|s| s.len()), Some(gridcraft_math::MAX_SOURCE_BYTES)); + let minus = el(&format!("{}", "\u{2212}".repeat(gridcraft_math::MAX_SOURCE_BYTES))); + assert_eq!(to_latex(&minus), Some("-".repeat(gridcraft_math::MAX_SOURCE_BYTES))); } #[test] @@ -764,17 +322,17 @@ mod tests { #[test] fn a_limit_on_the_opposite_side_of_a_brace_keeps_its_placement() { - for (properties, brace, opposite, same, script) in [ - (r#""#, "underbrace", "limUpp", "limLow", '_'), - (r#""#, "overbrace", "limLow", "limUpp", '^'), - (r#""#, "underbrace", "limUpp", "limLow", '_'), - (r#""#, "overbrace", "limLow", "limUpp", '^'), + for (properties, brace, opposite, same) in [ + (r#""#, "overbrace", "limUpp", "limLow"), + (r#""#, "underbrace", "limLow", "limUpp"), + (r#""#, "overbrace", "limUpp", "limLow"), + (r#""#, "overbrace", "limLow", "limUpp"), ] { let base = format!("{properties}x"); let limit = |kind: &str| format!("{base}n"); - let placement = if opposite == "limLow" { "underset" } else { "overset" }; - assert_eq!(latex(&limit(opposite)), Some(format!("\\{placement}{{n}}{{\\{brace}{{x}}}}")), "{properties}"); - assert_eq!(latex(&limit(same)), Some(format!("\\{brace}{{x}}{script}{{n}}")), "{properties}"); + let script = |kind: &str| if kind == "limUpp" { '^' } else { '_' }; + assert_eq!(latex(&limit(opposite)), Some(format!("\\{brace}{{x}}{}{{n}}", script(opposite))), "{properties}"); + assert_eq!(latex(&limit(same)), Some(format!("\\{brace}{{x}}{}{{n}}", script(same))), "{properties}"); } } diff --git a/crates/xlsx/src/tests/equation_tests.rs b/crates/xlsx/src/tests/equation_tests.rs index 53867c125..f1b8fd561 100644 --- a/crates/xlsx/src/tests/equation_tests.rs +++ b/crates/xlsx/src/tests/equation_tests.rs @@ -210,7 +210,7 @@ fn a_marker_over_garbage_office_math_falls_back_without_panicking() { let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); let mut d = drawing(&parts); let (m0, m1) = (d.find("").unwrap(), d.find("").unwrap()); - d.replace_range(m0..m1 + "".len(), "junk"); + d.replace_range(m0..m1 + "".len(), "junk"); parts.insert(name.clone(), d.into_bytes()); let (back, _) = read_xlsx(&rezip(&parts)).unwrap(); let s = shapes(&back); @@ -233,17 +233,14 @@ fn office_math_outside_the_subset_reads_the_fallback() { let mut parts = unzip(&write_xlsx(&wb).unwrap()); let name = parts.keys().find(|k| k.starts_with("xl/drawings/drawing")).unwrap().clone(); let mut d = drawing(&parts); - // Another writer: no GridCraft source, Office Math the reader does not convert (a - // pre-subscript), and a fallback text box with its own text. + // Another writer: no GridCraft source, Office Math the reader does not convert, + // and a fallback text box with its own text. while let Some(a) = d.find(" descr=\"gridcraft:latex:") { let b = d[a + 8..].find('"').unwrap() + a + 9; d.replace_range(a..b, ""); } let (m0, m1) = (d.find("").unwrap(), d.find("").unwrap()); - d.replace_range( - m0..m1 + "".len(), - "12y", - ); + d.replace_range(m0..m1 + "".len(), "y"); let fb = d.find("").unwrap(); let t = d[fb..].find("x^2").unwrap() + fb; d.replace_range(t..t + "x^2".len(), "the writer's fallback");