Skip to main content

latexml_post/
tex_math.rs

1//! TeX math preservation processor.
2//!
3//! Port of `LaTeXML::Post::TeXMath`.
4//! Trivial math post-processor that supplies the TeX string
5//! from the `tex` attribute of the `ltx:Math` element.
6
7use libxml::tree::Node;
8
9use crate::{
10  document::PostDocument,
11  math_processor::{MathConversion, MathProcessor},
12  processor::{ProcessResult, Processor},
13};
14
15const TEX_MIMETYPE: &str = "application/x-tex";
16
17/// TeXMath post-processor: preserves the TeX source as a math representation.
18///
19/// Port of `LaTeXML::Post::TeXMath`.
20pub struct TeXMath {
21  name:         String,
22  is_secondary: bool,
23}
24
25impl Default for TeXMath {
26  fn default() -> Self { Self::new() }
27}
28
29impl TeXMath {
30  pub fn new() -> Self {
31    TeXMath {
32      name:         "TeXMath".to_string(),
33      is_secondary: false,
34    }
35  }
36}
37
38impl Processor for TeXMath {
39  fn get_name(&self) -> &str { &self.name }
40
41  fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
42    doc.findnodes("//ltx:Math[not(ancestor::ltx:Math)]")
43  }
44
45  fn process(&mut self, doc: PostDocument, _nodes: Vec<Node>) -> ProcessResult {
46    // Delegated to math_processor::process_math
47    Ok(vec![doc])
48  }
49}
50
51impl MathProcessor for TeXMath {
52  fn convert_node(&self, _doc: &PostDocument, xmath: &Node) -> Option<MathConversion> {
53    let math = xmath.get_parent()?;
54    let tex = math.get_attribute("tex")?;
55    Some(MathConversion {
56      processor_name: self.name.clone(),
57      mimetype:       Some(TEX_MIMETYPE.to_string()),
58      xml:            None,
59      string:         Some(tex),
60      src:            None,
61      width:          None,
62      height:         None,
63      depth:          None,
64    })
65  }
66
67  fn raw_id_suffix(&self) -> &str { ".tm" }
68
69  fn is_secondary(&self) -> bool { self.is_secondary }
70}
71
72#[cfg(test)]
73mod tests {
74  use super::*;
75
76  #[test]
77  fn tex_math_new_has_default_name() {
78    let tm = TeXMath::new();
79    assert_eq!(tm.get_name(), "TeXMath");
80    assert!(!tm.is_secondary);
81  }
82
83  #[test]
84  fn tex_math_default_matches_new() {
85    let a = TeXMath::default();
86    let b = TeXMath::new();
87    assert_eq!(a.get_name(), b.get_name());
88    assert_eq!(a.is_secondary, b.is_secondary);
89  }
90
91  #[test]
92  fn tex_math_raw_id_suffix() {
93    let tm = TeXMath::new();
94    assert_eq!(tm.raw_id_suffix(), ".tm");
95  }
96
97  #[test]
98  fn tex_math_is_secondary_false_by_default() {
99    let tm = TeXMath::new();
100    assert!(!tm.is_secondary());
101  }
102
103  #[test]
104  fn tex_mimetype_is_application_x_tex() {
105    assert_eq!(TEX_MIMETYPE, "application/x-tex");
106  }
107}