1use libxml::tree::Node;
16use rustc_hash::FxHashMap as HashMap;
17
18use crate::document::{NodeData, PostDocument, element_children};
19
20pub(crate) fn meaning_to_cmml_element_pub(meaning: &str) -> Option<&'static str> {
25 meaning_to_cmml_element(meaning)
26}
27
28fn meaning_to_cmml_element(meaning: &str) -> Option<&'static str> {
29 match meaning {
30 "plus" => Some("m:plus"),
32 "minus" | "uminus" => Some("m:minus"),
33 "times" => Some("m:times"),
34 "divide" => Some("m:divide"),
35 "power" => Some("m:power"),
36 "quotient" => Some("m:quotient"),
37 "factorial" => Some("m:factorial"),
38 "remainder" => Some("m:rem"),
39 "maximum" => Some("m:max"),
40 "minimum" => Some("m:min"),
41 "gcd" => Some("m:gcd"),
42 "lcm" => Some("m:lcm"),
43 "absolute-value" => Some("m:abs"),
44 "conjugate" => Some("m:conjugate"),
45 "argument" => Some("m:arg"),
46 "real-part" => Some("m:real"),
47 "imaginary-part" => Some("m:imaginary"),
48 "floor" => Some("m:floor"),
49 "ceiling" => Some("m:ceiling"),
50 "and" => Some("m:and"),
52 "or" => Some("m:or"),
53 "xor" => Some("m:xor"),
54 "not" => Some("m:not"),
55 "implies" => Some("m:implies"),
56 "forall" => Some("m:forall"),
57 "exists" => Some("m:exists"),
58 "equals" => Some("m:eq"),
60 "not-equals" => Some("m:neq"),
61 "greater-than" => Some("m:gt"),
62 "less-than" => Some("m:lt"),
63 "greater-than-or-equals" => Some("m:geq"),
64 "less-than-or-equals" => Some("m:leq"),
65 "equivalent-to" => Some("m:equivalent"),
66 "approximately-equals" => Some("m:approx"),
67 "factor-of" => Some("m:factorof"),
68 "integral" => Some("m:int"),
70 "differential" => Some("m:diff"),
71 "partial-differential" => Some("m:partialdiff"),
72 "divergence" => Some("m:divergence"),
73 "gradient" => Some("m:grad"),
74 "curl" => Some("m:curl"),
75 "laplacian" => Some("m:laplacian"),
76 "union" => Some("m:union"),
78 "intersection" => Some("m:intersect"),
79 "element-of" => Some("m:in"),
80 "not-element-of" => Some("m:notin"),
81 "subset-of" | "subset-of-or-equals" => Some("m:subset"),
82 "subset-of-and-not-equals" => Some("m:prsubset"),
83 "set-minus" => Some("m:setdiff"),
84 "cardinality" => Some("m:card"),
85 "cartesian-product" => Some("m:cartesianproduct"),
86 "sum" => Some("m:sum"),
88 "prod" => Some("m:prod"),
89 "limit" => Some("m:limit"),
90 "tends-to" => Some("m:tendsto"),
91 "exponential" => Some("m:exp"),
93 "natural-logarithm" => Some("m:ln"),
94 "logarithm" => Some("m:log"),
95 "sine" => Some("m:sin"),
96 "cosine" => Some("m:cos"),
97 "tangent" => Some("m:tan"),
98 "secant" => Some("m:sec"),
99 "cosecant" => Some("m:csc"),
100 "cotangent" => Some("m:cot"),
101 "hyperbolic-sine" => Some("m:sinh"),
102 "hyperbolic-cosine" => Some("m:cosh"),
103 "hyperbolic-tangent" => Some("m:tanh"),
104 "hyperbolic-secant" => Some("m:sech"),
105 "hyperbolic-cosecant" => Some("m:csch"),
106 "hyperbolic-cotantent" => Some("m:coth"),
107 "inverse-sine" => Some("m:arcsin"),
108 "inverse-cosine" => Some("m:arccos"),
109 "inverse-tangent" => Some("m:arctan"),
110 "inverse-secant" => Some("m:arcsec"),
111 "inverse-cosecant" => Some("m:arccsc"),
112 "inverse-cotangent" => Some("m:arccot"),
113 "inverse-hyperbolic-sine" => Some("m:arcsinh"),
114 "inverse-hyperbolic-cosine" => Some("m:arccosh"),
115 "inverse-hyperbolic-tangent" => Some("m:arctanh"),
116 "inverse-hyperbolic-secant" => Some("m:arcsech"),
117 "inverse-hyperbolic-cosecant" => Some("m:arccsch"),
118 "inverse-hyperbolic-cotangent" => Some("m:arccoth"),
119 "mean" => Some("m:mean"),
121 "standard-deviation" => Some("m:sdev"),
122 "variance" => Some("m:var"),
123 "median" => Some("m:median"),
124 "mode" => Some("m:mode"),
125 "moment" => Some("m:moment"),
126 "determinant" => Some("m:determinant"),
128 "transpose" => Some("m:transpose"),
129 "selector" => Some("m:selector"),
130 "vector-product" => Some("m:vectorproduct"),
131 "scalar-product" => Some("m:scalarproduct"),
132 "outer-product" => Some("m:outerproduct"),
133 "integers" => Some("m:integers"),
135 "reals" => Some("m:reals"),
136 "rationals" => Some("m:rationals"),
137 "numbers" => Some("m:naturalnumbers"),
138 "complexes" => Some("m:complexes"),
139 "primes" => Some("m:primes"),
140 "exponential-e" => Some("m:exponentiale"),
141 "imaginary-i" => Some("m:imaginaryi"),
142 "notanumber" => Some("m:notanumber"),
143 "true" => Some("m:true"),
144 "false" => Some("m:false"),
145 "empty-set" => Some("m:emptyset"),
146 "circular-pi" => Some("m:pi"),
147 "Euler-constant" => Some("m:eulergamma"),
148 "infinity" => Some("m:infinity"),
149 "inverse" => Some("m:inverse"),
151 "lambda" => Some("m:lambda"),
152 "compose" => Some("m:compose"),
153 "identity" => Some("m:ident"),
154 "domain" => Some("m:domain"),
155 "codomain" => Some("m:codomain"),
156 "image" => Some("m:image"),
157 "square-root" => Some("m:root"),
158 _ => None,
159 }
160}
161
162pub fn convert_to_cmml(doc: &PostDocument, xmath: &Node) -> NodeData {
166 reset_share_counter();
167 super::presentation::bind_cmml_top_context(doc, xmath);
169 CMML_DEPTH.with(|d| d.set(0));
170 CMML_PATH.with(|p| p.borrow_mut().clear());
171 cmml_contents(doc, xmath)
172}
173
174const CMML_MAX_DEPTH: u32 = 256;
193thread_local! {
194 static CMML_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
195 static CMML_PATH: std::cell::RefCell<rustc_hash::FxHashSet<usize>>
196 = std::cell::RefCell::new(rustc_hash::FxHashSet::default());
197}
198
199enum CmmlEnter {
200 Ok,
201 DepthExceeded,
202 Cycle,
203}
204
205fn cmml_enter(node: &Node) -> CmmlEnter {
206 let ptr = node.node_ptr() as usize;
207 let in_path = CMML_PATH.with(|p| !p.borrow_mut().insert(ptr));
208 if in_path {
209 if std::env::var_os("LATEXML_CMML_TRACE_CYCLE").is_some() {
215 let id = node
216 .get_attribute("xml:id")
217 .or_else(|| node.get_attribute("id"))
218 .unwrap_or_else(|| format!("({})", node.get_name()));
219 eprintln!("cmml_cycle: re-entering {} ptr=0x{:x}", id, ptr);
220 }
221 return CmmlEnter::Cycle;
222 }
223 CMML_DEPTH.with(|d| {
224 let cur = d.get();
225 if cur >= CMML_MAX_DEPTH {
226 CMML_PATH.with(|p| {
228 p.borrow_mut().remove(&ptr);
229 });
230 CmmlEnter::DepthExceeded
231 } else {
232 d.set(cur + 1);
233 CmmlEnter::Ok
234 }
235 })
236}
237
238fn cmml_exit(node: &Node) {
239 CMML_PATH.with(|p| {
240 p.borrow_mut().remove(&(node.node_ptr() as usize));
241 });
242 CMML_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
243}
244
245fn cmml_contents(doc: &PostDocument, node: &Node) -> NodeData {
249 if let Some(item) = latexml_core::document::item_beside_phantoms(node) {
251 return cmml(doc, &item);
252 }
253 let children = element_children(node);
254 if children.is_empty() {
255 cmml_error("missing-subexpression")
256 } else if children.len() == 1 {
257 cmml(doc, &children[0])
258 } else {
259 cmml_unparsed(doc, &children)
260 }
261}
262
263fn cmml(doc: &PostDocument, node: &Node) -> NodeData {
267 match cmml_enter(node) {
268 CmmlEnter::Cycle => return cmml_error("cycle"),
269 CmmlEnter::DepthExceeded => return cmml_error("recursion-depth-exceeded"),
270 CmmlEnter::Ok => {},
271 }
272 let result = cmml_impl(doc, node);
273 cmml_exit(node);
274 result
275}
276
277fn cmml_impl(doc: &PostDocument, node: &Node) -> NodeData {
278 let tag = doc.get_qname(node).unwrap_or_default();
279
280 if tag == "ltx:XMRef" {
282 if let Some(idref) = node.get_attribute("idref") {
283 if let Some(target) = doc.find_node_by_id(&idref) {
284 return cmml(doc, target);
285 }
286 }
287 return cmml_error("unresolved-reference");
288 }
289
290 match tag.as_str() {
291 "ltx:XMDual" => {
292 let children = element_children(node);
293 if !children.is_empty() {
294 cmml(doc, &children[0]) } else {
296 cmml_error("empty-dual")
297 }
298 },
299 "ltx:XMWrap" | "ltx:XMArg" => cmml_contents(doc, node),
300 "ltx:XMApp" => {
301 if let Some(meaning) = node.get_attribute("meaning") {
303 return cmml_token_by_meaning(&meaning, node);
304 }
305 if node.with_attribute(c"role", |v| v == "ID") == Some(true) {
307 return cmml_decorated_symbol(doc, node);
308 }
309 let children = element_children(node);
311 if children.is_empty() {
312 return cmml_error("missing-operator");
313 }
314 let op = &children[0];
315 let args = &children[1..];
316
317 let rop = if doc.is_qname(op, "ltx:XMRef") {
319 op.get_attribute("idref")
320 .and_then(|id| doc.find_node_by_id(&id).cloned())
321 .unwrap_or_else(|| op.clone())
322 } else {
323 op.clone()
324 };
325
326 let meaning = rop.get_attribute("meaning").unwrap_or_default();
327 let _role = rop.get_attribute("role").unwrap_or_default();
328
329 match meaning.as_str() {
331 "multirelation" if !args.is_empty() => {
335 let lhs0 = cmml(doc, &args[0]);
336 if args.len() == 1 {
337 return lhs0;
338 }
339 let mut lhs = lhs0;
340 let mut relations = Vec::new();
341 let mut i = 1;
342 while i < args.len() {
343 let rel = &args[i];
344 let Some(rhs) = args.get(i + 1) else { break };
345 relations.push(NodeData::Element {
346 tag: "m:apply".to_string(),
347 attributes: None,
348 children: vec![cmml(doc, rel), lhs, cmml_shared(doc, rhs)],
349 });
350 lhs = cmml_share(rhs);
351 i += 2;
352 }
353 if relations.len() > 1 {
354 let mut children = vec![NodeData::Element {
355 tag: "m:and".to_string(),
356 attributes: None,
357 children: vec![],
358 }];
359 children.extend(relations);
360 NodeData::Element {
361 tag: "m:apply".to_string(),
362 attributes: None,
363 children,
364 }
365 } else {
366 relations
367 .pop()
368 .unwrap_or_else(|| cmml_error("multirelation"))
369 }
370 },
371 "less-than-or-approximately-equals" if !args.is_empty() => {
375 let first: Vec<NodeData> = args.iter().map(|a| cmml_shared(doc, a)).collect();
376 let second: Vec<NodeData> = args.iter().map(cmml_share).collect();
377 let mk = |op: &str, ops: Vec<NodeData>| {
378 let mut children = vec![NodeData::Element {
379 tag: op.to_string(),
380 attributes: None,
381 children: vec![],
382 }];
383 children.extend(ops);
384 NodeData::Element {
385 tag: "m:apply".to_string(),
386 attributes: None,
387 children,
388 }
389 };
390 NodeData::Element {
391 tag: "m:or".to_string(),
392 attributes: None,
393 children: vec![mk("m:lt", first), mk("m:approx", second)],
394 }
395 },
396 "square-root" if !args.is_empty() => NodeData::Element {
397 tag: "m:apply".to_string(),
398 attributes: None,
399 children: vec![
400 NodeData::Element {
401 tag: "m:root".to_string(),
402 attributes: None,
403 children: vec![],
404 },
405 cmml(doc, &args[0]),
406 ],
407 },
408 "nth-root" if args.len() >= 2 => NodeData::Element {
409 tag: "m:apply".to_string(),
410 attributes: None,
411 children: vec![
412 NodeData::Element {
413 tag: "m:root".to_string(),
414 attributes: None,
415 children: vec![],
416 },
417 NodeData::Element {
418 tag: "m:degree".to_string(),
419 attributes: None,
420 children: vec![cmml(doc, &args[0])],
422 },
423 cmml(doc, &args[1]),
424 ],
425 },
426 "set" => {
427 let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
428 NodeData::Element {
429 tag: "m:set".to_string(),
430 attributes: None,
431 children: items,
432 }
433 },
434 "list" => {
435 let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
436 NodeData::Element {
437 tag: "m:list".to_string(),
438 attributes: None,
439 children: items,
440 }
441 },
442 "vector" => {
443 let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
444 NodeData::Element {
445 tag: "m:vector".to_string(),
446 attributes: None,
447 children: items,
448 }
449 },
450 "open-interval" => {
452 let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
453 NodeData::Element {
454 tag: "m:interval".to_string(),
455 attributes: Some(HashMap::from_iter([(
456 "closure".to_string(),
457 "open".to_string(),
458 )])),
459 children: items,
460 }
461 },
462 "closed-interval" => {
463 let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
464 NodeData::Element {
465 tag: "m:interval".to_string(),
466 attributes: Some(HashMap::from_iter([(
467 "closure".to_string(),
468 "closed".to_string(),
469 )])),
470 children: items,
471 }
472 },
473 "closed-open-interval" => {
474 let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
475 NodeData::Element {
476 tag: "m:interval".to_string(),
477 attributes: Some(HashMap::from_iter([(
478 "closure".to_string(),
479 "closed-open".to_string(),
480 )])),
481 children: items,
482 }
483 },
484 "open-closed-interval" => {
485 let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
486 NodeData::Element {
487 tag: "m:interval".to_string(),
488 attributes: Some(HashMap::from_iter([(
489 "closure".to_string(),
490 "open-closed".to_string(),
491 )])),
492 children: items,
493 }
494 },
495 "contains" | "superset-of" | "superset-of-or-equals" | "superset-of-and-not-equals" => {
497 let cmml_op = match meaning.as_str() {
498 "contains" => "m:in",
499 "superset-of" | "superset-of-or-equals" => "m:subset",
500 "superset-of-and-not-equals" => "m:prsubset",
501 _ => "m:subset",
502 };
503 let mut reversed_args: Vec<NodeData> = args.iter().rev().map(|a| cmml(doc, a)).collect();
504 reversed_args.insert(0, NodeData::Element {
505 tag: cmml_op.to_string(),
506 attributes: None,
507 children: vec![],
508 });
509 NodeData::Element {
510 tag: "m:apply".to_string(),
511 attributes: None,
512 children: reversed_args,
513 }
514 },
515 "not-contains" => {
517 let mut reversed_args: Vec<NodeData> = args.iter().rev().map(|a| cmml(doc, a)).collect();
518 reversed_args.insert(0, NodeData::Element {
519 tag: "m:notin".to_string(),
520 attributes: None,
521 children: vec![],
522 });
523 NodeData::Element {
524 tag: "m:apply".to_string(),
525 attributes: None,
526 children: reversed_args,
527 }
528 },
529 "not-approximately-equals" => {
531 let inner_args: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
532 let mut apply_children = vec![NodeData::Element {
533 tag: "m:approx".to_string(),
534 attributes: None,
535 children: vec![],
536 }];
537 apply_children.extend(inner_args);
538 NodeData::Element {
539 tag: "m:apply".to_string(),
540 attributes: None,
541 children: vec![
542 NodeData::Element {
543 tag: "m:not".to_string(),
544 attributes: None,
545 children: vec![],
546 },
547 NodeData::Element {
548 tag: "m:apply".to_string(),
549 attributes: None,
550 children: apply_children,
551 },
552 ],
553 }
554 },
555 "hack-definite-integral" if args.len() >= 4 => NodeData::Element {
557 tag: "m:apply".to_string(),
558 attributes: None,
559 children: vec![
560 NodeData::Element {
561 tag: "m:int".to_string(),
562 attributes: None,
563 children: vec![],
564 },
565 NodeData::Element {
566 tag: "m:bvar".to_string(),
567 attributes: None,
568 children: vec![cmml(doc, &args[3])],
569 },
570 NodeData::Element {
571 tag: "m:lowlimit".to_string(),
572 attributes: None,
573 children: vec![cmml(doc, &args[0])],
574 },
575 NodeData::Element {
576 tag: "m:uplimit".to_string(),
577 attributes: None,
578 children: vec![cmml(doc, &args[1])],
579 },
580 cmml(doc, &args[2]),
581 ],
582 },
583 "formulae" => {
585 let items: Vec<NodeData> = args.iter().map(|a| cmml(doc, a)).collect();
586 let mut children = vec![NodeData::Element {
587 tag: "m:csymbol".to_string(),
588 attributes: Some(HashMap::from_iter([(
589 "cd".to_string(),
590 "ambiguous".to_string(),
591 )])),
592 children: vec![NodeData::Text("formulae-sequence".to_string())],
593 }];
594 children.extend(items);
595 NodeData::Element {
596 tag: "m:apply".to_string(),
597 attributes: None,
598 children,
599 }
600 },
601 _ => {
602 let mut apply_children = vec![cmml(doc, op)];
604 apply_children.extend(args.iter().map(|a| cmml(doc, a)));
605 NodeData::Element {
606 tag: "m:apply".to_string(),
607 attributes: None,
608 children: apply_children,
609 }
610 },
611 }
612 },
613 "ltx:XMTok" => cmml_leaf(doc, node),
614 "ltx:XMHint" => {
615 NodeData::Text(String::new())
617 },
618 "ltx:XMArray" => cmml_array(doc, node),
619 "ltx:XMText" => cmml_decorated_symbol(doc, node),
620 _ => cmml_decorated_symbol(doc, node),
621 }
622}
623
624fn cmml_leaf(_doc: &PostDocument, node: &Node) -> NodeData {
628 let meaning = node.get_attribute("meaning");
629 let role = node.get_attribute("role").unwrap_or_default();
630
631 if let Some(ref m) = meaning {
632 if let Some(element_name) = meaning_to_cmml_element(m) {
634 return NodeData::Element {
635 tag: element_name.to_string(),
636 attributes: None,
637 children: vec![],
638 };
639 }
640
641 if let Some(cd) = node.get_attribute("omcd") {
643 return NodeData::Element {
644 tag: "m:csymbol".to_string(),
645 attributes: Some(HashMap::from_iter([("cd".to_string(), cd)])),
646 children: vec![NodeData::Text(m.clone())],
647 };
648 }
649
650 if role == "NUMBER" {
652 let cn_type = if is_perl_integer(m) {
654 "integer"
655 } else {
656 "float"
657 };
658 return NodeData::Element {
659 tag: "m:cn".to_string(),
660 attributes: Some(HashMap::from_iter([(
661 "type".to_string(),
662 cn_type.to_string(),
663 )])),
664 children: vec![NodeData::Text(m.clone())],
665 };
666 }
667
668 return NodeData::Element {
670 tag: "m:csymbol".to_string(),
671 attributes: Some(HashMap::from_iter([(
672 "cd".to_string(),
673 "latexml".to_string(),
674 )])),
675 children: vec![NodeData::Text(m.clone())],
676 };
677 }
678
679 let content = node.get_content();
681 match role.as_str() {
682 "NUMBER" => {
683 let cn_type = if is_perl_integer(&content) {
684 "integer"
685 } else {
686 "float"
687 };
688 NodeData::Element {
689 tag: "m:cn".to_string(),
690 attributes: Some(HashMap::from_iter([(
691 "type".to_string(),
692 cn_type.to_string(),
693 )])),
694 children: vec![NodeData::Text(content)],
695 }
696 },
697 "SUPERSCRIPTOP" => NodeData::Element {
698 tag: "m:csymbol".to_string(),
699 attributes: Some(HashMap::from_iter([(
700 "cd".to_string(),
701 "ambiguous".to_string(),
702 )])),
703 children: vec![NodeData::Text("superscript".to_string())],
704 },
705 "SUBSCRIPTOP" => NodeData::Element {
706 tag: "m:csymbol".to_string(),
707 attributes: Some(HashMap::from_iter([(
708 "cd".to_string(),
709 "ambiguous".to_string(),
710 )])),
711 children: vec![NodeData::Text("subscript".to_string())],
712 },
713 _ => {
714 let name = if content.is_empty() {
716 node
717 .get_attribute("name")
718 .unwrap_or_else(|| "?".to_string())
719 } else {
720 content
721 };
722 NodeData::Element {
723 tag: "m:ci".to_string(),
724 attributes: None,
725 children: vec![NodeData::Text(stylize_ci_content(node, name))],
726 }
727 },
728 }
729}
730
731fn cmml_token_by_meaning(meaning: &str, _node: &Node) -> NodeData {
733 if let Some(element_name) = meaning_to_cmml_element(meaning) {
734 NodeData::Element {
735 tag: element_name.to_string(),
736 attributes: None,
737 children: vec![],
738 }
739 } else {
740 NodeData::Element {
741 tag: "m:csymbol".to_string(),
742 attributes: Some(HashMap::from_iter([(
743 "cd".to_string(),
744 "latexml".to_string(),
745 )])),
746 children: vec![NodeData::Text(meaning.to_string())],
747 }
748 }
749}
750
751thread_local! {
755 static SH_COUNTER: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
756 static SH_GLOBAL_COUNTER: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
760}
761pub(super) fn reset_share_counter() { SH_COUNTER.with(|c| c.set(0)); }
762pub(super) fn reset_document_share_counter() { SH_GLOBAL_COUNTER.with(|c| c.set(0)); }
764
765fn cmml_shared(doc: &PostDocument, node: &Node) -> NodeData {
769 if crate::document::get_xml_id(node).is_none() {
770 let mut parent = node.get_parent();
773 while let Some(ref p) = parent {
774 if crate::document::get_xml_id(p).is_some() {
775 break;
776 }
777 parent = p.get_parent();
778 }
779 let pid = parent
780 .as_ref()
781 .and_then(crate::document::get_xml_id)
782 .map(|id| format!("{id}."))
783 .unwrap_or_default();
784 let n = if pid.is_empty() {
791 SH_GLOBAL_COUNTER.with(|c| {
792 let v = c.get() + 1;
793 c.set(v);
794 v
795 })
796 } else {
797 SH_COUNTER.with(|c| {
798 let v = c.get() + 1;
799 c.set(v);
800 v
801 })
802 };
803 let mut handle = node.clone();
804 handle.set_attribute("xml:id", &format!("{pid}sh{n}")).ok();
805 if let Some(pfragid) = parent.as_ref().and_then(|p| p.get_attribute("fragid")) {
806 handle
807 .set_attribute("fragid", &format!("{pfragid}.sh{n}"))
808 .ok();
809 }
810 }
811 cmml(doc, node)
812}
813
814fn cmml_share(node: &Node) -> NodeData {
816 if let Some(fragid) = node.get_attribute("fragid") {
817 NodeData::Element {
820 tag: "m:share".to_string(),
821 attributes: Some(HashMap::from_iter([(
822 "href".to_string(),
823 format!("#{fragid}"),
824 )])),
825 children: vec![],
826 }
827 } else {
828 crate::Warn!(
829 "expected",
830 "fragid",
831 "Shared node is missing fragid (multirelation/or-compose share)"
832 );
833 NodeData::Element {
834 tag: "m:share".to_string(),
835 attributes: None,
836 children: vec![],
837 }
838 }
839}
840
841fn is_perl_integer(s: &str) -> bool {
843 let digits = s.strip_prefix(['+', '-']).unwrap_or(s);
844 !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
845}
846
847fn stylize_ci_content(node: &Node, text: String) -> String {
852 if text.chars().all(|c| {
855 matches!(c,
856 '\u{00AD}' | '\u{200B}'..='\u{200F}' | '\u{2060}'..='\u{2064}' | '\u{FEFF}')
857 }) {
858 return text;
859 }
860 let Some(font) = node
862 .get_attribute("font")
863 .or_else(super::presentation::ctx_font)
864 else {
865 return text;
866 };
867 let variant = crate::unicode::unicode_mathvariant(&font);
868 if variant.is_empty() || variant == "normal" {
869 return text;
870 }
871 if let Some(u) = crate::unicode::unicode_convert(&text, variant)
872 && !u.is_empty()
873 {
874 return u;
875 }
876 format!("{variant}-{text}")
877}
878
879fn cmml_decorated_symbol(doc: &PostDocument, node: &Node) -> NodeData {
885 if let Some(meaning) = node.get_attribute("meaning") {
886 let cd = node
887 .get_attribute("omcd")
888 .unwrap_or_else(|| "latexml".to_string());
889 return NodeData::Element {
890 tag: "m:csymbol".to_string(),
891 attributes: Some(HashMap::from_iter([("cd".to_string(), cd)])),
892 children: vec![NodeData::Text(meaning)],
893 };
894 }
895 NodeData::Element {
896 tag: "m:ci".to_string(),
897 attributes: None,
898 children: vec![super::presentation::pmml_for_ci(doc, node)],
899 }
900}
901
902fn cmml_array(doc: &PostDocument, node: &Node) -> NodeData {
906 let meaning = node.get_attribute("meaning").unwrap_or_default();
907
908 if meaning == "cases" {
909 let mut pieces = Vec::new();
911 let mut otherwises = Vec::new();
912
913 for row in element_children(node) {
914 let items = element_children(&row);
915 if items.is_empty() {
916 continue;
917 }
918 if items.len() == 1 {
919 otherwises.push(cmml_contents(doc, &items[0]));
920 } else if items[1].get_content().contains("otherwise") {
921 otherwises.push(cmml_contents(doc, &items[0]));
922 } else {
923 pieces.push(NodeData::Element {
924 tag: "m:piece".to_string(),
925 attributes: None,
926 children: vec![cmml_contents(doc, &items[0]), cmml_contents(doc, &items[1])],
927 });
928 }
929 }
930
931 if let Some(ow) = otherwises.into_iter().next() {
932 pieces.push(NodeData::Element {
933 tag: "m:otherwise".to_string(),
934 attributes: None,
935 children: vec![ow],
936 });
937 }
938
939 NodeData::Element {
940 tag: "m:piecewise".to_string(),
941 attributes: None,
942 children: pieces,
943 }
944 } else {
945 let mut rows = Vec::new();
947 for row in element_children(node) {
948 let cells: Vec<NodeData> = element_children(&row)
949 .iter()
950 .map(|cell| cmml_contents(doc, cell))
951 .collect();
952 rows.push(NodeData::Element {
953 tag: "m:matrixrow".to_string(),
954 attributes: None,
955 children: cells,
956 });
957 }
958 NodeData::Element {
959 tag: "m:matrix".to_string(),
960 attributes: None,
961 children: rows,
962 }
963 }
964}
965
966fn cmml_unparsed(doc: &PostDocument, nodes: &[Node]) -> NodeData {
970 let mut results = vec![NodeData::Element {
971 tag: "m:csymbol".to_string(),
972 attributes: Some(HashMap::from_iter([(
973 "cd".to_string(),
974 "ambiguous".to_string(),
975 )])),
976 children: vec![NodeData::Text("fragments".to_string())],
977 }];
978
979 for node in nodes {
980 let tag = doc.get_qname(node).unwrap_or_default();
981 if tag == "ltx:XMTok" && node.with_attribute(c"role", |v| v == "UNKNOWN") == Some(true) {
982 results.push(NodeData::Element {
983 tag: "m:csymbol".to_string(),
984 attributes: Some(HashMap::from_iter([(
985 "cd".to_string(),
986 "unknown".to_string(),
987 )])),
988 children: vec![NodeData::Text(node.get_content())],
989 });
990 } else {
991 results.push(cmml(doc, node));
992 }
993 }
994
995 NodeData::Element {
996 tag: "m:cerror".to_string(),
997 attributes: None,
998 children: results,
999 }
1000}
1001
1002fn cmml_error(symbol: &str) -> NodeData {
1004 NodeData::Element {
1005 tag: "m:cerror".to_string(),
1006 attributes: None,
1007 children: vec![NodeData::Element {
1008 tag: "m:csymbol".to_string(),
1009 attributes: Some(HashMap::from_iter([(
1010 "cd".to_string(),
1011 "ambiguous".to_string(),
1012 )])),
1013 children: vec![NodeData::Text(symbol.to_string())],
1014 }],
1015 }
1016}