Skip to main content

latexml_post/
unicode_math.rs

1//! Unicode math conversion processor.
2//!
3//! Port of `LaTeXML::Post::UnicodeMath` (435 lines of Perl).
4//! Converts XMath nodes to Unicode mathematical notation strings.
5//! Attempts compliance with UTN#28 (Unicode Technical Note on Plain Text Math).
6//!
7//! Used as:
8//! 1. A standalone text math format
9//! 2. A secondary format within MathML `m:annotation`
10//! 3. A utility for converting math to plain text (e.g. for title attributes)
11
12use libxml::tree::Node;
13
14use crate::{
15  document::{PostDocument, element_children},
16  math_processor::{MathConversion, MathProcessor, process_math},
17  processor::{ProcessResult, Processor},
18};
19
20const UNICODE_MATH_MIMETYPE: &str = "application/x-unicodemath";
21
22// Precedence levels (matching Perl)
23const PREC_RELOP: i32 = 1;
24const PREC_ADDOP: i32 = 2;
25const PREC_MULOP: i32 = 3;
26const PREC_SCRIPTOP: i32 = 4;
27const PREC_SYMBOL: i32 = 10;
28
29/// UnicodeMath post-processor.
30///
31/// Port of `LaTeXML::Post::UnicodeMath`.
32pub struct UnicodeMath {
33  name:         String,
34  is_secondary: bool,
35  keep_xmath:   bool,
36}
37
38impl Default for UnicodeMath {
39  fn default() -> Self { Self::new() }
40}
41
42impl UnicodeMath {
43  pub fn new() -> Self {
44    UnicodeMath {
45      name:         "UnicodeMath".to_string(),
46      is_secondary: false,
47      keep_xmath:   false,
48    }
49  }
50
51  /// Keep the XMath beside the converted string (`--keepXMath`), as the MathML
52  /// processors do.
53  pub fn with_keep_xmath(mut self, keep: bool) -> Self {
54    self.keep_xmath = keep;
55    self
56  }
57
58  /// Mark this processor as a parallel-markup secondary: its string becomes an
59  /// `<m:annotation>` of the primary's `<m:semantics>` (Perl `setParallel`, Post.pm
60  /// L348-357, which flags every extra processor `is_secondary`).
61  pub fn secondary(mut self) -> Self {
62    self.is_secondary = true;
63    self
64  }
65}
66
67impl Processor for UnicodeMath {
68  fn get_name(&self) -> &str { &self.name }
69
70  fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
71    doc.findnodes("//ltx:Math[not(ancestor::ltx:Math)]")
72  }
73
74  /// Standalone (no MathML primary): Perl inherits `MathProcessor::process`
75  /// (Post.pm L290-342), whose `processNode` wraps the string as
76  /// `<ltx:text class="ltx_math_application/x-unicodemath">` in place of the XMath
77  /// (L394-396) — what `latexmlmath --unicodemath` reads back (`bin/latexmlmath`
78  /// L244-248).
79  fn process(&mut self, mut doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
80    process_math(self, &mut doc, nodes, self.keep_xmath)?;
81    Ok(vec![doc])
82  }
83}
84
85impl MathProcessor for UnicodeMath {
86  fn convert_node(&self, doc: &PostDocument, xmath: &Node) -> Option<MathConversion> {
87    let math = xmath.get_parent()?;
88    let (string, _prec) = unimath_internal(doc, &math);
89    Some(MathConversion {
90      processor_name: self.name.clone(),
91      mimetype:       Some(UNICODE_MATH_MIMETYPE.to_string()),
92      xml:            None,
93      string:         Some(string),
94      src:            None,
95      width:          None,
96      height:         None,
97      depth:          None,
98    })
99  }
100
101  fn raw_id_suffix(&self) -> &str { ".muni" }
102
103  fn is_secondary(&self) -> bool { self.is_secondary }
104}
105
106/// Public entry point: convert a Math/XMath node to Unicode string.
107///
108/// Port of `unicodemath($doc, $node)`.
109pub fn unicodemath(doc: &PostDocument, node: &Node) -> String {
110  let (uni, _prec) = unimath_internal(doc, node);
111  uni
112}
113
114// ======================================================================
115// Precedence-based infix roles
116
117fn infix_prec(role: &str) -> Option<i32> {
118  match role {
119    "ADDOP" | "BINOP" => Some(PREC_ADDOP),
120    "MULOP" | "MIDDLE" | "COMPOSEOP" | "MODIFIEROP" => Some(PREC_MULOP),
121    "RELOP" | "METARELOP" | "ARROW" => Some(PREC_RELOP),
122    _ => None,
123  }
124}
125
126/// Get the operator role, following embellished operators.
127///
128/// Port of `getOperatorRole`.
129fn get_operator_role(doc: &PostDocument, node: &Node) -> Option<String> {
130  if let Some(role) = node.get_attribute("role") {
131    return Some(role);
132  }
133  if doc.is_qname(node, "ltx:XMApp") {
134    let children = element_children(node);
135    if children.len() >= 2 {
136      let op_role = children[0].get_attribute("role").unwrap_or_default();
137      if matches!(
138        op_role.as_str(),
139        "SUPERSCRIPTOP" | "SUBSCRIPTOP" | "OVERACCENT" | "UNDERACCENT" | "MODIFIER" | "MODIFIEROP"
140      ) {
141        return get_operator_role(doc, &children[1]);
142      }
143    }
144  }
145  None
146}
147
148/// Realize an XMRef node to its target.
149fn realize(doc: &PostDocument, node: &Node) -> Option<Node> { doc.realize_xm_node(node) }
150
151// ======================================================================
152// Core conversion
153
154/// Convert a node, returning (string, precedence).
155///
156/// Port of `unimath_internal`.
157fn unimath_internal(doc: &PostDocument, node: &Node) -> (String, i32) {
158  let tag = doc.get_qname(node).unwrap_or_default();
159  let role = node.get_attribute("role").unwrap_or_default();
160
161  match tag.as_str() {
162    "ltx:Math" | "ltx:XMath" => unimath_map(doc, &element_children(node)),
163    "ltx:XMDual" => {
164      let children = element_children(node);
165      if children.len() >= 2 {
166        unimath_internal(doc, &children[1]) // Presentation branch
167      } else {
168        unimath_error("Empty XMDual")
169      }
170    },
171    "ltx:XMWrap" | "ltx:XMArg" => unimath_map(doc, &element_children(node)),
172    "ltx:XMApp" => {
173      let children = element_children(node);
174      if children.is_empty() {
175        return unimath_error("Missing Operator");
176      }
177      let op = &children[0];
178      let args = &children[1..];
179
180      // Floating/post scripts left by a failed parse (Perl
181      // `/^(FLOAT|POST)(SUB|SUPER)SCRIPT$/`): the script alone, no base.
182      match role.as_str() {
183        "FLOATSUBSCRIPT" | "POSTSUBSCRIPT" => return unimath_sub(doc, None, None, op),
184        "FLOATSUPERSCRIPT" | "POSTSUPERSCRIPT" => return unimath_sup(doc, None, None, op),
185        _ => {},
186      }
187
188      // Realize operator and dispatch
189      let rop = realize(doc, op).unwrap_or_else(|| op.clone());
190      let op_role = get_operator_role(doc, &rop).unwrap_or_default();
191      let meaning = rop.get_attribute("meaning").unwrap_or_default();
192
193      // Dispatch by role/meaning
194      match (op_role.as_str(), meaning.as_str()) {
195        (_, "formulae") | (_, "multirelation") => unimath_map(doc, args),
196        (_, "limit-from") | (_, "annotated") => unimath_prefix(doc, op, args),
197        (_, "square-root") => {
198          if !args.is_empty() {
199            let inner = unimath_nested(doc, &args[0], PREC_MULOP);
200            (format!("\u{221A}{}", inner), PREC_MULOP)
201          } else {
202            ("\u{221A}".to_string(), PREC_MULOP)
203          }
204        },
205        (_, "nth-root") => {
206          if args.len() >= 2 {
207            // The XMath args are (degree, radicand), in Perl's XMath too; Perl's
208            // converter reads them swapped (KNOWN_PERL_ERRORS #1291).
209            let (n, _) = unimath_internal(doc, &args[0]);
210            let base = unimath_nested(doc, &args[1], PREC_MULOP);
211            let op_str = match n.as_str() {
212              "2" => "\u{221A}".to_string(),
213              "3" => "\u{221B}".to_string(),
214              "4" => "\u{221C}".to_string(),
215              _ => format!("\\root {}\\of", n),
216            };
217            (format!("{}{}", op_str, base), PREC_MULOP)
218          } else {
219            unimath_prefix(doc, op, args)
220          }
221        },
222        (_, "continued-fraction") => unimath_error("continued fraction"),
223        ("FRACOP", _) => {
224          if args.len() >= 2 {
225            let thickness = children[0].get_attribute("thickness");
226            if thickness.is_some() {
227              // Binomial-like
228              let num = unimath_nested(doc, &args[0], 0);
229              let den = unimath_nested(doc, &args[1], 0);
230              (format!("({}\u{00A6}{})", num, den), PREC_SYMBOL)
231            } else {
232              let num = unimath_nested(doc, &args[0], PREC_MULOP);
233              let den = unimath_nested(doc, &args[1], PREC_MULOP);
234              (format!("{}/{}", num, den), 1)
235            }
236          } else {
237            unimath_prefix(doc, op, args)
238          }
239        },
240        ("SUPERSCRIPTOP", _) => {
241          if args.len() >= 2 {
242            unimath_sup(doc, Some(op), Some(&args[0]), &args[1])
243          } else {
244            unimath_prefix(doc, op, args)
245          }
246        },
247        ("SUBSCRIPTOP", _) => {
248          if args.len() >= 2 {
249            unimath_sub(doc, Some(op), Some(&args[0]), &args[1])
250          } else {
251            unimath_prefix(doc, op, args)
252          }
253        },
254        ("OVERACCENT", _) => {
255          if !args.is_empty() {
256            unimath_overaccent(doc, op, &args[0])
257          } else {
258            unimath_prefix(doc, op, args)
259          }
260        },
261        ("UNDERACCENT", _) => {
262          if !args.is_empty() {
263            unimath_underaccent(doc, op, &args[0])
264          } else {
265            unimath_prefix(doc, op, args)
266          }
267        },
268        ("POSTFIX", _) => {
269          if !args.is_empty() {
270            let (op_str, _) = unimath_internal(doc, op);
271            let base = unimath_nested(doc, &args[0], PREC_MULOP);
272            (format!("{}{}", base, op_str), PREC_MULOP)
273          } else {
274            unimath_prefix(doc, op, args)
275          }
276        },
277        ("ENCLOSE", _) => {
278          if !args.is_empty() {
279            (unimath_nested(doc, &args[0], PREC_SYMBOL), PREC_SYMBOL)
280          } else {
281            (String::new(), PREC_SYMBOL)
282          }
283        },
284        _ => {
285          // Check if it's an infix role
286          if let Some(prec) = infix_prec(&op_role) {
287            unimath_infix_with_prec(doc, op, args, prec)
288          } else {
289            // Default: prefix
290            unimath_prefix(doc, op, args)
291          }
292        },
293      }
294    },
295    "ltx:XMTok" => {
296      let meaning = node.get_attribute("meaning").unwrap_or_default();
297      if meaning == "absent" {
298        return (String::new(), PREC_SYMBOL);
299      }
300      let text = stylize_content(node);
301      (text, PREC_SYMBOL)
302    },
303    "ltx:XMHint" => (String::new(), 0),
304    "ltx:XMArray" => {
305      let rows: Vec<String> = element_children(node)
306        .iter()
307        .map(|row| {
308          element_children(row)
309            .iter()
310            .map(|cell| unimath_nested(doc, cell, 0))
311            .collect::<Vec<_>>()
312            .join("&")
313        })
314        .collect();
315      (format!("\u{25A0}({})", rows.join("@")), 0)
316    },
317    "ltx:XMText" => unimath_text(node),
318    "ltx:XMRef" => match realize(doc, node) {
319      Some(target) => unimath_internal(doc, &target),
320      _ => unimath_error("Unresolved XMRef"),
321    },
322    "ltx:ERROR" => unimath_error(&node.get_content()),
323    _ => unimath_text(node),
324  }
325}
326
327/// Convert and wrap in braces if precedence is too low.
328///
329/// Port of `unimath_nested`.
330fn unimath_nested(doc: &PostDocument, node: &Node, prec: i32) -> String {
331  let (string, iprec) = unimath_internal(doc, node);
332  if iprec >= prec {
333    string
334  } else {
335    format!("{{{}}}", string)
336  }
337}
338
339/// Combine conversion of multiple nodes.
340///
341/// Port of `unimath_map`.
342fn unimath_map(doc: &PostDocument, args: &[Node]) -> (String, i32) {
343  let mut oprec = 0;
344  // If wrapped in OPEN...CLOSE, it's a symbol-level expression
345  if args.len() > 1 {
346    let first_role = args
347      .first()
348      .and_then(|n| n.get_attribute("role"))
349      .unwrap_or_default();
350    let last_role = args
351      .last()
352      .and_then(|n| n.get_attribute("role"))
353      .unwrap_or_default();
354    if first_role == "OPEN" && last_role == "CLOSE" {
355      oprec = PREC_SYMBOL;
356    }
357  }
358  let result: String = args.iter().map(|a| unimath_nested(doc, a, 0)).collect();
359  (result, oprec)
360}
361
362/// Prefix application: op arg1 arg2 ...
363///
364/// Port of `unimath_prefix`.
365fn unimath_prefix(doc: &PostDocument, op: &Node, args: &[Node]) -> (String, i32) {
366  if args.is_empty() {
367    return (String::new(), PREC_SYMBOL);
368  }
369  let op_str = unimath_nested(doc, op, 0);
370  let args_str: String = args
371    .iter()
372    .map(|a| unimath_nested(doc, a, PREC_SYMBOL))
373    .collect();
374  (format!("{}{}", op_str, args_str), PREC_SYMBOL)
375}
376
377/// Infix application with explicit precedence.
378///
379/// Port of `unimath_infix`.
380fn unimath_infix_with_prec(
381  doc: &PostDocument,
382  op: &Node,
383  args: &[Node],
384  prec: i32,
385) -> (String, i32) {
386  if args.is_empty() {
387    return (String::new(), PREC_SYMBOL);
388  }
389  let opuni = unimath_nested(doc, op, prec);
390  if args.len() == 1 {
391    // Single arg = prefix
392    let arg = unimath_nested(doc, &args[0], prec);
393    (format!("{}{}", opuni, arg), prec)
394  } else {
395    let mut items = vec![unimath_nested(doc, &args[0], prec)];
396    for arg in &args[1..] {
397      items.push(opuni.clone());
398      items.push(unimath_nested(doc, arg, prec));
399    }
400    (items.join(""), prec)
401  }
402}
403
404/// Subscript: `base_script`, `base┬script` (a `mid` limit), `{_script}base` (a
405/// `pre` script), or the subscript codepoints when every character has one
406/// (`∫₀`).
407///
408/// Port of `unimath_sub`.
409fn unimath_sub(
410  doc: &PostDocument,
411  op: Option<&Node>,
412  base: Option<&Node>,
413  script: &Node,
414) -> (String, i32) {
415  unimath_script(doc, op, base, script, "subscript", '_', '\u{252C}')
416}
417
418/// Superscript: `base^script`, `base┴script` (a `mid` limit), `{^script}base` (a
419/// `pre` script), or the superscript codepoints when every character has one
420/// (`𝑥²`, `¹⁴𝐶`, `𝑥'` for `x^\prime`).
421///
422/// Port of `unimath_sup`.
423fn unimath_sup(
424  doc: &PostDocument,
425  op: Option<&Node>,
426  base: Option<&Node>,
427  script: &Node,
428) -> (String, i32) {
429  unimath_script(doc, op, base, script, "superscript", '^', '\u{2534}')
430}
431
432/// The body Perl's `unimath_sub` and `unimath_sup` share (UnicodeMath.pm L259-293),
433/// differing only in the codepoint table, the script operator and the `mid` mark.
434/// The op's `scriptpos` (`pre…`, `mid…`, else `post`) places the script.
435fn unimath_script(
436  doc: &PostDocument,
437  op: Option<&Node>,
438  base: Option<&Node>,
439  script: &Node,
440  codepoints: &str,
441  operator: char,
442  mid_mark: char,
443) -> (String, i32) {
444  let pos = op
445    .and_then(|o| o.get_attribute("scriptpos"))
446    .filter(|p| !p.is_empty())
447    .unwrap_or_else(|| "post".to_string());
448  let pre = pos.starts_with("pre");
449  let mid = pos.starts_with("mid");
450  let ubase = base
451    .map(|b| unimath_nested(doc, b, PREC_SCRIPTOP))
452    .unwrap_or_default();
453  let (mut uscript, prec) = unimath_internal(doc, script);
454  // A `mid` limit keeps its characters ("Could try for combining accents?").
455  let mapped = match (!mid)
456    .then(|| crate::unicode::unicode_convert(&uscript, codepoints))
457    .flatten()
458  {
459    Some(converted) => {
460      uscript = converted;
461      true
462    },
463    None => false,
464  };
465  if !mapped && prec < PREC_SCRIPTOP {
466    uscript = format!("{{{uscript}}}");
467  }
468  let string = if pre {
469    if mapped {
470      format!("{uscript}{ubase}")
471    } else {
472      format!("{{{operator}{uscript}}}{ubase}")
473    }
474  } else if mapped {
475    format!("{ubase}{uscript}")
476  } else {
477    format!("{ubase}{}{uscript}", if mid { mid_mark } else { operator })
478  };
479  (string, PREC_SCRIPTOP)
480}
481
482/// Over-accent: combining character above.
483///
484/// Port of `unimath_overaccent`.
485fn unimath_overaccent(doc: &PostDocument, op: &Node, base: &Node) -> (String, i32) {
486  let acc = op.get_content();
487  let combining = overaccent_combining(&acc);
488  let (mut ubase, _) = unimath_internal(doc, base);
489  if ubase.chars().count() > 1 {
490    ubase = format!("({})", ubase);
491  }
492  let accent_str = combining.unwrap_or_else(|| format!("\u{252C}{}", acc));
493  (format!("{}{}", ubase, accent_str), PREC_SCRIPTOP)
494}
495
496/// Under-accent: combining character below.
497///
498/// Port of `unimath_underaccent`.
499fn unimath_underaccent(doc: &PostDocument, op: &Node, base: &Node) -> (String, i32) {
500  let acc = op.get_content();
501  let combining = underaccent_combining(&acc);
502  let (mut ubase, _) = unimath_internal(doc, base);
503  if ubase.chars().count() > 1 {
504    ubase = format!("({})", ubase);
505  }
506  let accent_str = combining.unwrap_or_else(|| format!("\u{252C}{}", acc));
507  (format!("{}{}", ubase, accent_str), PREC_SCRIPTOP)
508}
509
510/// Convert an XMTok's content to styled Unicode text.
511///
512/// Port of `stylizeContent` (`UnicodeMath.pm` L234-252): resolve the token text
513/// (with the empty-token failsafe), then remap it into the plane-1 math alphabet
514/// for the token's `font` mathvariant — `unicode_convert` is all-or-nothing, so
515/// a partly-unmappable string keeps its original text (Perl: "didn't remap the
516/// text? Keep text & variant"). This is what turns an italic `x` into `𝑥` in a
517/// title tooltip (issue #761) and in the UnicodeMath annotation.
518fn stylize_content(node: &Node) -> String {
519  let role = node
520    .get_attribute("role")
521    .unwrap_or_else(|| "ID".to_string());
522  let font = node.get_attribute("font").unwrap_or_default();
523  let mut text = node.get_content();
524  if text.is_empty() {
525    // Failsafe for empty tokens: %default_token_content, else name/meaning/role.
526    static DEFAULT_CONTENT: &[(&str, &str)] = &[
527      ("MULOP", "\u{2062}"), // INVISIBLE TIMES
528      ("ADDOP", "\u{2064}"), // INVISIBLE PLUS
529      ("PUNCT", "\u{2063}"), // INVISIBLE SEPARATOR
530    ];
531    text = DEFAULT_CONTENT
532      .iter()
533      .find(|(r, _)| role == *r)
534      .map(|(_, d)| (*d).to_string())
535      .unwrap_or_else(|| {
536        node
537          .get_attribute("name")
538          .or_else(|| node.get_attribute("meaning"))
539          .unwrap_or_else(|| role.clone())
540      });
541  }
542  // Perl: `$variant = $font ? unicode_mathvariant($font) : ''`, then
543  // `$u_text = $variant && unicode_convert($text, $variant)`; keep `$u_text`
544  // only if it remapped to a non-empty string. Gating on a non-empty `font`
545  // mirrors the ternary — `unicode_mathvariant("")` would otherwise yield
546  // "normal" and trigger a needless lookup.
547  if !font.is_empty() {
548    let variant = crate::unicode::unicode_mathvariant(&font);
549    if let Some(u) = crate::unicode::unicode_convert(&text, variant) {
550      if !u.is_empty() {
551        text = u;
552      }
553    }
554  }
555  text
556}
557
558/// Text content in quotes.
559///
560/// Port of `unimath_text`.
561fn unimath_text(node: &Node) -> (String, i32) {
562  let text = node.get_content();
563  (format!("\"{}\"", text), PREC_SYMBOL)
564}
565
566/// Error representation.
567fn unimath_error(msg: &str) -> (String, i32) { (format!("\"ERROR {}\"", msg), PREC_SYMBOL) }
568
569/// The accent's only character: Perl looks the whole accent string up
570/// (`$overaccents{$acc}`), so a longer one has no combining form.
571fn single_char(acc: &str) -> Option<char> {
572  let mut chars = acc.chars();
573  chars.next().filter(|_| chars.next().is_none())
574}
575
576/// Map over-accent character to combining equivalent.
577fn overaccent_combining(acc: &str) -> Option<String> {
578  let c = single_char(acc)?;
579  let combining = match c {
580    '^' => '\u{0302}',        // hat
581    '\u{02C7}' => '\u{030C}', // check
582    '~' => '\u{0303}',        // tilde
583    '\u{0084}' => '\u{0301}', // acute
584    '\u{0060}' => '\u{0300}', // grave
585    '\u{02D9}' => '\u{0307}', // dot
586    '\u{00AB}' => '\u{0308}', // ddot
587    '\u{00AF}' => '\u{0304}', // bar/overline
588    '\u{2192}' => '\u{20D7}', // vec
589    '\u{02D8}' => '\u{0306}', // breve
590    'o' => '\u{030A}',        // ring
591    '\u{02DD}' => '\u{030B}', // double acute
592    _ => return None,
593  };
594  Some(combining.to_string())
595}
596
597/// Map under-accent character to combining equivalent.
598fn underaccent_combining(acc: &str) -> Option<String> {
599  let c = single_char(acc)?;
600  let combining = match c {
601    '\u{00B8}' => '\u{0327}', // cedilla
602    '.' => '\u{0323}',        // dot below
603    '\u{00AF}' => '\u{0331}', // macron below
604    '=' | ',' => '\u{0361}',  // tie / lfhook
605    _ => return None,
606  };
607  Some(combining.to_string())
608}
609
610#[cfg(test)]
611mod tests {
612  use super::*;
613  use crate::document::PostDocumentOptions;
614
615  /// The UnicodeMath of one `ltx:Math` holding `xmath` (XMath children).
616  fn unicodemath_of(xmath: &str) -> String {
617    let xml = format!(
618      "<document xmlns='http://dlmf.nist.gov/LaTeXML'><Math><XMath>{xmath}</XMath></Math></document>"
619    );
620    let doc = PostDocument::new_from_string(&xml, PostDocumentOptions::default()).expect("parse");
621    let math = doc.findnodes("//ltx:Math").remove(0);
622    unicodemath(&doc, &math)
623  }
624
625  /// Perl's own XMath of `{}^{14}C+\sum_{i}^{n}x^{2}` (latexmlmath --XMath), and Perl's
626  /// string for it: script codepoints where every character has one, a prescript
627  /// before its base, `┬`/`┴` for `mid` limits (UnicodeMath.pm L259-293).
628  #[test]
629  fn scripts_follow_scriptpos_and_take_script_codepoints() {
630    let xmath = "<XMApp><XMTok meaning='plus' role='ADDOP'>+</XMTok>\
631       <XMApp><XMTok role='SUPERSCRIPTOP' scriptpos='pre1'/>\
632         <XMTok role='UNKNOWN' font='italic'>C</XMTok><XMTok meaning='14' role='NUMBER'>14</XMTok></XMApp>\
633       <XMApp><XMApp><XMTok role='SUPERSCRIPTOP' scriptpos='mid1'/>\
634           <XMApp><XMTok role='SUBSCRIPTOP' scriptpos='mid1'/>\
635             <XMTok meaning='sum' role='SUMOP' scriptpos='mid'>\u{2211}</XMTok>\
636             <XMTok role='UNKNOWN' font='italic'>i</XMTok></XMApp>\
637           <XMTok role='UNKNOWN' font='italic'>n</XMTok></XMApp>\
638         <XMApp><XMTok role='SUPERSCRIPTOP' scriptpos='post1'/>\
639           <XMTok role='UNKNOWN' font='italic'>x</XMTok><XMTok meaning='2' role='NUMBER'>2</XMTok></XMApp>\
640       </XMApp></XMApp>";
641    assert_eq!(unicodemath_of(xmath), "¹⁴𝐶+∑┬𝑖┴𝑛{𝑥²}");
642  }
643
644  /// A script with no codepoint keeps the script operator: after the base, or
645  /// braced before it for a prescript.
646  #[test]
647  fn unmapped_scripts_keep_the_script_operator() {
648    let post = "<XMApp><XMTok role='SUBSCRIPTOP' scriptpos='post1'/>\
649       <XMTok role='UNKNOWN' font='italic'>x</XMTok><XMTok role='UNKNOWN' font='italic'>n</XMTok></XMApp>";
650    assert_eq!(unicodemath_of(post), "𝑥_𝑛");
651    let pre = "<XMApp><XMTok role='SUPERSCRIPTOP' scriptpos='pre1'/>\
652       <XMTok role='UNKNOWN' font='italic'>C</XMTok><XMTok role='UNKNOWN' font='italic'>n</XMTok></XMApp>";
653    assert_eq!(unicodemath_of(pre), "{^𝑛}𝐶");
654  }
655
656  /// `\sqrt[3]{x}`: the XMath args are (degree, radicand); Perl's converter reads
657  /// them swapped, `\root 𝑥\of3` (KNOWN_PERL_ERRORS #1291).
658  #[test]
659  fn nth_root_reads_degree_then_radicand() {
660    let xmath = "<XMApp><XMTok meaning='nth-root'/>\
661       <XMTok meaning='3' role='NUMBER'>3</XMTok><XMTok role='UNKNOWN' font='italic'>x</XMTok></XMApp>";
662    assert_eq!(unicodemath_of(xmath), "∛𝑥");
663  }
664
665  #[test]
666  fn test_stylize_empty_token() {
667    // MULOP with no text should produce invisible times
668    let result = stylize_content_for_role("MULOP", "");
669    assert_eq!(result, "\u{2062}");
670  }
671
672  #[test]
673  fn test_overaccent_combining() {
674    assert_eq!(overaccent_combining("^"), Some("\u{0302}".to_string()));
675    assert_eq!(overaccent_combining("~"), Some("\u{0303}".to_string()));
676    assert_eq!(overaccent_combining("x"), None);
677  }
678
679  /// Helper for testing stylize_content without a Node.
680  fn stylize_content_for_role(role: &str, text: &str) -> String {
681    static DEFAULT_CONTENT: &[(&str, &str)] = &[
682      ("MULOP", "\u{2062}"),
683      ("ADDOP", "\u{2064}"),
684      ("PUNCT", "\u{2063}"),
685    ];
686    if text.is_empty() {
687      for (r, default) in DEFAULT_CONTENT {
688        if role == *r {
689          return default.to_string();
690        }
691      }
692    }
693    text.to_string()
694  }
695}