1use 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
22const 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
29pub 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 pub fn with_keep_xmath(mut self, keep: bool) -> Self {
54 self.keep_xmath = keep;
55 self
56 }
57
58 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 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
106pub fn unicodemath(doc: &PostDocument, node: &Node) -> String {
110 let (uni, _prec) = unimath_internal(doc, node);
111 uni
112}
113
114fn 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
126fn 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
148fn realize(doc: &PostDocument, node: &Node) -> Option<Node> { doc.realize_xm_node(node) }
150
151fn 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]) } 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 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 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 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 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 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 if let Some(prec) = infix_prec(&op_role) {
287 unimath_infix_with_prec(doc, op, args, prec)
288 } else {
289 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
327fn 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
339fn unimath_map(doc: &PostDocument, args: &[Node]) -> (String, i32) {
343 let mut oprec = 0;
344 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
362fn 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
377fn 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 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
404fn 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
418fn 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
432fn 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 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
482fn 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
496fn 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
510fn 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 static DEFAULT_CONTENT: &[(&str, &str)] = &[
527 ("MULOP", "\u{2062}"), ("ADDOP", "\u{2064}"), ("PUNCT", "\u{2063}"), ];
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 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
558fn unimath_text(node: &Node) -> (String, i32) {
562 let text = node.get_content();
563 (format!("\"{}\"", text), PREC_SYMBOL)
564}
565
566fn unimath_error(msg: &str) -> (String, i32) { (format!("\"ERROR {}\"", msg), PREC_SYMBOL) }
568
569fn single_char(acc: &str) -> Option<char> {
572 let mut chars = acc.chars();
573 chars.next().filter(|_| chars.next().is_none())
574}
575
576fn overaccent_combining(acc: &str) -> Option<String> {
578 let c = single_char(acc)?;
579 let combining = match c {
580 '^' => '\u{0302}', '\u{02C7}' => '\u{030C}', '~' => '\u{0303}', '\u{0084}' => '\u{0301}', '\u{0060}' => '\u{0300}', '\u{02D9}' => '\u{0307}', '\u{00AB}' => '\u{0308}', '\u{00AF}' => '\u{0304}', '\u{2192}' => '\u{20D7}', '\u{02D8}' => '\u{0306}', 'o' => '\u{030A}', '\u{02DD}' => '\u{030B}', _ => return None,
593 };
594 Some(combining.to_string())
595}
596
597fn underaccent_combining(acc: &str) -> Option<String> {
599 let c = single_char(acc)?;
600 let combining = match c {
601 '\u{00B8}' => '\u{0327}', '.' => '\u{0323}', '\u{00AF}' => '\u{0331}', '=' | ',' => '\u{0361}', _ => 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 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 #[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 #[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 #[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 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 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}