mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 10:18:05 +00:00
craft-math, craft-docx: keep an equation's kept OMML only when it is one well-formed m:oMath (port of wordcraft#6081)
write_equation writes Math::omml verbatim into the host document once a check passes, and documents saved as JSON carry that field, so a JSON → .docx conversion could write a document.xml that isn't well-formed, or any WordprocessingML verbatim. craft-math's check was a strict craft-xml read of text starting with <m:oMath, which already refuses unclosed and mismatched tags, unknown entities and trailing markup, but let through: an m:oMathPara (nested in a second one), an m: bound to another namespace, names that aren't XML names, undeclared prefixes, two attributes with one expanded name, a < in an attribute value, ]]> in text, and characters XML 1.0 doesn't allow. The kept XML is now written only when it starts with <m:oMath> (not m:oMathPara), passes the strict read (which also bounds the nesting), and then parses with roxmltree, a conforming parser, as exactly one element that is m:oMath by namespace. The canonical prefixes of kept OMML (m:, w:, mc:) are declared for that parse, as craft-math already documents them and the .docx root declares them; any other prefix is undeclared there. Otherwise the equation is written from its nodes. In craft-docx, Flat OPC's one_element (the gate for inlining kept bytes as pkg:xmlData) now also requires XML names and attribute values that unescape, as in the WordCraft PR. Ported from storytold/wordcraft#6081 (issue wordcraft#6072). The check differs from the PR's in where it lives: the PR combined flat::one_element, parse_strict and roxmltree in the DOCX writer, over the OMML wrapped in every namespace document.xml declares. Here the writer is in craft-math, which doesn't know the host's namespaces, so it declares the three canonical ones. Its tests go into craft-docx's integration tests (tests/it/kept_omml_check.rs), with only the crate names changed; all 22 malformed cases fail without this commit except the 11 craft-math already refused. roxmltree 0.21 is already in the lock as a dependency of other crates. Checked on the 72 .docx files with equations from earlier Word probes (488 equations with kept OMML, 35 files saved by Word): the same equations are written back verbatim as before, except one empty <m:oMath/> in a hand-made repro file, which is now written from its (empty) nodes.
This commit is contained in:
Generated
+1
@@ -1710,6 +1710,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-xml",
|
||||
"proptest",
|
||||
"roxmltree 0.21.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
+35
-1
@@ -448,7 +448,13 @@ fn one_element(s: &str) -> bool {
|
||||
r.config_mut().check_comments = true;
|
||||
let (mut depth, mut roots) = (0usize, 0usize);
|
||||
loop {
|
||||
let attrs_ok = |e: &BytesStart| e.attributes().all(|a| a.is_ok());
|
||||
// Each attribute parses and its value unescapes: an undeclared entity (`x="&no;"`) isn't
|
||||
// well-formed, and the reader would keep it raw (#6072).
|
||||
// Names must be XML names too: the reader takes `<a?b>` and `x?="1"` without complaint.
|
||||
let attrs_ok = |e: &BytesStart| {
|
||||
is_qname(e.name().as_ref())
|
||||
&& e.attributes().all(|a| a.is_ok_and(|a| is_qname(a.key.as_ref()) && a.normalized_value(quick_xml::XmlVersion::Explicit1_0).is_ok()))
|
||||
};
|
||||
match r.read_event() {
|
||||
Ok(Event::Start(e)) => {
|
||||
if !attrs_ok(&e) || (depth == 0 && roots > 0) {
|
||||
@@ -480,6 +486,28 @@ fn one_element(s: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `name` is an XML name with at most one colon, neither first nor last: a qualified name
|
||||
/// in Namespaces in XML 1.0 (§4), with the name characters of XML 1.0 (Fifth Edition) §2.3.
|
||||
fn is_qname(name: &[u8]) -> bool {
|
||||
fn start(c: char) -> bool {
|
||||
matches!(c, 'A'..='Z' | '_' | 'a'..='z' | '\u{C0}'..='\u{D6}' | '\u{D8}'..='\u{F6}' | '\u{F8}'..='\u{2FF}' | '\u{370}'..='\u{37D}'
|
||||
| '\u{37F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}' | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}'
|
||||
| '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}' | '\u{10000}'..='\u{EFFFF}')
|
||||
}
|
||||
fn more(c: char) -> bool {
|
||||
start(c) || matches!(c, '-' | '.' | '0'..='9' | '\u{B7}' | '\u{300}'..='\u{36F}' | '\u{203F}'..='\u{2040}')
|
||||
}
|
||||
let ncname = |p: &str| {
|
||||
let mut cs = p.chars();
|
||||
cs.next().is_some_and(start) && cs.all(more)
|
||||
};
|
||||
let Ok(name) = std::str::from_utf8(name) else { return false };
|
||||
match name.split_once(':') {
|
||||
Some((prefix, local)) => ncname(prefix) && ncname(local),
|
||||
None => ncname(name),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -587,6 +615,12 @@ mod tests {
|
||||
"<a></a></pkg:xmlData>",
|
||||
"<a><!-- x -- y --></a>",
|
||||
"<a/><!-- x--->",
|
||||
"<a x=\"&no;\"/>",
|
||||
"<a><b x=\"&no;\"/></a>",
|
||||
"<a?b/>",
|
||||
"<a x?=\"1\"/>",
|
||||
"<a><b:c:d/></a>",
|
||||
"<a :x=\"1\"/>",
|
||||
] {
|
||||
assert!(xml_fragment(ct, bad.as_bytes()).is_none(), "{bad}");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! An equation's kept source OMML is written back verbatim only when it is exactly one well-formed
|
||||
//! `m:oMath` (#6072). `Math::omml` also comes from `.json` documents, so anything else must not
|
||||
//! reach `document.xml`: it is written from the equation's nodes instead.
|
||||
|
||||
use craft_math::math::{MNode, MRun, Math};
|
||||
use craft_wordmodel::para::{InlineObject, OBJ};
|
||||
use craft_wordmodel::props::CharProps;
|
||||
use craft_wordmodel::{Document, Paragraph, para_block};
|
||||
|
||||
/// Save a one-equation document whose equation keeps `omml` and has the nodes `NODES`.
|
||||
fn save(omml: &str, display: bool) -> (String, Document) {
|
||||
let math = Math { nodes: vec![MNode::Run(MRun::new("NODES"))], omml: omml.into(), ..Default::default() };
|
||||
let mut p = Paragraph::new();
|
||||
p.insert_object(0, InlineObject::Equation { linear: "NODES".into(), display, math }, &CharProps::default()).unwrap();
|
||||
let mut doc = Document::new();
|
||||
doc.body = vec![para_block(p)];
|
||||
let bytes = craft_docx::write(&doc).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
|
||||
let mut xml = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("word/document.xml").unwrap(), &mut xml).unwrap();
|
||||
// The saved file must open again (the main part is read strictly).
|
||||
let back = craft_docx::read(&bytes).unwrap_or_else(|e| panic!("{omml:?} doesn't reopen: {e}"));
|
||||
(xml, back)
|
||||
}
|
||||
|
||||
/// The text of the reopened document's equations and paragraphs.
|
||||
fn texts(doc: &Document) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
for b in &doc.body {
|
||||
let Some(p) = b.as_para() else { continue };
|
||||
for o in &p.objects {
|
||||
if let InlineObject::Equation { math, .. } = o {
|
||||
out.push(craft_math::math::to_linear(&math.nodes));
|
||||
}
|
||||
}
|
||||
let text: String = p.text.chars().filter(|c| *c != OBJ).collect();
|
||||
if !text.trim().is_empty() {
|
||||
out.push(text);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn well_formed_kept_omml_is_written_back_unchanged() {
|
||||
let kept = "<m:oMath><m:r><m:t>KEPT</m:t></m:r></m:oMath>";
|
||||
let (xml, back) = save(kept, false);
|
||||
assert!(xml.contains(kept), "{xml}");
|
||||
assert_eq!(texts(&back), vec!["KEPT".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_kept_omml_is_written_from_the_nodes() {
|
||||
for kept in [
|
||||
// Unclosed, mismatched, an undefined entity.
|
||||
"<m:oMath><m:r>",
|
||||
"<m:oMath></m:r>",
|
||||
"<m:oMath><m:r><m:t>&bad;</m:t></m:r></m:oMath>",
|
||||
// Markup after the element, text after it, a second element.
|
||||
"<m:oMath></m:oMath></w:p><w:p><w:r><w:t>INJECTED</w:t></w:r></w:p><w:p>",
|
||||
"<m:oMath></m:oMath>INJECTED",
|
||||
"<m:oMath></m:oMath><w:r><w:t>INJECTED</w:t></w:r>",
|
||||
// Not an m:oMath.
|
||||
"<m:r><m:t>INJECTED</m:t></m:r>",
|
||||
// An m:oMath in another namespace, and an unknown entity in an attribute.
|
||||
"<m:oMath xmlns:m=\"urn:other\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
"<m:oMath><m:r bad=\"&missing;\"><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
// Names that aren't XML names, and prefixes that aren't declared.
|
||||
"<m:oMath bad?=\"1\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
"<m:oMath><m:r><m:t a:b:c=\"1\">INJECTED</m:t></m:r></m:oMath>",
|
||||
"<m:oMath><m:r><m:t>INJECTED</m:t></m:r><m:r?/></m:oMath>",
|
||||
"<m:oMath missing:x=\"1\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
"<m:oMath><missing:r><m:t>INJECTED</m:t></missing:r></m:oMath>",
|
||||
// Two attributes with one expanded name (Namespaces in XML §6.3).
|
||||
"<m:oMath xmlns:p=\"urn:x\" xmlns:q=\"urn:x\" p:a=\"1\" q:a=\"2\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
// A `<` in an attribute value, `]]>` in text.
|
||||
"<m:oMath bad=\"<\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
"<m:oMath><m:r><m:t>INJECTED]]></m:t></m:r></m:oMath>",
|
||||
// Characters XML 1.0 doesn't allow, as references or as they are.
|
||||
"<m:oMath bad=\"\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
"<m:oMath><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
"<m:oMath><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
"<m:oMath bad=\"\u{1}\"><m:r><m:t>INJECTED</m:t></m:r></m:oMath>",
|
||||
"<m:oMath><m:r><m:t>INJECTED\u{1}</m:t></m:r></m:oMath>",
|
||||
] {
|
||||
let (xml, back) = save(kept, false);
|
||||
assert!(!xml.contains("INJECTED") && !xml.contains("&bad;"), "{kept:?} was written: {xml}");
|
||||
assert_eq!(texts(&back), vec!["NODES".to_string()], "{kept:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_omath_para_is_not_nested_in_another() {
|
||||
let kept = "<m:oMathPara><m:oMath><m:r><m:t>P</m:t></m:r></m:oMath></m:oMathPara>";
|
||||
let (xml, back) = save(kept, true);
|
||||
assert!(!xml.contains("<m:oMathPara><m:oMathPara>"), "{xml}");
|
||||
assert_eq!(texts(&back), vec!["NODES".to_string()]);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ mod emphasis_marks;
|
||||
mod fixtures;
|
||||
mod glossary;
|
||||
mod heading_levels;
|
||||
mod kept_omml_check;
|
||||
mod legacy_forms;
|
||||
mod ligatures;
|
||||
mod line_numbering;
|
||||
|
||||
@@ -12,6 +12,9 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-xml = { workspace = true }
|
||||
# A conforming XML parser (names, namespaces, characters), for checking kept OMML before it is
|
||||
# written verbatim; already in the lock as a dependency of other crates.
|
||||
roxmltree = "0.21"
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
+20
-2
@@ -58,9 +58,27 @@ fn parse_kept(xml: &str) -> Option<El> {
|
||||
Options { ns_decls: false, ..Options::default() }.with_limits(limits).parse(xml.as_bytes()).ok()
|
||||
}
|
||||
|
||||
/// Is `xml` (kept OMML) well-formed enough to write back as it is?
|
||||
/// Whether `xml` (kept OMML) can be written back as it is: exactly one well-formed `m:oMath` (not
|
||||
/// `m:oMathPara`), with nothing around it. The writer copies it verbatim into the host document,
|
||||
/// and [`Math::omml`] also comes from documents saved as JSON, so anything else (an unclosed or
|
||||
/// mismatched tag, an unknown entity, markup or text after the element, an `m:oMathPara` that
|
||||
/// would be nested in a second one) is written from the nodes instead (wordcraft#6072).
|
||||
///
|
||||
/// The strict [`craft_xml`] read bounds the nesting and rejects bad tags, entities and trailing
|
||||
/// content, but it is lenient about the rest of XML: names that aren't XML names, undeclared
|
||||
/// prefixes, two attributes with one expanded name, a `<` in an attribute value, `]]>` in text,
|
||||
/// characters XML 1.0 doesn't allow. A conforming parser rejects all of those, so it runs last,
|
||||
/// with only the canonical prefixes of kept OMML declared (`m:`, `w:`, `mc:`, as the host
|
||||
/// 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 {
|
||||
xml.starts_with("<m:oMath") && Options::default().strict().parse(xml.as_bytes()).is_ok()
|
||||
if !(xml.starts_with("<m:oMath>") || xml.starts_with("<m:oMath ")) || 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>");
|
||||
let Ok(doc) = roxmltree::Document::parse(&wrapped) else { return false };
|
||||
let mut nodes = doc.root_element().children();
|
||||
matches!((nodes.next(), nodes.next()), (Some(e), None) if e.tag_name().namespace() == Some(MATH_NS) && e.tag_name().name() == "oMath")
|
||||
}
|
||||
|
||||
/// An equation from OMML text ([`parse`]): an `m:oMathPara`'s first `m:oMath` with the
|
||||
|
||||
@@ -44,7 +44,7 @@ pub fn write_equation(w: &mut W, linear: &str, display: bool, math: &Math, color
|
||||
w.close("m:oMathParaPr");
|
||||
}
|
||||
}
|
||||
if !math.omml.is_empty() && math.omml.starts_with("<m:oMath") && is_well_formed(&math.omml) {
|
||||
if is_well_formed(&math.omml) {
|
||||
w.raw(&math.omml);
|
||||
} else {
|
||||
let parsed;
|
||||
|
||||
Reference in New Issue
Block a user