1use std::cell::Cell;
14
15use latexml_core::common::xml::name_is;
16use libxml::tree::Node;
17use rustc_hash::FxHashMap as HashMap;
18
19use super::operator_dictionary;
20use crate::document::{NodeData, PostDocument, XMBranch, element_children, element_children_iter};
21
22thread_local! {
25 static INVISIBLE_TIMES: Cell<bool> = const { Cell::new(true) };
26 static PLANE1: Cell<bool> = const { Cell::new(true) };
33 static HACK_PLANE1: Cell<bool> = const { Cell::new(false) };
40 static CTX_FONT: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
49 static CTX_TEXTFONT: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
53 static CTX_COLOR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
54 static CTX_BGCOLOR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
55 static CTX_OPACITY: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
56 static CURRENT_STYLE: Cell<MathStyle> = const { Cell::new(MathStyle::Display) };
64}
65
66pub fn set_invisible_times(emit: bool) { INVISIBLE_TIMES.with(|f| f.set(emit)); }
68
69fn get_invisible_times() -> bool { INVISIBLE_TIMES.with(|f| f.get()) }
70
71pub fn set_plane1(plane1: bool, hack_plane1: bool) {
74 PLANE1.with(|f| f.set(plane1 || hack_plane1));
75 HACK_PLANE1.with(|f| f.set(hack_plane1));
76}
77
78fn plane1_hackable(variant: &str) -> Option<&'static str> {
83 match variant {
84 "script" | "bold-script" => Some("script"),
85 "fraktur" | "bold-fraktur" => Some("fraktur"),
86 "double-struck" => Some("double-struck"),
87 _ => None,
88 }
89}
90
91fn plane1_target_variant(variant: &str) -> Option<&str> {
100 if HACK_PLANE1.with(|f| f.get()) {
101 plane1_hackable(variant)
102 } else if PLANE1.with(|f| f.get()) {
103 Some(variant)
104 } else {
105 None
106 }
107}
108
109fn current_context_size() -> &'static str { CURRENT_STYLE.with(|s| s.get().size_percent()) }
112
113#[derive(Debug, Clone, Copy, PartialEq)]
115pub enum MathStyle {
116 Display,
117 Text,
118 Script,
119 ScriptScript,
120}
121
122impl MathStyle {
123 pub fn step_down(self) -> Self {
125 match self {
126 MathStyle::Display => MathStyle::Text,
127 MathStyle::Text => MathStyle::Script,
128 MathStyle::Script => MathStyle::ScriptScript,
129 MathStyle::ScriptScript => MathStyle::ScriptScript,
130 }
131 }
132
133 pub fn script_step(self) -> Self {
135 match self {
136 MathStyle::Display | MathStyle::Text => MathStyle::Script,
137 MathStyle::Script => MathStyle::ScriptScript,
138 MathStyle::ScriptScript => MathStyle::ScriptScript,
139 }
140 }
141
142 pub fn size_percent(self) -> &'static str {
144 match self {
145 MathStyle::Display | MathStyle::Text => "100%",
146 MathStyle::Script => "70%",
147 MathStyle::ScriptScript => "50%",
148 }
149 }
150
151 pub fn from_attr(s: &str) -> Option<Self> {
154 match s {
155 "display" => Some(MathStyle::Display),
156 "text" => Some(MathStyle::Text),
157 "script" => Some(MathStyle::Script),
158 "scriptscript" => Some(MathStyle::ScriptScript),
159 _ => None,
160 }
161 }
162}
163
164fn stylemap_attrs(
170 ostyle: MathStyle,
171 nstyle: MathStyle,
172 needs: bool,
173) -> &'static [(&'static str, &'static str)] {
174 use MathStyle::*;
175 match (ostyle, nstyle, needs) {
176 (Display, Text, true) => &[("displaystyle", "false")],
177 (Display, Script, true) => &[("displaystyle", "false"), ("scriptlevel", "+1")],
178 (Display, ScriptScript, true) => &[("displaystyle", "false"), ("scriptlevel", "+2")],
179 (Text, Display, true) => &[("displaystyle", "true")],
180 (Display, Script, false) | (Text, Script, _) => &[("scriptlevel", "+1")],
181 (Display, ScriptScript, false) | (Text, ScriptScript, _) => &[("scriptlevel", "+2")],
182 (Script, Display, _) => &[("displaystyle", "true"), ("scriptlevel", "-1")],
183 (Script, Text, _) => &[("scriptlevel", "-1")],
184 (Script, ScriptScript, _) => &[("scriptlevel", "+1")],
185 (ScriptScript, Display, _) => &[("displaystyle", "true"), ("scriptlevel", "-2")],
186 (ScriptScript, Text, _) => &[("scriptlevel", "-2")],
187 (ScriptScript, Script, _) => &[("scriptlevel", "-1")],
188 _ => &[],
189 }
190}
191
192fn needs_mathstyle(node: &NodeData) -> bool {
197 if let NodeData::Element { tag, attributes, children } = node {
198 if tag == "m:mfrac" {
199 return true;
200 }
201 if let Some(attrs) = attributes {
202 if attrs.contains_key("_largeop") {
203 return true;
204 }
205 if tag == "m:mstyle" && attrs.contains_key("displaystyle") {
206 return false;
207 }
208 }
209 return children.iter().any(needs_mathstyle);
210 }
211 false
212}
213
214fn maybe_style_wrap(result: NodeData, ostyle: MathStyle, nstyle: Option<MathStyle>) -> NodeData {
218 let Some(nstyle) = nstyle else { return result };
219 let style_attrs = stylemap_attrs(ostyle, nstyle, needs_mathstyle(&result));
220 if style_attrs.is_empty() {
221 return result;
222 }
223 NodeData::Element {
224 tag: "m:mstyle".to_string(),
225 attributes: Some(HashMap::from_iter(
226 style_attrs
227 .iter()
228 .map(|(k, v)| (k.to_string(), v.to_string())),
229 )),
230 children: vec![result],
231 }
232}
233
234fn pmml_maybe_resize(doc: &PostDocument, node: &Node, result: NodeData) -> NodeData {
242 let parent = node.get_parent().filter(|p| doc.is_qname(p, "ltx:XMDual"));
244 let getattr = |name: &str| {
245 node
246 .get_attribute(name)
247 .or_else(|| parent.as_ref().and_then(|p| p.get_attribute(name)))
248 };
249 let width = getattr("width");
250 let height = getattr("height");
251 let depth = getattr("depth");
252 let xoff = getattr("xoffset");
253 let yoff = getattr("yoffset");
254 let role = getattr("role");
255 let class = getattr("class");
256
257 let mut result = result;
258 if let Some(ref w) = width
259 && role.as_deref() == Some("ARROW")
260 && class.as_deref().is_some_and(|c| {
261 c.split_ascii_whitespace()
262 .any(|w| w == "ltx_horizontally_stretchy")
263 })
264 {
265 result = NodeData::Element {
268 tag: "m:mover".to_string(),
269 attributes: None,
270 children: vec![result, NodeData::Element {
271 tag: "m:mspace".to_string(),
272 attributes: Some(HashMap::from_iter([("width".to_string(), w.clone())])),
273 children: vec![],
274 }],
275 };
276 } else if width.is_some()
277 || height.is_some()
278 || depth.is_some()
279 || xoff.is_some()
280 || yoff.is_some()
281 {
282 let needs_wrap = !matches!(&result,
284 NodeData::Element { tag, .. } if tag == "m:mpadded" || tag == "m:mrow");
285 if needs_wrap {
286 result = NodeData::Element {
287 tag: "m:mpadded".to_string(),
288 attributes: None,
289 children: vec![result],
290 };
291 }
292 if let NodeData::Element { tag, attributes, .. } = &mut result {
293 if tag == "m:mrow" {
294 *tag = "m:mpadded".to_string();
295 }
296 let attrs = attributes.get_or_insert_with(Default::default);
297 for (key, val) in [
298 ("width", width),
299 ("height", height),
300 ("depth", depth),
301 ("lspace", xoff),
302 ("voffset", yoff),
303 ] {
304 if let Some(v) = val {
305 attrs.insert(key.to_string(), v);
306 }
307 }
308 }
309 }
310
311 if let Some(frame) = node.get_attribute("framed")
313 && let NodeData::Element { attributes, .. } = &mut result
314 {
315 let attrs = attributes.get_or_insert_with(Default::default);
316 let frame_class = format!("ltx_framed_{frame}");
317 let merged = match attrs.get("class") {
318 Some(c) if !c.is_empty() => format!("{c} {frame_class}"),
319 _ => frame_class,
320 };
321 attrs.insert("class".to_string(), merged);
322 if let Some(color) = node.get_attribute("framecolor") {
323 let style = format!("border-color: {color}");
324 let merged = match attrs.get("style") {
325 Some(s) if !s.is_empty() => format!("{s}; {style}"),
326 _ => style,
327 };
328 attrs.insert("style".to_string(), merged);
329 }
330 }
331 result
332}
333
334fn ctx_get(
335 cell: &'static std::thread::LocalKey<std::cell::RefCell<Option<String>>>,
336) -> Option<String> {
337 cell.with(|c| c.borrow().clone())
338}
339
340fn ctx_rebind(
343 cell: &'static std::thread::LocalKey<std::cell::RefCell<Option<String>>>,
344 attr: Option<String>,
345) -> Option<String> {
346 let attr = attr.filter(|v| !v.is_empty());
348 cell.with(|c| {
349 let old = c.borrow().clone();
350 if attr.is_some() {
351 *c.borrow_mut() = attr;
352 }
353 old
354 })
355}
356
357fn ctx_set(
358 cell: &'static std::thread::LocalKey<std::cell::RefCell<Option<String>>>,
359 val: Option<String>,
360) {
361 cell.with(|c| *c.borrow_mut() = val);
362}
363
364fn is_embellishing_role(role: &str) -> bool {
366 matches!(
367 role,
368 "SUPERSCRIPTOP" | "SUBSCRIPTOP" | "OVERACCENT" | "UNDERACCENT" | "MODIFIER" | "MODIFIEROP"
369 )
370}
371
372pub(super) fn default_token_content(role: &str) -> Option<&'static str> {
377 match role {
378 "MULOP" => Some("\u{2062}"), "ADDOP" => Some("\u{2064}"), "PUNCT" => Some("\u{2063}"), _ => None,
382 }
383}
384
385fn get_operator_role(doc: &PostDocument, node: &Node) -> Option<String> {
387 if let Some(role) = node.get_attribute("role") {
388 return Some(role);
389 }
390 if doc.is_qname(node, "ltx:XMApp") {
391 let children = element_children(node);
392 if children.len() >= 2 {
393 let op_role = children[0].get_attribute("role").unwrap_or_default();
394 if is_embellishing_role(&op_role) {
395 return get_operator_role(doc, &children[1]);
396 }
397 }
398 }
399 None
400}
401
402pub fn convert_to_pmml(doc: &PostDocument, xmath: &Node) -> NodeData {
407 let saved_style = CURRENT_STYLE.with(|s| s.get());
414 let saved_font = CTX_FONT.with(|c| c.borrow().clone());
415 let saved_text_font = CTX_TEXTFONT.with(|c| c.borrow().clone());
416 let saved_color = CTX_COLOR.with(|c| c.borrow().clone());
417 let saved_bgcolor = CTX_BGCOLOR.with(|c| c.borrow().clone());
418 let saved_opacity = CTX_OPACITY.with(|c| c.borrow().clone());
419
420 let mode_is_display = xmath
425 .get_parent()
426 .and_then(|p| p.get_attribute("mode"))
427 .is_some_and(|m| m == "display");
428 CURRENT_STYLE.with(|s| {
429 s.set(if mode_is_display {
430 MathStyle::Display
431 } else {
432 MathStyle::Text
433 })
434 });
435 ctx_set(&CTX_FONT, super::math_context_font(xmath));
440 ctx_set(
441 &CTX_TEXTFONT,
442 super::find_inherited_attribute(doc, xmath, "font"),
443 );
444 ctx_set(
445 &CTX_COLOR,
446 super::find_inherited_attribute(doc, xmath, "color"),
447 );
448 ctx_set(
449 &CTX_BGCOLOR,
450 super::find_inherited_attribute(doc, xmath, "backgroundcolor"),
451 );
452 ctx_set(
453 &CTX_OPACITY,
454 super::find_inherited_attribute(doc, xmath, "opacity"),
455 );
456 let children = element_children(xmath);
457 let results: Vec<NodeData> = children.iter().map(|c| pmml(doc, c)).collect();
458 let mut result = if results.len() == 1 {
459 results.into_iter().next().unwrap()
460 } else {
461 pmml_row(results)
462 };
463 fill_empty_operands(&mut result);
464 adjust_spacing(&mut result);
466 clean_internal_attrs(&mut result);
468
469 CURRENT_STYLE.with(|s| s.set(saved_style));
471 ctx_set(&CTX_FONT, saved_font);
472 ctx_set(&CTX_TEXTFONT, saved_text_font);
473 ctx_set(&CTX_COLOR, saved_color);
474 ctx_set(&CTX_BGCOLOR, saved_bgcolor);
475 ctx_set(&CTX_OPACITY, saved_opacity);
476 result
477}
478
479pub(super) fn pmml_for_ci(doc: &PostDocument, node: &Node) -> NodeData { pmml(doc, node) }
482
483pub(super) fn bind_cmml_top_context(doc: &PostDocument, xmath: &Node) {
492 CURRENT_STYLE.with(|s| s.set(MathStyle::Text));
493 ctx_set(&CTX_FONT, super::math_context_font(xmath));
494 ctx_set(
495 &CTX_TEXTFONT,
496 super::find_inherited_attribute(doc, xmath, "font"),
497 );
498 ctx_set(
499 &CTX_COLOR,
500 super::find_inherited_attribute(doc, xmath, "color"),
501 );
502 ctx_set(
503 &CTX_BGCOLOR,
504 super::find_inherited_attribute(doc, xmath, "backgroundcolor"),
505 );
506 ctx_set(
507 &CTX_OPACITY,
508 super::find_inherited_attribute(doc, xmath, "opacity"),
509 );
510}
511
512pub(super) fn ctx_font() -> Option<String> { ctx_get(&CTX_FONT) }
515
516pub(super) fn ctx_text_font() -> Option<String> { ctx_get(&CTX_TEXTFONT) }
518
519pub(super) fn ctx_color() -> Option<String> { ctx_get(&CTX_COLOR) }
521
522pub(super) fn ctx_bgcolor() -> Option<String> { ctx_get(&CTX_BGCOLOR) }
524
525pub(super) fn ctx_opacity() -> Option<String> { ctx_get(&CTX_OPACITY) }
527
528pub(super) fn context_size() -> &'static str { current_context_size() }
531
532pub(super) fn resolve_size(s: String) -> String { resolve_token_size(s) }
534
535pub(super) fn maybe_resize(doc: &PostDocument, node: &Node, result: NodeData) -> NodeData {
537 pmml_maybe_resize(doc, node, result)
538}
539
540fn pmml(doc: &PostDocument, node: &Node) -> NodeData {
544 let saved_color = ctx_rebind(&CTX_COLOR, node.get_attribute("color"));
547 let saved_bg = ctx_rebind(&CTX_BGCOLOR, node.get_attribute("backgroundcolor"));
548 let saved_op = ctx_rebind(&CTX_OPACITY, node.get_attribute("opacity"));
549 let mut result = pmml_inner(doc, node);
550 ctx_set(&CTX_COLOR, saved_color);
551 ctx_set(&CTX_BGCOLOR, saved_bg);
552 ctx_set(&CTX_OPACITY, saved_op);
553 if let Some(enclose) = node.get_attribute("enclose").filter(|e| !e.is_empty()) {
556 let mut attrs = HashMap::default();
557 attrs.insert("notation".to_string(), enclose);
558 result = NodeData::Element {
559 tag: "m:menclose".to_string(),
560 attributes: Some(attrs),
561 children: vec![result],
562 };
563 }
564 if doc.is_qname(node, "ltx:XMRef") {
578 add_source_padding(node, &mut result);
581 } else {
582 attach_source_padding(node, &mut result);
585 }
586 if let Some(cl) = node.get_attribute("class").filter(|cl| !cl.is_empty()) {
589 let standin = cl.split_whitespace().any(|c| c == "ltx_standin");
590 match standin.then(|| standin_token(&mut result)).flatten() {
591 Some(token) => merge_class(token, cl),
592 None => merge_class(&mut result, cl),
593 }
594 }
595 if let NodeData::Element { ref mut attributes, .. } = result {
596 if let Some(role) = node.get_attribute("role") {
599 let attrs = attributes.get_or_insert_with(Default::default);
600 attrs.insert("_role".to_string(), role);
601 }
602 }
603 result
604}
605
606fn merge_class(result: &mut NodeData, cl: String) {
608 if let NodeData::Element { attributes, .. } = result {
609 let attrs = attributes.get_or_insert_with(Default::default);
610 match attrs.get("class") {
611 Some(ocl) if !ocl.is_empty() && *ocl != cl => {
612 let merged = format!("{ocl} {cl}");
613 attrs.insert("class".to_string(), merged);
614 },
615 _ => {
616 attrs.insert("class".to_string(), cl);
617 },
618 }
619 }
620}
621
622const TOKEN_TAGS: [&str; 4] = ["m:mtext", "m:mi", "m:mn", "m:mo"];
623
624fn is_token(data: &NodeData) -> bool {
625 matches!(data, NodeData::Element { tag, .. } if TOKEN_TAGS.contains(&tag.as_str()))
626}
627
628fn standin_token(result: &mut NodeData) -> Option<&mut NodeData> {
631 fn count(data: &NodeData) -> usize {
632 match data {
633 NodeData::Element { children, .. } => children
634 .iter()
635 .map(|child| usize::from(is_token(child)) + count(child))
636 .sum(),
637 _ => 0,
638 }
639 }
640 fn first(data: &mut NodeData) -> Option<&mut NodeData> {
641 let NodeData::Element { children, .. } = data else {
642 return None;
643 };
644 for child in children {
645 if is_token(child) {
646 return Some(child);
647 }
648 if let Some(token) = first(child) {
649 return Some(token);
650 }
651 }
652 None
653 }
654 if is_token(result) || count(result) != 1 {
655 return None;
656 }
657 first(result)
658}
659
660fn attach_source_padding(node: &Node, result: &mut NodeData) {
663 for (src, dst) in [("lpadding", "_lpadding"), ("rpadding", "_rpadding")] {
669 if let Some(v) = node.get_attribute(src) {
670 let em = super::get_xm_hint_spacing(&v);
671 if em != 0.0
672 && let NodeData::Element { ref mut attributes, .. } = *result
673 {
674 let attrs = attributes.get_or_insert_with(Default::default);
675 attrs.insert(dst.to_string(), fmt_em(em));
676 }
677 }
678 }
679}
680
681fn add_source_padding(node: &Node, result: &mut NodeData) {
684 for (src, dst) in [("lpadding", "_lpadding"), ("rpadding", "_rpadding")] {
685 if let Some(v) = node.get_attribute(src) {
686 let em = super::get_xm_hint_spacing(&v);
687 if em != 0.0
688 && let NodeData::Element { ref mut attributes, .. } = *result
689 {
690 let attrs = attributes.get_or_insert_with(Default::default);
691 let prior = attrs
692 .get(dst)
693 .and_then(|s| s.trim_end_matches("em").parse::<f64>().ok())
694 .unwrap_or(0.0);
695 attrs.insert(dst.to_string(), fmt_em(prior + em));
696 }
697 }
698 }
699}
700
701fn pmml_inner(doc: &PostDocument, node: &Node) -> NodeData {
702 let is_ltx = doc.qname_prefix(node).as_deref() == Some("ltx");
708 let localname = if is_ltx {
709 node.get_name()
710 } else {
711 String::new()
712 };
713
714 if is_ltx && localname == "XMRef" {
716 if let Some(idref) = node.get_attribute("idref") {
717 if let Some(target) = doc.find_node_by_id(&idref) {
718 return pmml(doc, target);
719 }
720 }
721 return pmml_error("Unresolved XMRef");
722 }
723
724 if is_ltx {
725 match localname.as_str() {
726 "XMath" => {
727 let results: Vec<NodeData> = element_children_iter(node).map(|c| pmml(doc, &c)).collect();
728 return pmml_row(results);
729 },
730 "XMDual" => {
731 let children = element_children(node);
732 return if children.len() >= 2 {
733 pmml(doc, &children[1]) } else {
735 pmml_error("Empty XMDual")
736 };
737 },
738 "XMWrap" | "XMArg" => {
739 let results: Vec<NodeData> = element_children_iter(node).map(|c| pmml(doc, &c)).collect();
741 return pmml_maybe_resize(doc, node, pmml_row(results));
742 },
743 "XMApp" => return pmml_apply(doc, node),
744 "XMTok" => return pmml_token(doc, node),
745 "XMHint" => return pmml_hint(doc, node),
746 "XMArray" => return pmml_array(doc, node),
747 "XMText" => {
748 let mut children = Vec::new();
751 if let Some(child) = node.get_first_child() {
752 let mut current = Some(child);
753 while let Some(ref c) = current {
754 children.extend(super::pmml_text_aux(doc, c, &super::TextAttrs::default()));
755 current = c.get_next_sibling();
756 }
757 }
758 return pmml_maybe_resize(doc, node, pmml_row(children));
759 },
760 "ERROR" => {
761 let mut merror = pmml_error(&node.get_content());
765 if let NodeData::Element { ref mut attributes, .. } = merror {
766 *attributes = Some(HashMap::from_iter([(
767 "class".to_string(),
768 "ltx_ERROR".to_string(),
769 )]));
770 }
771 return merror;
772 },
773 _ => {},
774 }
775 }
776
777 NodeData::Element {
779 tag: "m:mtext".to_string(),
780 attributes: None,
781 children: vec![NodeData::Text(node.get_content())],
782 }
783}
784
785fn pmml_apply(doc: &PostDocument, node: &Node) -> NodeData {
789 let children = element_children(node);
790 if children.is_empty() {
791 return pmml_error("Missing Operator");
792 }
793
794 let role = node.get_attribute("role").unwrap_or_default();
795
796 if role.contains("SUBSCRIPT") || role.contains("SUPERSCRIPT") {
805 let is_sub = role.contains("SUB");
806 let tag = if is_sub { "m:msub" } else { "m:msup" };
807 return NodeData::Element {
808 tag: tag.to_string(),
809 attributes: None,
810 children: vec![
811 NodeData::Element {
812 tag: "m:mrow".to_string(),
813 attributes: None,
814 children: vec![],
815 },
816 pmml_scriptsize(doc, &children[0]),
817 ],
818 };
819 }
820
821 let op = &children[0];
822 let args = &children[1..];
823
824 let rop = if doc.is_qname(op, "ltx:XMRef") {
826 op.get_attribute("idref")
827 .and_then(|id| doc.find_node_by_id(&id).cloned())
828 .unwrap_or_else(|| op.clone())
829 } else {
830 op.clone()
831 };
832
833 let op_role = get_operator_role(doc, &rop).unwrap_or_default();
834 let meaning = rop.get_attribute("meaning").unwrap_or_default();
835
836 let style_attr = rop
841 .get_attribute("mathstyle")
842 .or_else(|| op.get_attribute("mathstyle"));
843 let ostyle = CURRENT_STYLE.with(|s| s.get());
844 let nstyle = style_attr.as_deref().and_then(MathStyle::from_attr);
845 if let Some(n) = nstyle {
846 CURRENT_STYLE.with(|s| s.set(n));
847 }
848 let result = pmml_apply_dispatch(doc, op, &rop, args, &op_role, &meaning);
849 CURRENT_STYLE.with(|s| s.set(ostyle));
850 let result = pmml_maybe_resize(doc, node, result);
852 maybe_style_wrap(result, ostyle, nstyle)
853}
854
855fn pmml_apply_dispatch(
858 doc: &PostDocument,
859 op: &Node,
860 rop: &Node,
861 args: &[Node],
862 op_role: &str,
863 meaning: &str,
864) -> NodeData {
865 match op_role {
867 "SUPERSCRIPTOP" | "SUBSCRIPTOP" if args.len() >= 2 => {
868 pmml_script_full(doc, op, &args[0], &args[1])
869 },
870 "FRACOP" if args.len() >= 2 => {
871 let mut attrs = HashMap::default();
877 if let Some(t) = rop.get_attribute("thickness") {
878 attrs.insert("linethickness".to_string(), t);
879 }
880 if let Some(c) = rop
881 .get_attribute("color")
882 .filter(|c| !c.is_empty())
883 .or_else(|| ctx_get(&CTX_COLOR))
884 {
885 attrs.insert("mathcolor".to_string(), c);
886 }
887 if let Some(cl) = rop.get_attribute("class")
888 && cl.split_ascii_whitespace().any(|c| c == "ltx_bevelled")
889 {
890 attrs.insert("bevelled".to_string(), "true".to_string());
891 }
892 NodeData::Element {
893 tag: "m:mfrac".to_string(),
894 attributes: if attrs.is_empty() { None } else { Some(attrs) },
895 children: vec![pmml_smaller(doc, &args[0]), pmml_smaller(doc, &args[1])],
896 }
897 },
898 "OVERACCENT" if !args.is_empty() => {
899 let base = &args[0];
901 let base_children = element_children(base);
902 if doc.is_qname(base, "ltx:XMApp") && base_children.len() == 2 {
903 let inner_role = base_children[0].get_attribute("role").unwrap_or_default();
904 if inner_role == "UNDERACCENT" {
905 return NodeData::Element {
907 tag: "m:munderover".to_string(),
908 attributes: Some(HashMap::from_iter([
909 ("accent".to_string(), "true".to_string()),
910 ("accentunder".to_string(), "true".to_string()),
911 ])),
912 children: vec![
913 pmml(doc, &base_children[1]), pmml(doc, &base_children[0]), pmml(doc, op), ],
917 };
918 }
919 }
920 NodeData::Element {
921 tag: "m:mover".to_string(),
922 attributes: Some(HashMap::from_iter([(
923 "accent".to_string(),
924 "true".to_string(),
925 )])),
926 children: vec![pmml(doc, base), pmml(doc, op)],
927 }
928 },
929 "UNDERACCENT" if !args.is_empty() => {
930 let base = &args[0];
932 let base_children = element_children(base);
933 if doc.is_qname(base, "ltx:XMApp") && base_children.len() == 2 {
934 let inner_role = base_children[0].get_attribute("role").unwrap_or_default();
935 if inner_role == "OVERACCENT" {
936 return NodeData::Element {
937 tag: "m:munderover".to_string(),
938 attributes: Some(HashMap::from_iter([
939 ("accent".to_string(), "true".to_string()),
940 ("accentunder".to_string(), "true".to_string()),
941 ])),
942 children: vec![
943 pmml(doc, &base_children[1]), pmml(doc, op), pmml(doc, &base_children[0]), ],
947 };
948 }
949 }
950 NodeData::Element {
951 tag: "m:munder".to_string(),
952 attributes: Some(HashMap::from_iter([(
953 "accentunder".to_string(),
954 "true".to_string(),
955 )])),
956 children: vec![pmml(doc, base), pmml(doc, op)],
957 }
958 },
959 "POSTFIX" if !args.is_empty() => {
960 let mut items: Vec<NodeData> = args.iter().map(|a| pmml(doc, a)).collect();
961 items.push(pmml(doc, op));
962 pmml_row(items)
963 },
964 "ADDOP" | "RELOP" | "MULOP" | "BINOP" | "ARROW" | "METARELOP" | "COMPOSEOP" | "MODIFIEROP"
965 | "MIDDLE" => {
966 pmml_infix(doc, op, args)
968 },
969 "SUMOP" | "INTOP" | "BIGOP" | "LIMITOP" => {
970 pmml_summation(doc, op, args)
976 },
977 "OPEN" | "CLOSE" if !args.is_empty() => {
978 pmml_parenthesize(doc, op, args)
980 },
981 "ENCLOSE" if !args.is_empty() => {
982 let mut attrs = HashMap::default();
988 if let Some(notation) = rop.get_attribute("enclose").filter(|n| !n.is_empty()) {
989 attrs.insert("notation".to_string(), notation);
990 }
991 let color = rop
992 .get_attribute("color")
993 .filter(|c| !c.is_empty())
994 .or_else(|| ctx_get(&CTX_COLOR));
995 let base = pmml(doc, &args[0]);
996 let inner = if let Some(ref c) = color {
997 attrs.insert("mathcolor".to_string(), c.clone());
998 NodeData::Element {
1001 tag: "m:mstyle".to_string(),
1002 attributes: Some(HashMap::from_iter([(
1003 "mathcolor".to_string(),
1004 ctx_get(&CTX_COLOR).unwrap_or_else(|| "black".to_string()),
1005 )])),
1006 children: vec![base],
1007 }
1008 } else {
1009 base
1010 };
1011 NodeData::Element {
1012 tag: "m:menclose".to_string(),
1013 attributes: if attrs.is_empty() { None } else { Some(attrs) },
1014 children: vec![inner],
1015 }
1016 },
1017 _ if meaning == "multirelation" => {
1018 let mut items = Vec::new();
1021 for (i, arg) in args.iter().enumerate() {
1022 if i > 0 && i % 2 == 1 {
1023 items.push(pmml(doc, arg));
1025 } else {
1026 items.push(pmml(doc, arg));
1027 }
1028 }
1029 pmml_row(items)
1030 },
1031 _ => {
1032 if meaning == "limit-from" && !args.is_empty() {
1034 let items: Vec<NodeData> = args.iter().map(|a| pmml(doc, a)).collect();
1036 pmml_row(items)
1037 } else if meaning == "annotated" && args.len() >= 2 {
1038 pmml_row(vec![
1040 pmml(doc, &args[0]),
1041 NodeData::Element {
1042 tag: "m:mspace".to_string(),
1043 attributes: Some(HashMap::from_iter([(
1044 "width".to_string(),
1045 "0.389em".to_string(),
1046 )])),
1047 children: vec![],
1048 },
1049 pmml(doc, &args[1]),
1050 ])
1051 } else if meaning == "square-root" && !args.is_empty() {
1052 NodeData::Element {
1054 tag: "m:msqrt".to_string(),
1055 attributes: rop
1056 .get_attribute("color")
1057 .or_else(|| ctx_get(&CTX_COLOR))
1058 .map(|c| HashMap::from_iter([("mathcolor".to_string(), c)])),
1059 children: vec![pmml(doc, &args[0])],
1060 }
1061 } else if meaning == "continued-fraction" && args.len() >= 2 {
1062 pmml_cfrac(doc, op, &args[0], &args[1])
1063 } else if meaning == "nth-root" && args.len() >= 2 {
1064 NodeData::Element {
1069 tag: "m:mroot".to_string(),
1070 attributes: rop
1071 .get_attribute("color")
1072 .or_else(|| ctx_get(&CTX_COLOR))
1073 .map(|c| HashMap::from_iter([("mathcolor".to_string(), c)])),
1074 children: vec![pmml(doc, &args[1]), pmml_scriptsize(doc, &args[0])],
1075 }
1076 } else {
1077 let pop = pmml(doc, op);
1083 let needs_apply = !op_base_is_mo(&pop);
1084 let mut items = vec![pop];
1085 if needs_apply {
1086 items.push(pmml_mo_str("\u{2061}")); }
1088 for arg in args {
1089 items.push(pmml(doc, arg));
1090 }
1091 pmml_row(items)
1092 }
1093 },
1094 }
1095}
1096
1097fn pmml_token(doc: &PostDocument, node: &Node) -> NodeData {
1101 let nstyle = match node.get_attribute("role").as_deref() {
1107 Some("SUMOP" | "INTOP" | "BIGOP") => node
1108 .get_attribute("mathstyle")
1109 .as_deref()
1110 .and_then(MathStyle::from_attr),
1111 _ => None,
1112 };
1113 let ostyle = CURRENT_STYLE.with(|s| s.get());
1114 if let Some(n) = nstyle {
1115 CURRENT_STYLE.with(|s| s.set(n));
1116 }
1117 let result = pmml_token_inner(doc, node, None);
1118 CURRENT_STYLE.with(|s| s.set(ostyle));
1119 match nstyle {
1120 Some(n) if n != ostyle => {
1121 let style_attrs = stylemap_attrs(ostyle, n, true);
1122 if style_attrs.is_empty() {
1123 result
1124 } else {
1125 NodeData::Element {
1126 tag: "m:mstyle".to_string(),
1127 attributes: Some(HashMap::from_iter(
1128 style_attrs
1129 .iter()
1130 .map(|(k, v)| (k.to_string(), v.to_string())),
1131 )),
1132 children: vec![result],
1133 }
1134 }
1135 },
1136 _ => result,
1137 }
1138}
1139
1140fn resolve_token_size(mut s: String) -> String {
1145 if let Some(req) = s.strip_suffix('%') {
1146 let ctx = current_context_size().trim_end_matches('%');
1147 if matches!(
1148 CURRENT_STYLE.with(|c| c.get()),
1149 MathStyle::Script | MathStyle::ScriptScript
1150 ) && let (Ok(req), Ok(ex)) = (req.parse::<f64>(), ctx.parse::<f64>())
1151 && ex != 0.0
1152 {
1153 s = format!("{}%", (100.0 * req / ex) as i32);
1154 }
1155 if let Some(pct) = s.strip_suffix('%')
1156 && let Ok(pct) = pct.parse::<f64>()
1157 {
1158 s = fmt_em(pct / 100.0);
1159 }
1160 }
1161 s
1162}
1163
1164fn is_format_char(c: char) -> bool {
1166 matches!(c,
1167 '\u{00AD}' | '\u{200B}'..='\u{200F}' | '\u{2060}'..='\u{2064}' | '\u{FEFF}')
1168}
1169
1170fn is_core_k_glyph(text: &str, role: &str) -> bool {
1174 !text.chars().all(is_format_char) && operator_dictionary::opdict_category(text, role) == "K"
1175}
1176
1177const INVISIBLE_OPERAND_TEXT: &str = "\u{2060}";
1181
1182fn invisible_operand() -> NodeData {
1189 NodeData::Element {
1190 tag: "m:mphantom".to_string(),
1191 attributes: None,
1192 children: vec![NodeData::Element {
1193 tag: "m:mi".to_string(),
1194 attributes: None,
1195 children: vec![NodeData::Text(INVISIBLE_OPERAND_TEXT.to_string())],
1196 }],
1197 }
1198}
1199
1200fn fill_empty_operands(node: &mut NodeData) {
1207 let NodeData::Element { tag, children, .. } = node else {
1208 return;
1209 };
1210 if is_mrow_like(tag) {
1211 let beside_operator = |i: usize| {
1212 let left = children[..i].iter().rev().find(|c| !is_space_like(c));
1213 let right = children[i + 1..].iter().find(|c| !is_space_like(c));
1214 left.is_some_and(is_embellished_operator) || right.is_some_and(is_embellished_operator)
1215 };
1216 let empty: Vec<usize> = (0..children.len())
1217 .filter(|&i| is_empty_box(&children[i]) && beside_operator(i))
1218 .collect();
1219 for i in empty {
1220 let slot = &mut children[i];
1221 if has_output_attributes(slot) {
1222 if let NodeData::Element { children: inner, .. } = slot {
1223 inner.push(invisible_operand());
1224 }
1225 } else {
1226 let internal = match slot {
1228 NodeData::Element { attributes, .. } => attributes.take(),
1229 _ => None,
1230 };
1231 *slot = invisible_operand();
1232 if let NodeData::Element { attributes, .. } = slot {
1233 *attributes = internal;
1234 }
1235 }
1236 }
1237 }
1238 for child in children.iter_mut() {
1239 fill_empty_operands(child);
1240 }
1241}
1242
1243fn is_empty_box(node: &NodeData) -> bool {
1245 matches!(node, NodeData::Element { tag, children, .. }
1246 if matches!(tag.as_str(), "m:mrow" | "m:mpadded" | "m:mstyle") && children.iter().all(is_empty_box))
1247}
1248
1249fn has_output_attributes(node: &NodeData) -> bool {
1251 matches!(node, NodeData::Element { attributes, children, .. }
1252 if attributes.as_ref().is_some_and(|a| a.keys().any(|k| !k.starts_with('_')))
1253 || children.iter().any(has_output_attributes))
1254}
1255
1256fn is_space_like(node: &NodeData) -> bool {
1258 match node {
1259 NodeData::Element { tag, children, .. } => match tag.as_str() {
1260 "m:mtext" | "m:mspace" => true,
1261 "m:mrow" | "m:mpadded" | "m:mstyle" | "m:mphantom" => children.iter().all(is_space_like),
1262 _ => false,
1263 },
1264 _ => false,
1265 }
1266}
1267
1268fn is_embellished_operator(node: &NodeData) -> bool {
1271 match node {
1272 NodeData::Element { tag, .. } if tag == "m:mo" => !is_node_text_invisible_op(node),
1273 NodeData::Element { tag, children, .. } if is_embellisher_tag(tag) => {
1274 children.first().is_some_and(is_embellished_operator)
1275 },
1276 _ => false,
1277 }
1278}
1279
1280fn pmml_token_inner(doc: &PostDocument, node: &Node, role_override: Option<&str>) -> NodeData {
1288 let role = role_override
1289 .map(String::from)
1290 .or_else(|| node.get_attribute("role"))
1291 .unwrap_or_else(|| "UNKNOWN".to_string());
1292 let font = node.get_attribute("font").or_else(|| ctx_get(&CTX_FONT));
1294 let mut text = node.get_content();
1295 let meaning = node.get_attribute("meaning");
1296
1297 if meaning.as_deref() == Some("absent") {
1299 return invisible_operand();
1302 }
1303
1304 let tag = match role.as_str() {
1306 "NUMBER" => "m:mn",
1307 "ID" | "UNKNOWN" => "m:mi",
1308 "FUNCTION" | "OPFUNCTION" | "TRIGFUNCTION" => "m:mi",
1309 _ => "m:mo",
1310 };
1311
1312 if text.is_empty() {
1314 if node
1322 .get_attribute("class")
1323 .is_some_and(|c| c.split_whitespace().any(|w| w == "ltx_unit"))
1324 {
1325 return invisible_operand();
1326 }
1327 if let Some(default) = default_token_content(&role) {
1328 text = default.to_string();
1329 } else {
1330 text = meaning
1331 .or_else(|| node.get_attribute("name"))
1332 .unwrap_or_else(|| role.clone());
1333 }
1334 }
1335
1336 if text == "-" && matches!(role.as_str(), "ADDOP" | "OPERATOR") {
1338 text = "\u{2212}".to_string(); }
1340
1341 let is_replaced_invisible_times = text == "\u{2062}" && !get_invisible_times();
1343 if is_replaced_invisible_times {
1344 text = "\u{200B}".to_string(); }
1346
1347 let mut attrs = HashMap::default();
1348
1349 let is_format_only = text.chars().all(is_format_char);
1354
1355 if tag == "m:mo" && (is_replaced_invisible_times || is_core_k_glyph(&text, &role)) {
1360 attrs.insert("lspace".to_string(), "0em".to_string());
1361 attrs.insert("rspace".to_string(), "0em".to_string());
1362 }
1363
1364 if !is_format_only {
1367 use crate::unicode;
1368 let mut variant: Option<&str> = font.as_deref().map(unicode::unicode_mathvariant);
1369
1370 if tag == "m:mi" && text.chars().count() == 1 {
1377 if variant == Some("italic") {
1378 variant = None;
1379 } else if variant.is_none_or(str::is_empty) {
1380 variant = Some("normal");
1381 }
1382 } else if font.is_some() && variant == Some("normal") {
1383 variant = None; } else if tag == "m:mi" && text.chars().count() > 1 && font.is_none() {
1385 variant = Some("normal"); }
1387
1388 if let Some(v) = variant
1395 && tag != "m:mtext"
1396 && let Some(u_variant) = plane1_target_variant(v)
1397 && let Some(u_text) = unicode::unicode_convert(&text, u_variant)
1398 && (!u_text.is_empty() || text.is_empty())
1399 {
1400 text = u_text;
1401 variant = if u_variant != v && v.starts_with("bold") {
1406 Some("bold")
1407 } else {
1408 None
1409 };
1410 }
1411
1412 if let Some(v) = variant {
1414 if tag == "m:mi" && text.chars().count() == 1 {
1415 if v != "italic" {
1416 attrs.insert("mathvariant".to_string(), v.to_string());
1417 }
1418 } else if v != "normal" {
1419 attrs.insert("mathvariant".to_string(), v.to_string());
1420 }
1421 }
1422
1423 let is_format_only = text.chars().all(|c| {
1426 matches!(c,
1427 '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202F}'
1428 | '\u{2060}'..='\u{2064}' | '\u{FEFF}' | '\u{00AD}')
1429 }) && !text.is_empty();
1430 if let Some(ref f) = font {
1431 if !is_format_only {
1432 if f.contains("caligraphic") {
1433 let prev = attrs.get("class").cloned().unwrap_or_default();
1434 let new = if prev.is_empty() {
1435 "ltx_font_mathcaligraphic".to_string()
1436 } else {
1437 format!("{} ltx_font_mathcaligraphic", prev)
1438 };
1439 attrs.insert("class".to_string(), new);
1440 } else if f.contains("script") {
1441 let prev = attrs.get("class").cloned().unwrap_or_default();
1442 let new = if prev.is_empty() {
1443 "ltx_font_mathscript".to_string()
1444 } else {
1445 format!("{} ltx_font_mathscript", prev)
1446 };
1447 attrs.insert("class".to_string(), new);
1448 } else if f.contains("fraktur") && text.chars().all(|c| "+-0123456789.".contains(c)) {
1449 let prev = attrs.get("class").cloned().unwrap_or_default();
1450 let new = if prev.is_empty() {
1451 "ltx_font_oldstyle".to_string()
1452 } else {
1453 format!("{} ltx_font_oldstyle", prev)
1454 };
1455 attrs.insert("class".to_string(), new);
1456 } else if f.contains("smallcaps") {
1457 let prev = attrs.get("class").cloned().unwrap_or_default();
1458 let new = if prev.is_empty() {
1459 "ltx_font_smallcaps".to_string()
1460 } else {
1461 format!("{} ltx_font_smallcaps", prev)
1462 };
1463 attrs.insert("class".to_string(), new);
1464 } else if let Some(v) = variant {
1465 if v != "normal" {
1466 let prev = attrs.get("class").cloned().unwrap_or_default();
1467 let new = if prev.is_empty() {
1468 format!("ltx_mathvariant_{}", v)
1469 } else {
1470 format!("{} ltx_mathvariant_{}", prev, v)
1471 };
1472 attrs.insert("class".to_string(), new);
1473 }
1474 }
1475 }
1476 }
1477 }
1478
1479 if tag != "m:mo"
1484 && let Some(size) = node.get_attribute("fontsize")
1485 && size != current_context_size()
1486 {
1487 attrs.insert("mathsize".to_string(), resolve_token_size(size));
1488 }
1489
1490 if tag == "m:mo" {
1494 let props = operator_dictionary::opdict_lookup(&text, &role);
1495 let mut stretchy = node.with_attribute(c"stretchy", |v| v == "true") == Some(true);
1497 let is_fence = matches!(role.as_str(), "OPEN" | "CLOSE" | "MIDDLE");
1498 let is_sep = role == "PUNCT";
1499 let is_largeop = matches!(role.as_str(), "SUMOP" | "INTOP");
1500 let is_moveop = matches!(role.as_str(), "SUMOP" | "INTOP" | "BIGOP" | "LIMITOP"); let is_symm = is_largeop || text == "/"; let pos = node
1503 .get_attribute("scriptpos")
1504 .unwrap_or_else(|| "post".to_string());
1505
1506 let mut size = node.get_attribute("fontsize");
1509 if stretchy {
1510 size = None;
1511 }
1512 let is_invisible = !text.is_empty()
1516 && text
1517 .chars()
1518 .all(|c| matches!(c, '\u{2061}'..='\u{2063}' | '\u{200B}'));
1519 if is_invisible {
1520 stretchy = false;
1521 size = None;
1522 }
1523
1524 let mut props_stretchy = props.stretchy;
1533 let mut stretchyhack = false;
1534 let resolved_size = size
1535 .filter(|s| s != current_context_size())
1536 .map(resolve_token_size);
1537 if let Some(size) = resolved_size {
1538 if is_symm || props.symmetric {
1539 stretchyhack = true;
1540 if !matches!(text.as_str(), "(" | ")" | "[" | "]" | "{" | "}") {
1542 props_stretchy = false;
1543 }
1544 stretchy = true; attrs.insert("minsize".to_string(), size.clone());
1546 attrs.insert("maxsize".to_string(), size);
1547 } else {
1548 stretchy = false; attrs.insert("mathsize".to_string(), size);
1550 }
1551 }
1552 let _ = stretchyhack;
1553
1554 if stretchy != props_stretchy {
1557 attrs.insert(
1558 "stretchy".to_string(),
1559 (if stretchy { "true" } else { "false" }).to_string(),
1560 );
1561 }
1562 if is_fence != props.fence {
1563 attrs.insert(
1564 "fence".to_string(),
1565 (if is_fence { "true" } else { "false" }).to_string(),
1566 );
1567 }
1568 if is_sep != props.separator {
1569 attrs.insert(
1570 "separator".to_string(),
1571 (if is_sep { "true" } else { "false" }).to_string(),
1572 );
1573 }
1574 if is_largeop != props.largeop {
1575 attrs.insert(
1576 "largeop".to_string(),
1577 (if is_largeop { "true" } else { "false" }).to_string(),
1578 );
1579 }
1580 if is_largeop {
1581 attrs.insert("_largeop".to_string(), "1".to_string()); }
1583 if is_symm && !props.symmetric && (stretchy || props_stretchy) {
1584 attrs.insert("symmetric".to_string(), "true".to_string());
1585 }
1586 if is_moveop && pos.contains("mid") {
1590 attrs.insert("movablelimits".to_string(), "false".to_string());
1591 }
1592
1593 if role_override.is_none() {
1600 attrs.insert("_role".to_string(), role);
1601 }
1602 if props.lspace > 0.0 {
1603 attrs.insert("_lspace".to_string(), fmt_em(props.lspace));
1604 }
1605 if props.rspace > 0.0 {
1606 attrs.insert("_rspace".to_string(), fmt_em(props.rspace));
1607 }
1608 }
1609
1610 if !is_format_only {
1613 if let Some(color) = node.get_attribute("color").or_else(|| ctx_get(&CTX_COLOR)) {
1614 attrs.insert("mathcolor".to_string(), color);
1615 }
1616 if let Some(bg) = ctx_get(&CTX_BGCOLOR) {
1620 attrs.insert("mathbackground".to_string(), bg);
1621 }
1622 let cssstyle = node.get_attribute("cssstyle").unwrap_or_default();
1623 let opacity = node
1624 .get_attribute("opacity")
1625 .or_else(|| ctx_get(&CTX_OPACITY));
1626 let style = match (cssstyle.is_empty(), opacity) {
1627 (true, None) => String::new(),
1628 (true, Some(op)) => format!("opacity:{op}"),
1629 (false, None) => cssstyle,
1630 (false, Some(op)) => format!("{cssstyle};opacity:{op}"),
1631 };
1632 if !style.is_empty() {
1633 attrs.insert("style".to_string(), style);
1634 }
1635 }
1636
1637 if let Some(href) = node.get_attribute("href") {
1639 attrs.insert("href".to_string(), href);
1640 }
1641
1642 if let Some(class) = node.get_attribute("class") {
1644 attrs.insert("class".to_string(), class);
1645 }
1646
1647 if let Some(sp) = node.get_attribute_ns("sourcepos", "http://dlmf.nist.gov/LaTeXML/data") {
1654 attrs.insert("data-sourcepos".to_string(), sp);
1655 }
1656
1657 pmml_maybe_resize(doc, node, NodeData::Element {
1660 tag: tag.to_string(),
1661 attributes: if attrs.is_empty() { None } else { Some(attrs) },
1662 children: vec![NodeData::Text(text)],
1663 })
1664}
1665
1666fn pmml_hint(doc: &PostDocument, node: &Node) -> NodeData {
1670 if latexml_core::document::is_phantom_box(node) {
1671 return pmml_phantom(doc, node);
1672 }
1673 let w = node
1678 .get_attribute("width")
1679 .map(|w| super::get_xm_hint_spacing(&w))
1680 .unwrap_or(0.0);
1681 let attrs = if w != 0.0 {
1682 HashMap::from_iter([("width".to_string(), format!("{}em", perl_num(w)))])
1685 } else {
1686 HashMap::from_iter([("_ignorable".to_string(), "1".to_string())])
1687 };
1688 NodeData::Element {
1689 tag: "m:mspace".to_string(),
1690 attributes: Some(attrs),
1691 children: vec![],
1692 }
1693}
1694
1695fn pmml_phantom(doc: &PostDocument, node: &Node) -> NodeData {
1700 let content: Vec<NodeData> = element_children_iter(node).map(|c| pmml(doc, &c)).collect();
1701 let mut content = pmml_row(content);
1702 if is_phantom_operator(&content) {
1703 quiet_phantom_operator(&mut content);
1704 }
1705 let name = node.get_attribute("name");
1706 let width = if name.as_deref() == Some("vphantom") {
1707 None
1708 } else {
1709 phantom_spacing_as_width(node, &mut content)
1710 };
1711 let phantom = NodeData::Element {
1712 tag: "m:mphantom".to_string(),
1713 attributes: None,
1714 children: vec![content],
1715 };
1716 let zero = || "0pt".to_string();
1718 let mut padded = match name.as_deref() {
1719 Some("hphantom") => HashMap::from_iter([
1720 ("height".to_string(), zero()),
1721 ("depth".to_string(), zero()),
1722 ]),
1723 Some("vphantom") => HashMap::from_iter([("width".to_string(), zero())]),
1724 _ => HashMap::default(),
1725 };
1726 if let Some(width) = width {
1727 padded.insert("width".to_string(), width);
1728 }
1729 if padded.is_empty() {
1730 return phantom;
1731 }
1732 NodeData::Element {
1733 tag: "m:mpadded".to_string(),
1734 attributes: Some(padded),
1735 children: vec![phantom],
1736 }
1737}
1738
1739fn phantom_spacing_as_width(node: &Node, content: &mut NodeData) -> Option<String> {
1744 let items: Vec<Node> = element_children_iter(node)
1745 .flat_map(|child| {
1746 if child.get_name() == "XMArg" {
1747 element_children_iter(&child).collect()
1748 } else {
1749 vec![child]
1750 }
1751 })
1752 .collect();
1753 if !items
1754 .iter()
1755 .any(|item| item.has_attribute("lpadding") || item.has_attribute("rpadding"))
1756 {
1757 return None;
1758 }
1759 let width = super::get_xm_hint_spacing(&node.get_attribute("width")?);
1760 let mut unpad = |item: &mut NodeData| {
1761 if let NodeData::Element { attributes: Some(attrs), .. } = item {
1762 attrs.remove("_lpadding");
1763 attrs.remove("_rpadding");
1764 }
1765 };
1766 match content {
1767 NodeData::Element { tag, children, .. } if tag == "m:mrow" => {
1768 children.iter_mut().for_each(&mut unpad)
1769 },
1770 item => unpad(item),
1771 }
1772 Some(fmt_em(width.max(0.0)))
1773}
1774
1775fn is_phantom_operator(node: &NodeData) -> bool {
1779 match node {
1780 NodeData::Element { tag, children, .. }
1781 if matches!(tag.as_str(), "m:mstyle" | "m:mrow" | "m:mpadded") =>
1782 {
1783 matches!(&children[..], [only] if is_phantom_operator(only))
1784 },
1785 _ => is_embellished_operator(node),
1786 }
1787}
1788
1789fn quiet_phantom_operator(node: &mut NodeData) {
1795 let text = get_node_text(node);
1796 let NodeData::Element { tag, attributes, children } = node else {
1797 return;
1798 };
1799 if is_embellisher_tag(tag) || matches!(tag.as_str(), "m:mstyle" | "m:mrow" | "m:mpadded") {
1800 if let Some(base) = children.first_mut() {
1801 quiet_phantom_operator(base);
1802 }
1803 return;
1804 }
1805 if tag != "m:mo" {
1806 return;
1807 }
1808 let attrs = attributes.get_or_insert_with(HashMap::default);
1809 attrs.insert("lspace".to_string(), "0em".to_string());
1810 attrs.insert("rspace".to_string(), "0em".to_string());
1811 let role = attrs.get("_role").map_or("ATOM", String::as_str);
1812 let stretchy = match attrs.get("stretchy").map(String::as_str) {
1813 Some(stretchy) => stretchy == "true",
1814 None => operator_dictionary::opdict_lookup(&text, role).stretchy,
1815 };
1816 if !stretchy {
1817 return;
1818 }
1819 if !attrs.contains_key("maxsize") {
1820 attrs.insert("stretchy".to_string(), "false".to_string());
1821 return;
1822 }
1823 let operator = std::mem::replace(node, NodeData::Text(String::new()));
1824 *node = NodeData::Element {
1825 tag: "m:mrow".to_string(),
1826 attributes: None,
1827 children: vec![
1828 NodeData::Element {
1829 tag: "m:mi".to_string(),
1830 attributes: None,
1831 children: vec![NodeData::Text(INVISIBLE_OPERAND_TEXT.to_string())],
1832 },
1833 operator,
1834 ],
1835 };
1836}
1837
1838fn perl_num(v: f64) -> String {
1842 if v == 0.0 {
1843 return "0".to_string();
1844 }
1845 let magnitude = v.abs().log10().floor() as i32;
1846 let decimals = (14 - magnitude).clamp(0, 17) as usize;
1847 let s = format!("{v:.decimals$}");
1848 if s.contains('.') {
1849 s.trim_end_matches('0').trim_end_matches('.').to_string()
1850 } else {
1851 s
1852 }
1853}
1854
1855fn pmml_array(doc: &PostDocument, node: &Node) -> NodeData {
1859 let ostyle = CURRENT_STYLE.with(|s| s.get());
1865 let nstyle = node
1866 .get_attribute("mathstyle")
1867 .as_deref()
1868 .and_then(MathStyle::from_attr);
1869 if let Some(n) = nstyle {
1870 CURRENT_STYLE.with(|s| s.set(n));
1871 }
1872 let result = pmml_array_inner(doc, node);
1873 CURRENT_STYLE.with(|s| s.set(ostyle));
1874 let result = maybe_style_wrap(result, ostyle, nstyle);
1876 pmml_maybe_resize(doc, node, result)
1877}
1878
1879fn is_zero_length(length: &str) -> bool {
1881 length
1882 .trim()
1883 .trim_end_matches(|c: char| c.is_ascii_alphabetic())
1884 .trim()
1885 .parse::<f64>()
1886 .is_ok_and(|v| v == 0.0)
1887}
1888
1889fn pmml_array_inner(doc: &PostDocument, node: &Node) -> NodeData {
1890 let mut rows = Vec::new();
1891 let width = node.get_attribute("width");
1892 let vattach = node
1893 .get_attribute("vattach")
1894 .unwrap_or_else(|| "middle".to_string());
1895 let align = match vattach.as_str() {
1897 "top" => "baseline1",
1898 "bottom" => "baseline-1",
1899 "middle" | "" => "axis",
1900 _ => vattach.as_str(),
1901 };
1902 let rowsep = node
1904 .get_attribute("rowsep")
1905 .filter(|sep| !is_zero_length(sep));
1906 let colsep = node
1907 .get_attribute("colsep")
1908 .unwrap_or_else(|| "5pt".to_string());
1909
1910 let mut nrows = 0;
1911 let mut ncols = 0;
1912 for row_node in element_children(node) {
1913 let mut cols = Vec::new();
1914 let mut nc = 0;
1915 for cell_node in element_children(&row_node) {
1916 nc += 1;
1917 let cell_align = cell_node.get_attribute("align");
1918 let colspan = cell_node.get_attribute("colspan");
1919 let rowspan = cell_node.get_attribute("rowspan");
1920 let mut td_attrs = HashMap::default();
1921 if let Some(a) = &cell_align {
1922 if a != "center" {
1923 td_attrs.insert("columnalign".to_string(), a.clone());
1924 td_attrs.insert("class".to_string(), format!("ltx_align_{}", a));
1925 }
1926 }
1927 let bc = cell_node.get_attribute("border").and_then(|b| {
1937 let s = b
1938 .split_whitespace()
1939 .map(|p| format!("ltx_border_{p}"))
1940 .collect::<Vec<_>>()
1941 .join(" ");
1942 (!s.is_empty()).then_some(s)
1943 });
1944 let hc = cell_node.get_attribute("thead").and_then(|t| {
1945 let s = t
1946 .split_whitespace()
1947 .map(|p| format!("ltx_th_{p}"))
1948 .collect::<Vec<_>>()
1949 .join(" ");
1950 (!s.is_empty()).then_some(s)
1951 });
1952 let border_thead = match (bc, hc) {
1954 (Some(bc), Some(hc)) => Some(format!("{bc} {hc}")),
1955 (Some(bc), None) => Some(bc),
1956 (None, Some(hc)) => Some(hc),
1957 (None, None) => None,
1958 };
1959 let cl = cell_node.get_attribute("class").filter(|s| !s.is_empty());
1960 if let Some(class) = match (border_thead, cl) {
1962 (Some(c), Some(cl)) => Some(format!("{c} {cl}")),
1963 (Some(c), None) => Some(c),
1964 (None, Some(cl)) => Some(cl),
1965 (None, None) => None,
1966 } {
1967 td_attrs.insert("class".to_string(), class);
1968 }
1969 if let Some(cs) = colspan {
1970 td_attrs.insert("columnspan".to_string(), cs);
1971 }
1972 if let Some(rs) = rowspan {
1973 td_attrs.insert("rowspan".to_string(), rs);
1974 }
1975 if let Some(bg) = cell_node.get_attribute("backgroundcolor") {
1979 td_attrs.insert("mathbackground".to_string(), bg);
1980 }
1981
1982 let cell_children = element_children(&cell_node);
1983 let cell_content = if cell_children.is_empty() {
1984 vec![]
1985 } else {
1986 filter_row(cell_children.iter().map(|c| pmml(doc, c)).collect())
1988 };
1989
1990 cols.push(NodeData::Element {
1991 tag: "m:mtd".to_string(),
1992 attributes: if td_attrs.is_empty() {
1993 None
1994 } else {
1995 Some(td_attrs)
1996 },
1997 children: cell_content,
1998 });
1999 }
2000 if nc > ncols {
2001 ncols = nc;
2002 }
2003 nrows += 1;
2004 rows.push(NodeData::Element {
2005 tag: "m:mtr".to_string(),
2006 attributes: None,
2007 children: cols,
2008 });
2009 }
2010
2011 let emit_colsep = ncols >= 2;
2014
2015 let mut table_attrs = HashMap::default();
2016 if align != "axis" {
2017 table_attrs.insert("align".to_string(), align.to_string());
2018 }
2019 if let Some(rowsep) = rowsep.filter(|_| nrows >= 2) {
2020 table_attrs.insert("rowspacing".to_string(), rowsep);
2021 }
2022 if emit_colsep {
2023 table_attrs.insert("columnspacing".to_string(), colsep);
2024 }
2025 if let Some(w) = width {
2026 table_attrs.insert("width".to_string(), w);
2027 }
2028 if CURRENT_STYLE.with(|s| s.get()) == MathStyle::Display {
2030 table_attrs.insert("displaystyle".to_string(), "true".to_string());
2031 }
2032
2033 NodeData::Element {
2034 tag: "m:mtable".to_string(),
2035 attributes: if table_attrs.is_empty() {
2036 None
2037 } else {
2038 Some(table_attrs)
2039 },
2040 children: rows,
2041 }
2042}
2043
2044fn pmml_script_simple(doc: &PostDocument, tag: &str, base: &Node, script: &Node) -> NodeData {
2049 NodeData::Element {
2050 tag: tag.to_string(),
2051 attributes: None,
2052 children: vec![pmml(doc, base), pmml_scriptsize(doc, script)],
2053 }
2054}
2055
2056fn pmml_scriptsize(doc: &PostDocument, node: &Node) -> NodeData {
2060 let old = CURRENT_STYLE.with(|s| {
2061 let o = s.get();
2062 s.set(o.script_step());
2063 o
2064 });
2065 let r = pmml(doc, node);
2066 CURRENT_STYLE.with(|s| s.set(old));
2067 r
2068}
2069
2070fn pmml_smaller(doc: &PostDocument, node: &Node) -> NodeData {
2073 let old = CURRENT_STYLE.with(|s| {
2074 let o = s.get();
2075 s.set(o.step_down());
2076 o
2077 });
2078 let r = pmml(doc, node);
2079 CURRENT_STYLE.with(|s| s.set(old));
2080 r
2081}
2082
2083fn pmml_infix(doc: &PostDocument, op: &Node, args: &[Node]) -> NodeData {
2087 match args {
2104 [] => pmml(doc, op),
2105 [arg] => {
2117 let op_prefix = if name_is(op, "XMTok") {
2118 pmml_token_inner(doc, op, Some("OPERATOR"))
2119 } else {
2120 pmml(doc, op)
2121 };
2122 pmml_row(vec![op_prefix, pmml(doc, arg)])
2123 },
2124 [first, rest @ ..] => {
2126 let op_mml = pmml(doc, op);
2127 let mut items = vec![pmml(doc, first)];
2128 for arg in rest {
2129 items.push(op_mml.clone());
2130 items.push(pmml(doc, arg));
2131 }
2132 pmml_row(items)
2133 },
2134 }
2135}
2136
2137fn is_absent_operand(node: &Node) -> bool {
2144 if !name_is(node, "XMTok") {
2145 return false;
2146 }
2147 node.with_attribute(c"meaning", |v| v == "absent") == Some(true)
2148}
2149
2150fn pmml_summation(doc: &PostDocument, op: &Node, args: &[Node]) -> NodeData {
2154 let op_mml = pmml(doc, op);
2155 let needs_apply = !op_base_is_mo(&op_mml);
2160 let mut items = vec![op_mml];
2161 if needs_apply {
2162 items.push(pmml_mo_str("\u{2061}")); }
2164 for arg in args {
2165 items.push(pmml(doc, arg));
2166 }
2167 pmml_row(items)
2168}
2169
2170fn pmml_parenthesize(doc: &PostDocument, op: &Node, args: &[Node]) -> NodeData {
2174 let mut items = vec![pmml(doc, op)];
2175 for arg in args {
2176 items.push(pmml(doc, arg));
2177 }
2178 pmml_row(items)
2179}
2180
2181type ScriptPair = (Option<Node>, Option<Node>);
2189
2190fn pmml_script_full(doc: &PostDocument, op: &Node, base: &Node, script: &Node) -> NodeData {
2194 let (inner_base, pre_scripts, mid_scripts, post_scripts, emb_right) =
2195 pmml_script_decipher(doc, op, base, script);
2196
2197 let ostyle = CURRENT_STYLE.with(|s| s.get());
2203 let bstyle = inner_base
2204 .get_attribute("mathstyle")
2205 .as_deref()
2206 .and_then(MathStyle::from_attr);
2207 if let Some(b) = bstyle {
2208 CURRENT_STYLE.with(|s| s.set(b));
2209 }
2210 let base_mml = pmml(doc, &inner_base);
2211 CURRENT_STYLE.with(|s| s.set(ostyle));
2212
2213 let base_mml = apply_mid_scripts(doc, base_mml, &mid_scripts, emb_right.as_ref());
2215
2216 let layout = apply_multi_scripts(doc, base_mml, &pre_scripts, &post_scripts);
2218 match bstyle {
2219 Some(b) if b != ostyle => NodeData::Element {
2220 tag: "m:mstyle".to_string(),
2221 attributes: Some(HashMap::from_iter([(
2222 "displaystyle".to_string(),
2223 (if b == MathStyle::Display {
2224 "true"
2225 } else {
2226 "false"
2227 })
2228 .to_string(),
2229 )])),
2230 children: vec![layout],
2231 },
2232 _ => layout,
2233 }
2234}
2235
2236fn pmml_script_decipher(
2240 doc: &PostDocument,
2241 op: &Node,
2242 base: &Node,
2243 script: &Node,
2244) -> (
2245 Node,
2246 Vec<ScriptPair>,
2247 Vec<ScriptPair>,
2248 Vec<ScriptPair>,
2249 Option<Node>,
2250) {
2251 let mut pre_scripts: Vec<ScriptPair> = Vec::new();
2252 let mut mid_scripts: Vec<ScriptPair> = Vec::new();
2253 let mut post_scripts: Vec<ScriptPair> = Vec::new();
2254 let mut emb_right: Option<Node> = None;
2259 let mut saw_mid = false;
2260
2261 let (mut pre_level, mut mid_level, mut post_level) =
2266 ("0".to_string(), "0".to_string(), "0".to_string());
2267
2268 let (pos, level) = parse_scriptpos(op);
2269 let is_sub = op.get_attribute("role").unwrap_or_default().contains("SUB");
2270
2271 let pair = if is_sub {
2273 (Some(script.clone()), None)
2274 } else {
2275 (None, Some(script.clone()))
2276 };
2277 match pos {
2278 ScriptPos::Pre => {
2279 pre_scripts.push(pair);
2280 pre_level = level;
2281 },
2282 ScriptPos::Mid => {
2283 saw_mid = true;
2284 mid_scripts.push(pair);
2285 mid_level = level;
2286 },
2287 ScriptPos::Post => {
2288 post_scripts.push(pair);
2289 post_level = level;
2290 },
2291 }
2292
2293 let mut current_base = base.clone();
2295 loop {
2296 let Some(realized) = doc.realize_xm_node_branch(¤t_base, XMBranch::Presentation) else {
2300 break;
2301 };
2302 current_base = realized;
2303
2304 if !doc.is_qname(¤t_base, "ltx:XMApp") {
2305 break;
2306 }
2307
2308 let children = element_children(¤t_base);
2309 if children.len() < 3 {
2310 break;
2311 }
2312
2313 let xop = &children[0];
2314 if !doc.is_qname(xop, "ltx:XMTok") {
2315 break;
2316 }
2317
2318 let xrole = xop.get_attribute("role").unwrap_or_default();
2319 let is_script_op = xrole.contains("SUPERSCRIPTOP") || xrole.contains("SUBSCRIPTOP");
2320 if !is_script_op {
2321 break;
2322 }
2323
2324 let xbase = children[1].clone();
2325 let xscript = &children[2];
2326 let (xpos, xlevel) = parse_scriptpos(xop);
2327 let x_is_sub = xrole.contains("SUB");
2328
2329 match xpos {
2330 ScriptPos::Pre => place_script(
2334 &mut pre_scripts,
2335 &mut pre_level,
2336 xlevel,
2337 x_is_sub,
2338 xscript.clone(),
2339 false,
2340 ),
2341 ScriptPos::Mid => {
2342 saw_mid = true;
2343 place_script(
2344 &mut mid_scripts,
2345 &mut mid_level,
2346 xlevel,
2347 x_is_sub,
2348 xscript.clone(),
2349 true,
2350 );
2351 },
2352 ScriptPos::Post => {
2353 if saw_mid {
2362 emb_right = Some(xscript.clone());
2363 break;
2364 }
2365 place_script(
2366 &mut post_scripts,
2367 &mut post_level,
2368 xlevel,
2369 x_is_sub,
2370 xscript.clone(),
2371 true,
2372 );
2373 },
2374 }
2375
2376 current_base = xbase;
2377 }
2378
2379 (
2380 current_base,
2381 pre_scripts,
2382 mid_scripts,
2383 post_scripts,
2384 emb_right,
2385 )
2386}
2387
2388#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2391enum ScriptPos {
2392 Pre,
2394 Mid,
2396 Post,
2398}
2399
2400fn parse_scriptpos(op: &Node) -> (ScriptPos, String) {
2410 let raw = op
2411 .get_attribute("scriptpos")
2412 .unwrap_or_else(|| "post0".to_string());
2413 let (pos, rest) = if let Some(rest) = raw.strip_prefix("pre") {
2414 (ScriptPos::Pre, rest)
2415 } else if let Some(rest) = raw.strip_prefix("mid") {
2416 (ScriptPos::Mid, rest)
2417 } else if let Some(rest) = raw.strip_prefix("post") {
2418 (ScriptPos::Post, rest)
2419 } else {
2420 (ScriptPos::Post, raw.as_str())
2421 };
2422 if rest.is_empty() || rest.bytes().all(|b| b.is_ascii_digit()) {
2425 (pos, rest.to_string())
2426 } else {
2427 (ScriptPos::Post, String::new())
2428 }
2429}
2430
2431fn place_script(
2452 list: &mut Vec<ScriptPair>,
2453 level: &mut String,
2454 new_level: String,
2455 is_sub: bool,
2456 script: Node,
2457 at_front: bool,
2458) {
2459 let slot_taken = |p: &ScriptPair| if is_sub { p.0.is_some() } else { p.1.is_some() };
2460 let current = if at_front { list.first() } else { list.last() };
2461 if current.is_none_or(slot_taken) || *level != new_level {
2462 if at_front {
2463 list.insert(0, (None, None));
2464 } else {
2465 list.push((None, None));
2466 }
2467 }
2468 let pair = if at_front {
2469 list.first_mut()
2470 } else {
2471 list.last_mut()
2472 }
2473 .expect("a pair was just ensured to exist");
2474 if is_sub {
2475 pair.0 = Some(script);
2476 } else {
2477 pair.1 = Some(script);
2478 }
2479 *level = new_level;
2480}
2481
2482fn apply_mid_scripts(
2484 doc: &PostDocument,
2485 mut base: NodeData,
2486 mid_scripts: &[ScriptPair],
2487 emb_right: Option<&Node>,
2488) -> NodeData {
2489 for (sub_opt, sup_opt) in mid_scripts {
2490 let under = sub_opt
2491 .as_ref()
2492 .map(|s| pmml_scriptsize_padded(doc, s, emb_right));
2493 let over = sup_opt
2494 .as_ref()
2495 .map(|s| pmml_scriptsize_padded(doc, s, emb_right));
2496
2497 base = match (under, over) {
2498 (Some(u), None) => NodeData::Element {
2499 tag: "m:munder".to_string(),
2500 attributes: None,
2501 children: vec![base, u],
2502 },
2503 (None, Some(o)) => NodeData::Element {
2504 tag: "m:mover".to_string(),
2505 attributes: None,
2506 children: vec![base, o],
2507 },
2508 (Some(u), Some(o)) => NodeData::Element {
2509 tag: "m:munderover".to_string(),
2510 attributes: None,
2511 children: vec![base, u, o],
2512 },
2513 (None, None) => base,
2514 };
2515 }
2516 base
2517}
2518
2519fn pmml_scriptsize_padded(doc: &PostDocument, script: &Node, emb_right: Option<&Node>) -> NodeData {
2532 let script_mml = pmml_scriptsize(doc, script);
2533 match emb_right {
2534 None => script_mml,
2535 Some(emb) => NodeData::Element {
2536 tag: "m:mrow".to_string(),
2537 attributes: None,
2538 children: vec![script_mml, NodeData::Element {
2539 tag: "m:mphantom".to_string(),
2540 attributes: None,
2541 children: vec![pmml_scriptsize(doc, emb)],
2542 }],
2543 },
2544 }
2545}
2546
2547fn apply_multi_scripts(
2551 doc: &PostDocument,
2552 base: NodeData,
2553 pre_scripts: &[ScriptPair],
2554 post_scripts: &[ScriptPair],
2555) -> NodeData {
2556 let none_mml = || NodeData::Element {
2561 tag: "m:mrow".to_string(),
2562 attributes: None,
2563 children: vec![],
2564 };
2565
2566 if !pre_scripts.is_empty() {
2567 let mut children = vec![base];
2569 for (sub_opt, sup_opt) in post_scripts {
2570 children.push(
2571 sub_opt
2572 .as_ref()
2573 .map(|s| pmml_scriptsize(doc, s))
2574 .unwrap_or_else(none_mml),
2575 );
2576 children.push(
2577 sup_opt
2578 .as_ref()
2579 .map(|s| pmml_scriptsize(doc, s))
2580 .unwrap_or_else(none_mml),
2581 );
2582 }
2583 children.push(NodeData::Element {
2584 tag: "m:mprescripts".to_string(),
2585 attributes: None,
2586 children: vec![],
2587 });
2588 for (sub_opt, sup_opt) in pre_scripts {
2589 children.push(
2590 sub_opt
2591 .as_ref()
2592 .map(|s| pmml_scriptsize(doc, s))
2593 .unwrap_or_else(none_mml),
2594 );
2595 children.push(
2596 sup_opt
2597 .as_ref()
2598 .map(|s| pmml_scriptsize(doc, s))
2599 .unwrap_or_else(none_mml),
2600 );
2601 }
2602 NodeData::Element {
2603 tag: "m:mmultiscripts".to_string(),
2604 attributes: None,
2605 children,
2606 }
2607 } else if post_scripts.len() > 1 {
2608 let mut children = vec![base];
2610 for (sub_opt, sup_opt) in post_scripts {
2611 children.push(
2612 sub_opt
2613 .as_ref()
2614 .map(|s| pmml_scriptsize(doc, s))
2615 .unwrap_or_else(none_mml),
2616 );
2617 children.push(
2618 sup_opt
2619 .as_ref()
2620 .map(|s| pmml_scriptsize(doc, s))
2621 .unwrap_or_else(none_mml),
2622 );
2623 }
2624 NodeData::Element {
2625 tag: "m:mmultiscripts".to_string(),
2626 attributes: None,
2627 children,
2628 }
2629 } else if post_scripts.is_empty() {
2630 base
2631 } else {
2632 let (sub_opt, sup_opt) = &post_scripts[0];
2634 match (sub_opt, sup_opt) {
2635 (Some(sub_node), None) => NodeData::Element {
2636 tag: "m:msub".to_string(),
2637 attributes: None,
2638 children: vec![base, pmml_scriptsize(doc, sub_node)],
2639 },
2640 (None, Some(sup_node)) => NodeData::Element {
2641 tag: "m:msup".to_string(),
2642 attributes: None,
2643 children: vec![base, pmml_scriptsize(doc, sup_node)],
2644 },
2645 (Some(sub_node), Some(sup_node)) => NodeData::Element {
2646 tag: "m:msubsup".to_string(),
2647 attributes: None,
2648 children: vec![
2649 base,
2650 pmml_scriptsize(doc, sub_node),
2651 pmml_scriptsize(doc, sup_node),
2652 ],
2653 },
2654 (None, None) => base,
2655 }
2656 }
2657}
2658
2659fn pmml_cfrac(doc: &PostDocument, op: &Node, numer: &Node, denom: &Node) -> NodeData {
2668 if op.with_attribute(c"name", |v| v == "cfrac-inline") == Some(true) {
2671 return pmml_row(do_cfrac(doc, numer, denom));
2672 }
2673 NodeData::Element {
2674 tag: "m:mfrac".to_string(),
2675 attributes: None,
2676 children: vec![pmml_smaller(doc, numer), pmml_smaller(doc, denom)],
2677 }
2678}
2679
2680fn do_cfrac(doc: &PostDocument, numer: &Node, denom: &Node) -> Vec<NodeData> {
2686 if doc.is_qname(denom, "ltx:XMApp") {
2687 let dchildren = element_children(denom);
2688 if dchildren.len() >= 2 {
2689 let denomop = &dchildren[0];
2690 let denomargs = &dchildren[1..];
2691 if denomop.with_attribute(c"role", |v| v == "ADDOP") == Some(true)
2692 || denomop.get_content() == "\u{22EF}"
2693 {
2694 let (rest, last) = denomargs.split_at(denomargs.len() - 1);
2695 let last = &last[0];
2696 if !rest.is_empty() {
2697 let curr = NodeData::Element {
2698 tag: "m:mfrac".to_string(),
2699 attributes: None,
2700 children: vec![pmml_smaller(doc, numer), NodeData::Element {
2701 tag: "m:mrow".to_string(),
2702 attributes: None,
2703 children: vec![
2704 if rest.len() > 1 {
2705 pmml_infix(doc, denomop, rest)
2706 } else {
2707 pmml_smaller(doc, &rest[0])
2708 },
2709 pmml_smaller(doc, denomop),
2710 ],
2711 }],
2712 };
2713 if last.get_content() == "\u{22EF}" {
2714 return vec![curr, pmml_smaller(doc, last)];
2716 } else if doc.is_qname(last, "ltx:XMApp") {
2717 let lchildren = element_children(last);
2718 if lchildren.len() >= 2 {
2719 let lastop = &lchildren[0];
2720 let lastargs = &lchildren[1..];
2721 if lastop.with_attribute(c"meaning", |v| v == "continued-fraction") == Some(true)
2722 && lastargs.len() >= 2
2723 {
2724 let mut out = vec![curr];
2726 out.extend(do_cfrac(doc, &lastargs[0], &lastargs[1]));
2727 return out;
2728 } else if lastop.get_content() == "\u{2062}"
2729 && lastargs.len() == 2
2730 && lastargs[0].get_content() == "\u{22EF}"
2731 {
2732 return vec![
2734 curr,
2735 pmml_smaller(doc, &lastargs[0]),
2736 pmml_smaller(doc, &lastargs[1]),
2737 ];
2738 }
2739 }
2740 }
2741 }
2742 }
2743 }
2744 }
2745 vec![NodeData::Element {
2746 tag: "m:mfrac".to_string(),
2747 attributes: None,
2748 children: vec![pmml_smaller(doc, numer), pmml_smaller(doc, denom)],
2749 }]
2750}
2751
2752fn op_base_is_mo(node: &NodeData) -> bool {
2762 let mut cur = node;
2763 loop {
2764 let NodeData::Element { tag, children, .. } = cur else {
2765 return false;
2766 };
2767 if tag == "m:mo" {
2768 return true;
2769 }
2770 if matches!(
2776 tag.as_str(),
2777 "m:msub"
2778 | "m:msup"
2779 | "m:msubsup"
2780 | "m:munder"
2781 | "m:mover"
2782 | "m:munderover"
2783 | "m:mprescripts"
2784 | "m:mstyle"
2785 ) {
2786 match children.first() {
2787 Some(child) => cur = child,
2788 None => return false,
2789 }
2790 } else if tag == "m:mrow"
2791 && let [child] = children
2792 .iter()
2793 .filter(|c| !is_drawn_phantom(c))
2794 .collect::<Vec<_>>()[..]
2795 {
2796 cur = child;
2799 } else {
2800 return false;
2801 }
2802 }
2803}
2804
2805fn is_drawn_phantom(node: &NodeData) -> bool {
2807 match node {
2808 NodeData::Element { tag, children, .. } => {
2809 tag == "m:mphantom"
2810 || (tag == "m:mpadded" && matches!(&children[..], [only] if is_drawn_phantom(only)))
2811 },
2812 _ => false,
2813 }
2814}
2815
2816fn filter_row(items: Vec<NodeData>) -> Vec<NodeData> {
2818 items
2819 .into_iter()
2820 .filter(|i| {
2821 !matches!(i, NodeData::Element { attributes: Some(a), .. } if a.contains_key("_ignorable"))
2822 })
2823 .collect()
2824}
2825
2826fn pmml_row(children: Vec<NodeData>) -> NodeData {
2827 let children = filter_row(children);
2829 if children.len() == 1 {
2830 children.into_iter().next().unwrap()
2831 } else {
2832 NodeData::Element {
2833 tag: "m:mrow".to_string(),
2834 attributes: None,
2835 children,
2836 }
2837 }
2838}
2839
2840fn pmml_mo_str(text: &str) -> NodeData {
2842 NodeData::Element {
2843 tag: "m:mo".to_string(),
2844 attributes: None,
2845 children: vec![NodeData::Text(text.to_string())],
2846 }
2847}
2848
2849fn pmml_error(msg: &str) -> NodeData {
2851 NodeData::Element {
2852 tag: "m:merror".to_string(),
2853 attributes: None,
2854 children: vec![NodeData::Element {
2855 tag: "m:mtext".to_string(),
2856 attributes: None,
2857 children: vec![NodeData::Text(msg.to_string())],
2858 }],
2859 }
2860}
2861
2862pub fn font_to_mathvariant(font: &str) -> Option<&'static str> {
2867 if font.is_empty() {
2868 return None;
2869 }
2870 Some(crate::unicode::unicode_mathvariant(font))
2871}
2872
2873const TEX_SPACING: [f64; 4] = [0.0, 0.167, 0.222, 0.2778];
2881
2882const SPACING_EPSILON: f64 = 0.01;
2884
2885const SPACING_FUDGE: f64 = 0.3;
2887
2888fn role_to_atom_type(role: &str) -> &'static str {
2890 match role {
2891 "ATOM" | "UNKNOWN" | "ID" | "NUMBER" | "POSTFIX" | "FUNCTION" | "DIFFOP" | "SUPOP"
2892 | "ELIDEOP" => "Ord",
2893 "OPFUNCTION" | "TRIGFUNCTION" | "BIGOP" | "SUMOP" | "INTOP" | "LIMITOP" | "OPERATOR" => "Op",
2894 "ADDOP" | "MULOP" | "BINOP" | "APPLYOP" | "COMPOSEOP" => "Bin",
2895 "RELOP" | "METARELOP" | "MODIFIEROP" | "MODIFIER" | "ARROW" => "Rel",
2896 "OPEN" => "Open",
2897 "CLOSE" => "Close",
2898 "PUNCT" | "VERTBAR" | "PERIOD" => "Punct",
2899 "ARRAY" | "POSTSUBSCRIPT" | "POSTSUPERSCRIPT" | "FLOATSUPERSCRIPT" | "FLOATSUBSCRIPT" => {
2900 "Inner"
2901 },
2902 "MIDDLE" => "Ord",
2903 _ => "Ord",
2904 }
2905}
2906
2907fn atompair_spacing(left: &str, right: &str) -> i32 {
2909 match (left, right) {
2910 ("Ord", "Op") | ("Op", "Ord") | ("Op", "Op") | ("Close", "Op") => 1,
2911 ("Ord", "Bin")
2912 | ("Bin", "Ord")
2913 | ("Bin", "Open")
2914 | ("Bin", "Inner")
2915 | ("Close", "Bin")
2916 | ("Inner", "Bin")
2917 | ("Bin", "Op") => -2,
2918 ("Ord", "Rel")
2919 | ("Rel", "Ord")
2920 | ("Op", "Rel")
2921 | ("Rel", "Open")
2922 | ("Rel", "Inner")
2923 | ("Close", "Rel")
2924 | ("Inner", "Rel")
2925 | ("Rel", "Op") => -3,
2926 ("Ord", "Inner")
2927 | ("Op", "Inner")
2928 | ("Close", "Inner")
2929 | ("Inner", "Inner")
2930 | ("Inner", "Open")
2931 | ("Punct", "Ord")
2932 | ("Punct", "Op")
2933 | ("Punct", "Rel")
2934 | ("Punct", "Open")
2935 | ("Punct", "Close")
2936 | ("Punct", "Punct")
2937 | ("Punct", "Inner")
2938 | ("Inner", "Ord")
2939 | ("Inner", "Punct") => -1,
2940 ("Inner", "Op") => 1,
2941 _ => 0,
2942 }
2943}
2944
2945fn m_atom_type(tag: &str) -> Option<&'static str> {
2947 match tag {
2948 "m:mfrac" => Some("Ord"),
2949 "m:marray" => Some("Inner"),
2950 "m:mspace" => Some("Ord"),
2951 _ => None,
2952 }
2953}
2954
2955fn is_embellisher_tag(tag: &str) -> bool {
2957 matches!(
2958 tag,
2959 "m:msub" | "m:msup" | "m:msubsup" | "m:munder" | "m:mover" | "m:munderover"
2960 )
2961}
2962
2963fn is_mrow_like(tag: &str) -> bool {
2965 matches!(
2966 tag,
2967 "m:mrow" | "m:mpadded" | "m:msqrt" | "m:mstyle" | "m:merror" | "m:mphantom" | "m:mtd"
2968 )
2969}
2970
2971fn is_invisible_op(text: &str) -> bool {
2973 !text.is_empty()
2974 && text
2975 .chars()
2976 .all(|c| matches!(c, '\u{200B}' | '\u{2061}' | '\u{2062}' | '\u{2063}'))
2977}
2978
2979fn fmt_em(val: f64) -> String {
2983 if val == 0.0 {
2984 "0em".to_string()
2985 } else {
2986 format!("{val:.3}em")
2987 }
2988}
2989
2990fn get_node_role(node: &NodeData) -> String {
2992 match node {
2993 NodeData::Element { tag, attributes, children } => {
2994 if is_embellisher_tag(tag) {
2995 if let Some(base) = children.first() {
2996 return get_node_role(base);
2997 }
2998 }
2999 attributes
3000 .as_ref()
3001 .and_then(|a| a.get("_role"))
3002 .cloned()
3003 .unwrap_or_default()
3004 },
3005 _ => String::new(),
3006 }
3007}
3008
3009fn get_node_tag(node: &NodeData) -> &str {
3010 match node {
3011 NodeData::Element { tag, .. } => tag,
3012 _ => "",
3013 }
3014}
3015
3016fn get_node_text(node: &NodeData) -> String {
3017 match node {
3018 NodeData::Text(t) => t.clone(),
3019 NodeData::Element { children, .. } => children.iter().map(get_node_text).collect(),
3020 _ => String::new(),
3021 }
3022}
3023
3024fn is_node_text_invisible_op(node: &NodeData) -> bool {
3028 fn check(node: &NodeData, seen_any: &mut bool) -> bool {
3029 match node {
3030 NodeData::Text(t) => {
3031 if !t.is_empty() {
3032 *seen_any = true;
3033 }
3034 t.chars()
3035 .all(|c| matches!(c, '\u{200B}' | '\u{2061}' | '\u{2062}' | '\u{2063}'))
3036 },
3037 NodeData::Element { children, .. } => children.iter().all(|c| check(c, seen_any)),
3038 _ => true,
3039 }
3040 }
3041 let mut seen_any = false;
3042 let ok = check(node, &mut seen_any);
3043 ok && seen_any
3044}
3045
3046fn set_node_attr(node: &mut NodeData, key: &str, value: &str) {
3047 if let NodeData::Element { attributes, .. } = node {
3048 let attrs = attributes.get_or_insert_with(HashMap::default);
3049 attrs.insert(key.to_string(), value.to_string());
3050 }
3051}
3052
3053fn get_node_attr(node: &NodeData, key: &str) -> Option<String> {
3054 match node {
3055 NodeData::Element { attributes, .. } => attributes.as_ref().and_then(|a| a.get(key)).cloned(),
3056 _ => None,
3057 }
3058}
3059
3060fn get_node_attr_f64(node: &NodeData, key: &str) -> f64 {
3061 match node {
3062 NodeData::Element { attributes, .. } => attributes
3063 .as_ref()
3064 .and_then(|a| a.get(key))
3065 .and_then(|v| v.strip_suffix("em"))
3066 .and_then(|v| v.parse::<f64>().ok())
3067 .unwrap_or(0.0),
3068 _ => 0.0,
3069 }
3070}
3071
3072#[derive(PartialEq, Clone, Copy)]
3075enum WalkType {
3076 Atom,
3077 Mrow,
3078 Other,
3079}
3080fn walk_type(tag: &str) -> WalkType {
3081 match tag {
3082 "m:mi" | "m:mo" | "m:mn" | "m:ms" | "m:mtext" => WalkType::Atom,
3083 "m:mrow" | "m:mpadded" | "m:msqrt" | "m:mstyle" | "m:merror" | "m:mphantom" | "m:mtd" => {
3084 WalkType::Mrow
3085 },
3086 _ => WalkType::Other,
3087 }
3088}
3089
3090fn node_at<'a>(root: &'a NodeData, path: &[usize]) -> &'a NodeData {
3094 let mut cur = root;
3095 for &i in path {
3096 match cur {
3097 NodeData::Element { children, .. } => cur = &children[i],
3098 _ => unreachable!("spacewalk path into non-element"),
3099 }
3100 }
3101 cur
3102}
3103
3104fn node_at_mut<'a>(root: &'a mut NodeData, path: &[usize]) -> &'a mut NodeData {
3105 let mut cur = root;
3106 for &i in path {
3107 match cur {
3108 NodeData::Element { children, .. } => cur = &mut children[i],
3109 _ => unreachable!("spacewalk path into non-element"),
3110 }
3111 }
3112 cur
3113}
3114
3115fn child_path(path: &[usize], i: usize) -> Vec<usize> {
3116 let mut p = path.to_vec();
3117 p.push(i);
3118 p
3119}
3120
3121fn descend_embellishers(root: &NodeData, mut path: Vec<usize>) -> Vec<usize> {
3124 loop {
3125 match node_at(root, &path) {
3126 NodeData::Element { tag, children, .. }
3127 if is_embellisher_tag(tag) && !children.is_empty() =>
3128 {
3129 path.push(0);
3130 },
3131 _ => return path,
3132 }
3133 }
3134}
3135
3136pub fn adjust_spacing(node: &mut NodeData) { space_walk(node, Vec::new()); }
3140
3141fn space_walk(root: &mut NodeData, path: Vec<usize>) {
3147 use std::collections::VecDeque;
3148 let (wt, nch) = match node_at(root, &path) {
3149 NodeData::Element { tag, children, .. } => (walk_type(tag), children.len()),
3150 _ => return,
3151 };
3152 match wt {
3153 WalkType::Atom => {},
3154 WalkType::Other => {
3155 for i in 0..nch {
3156 space_walk(root, child_path(&path, i));
3157 }
3158 },
3159 WalkType::Mrow => {
3160 let mut queue: VecDeque<Vec<usize>> = (0..nch).map(|i| child_path(&path, i)).collect();
3161 let mut first = None;
3163 while let Some(p) = queue.pop_front() {
3164 let unwrap = match node_at(root, &p) {
3165 NodeData::Element { tag, children, .. } if tag == "m:mrow" => Some(children.len()),
3166 _ => None,
3167 };
3168 match unwrap {
3169 Some(n) => {
3170 for i in (0..n).rev() {
3171 queue.push_front(child_path(&p, i));
3172 }
3173 },
3174 None => {
3175 first = Some(p);
3176 break;
3177 },
3178 }
3179 }
3180 let Some(first) = first else { return };
3181 space_walk(root, first.clone());
3182 let mut items: Vec<(Option<Vec<usize>>, Vec<usize>)> = vec![(None, first)];
3184 while let Some(popped) = queue.pop_front() {
3185 let mut next = popped;
3186 let mut invisop: Option<Vec<usize>> = None;
3189 {
3190 let n = node_at(root, &next);
3191 if get_node_tag(n) == "m:mo" && is_node_text_invisible_op(n) {
3192 invisop = Some(next);
3193 match queue.pop_front() {
3194 Some(p) => next = p,
3195 None => break,
3196 }
3197 }
3198 }
3199 enum Kind {
3200 Mrow(usize),
3201 Script(usize),
3202 Plain,
3203 }
3204 let kind = match node_at(root, &next) {
3205 NodeData::Element { tag, children, .. } => {
3206 if tag == "m:mrow" {
3207 Kind::Mrow(children.len())
3208 } else if !children.is_empty()
3209 && (tag.starts_with("m:msup")
3210 || tag.starts_with("m:msub")
3211 || tag.starts_with("m:munder")
3212 || tag.starts_with("m:mover")
3213 || tag.starts_with("m:mmultiscripts"))
3214 {
3215 Kind::Script(children.len())
3220 } else {
3221 Kind::Plain
3222 }
3223 },
3224 _ => Kind::Plain,
3225 };
3226 match kind {
3227 Kind::Mrow(n) => {
3228 for i in (0..n).rev() {
3230 queue.push_front(child_path(&next, i));
3231 }
3232 if let Some(iv) = invisop {
3233 queue.push_front(iv);
3234 }
3235 continue;
3236 },
3237 Kind::Script(n) => {
3238 for i in 1..n {
3240 space_walk(root, child_path(&next, i));
3241 }
3242 queue.push_front(child_path(&next, 0));
3243 if let Some(iv) = invisop {
3244 queue.push_front(iv);
3245 }
3246 continue;
3247 },
3248 Kind::Plain => {},
3249 }
3250 space_walk(root, next.clone());
3251 items.push((invisop, next));
3252 }
3253 let (roles, classes) = tex_atom_types(root, &items);
3254 let converted = |i: usize| roles[i] == "Bin" && classes[i] == "Ord";
3255 for (i, (_, path)) in items.iter().enumerate().skip(1) {
3258 let inner = descend_embellishers(root, path.clone());
3259 let node = node_at(root, &inner);
3260 if converted(i)
3261 && get_node_tag(node) == "m:mo"
3262 && get_node_attr_f64(node, "_lspace") + get_node_attr_f64(node, "_rspace")
3263 > SPACING_EPSILON
3264 {
3265 let sign = node_at_mut(root, &inner);
3266 for key in ["lspace", "rspace", "_lspace", "_rspace"] {
3267 set_node_attr(sign, key, "0em");
3268 }
3269 }
3270 }
3271 for (i, (invisop, next)) in items.iter().enumerate().skip(1) {
3273 let prev = &items[i - 1].1;
3274 let types = if converted(i - 1) || converted(i) {
3275 &classes
3276 } else {
3277 &roles
3278 };
3279 adjust_pair(root, prev, next, invisop.as_deref(), types[i - 1], types[i]);
3280 }
3281 },
3282 }
3283}
3284
3285fn item_atom_type(root: &NodeData, path: &[usize]) -> &'static str {
3289 let inner = descend_embellishers(root, path.to_vec());
3290 let node = node_at(root, &inner);
3291 let tag = get_node_tag(node);
3292 let role = get_node_attr(node, "_role").unwrap_or_else(|| "ATOM".to_string());
3293 m_atom_type(tag).unwrap_or_else(|| match role_to_atom_type(&role) {
3294 "Bin" if tag == "m:mo" && is_core_k_glyph(&get_node_text(node), &role) => "Ord",
3295 class => class,
3296 })
3297}
3298
3299fn tex_atom_types(
3304 root: &NodeData,
3305 items: &[(Option<Vec<usize>>, Vec<usize>)],
3306) -> (Vec<&'static str>, Vec<&'static str>) {
3307 let roles: Vec<&'static str> = items.iter().map(|(_, p)| item_atom_type(root, p)).collect();
3308 let mut types: Vec<&'static str> = items
3309 .iter()
3310 .zip(&roles)
3311 .map(|((_, p), &ty)| {
3312 let inner = descend_embellishers(root, p.clone());
3313 match get_node_attr(node_at(root, &inner), "_role").as_deref() {
3314 Some("OPERATOR" | "VERTBAR" | "PERIOD") => "Ord",
3315 _ => ty,
3316 }
3317 })
3318 .collect();
3319 let mut r: Option<usize> = None; for (i, (_, path)) in items.iter().enumerate() {
3321 if get_node_tag(node_at(root, path)) == "m:mspace" {
3322 continue;
3323 }
3324 let r_type = r.map_or("Op", |j| types[j]);
3325 match (types[i], r) {
3326 ("Bin", _) if matches!(r_type, "Bin" | "Op" | "Rel" | "Open" | "Punct") => types[i] = "Ord",
3327 ("Rel" | "Close" | "Punct", Some(j)) if r_type == "Bin" => types[j] = "Ord",
3328 _ => {},
3329 }
3330 r = Some(i);
3331 }
3332 if let Some(j) = r.filter(|&j| types[j] == "Bin") {
3333 types[j] = "Ord";
3334 }
3335 (roles, types)
3336}
3337
3338fn adjust_pair(
3341 root: &mut NodeData,
3342 prev: &[usize],
3343 next: &[usize],
3344 invisop: Option<&[usize]>,
3345 prev_type: &str,
3346 next_type: &str,
3347) {
3348 let iprev = descend_embellishers(root, prev.to_vec());
3349 let inext = descend_embellishers(root, next.to_vec());
3350
3351 let prev_req_right = get_node_attr_f64(node_at(root, prev), "_rpadding");
3354 let next_req_left = get_node_attr_f64(node_at(root, next), "_lpadding");
3355 let prev_dict_right = get_node_attr_f64(node_at(root, &iprev), "_rspace");
3356 let next_dict_left = get_node_attr_f64(node_at(root, &inext), "_lspace");
3357 let tex_code = atompair_spacing(prev_type, next_type);
3358 let tex_space = TEX_SPACING[tex_code.unsigned_abs() as usize];
3359 let target = prev_req_right + next_req_left + tex_space;
3360 let default = prev_dict_right + next_dict_left;
3361 if (target - default).abs() <= SPACING_EPSILON {
3362 return;
3363 }
3364
3365 let prev_tag = get_node_tag(node_at(root, prev)).to_string();
3366 let next_tag = get_node_tag(node_at(root, next)).to_string();
3367 if target < 0.0 {
3373 let sizeable = match node_at(root, prev) {
3374 NodeData::Element { tag, attributes, .. } if walk_type(tag) == WalkType::Atom => Some(
3375 attributes
3376 .as_ref()
3377 .and_then(|a| a.get("class"))
3378 .cloned()
3379 .unwrap_or_default(),
3380 ),
3381 _ => None,
3382 };
3383 if let Some(class) = sizeable {
3384 let text = get_node_text(node_at(root, prev));
3385 let font = latexml_core::common::font::Font::math_default();
3386 let (w, _h, _d) = font.compute_string_size(&text, Default::default());
3387 let mut w_sp = w.0;
3388 if class.contains("mathscript") {
3392 w_sp = w_sp.max(10 * 65535);
3393 }
3394 let mut reqw = (w_sp as f64 / 65536.0) / 10.0 + target;
3395 if reqw < 0.0 {
3396 reqw = 0.0;
3397 }
3398 let slot = node_at_mut(root, prev);
3399 let old = std::mem::replace(slot, NodeData::Text(String::new()));
3400 *slot = NodeData::Element {
3401 tag: "m:mpadded".to_string(),
3402 attributes: Some(HashMap::from_iter([("width".to_string(), fmt_em(reqw))])),
3403 children: vec![old],
3404 };
3405 }
3406 } else if prev_tag == "m:mspace" || next_tag == "m:mspace" {
3407 let target_path = if prev_tag == "m:mspace" { prev } else { next };
3409 let n = node_at_mut(root, target_path);
3410 let old_w = match n {
3411 NodeData::Element { attributes, .. } => attributes
3412 .as_ref()
3413 .and_then(|a| a.get("width"))
3414 .map(|w| super::get_xm_hint_spacing(w))
3415 .unwrap_or(0.0),
3416 _ => 0.0,
3417 };
3418 set_node_attr(n, "width", &fmt_em(target + old_w));
3419 } else if let Some(iv) = invisop {
3420 set_node_attr(node_at_mut(root, iv), "lspace", &fmt_em(target));
3421 } else if prev_tag == "m:mo" && next_tag == "m:mo" {
3422 let p = prev_dict_right;
3424 let n = next_dict_left;
3425 let rem = target - n;
3426 if rem >= 0.0 {
3427 let v = if rem > SPACING_EPSILON { rem } else { 0.0 };
3428 set_node_attr(node_at_mut(root, prev), "rspace", &fmt_em(v));
3429 } else {
3430 let rem = target - p;
3431 if rem >= 0.0 {
3432 let v = if rem > SPACING_EPSILON { rem } else { 0.0 };
3433 set_node_attr(node_at_mut(root, next), "lspace", &fmt_em(v));
3434 } else {
3435 let rem = target / 2.0;
3438 if rem != p {
3439 set_node_attr(
3440 node_at_mut(root, prev),
3441 "rspace",
3442 &format!("{}em", perl_num(rem)),
3443 );
3444 }
3445 if rem != n {
3446 set_node_attr(
3447 node_at_mut(root, next),
3448 "lspace",
3449 &format!("{}em", perl_num(rem)),
3450 );
3451 }
3452 }
3453 }
3454 } else if prev_tag == "m:mo" {
3455 set_node_attr(node_at_mut(root, prev), "rspace", &fmt_em(target));
3456 } else if next_tag == "m:mo" {
3457 set_node_attr(node_at_mut(root, next), "lspace", &fmt_em(target));
3458 } else if (target - default).abs() > SPACING_FUDGE {
3459 Info!(
3460 "ignored",
3461 "spacing",
3462 &format!("No place to set spacing to {target} (default {default})")
3463 );
3464 }
3465}
3466
3467pub fn clean_internal_attrs(node: &mut NodeData) {
3469 if let NodeData::Element { attributes, children, .. } = node {
3470 if let Some(attrs) = attributes {
3471 attrs.remove("_role");
3472 attrs.remove("_lspace");
3473 attrs.remove("_rspace");
3474 attrs.remove("_largeop");
3475 attrs.remove("_lpadding");
3476 attrs.remove("_rpadding");
3477 attrs.remove("_ignorable");
3478 if attrs.is_empty() {
3479 *attributes = None;
3480 }
3481 }
3482 for child in children {
3483 clean_internal_attrs(child);
3484 }
3485 }
3486}
3487
3488#[cfg(test)]
3489mod tests {
3490 use rustc_hash::FxHashMap as HashMap;
3491
3492 use super::*;
3493
3494 #[test]
3495 fn math_style_step_down_monotone_saturates_at_scriptscript() {
3496 assert_eq!(MathStyle::Display.step_down(), MathStyle::Text);
3497 assert_eq!(MathStyle::Text.step_down(), MathStyle::Script);
3498 assert_eq!(MathStyle::Script.step_down(), MathStyle::ScriptScript);
3499 assert_eq!(MathStyle::ScriptScript.step_down(), MathStyle::ScriptScript);
3500 }
3501
3502 #[test]
3503 fn math_style_script_step_collapses_display_and_text() {
3504 assert_eq!(MathStyle::Display.script_step(), MathStyle::Script);
3505 assert_eq!(MathStyle::Text.script_step(), MathStyle::Script);
3506 assert_eq!(MathStyle::Script.script_step(), MathStyle::ScriptScript);
3507 assert_eq!(
3508 MathStyle::ScriptScript.script_step(),
3509 MathStyle::ScriptScript
3510 );
3511 }
3512
3513 #[test]
3514 fn math_style_size_percent_matches_tex_tradition() {
3515 assert_eq!(MathStyle::Display.size_percent(), "100%");
3516 assert_eq!(MathStyle::Text.size_percent(), "100%");
3517 assert_eq!(MathStyle::Script.size_percent(), "70%");
3518 assert_eq!(MathStyle::ScriptScript.size_percent(), "50%");
3519 }
3520
3521 #[test]
3522 fn invisible_times_roundtrip() {
3523 set_invisible_times(false);
3524 assert!(!get_invisible_times());
3525 set_invisible_times(true);
3526 assert!(get_invisible_times());
3527 }
3528
3529 #[test]
3530 fn embellishing_role_matches_canonical_set() {
3531 for r in [
3532 "SUPERSCRIPTOP",
3533 "SUBSCRIPTOP",
3534 "OVERACCENT",
3535 "UNDERACCENT",
3536 "MODIFIER",
3537 "MODIFIEROP",
3538 ] {
3539 assert!(is_embellishing_role(r), "{} should embellish", r);
3540 }
3541 }
3542
3543 #[test]
3544 fn embellishing_role_rejects_others() {
3545 for r in ["ADDOP", "MULOP", "ATOM", "UNKNOWN", ""] {
3546 assert!(!is_embellishing_role(r), "{} should not embellish", r);
3547 }
3548 }
3549
3550 #[test]
3551 fn default_token_content_maps_invisible_chars() {
3552 assert_eq!(default_token_content("MULOP"), Some("\u{2062}"));
3553 assert_eq!(default_token_content("ADDOP"), Some("\u{2064}"));
3554 assert_eq!(default_token_content("PUNCT"), Some("\u{2063}"));
3555 }
3556
3557 #[test]
3558 fn default_token_content_none_for_other_roles() {
3559 assert_eq!(default_token_content("ATOM"), None);
3560 assert_eq!(default_token_content(""), None);
3561 assert_eq!(default_token_content("RELOP"), None);
3562 }
3563
3564 #[test]
3565 fn clean_internal_attrs_removes_underscore_attrs() {
3566 let mut node = NodeData::Element {
3567 tag: "mrow".to_string(),
3568 attributes: Some(HashMap::from_iter([
3569 ("_role".to_string(), "MULOP".to_string()),
3570 ("_lspace".to_string(), "4".to_string()),
3571 ("keep".to_string(), "yes".to_string()),
3572 ])),
3573 children: vec![],
3574 };
3575 clean_internal_attrs(&mut node);
3576 if let NodeData::Element { attributes, .. } = &node {
3577 let attrs = attributes
3578 .as_ref()
3579 .expect("still has the non-internal attr");
3580 assert_eq!(attrs.len(), 1);
3581 assert_eq!(attrs.get("keep").map(String::as_str), Some("yes"));
3582 } else {
3583 panic!("expected element");
3584 }
3585 }
3586
3587 #[test]
3588 fn clean_internal_attrs_unsets_attributes_when_empty() {
3589 let mut node = NodeData::Element {
3590 tag: "mrow".to_string(),
3591 attributes: Some(HashMap::from_iter([
3592 ("_role".to_string(), "MULOP".to_string()),
3593 ("_largeop".to_string(), "true".to_string()),
3594 ])),
3595 children: vec![],
3596 };
3597 clean_internal_attrs(&mut node);
3598 if let NodeData::Element { attributes, .. } = &node {
3599 assert!(attributes.is_none());
3601 } else {
3602 panic!("expected element");
3603 }
3604 }
3605
3606 #[test]
3607 fn clean_internal_attrs_recurses_into_children() {
3608 let mut node = NodeData::Element {
3609 tag: "mrow".to_string(),
3610 attributes: None,
3611 children: vec![NodeData::Element {
3612 tag: "mi".to_string(),
3613 attributes: Some(HashMap::from_iter([(
3614 "_rspace".to_string(),
3615 "1".to_string(),
3616 )])),
3617 children: vec![],
3618 }],
3619 };
3620 clean_internal_attrs(&mut node);
3621 if let NodeData::Element { children, .. } = &node {
3622 if let NodeData::Element { attributes, .. } = &children[0] {
3623 assert!(attributes.is_none(), "recursion cleared child's only attr");
3624 } else {
3625 panic!("expected element child");
3626 }
3627 } else {
3628 panic!("expected element root");
3629 }
3630 }
3631
3632 #[test]
3633 fn clean_internal_attrs_ignores_text_nodes() {
3634 let mut node = NodeData::Text("x".to_string());
3635 clean_internal_attrs(&mut node);
3636 match &node {
3637 NodeData::Text(s) => assert_eq!(s, "x"),
3638 _ => panic!("expected text untouched"),
3639 }
3640 }
3641 #[test]
3642 fn test_role_to_atom_type() {
3643 assert_eq!(role_to_atom_type("ID"), "Ord");
3645 assert_eq!(role_to_atom_type("NUMBER"), "Ord");
3646 assert_eq!(role_to_atom_type("ADDOP"), "Bin");
3647 assert_eq!(role_to_atom_type("RELOP"), "Rel");
3648 assert_eq!(role_to_atom_type("OPEN"), "Open");
3649 assert_eq!(role_to_atom_type("CLOSE"), "Close");
3650 assert_eq!(role_to_atom_type("SUMOP"), "Op");
3651 assert_eq!(role_to_atom_type("PUNCT"), "Punct");
3652 assert_eq!(role_to_atom_type("ARRAY"), "Inner");
3653 assert_eq!(role_to_atom_type("no-such-role"), "Ord");
3654 }
3655
3656 #[test]
3657 fn test_atompair_spacing() {
3658 assert_eq!(atompair_spacing("Ord", "Op"), 1);
3660 assert_eq!(atompair_spacing("Ord", "Bin"), -2);
3661 assert_eq!(atompair_spacing("Rel", "Ord"), -3);
3662 assert_eq!(atompair_spacing("Open", "Ord"), 0);
3663 assert_eq!(atompair_spacing("Open", "Open"), 0);
3664 assert_eq!(atompair_spacing("Punct", "Bin"), 0);
3665 assert_eq!(atompair_spacing("Inner", "Ord"), -1);
3669 assert_eq!(atompair_spacing("Inner", "Op"), 1);
3670 assert_eq!(atompair_spacing("Inner", "Bin"), -2);
3671 assert_eq!(atompair_spacing("Inner", "Rel"), -3);
3672 assert_eq!(atompair_spacing("Inner", "Open"), -1);
3673 assert_eq!(atompair_spacing("Inner", "Close"), 0);
3674 assert_eq!(atompair_spacing("Inner", "Punct"), -1);
3675 assert_eq!(atompair_spacing("Inner", "Inner"), -1);
3676 }
3677
3678 #[test]
3679 fn test_fmt_em() {
3680 assert_eq!(fmt_em(0.0), "0em");
3682 assert_eq!(fmt_em(1.0), "1.000em");
3683 assert_eq!(fmt_em(0.167), "0.167em");
3684 assert_eq!(fmt_em(0.33), "0.330em");
3685 assert_eq!(fmt_em(1.2), "1.200em");
3686 }
3687}