1use latexml_core::document::item_beside_phantoms;
8use libxml::tree::Node;
9use rustc_hash::FxHashMap as HashMap;
10
11use crate::{
12 document::{NodeData, PostDocument, element_children},
13 math_processor::{MathConversion, MathProcessor, math_is_parsed},
14 processor::{ProcessResult, Processor},
15};
16
17const OM_URI: &str = "http://www.openmath.org/OpenMath";
18const OM_MIMETYPE: &str = "application/openmath+xml";
19
20type OmConverter = fn(&PostDocument, &Node) -> NodeData;
22
23pub struct OpenMath {
27 name: String,
28 is_secondary: bool,
29 hack_plane1: bool,
30 plane1: bool,
31}
32
33impl Default for OpenMath {
34 fn default() -> Self { Self::new() }
35}
36
37impl OpenMath {
38 pub fn new() -> Self {
39 OpenMath {
40 name: "OpenMath".to_string(),
41 is_secondary: false,
42 hack_plane1: false,
43 plane1: true,
44 }
45 }
46}
47
48impl Processor for OpenMath {
49 fn get_name(&self) -> &str { &self.name }
50
51 fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
52 doc.findnodes("//ltx:Math[not(ancestor::ltx:Math)]")
53 }
54
55 fn process(&mut self, doc: PostDocument, _nodes: Vec<Node>) -> ProcessResult { Ok(vec![doc]) }
56}
57
58impl MathProcessor for OpenMath {
59 fn convert_node(&self, doc: &PostDocument, xmath: &Node) -> Option<MathConversion> {
60 let children = element_children(xmath);
61 let xml = if let Some(item) = item_beside_phantoms(xmath) {
63 om_expr(doc, &item)
64 } else if children.len() == 1 {
65 om_expr(doc, &children[0])
66 } else {
67 om_unparsed(doc, &children)
68 };
69
70 Some(MathConversion {
71 processor_name: self.name.clone(),
72 mimetype: Some(OM_MIMETYPE.to_string()),
73 xml: Some(xml),
74 string: None,
75 src: None,
76 width: None,
77 height: None,
78 depth: None,
79 })
80 }
81
82 fn combine_parallel(
83 &self,
84 _doc: &PostDocument,
85 _xmath: &Node,
86 primary: MathConversion,
87 secondaries: Vec<MathConversion>,
88 ) -> MathConversion {
89 let mut attr_children = Vec::new();
90
91 for secondary in &secondaries {
92 let mimetype = secondary.mimetype.as_deref().unwrap_or("unknown");
93 attr_children.push(NodeData::Element {
94 tag: "om:OMS".to_string(),
95 attributes: Some(HashMap::from_iter([
96 ("cd".to_string(), "Alternate".to_string()),
97 ("name".to_string(), mimetype.to_string()),
98 ])),
99 children: vec![],
100 });
101
102 if mimetype == OM_MIMETYPE {
103 if let Some(ref xml) = secondary.xml {
104 attr_children.push(xml.clone());
105 }
106 } else if let Some(ref xml) = secondary.xml {
107 attr_children.push(NodeData::Element {
108 tag: "om:OMFOREIGN".to_string(),
109 attributes: None,
110 children: vec![xml.clone()],
111 });
112 } else if let Some(ref string) = secondary.string {
113 attr_children.push(NodeData::Element {
114 tag: "om:OMSTR".to_string(),
115 attributes: None,
116 children: vec![NodeData::Text(string.clone())],
117 });
118 }
119 }
120
121 if let Some(ref xml) = primary.xml {
122 attr_children.push(xml.clone());
123 }
124
125 MathConversion {
126 processor_name: self.name.clone(),
127 mimetype: Some(OM_MIMETYPE.to_string()),
128 xml: Some(NodeData::Element {
129 tag: "om:OMATTR".to_string(),
130 attributes: None,
131 children: attr_children,
132 }),
133 string: None,
134 src: None,
135 width: None,
136 height: None,
137 depth: None,
138 }
139 }
140
141 fn outer_wrapper(&self, _doc: &PostDocument, _xmath: &Node, conversion: NodeData) -> NodeData {
142 NodeData::Element {
143 tag: "om:OMOBJ".to_string(),
144 attributes: None,
145 children: vec![conversion],
146 }
147 }
148
149 fn raw_id_suffix(&self) -> &str { ".om" }
150
151 fn is_secondary(&self) -> bool { self.is_secondary }
152
153 fn can_convert(&self, _doc: &PostDocument, math: &Node) -> bool { math_is_parsed(math) }
154
155 fn preprocess(&self, _doc: &PostDocument, _nodes: &[Node]) {
156 log::trace!("OpenMath: would register om namespace");
158 }
159}
160
161fn om_expr(doc: &PostDocument, node: &Node) -> NodeData {
168 let real_node = if doc.is_qname(node, "ltx:XMRef") {
170 if let Some(idref) = node.get_attribute("idref") {
171 doc.find_node_by_id(&idref).cloned()
172 } else {
173 None
174 }
175 } else {
176 Some(node.clone())
177 };
178
179 match real_node {
180 Some(ref n) => om_expr_aux(doc, n),
181 None => om_error("Missing Subexpression"),
182 }
183}
184
185fn om_expr_aux(doc: &PostDocument, node: &Node) -> NodeData {
189 let tag = match doc.get_qname(node) {
190 Some(t) => t,
191 None => return om_error("Missing Subexpression"),
192 };
193
194 match tag.as_str() {
195 "ltx:XMWrap" | "ltx:XMArg" => {
196 let children = element_children(node);
197 if let Some(item) = item_beside_phantoms(node) {
198 om_expr(doc, &item)
199 } else if children.len() == 1 {
200 om_expr(doc, &children[0])
201 } else {
202 om_unparsed(doc, &children)
203 }
204 },
205 "ltx:XMDual" => {
206 let children = element_children(node);
207 if !children.is_empty() {
208 om_expr(doc, &children[0]) } else {
210 om_error("Empty XMDual")
211 }
212 },
213 "ltx:XMApp" => {
214 let children = element_children(node);
215 if children.is_empty() {
216 return om_error("Missing Operator");
217 }
218 let mut oma_children = Vec::new();
220 for child in &children {
221 oma_children.push(om_expr(doc, child));
222 }
223 NodeData::Element {
224 tag: "om:OMA".to_string(),
225 attributes: None,
226 children: oma_children,
227 }
228 },
229 "ltx:XMTok" => {
230 if let Some(meaning) = node.get_attribute("meaning") {
231 let cd = node
232 .get_attribute("omcd")
233 .unwrap_or_else(|| "latexml".to_string());
234 NodeData::Element {
235 tag: "om:OMS".to_string(),
236 attributes: Some(HashMap::from_iter([
237 ("name".to_string(), meaning),
238 ("cd".to_string(), cd),
239 ])),
240 children: vec![],
241 }
242 } else {
243 let name = node.get_content();
245 let name = if name.trim().is_empty() {
246 node
247 .get_attribute("name")
248 .unwrap_or_else(|| "?".to_string())
249 } else {
250 name
251 };
252 NodeData::Element {
253 tag: "om:OMV".to_string(),
254 attributes: Some(HashMap::from_iter([("name".to_string(), name)])),
255 children: vec![],
256 }
257 }
258 },
259 "ltx:XMHint" => {
260 NodeData::Text(String::new())
262 },
263 "ltx:XMText" => {
264 let text = node.get_content();
265 NodeData::Element {
266 tag: "om:OMSTR".to_string(),
267 attributes: None,
268 children: vec![NodeData::Text(text)],
269 }
270 },
271 _ => {
272 let text = node.get_content();
273 NodeData::Element {
274 tag: "om:OMSTR".to_string(),
275 attributes: None,
276 children: vec![NodeData::Text(text)],
277 }
278 },
279 }
280}
281
282fn om_unparsed(doc: &PostDocument, nodes: &[Node]) -> NodeData {
284 if nodes.is_empty() {
285 return om_error("Missing Subexpression");
286 }
287
288 let mut children = vec![NodeData::Element {
289 tag: "om:OMS".to_string(),
290 attributes: Some(HashMap::from_iter([
291 ("cd".to_string(), "ambiguous".to_string()),
292 ("name".to_string(), "fragments".to_string()),
293 ])),
294 children: vec![],
295 }];
296
297 for node in nodes {
298 let tag = doc.get_qname(node).unwrap_or_default();
299 if tag == "ltx:XMHint" {
300 continue;
301 }
302 children.push(om_expr_aux(doc, node));
303 }
304
305 NodeData::Element {
306 tag: "om:OME".to_string(),
307 attributes: None,
308 children,
309 }
310}
311
312fn om_error(msg: &str) -> NodeData {
314 NodeData::Element {
315 tag: "om:OME".to_string(),
316 attributes: None,
317 children: vec![
318 NodeData::Element {
319 tag: "om:OMS".to_string(),
320 attributes: Some(HashMap::from_iter([
321 ("name".to_string(), "unexpected".to_string()),
322 ("cd".to_string(), "moreerrors".to_string()),
323 ])),
324 children: vec![],
325 },
326 NodeData::Element {
327 tag: "om:OMSTR".to_string(),
328 attributes: None,
329 children: vec![NodeData::Text(msg.to_string())],
330 },
331 ],
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 #[test]
340 fn openmath_new_has_default_name() {
341 let o = OpenMath::new();
342 assert_eq!(o.get_name(), "OpenMath");
343 assert!(!o.is_secondary);
344 assert!(!o.hack_plane1);
345 assert!(o.plane1, "plane1 defaults to true");
346 }
347
348 #[test]
349 fn openmath_default_matches_new() {
350 let a = OpenMath::default();
351 let b = OpenMath::new();
352 assert_eq!(a.get_name(), b.get_name());
353 assert_eq!(a.is_secondary, b.is_secondary);
354 assert_eq!(a.plane1, b.plane1);
355 assert_eq!(a.hack_plane1, b.hack_plane1);
356 }
357
358 #[test]
359 fn openmath_raw_id_suffix() {
360 let o = OpenMath::new();
361 assert_eq!(o.raw_id_suffix(), ".om");
362 }
363
364 #[test]
365 fn openmath_is_secondary_false_by_default() {
366 let o = OpenMath::new();
367 assert!(!o.is_secondary());
368 }
369
370 #[test]
371 fn om_constants() {
372 assert_eq!(OM_URI, "http://www.openmath.org/OpenMath");
373 assert_eq!(OM_MIMETYPE, "application/openmath+xml");
374 }
375}