use super::asvg::{read_entries, write_entries};
use crate::ConvertError;
#[derive(Debug, Clone)]
pub(crate) struct MathEmbed {
pub sentinel: String,
pub omml: String,
}
pub(crate) fn sentinel(id: usize) -> String {
format!("\u{E000}QDMATH{id}\u{E000}")
}
pub(crate) fn inject(docx: Vec<u8>, embeds: &[MathEmbed]) -> Result<Vec<u8>, ConvertError> {
if embeds.is_empty() {
return Ok(docx);
}
let mut entries = read_entries(&docx)?;
for (name, bytes) in entries.iter_mut() {
if name == "word/document.xml" {
let mut s = String::from_utf8_lossy(bytes).into_owned();
for e in embeds {
s = replace_run(&s, &e.sentinel, &e.omml);
}
*bytes = s.into_bytes();
}
}
write_entries(entries)
}
fn replace_run(doc: &str, sentinel: &str, omml: &str) -> String {
let Some(pos) = doc.find(sentinel) else {
return doc.to_string();
};
let before = &doc[..pos];
let Some(start) = before
.rfind("<w:r>")
.into_iter()
.chain(before.rfind("<w:r "))
.max()
else {
return doc.to_string();
};
let Some(rel_end) = doc[pos..].find("</w:r>") else {
return doc.to_string();
};
let end = pos + rel_end + "</w:r>".len();
let mut out = String::with_capacity(doc.len() - (end - start) + omml.len());
out.push_str(&doc[..start]);
out.push_str(omml);
out.push_str(&doc[end..]);
out
}