Skip to main content

latexml_post/
processor.rs

1//! Abstract post-processor base.
2//!
3//! Port of `LaTeXML::Post::Processor`.
4//! All post-processors implement the [`Processor`] trait.
5
6use std::path::PathBuf;
7
8use libxml::tree::Node;
9use rustc_hash::FxHashMap as HashMap;
10
11use crate::document::PostDocument;
12
13/// Options for constructing a processor.
14#[derive(Debug, Default, Clone)]
15pub struct ProcessorOptions {
16  pub resource_directory: Option<String>,
17  pub resource_prefix:    Option<String>,
18}
19
20/// Result of processing: the document (possibly split into multiple).
21pub type ProcessResult = Result<Vec<PostDocument>, PostError>;
22
23/// Errors from post-processing.
24#[derive(Debug)]
25pub enum PostError {
26  /// A processing error with context message.
27  Processing(String),
28  /// An I/O error.
29  Io(std::io::Error),
30  /// An XML error.
31  Xml(String),
32}
33
34impl std::fmt::Display for PostError {
35  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36    match self {
37      PostError::Processing(msg) => write!(f, "Post-processing error: {}", msg),
38      PostError::Io(err) => write!(f, "I/O error: {}", err),
39      PostError::Xml(msg) => write!(f, "XML error: {}", msg),
40    }
41  }
42}
43
44impl std::error::Error for PostError {}
45
46impl From<std::io::Error> for PostError {
47  fn from(err: std::io::Error) -> Self { PostError::Io(err) }
48}
49
50/// Abstract base trait for all post-processors.
51///
52/// Corresponds to `LaTeXML::Post::Processor`.
53/// Processors operate on a [`PostDocument`] and return one or more documents
54/// (splitting may produce multiple outputs).
55pub trait Processor {
56  /// Human-readable name for this processor.
57  fn get_name(&self) -> &str;
58
59  /// Resource directory for generated resources (images, etc.).
60  fn resource_directory(&self) -> Option<&str> { None }
61
62  /// Resource prefix for generated resource filenames.
63  fn resource_prefix(&self) -> Option<&str> { None }
64
65  /// Return the nodes to be processed; by default the document element.
66  /// This allows processors to focus on specific kinds of nodes,
67  /// or to skip processing if there are none to process.
68  fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
69    match doc.get_document_element() {
70      Some(el) => vec![el],
71      None => vec![],
72    }
73  }
74
75  /// Process the document given the nodes returned by `to_process`.
76  /// Returns the resulting document(s) — splitting may produce multiple.
77  fn process(&mut self, doc: PostDocument, nodes: Vec<Node>) -> ProcessResult;
78
79  /// Hint for a desired resource pathname.
80  fn desired_resource_pathname(
81    &self,
82    _doc: &PostDocument,
83    _node: &Node,
84    _source: Option<&str>,
85    _type_ext: Option<&str>,
86  ) -> Option<PathBuf> {
87    None
88  }
89}
90
91/// Information about a document class or package extracted from processing instructions.
92#[derive(Debug, Clone)]
93pub struct ClassInfo {
94  pub name:     String,
95  pub options:  String,
96  pub oldstyle: Option<String>,
97}
98
99/// Information about a loaded package.
100#[derive(Debug, Clone)]
101pub struct PackageInfo {
102  pub name:    String,
103  pub options: String,
104}
105
106/// Extract the document class and packages from `<?latexml ...?>` processing instructions.
107///
108/// Returns `(class_info, packages)` where `class_info` defaults to "article" if none found.
109///
110/// Port of `Processor::find_documentclass_and_packages`.
111pub fn find_documentclass_and_packages(doc: &PostDocument) -> (ClassInfo, Vec<PackageInfo>) {
112  static PI_RE: std::sync::LazyLock<regex::Regex> =
113    std::sync::LazyLock::new(|| regex::Regex::new(r#"\s*([\w\-_]*)=[\"'](.*?)[\"']"#).unwrap());
114  let pi_re = &*PI_RE;
115  let mut class: Option<String> = None;
116  let mut classoptions = String::from("onecolumn");
117  let mut oldstyle: Option<String> = None;
118  let mut packages = Vec::new();
119
120  for pi in doc.findnodes("//processing-instruction('latexml')") {
121    let data = pi.get_content();
122    let mut entry = HashMap::default();
123    for cap in pi_re.captures_iter(&data) {
124      entry.insert(cap[1].to_string(), cap[2].to_string());
125    }
126    if let Some(cls) = entry.get("class") {
127      class = Some(cls.clone());
128      classoptions = entry
129        .get("options")
130        .cloned()
131        .unwrap_or_else(|| "onecolumn".to_string());
132      oldstyle = entry.get("oldstyle").cloned();
133    } else if let Some(pkg) = entry.get("package") {
134      let opts = entry.get("options").cloned().unwrap_or_default();
135      for p in pkg.split(',').map(str::trim).filter(|s| !s.is_empty()) {
136        packages.push(PackageInfo {
137          name:    p.to_string(),
138          options: opts.clone(),
139        });
140      }
141    }
142  }
143
144  if class.is_none() {
145    // Perl Post.pm:226 — Warn('expected', 'class', undef,
146    //   "No document class found; using article")
147    Warn!(
148      "expected",
149      "class",
150      "No document class found; using article"
151    );
152  }
153
154  let class_info = ClassInfo {
155    name: class.unwrap_or_else(|| "article".to_string()),
156    options: classoptions,
157    oldstyle,
158  };
159  (class_info, packages)
160}
161
162/// Extract preamble data from `<?latexml ...?>` processing instructions.
163///
164/// Port of `Processor::find_preambles`.
165pub fn find_preambles(doc: &PostDocument) -> String {
166  static PI_RE: std::sync::LazyLock<regex::Regex> =
167    std::sync::LazyLock::new(|| regex::Regex::new(r#"\s*([\w\-_]*)=[\"'](.*?)[\"']"#).unwrap());
168  let pi_re = &*PI_RE;
169  let mut preambles = Vec::new();
170
171  for pi in doc.findnodes("//processing-instruction('latexml')") {
172    let data = pi.get_content();
173    for cap in pi_re.captures_iter(&data) {
174      if &cap[1] == "preamble" {
175        preambles.push(cap[2].to_string());
176      }
177    }
178  }
179
180  preambles.join("\n")
181}
182
183/// Copy foreign-namespace attributes from `source` to `target`.
184///
185/// "Foreign" means attributes with a namespace prefix (contains ':')
186/// but NOT `xml:*` attributes.
187///
188/// Port of `Processor::copy_foreign_attributes`.
189pub fn copy_foreign_attributes(target: &mut Node, source: &Node) {
190  let props = source.get_properties();
191  for (key, value) in &props {
192    if key.starts_with("xml:") {
193      continue;
194    }
195    if !key.contains(':') {
196      continue;
197    }
198    // Only set if target doesn't already have this attribute
199    if target.get_attribute(key).is_none() {
200      target.set_attribute(key, value).ok();
201    }
202  }
203}
204
205#[cfg(test)]
206mod tests {
207  use super::*;
208
209  #[test]
210  fn processor_options_default_is_empty() {
211    let o = ProcessorOptions::default();
212    assert!(o.resource_directory.is_none());
213    assert!(o.resource_prefix.is_none());
214  }
215
216  #[test]
217  fn processor_options_clone_preserves() {
218    let o = ProcessorOptions {
219      resource_directory: Some("/tmp".to_string()),
220      resource_prefix:    Some("pre".to_string()),
221    };
222    let c = o.clone();
223    assert_eq!(c.resource_directory, Some("/tmp".to_string()));
224    assert_eq!(c.resource_prefix, Some("pre".to_string()));
225  }
226
227  #[test]
228  fn post_error_display_processing() {
229    let e = PostError::Processing("boom".to_string());
230    let s = format!("{e}");
231    assert!(s.contains("Post-processing error"));
232    assert!(s.contains("boom"));
233  }
234
235  #[test]
236  fn post_error_display_xml() {
237    let e = PostError::Xml("malformed".to_string());
238    let s = format!("{e}");
239    assert!(s.contains("XML error"));
240    assert!(s.contains("malformed"));
241  }
242
243  #[test]
244  fn post_error_from_io_error() {
245    let io = std::io::Error::new(std::io::ErrorKind::NotFound, "x");
246    let pe: PostError = io.into();
247    match pe {
248      PostError::Io(_) => {},
249      other => panic!("expected Io, got {other:?}"),
250    }
251  }
252
253  #[test]
254  fn post_error_display_io() {
255    let io = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
256    let e = PostError::Io(io);
257    let s = format!("{e}");
258    assert!(s.contains("I/O error"));
259  }
260
261  #[test]
262  fn post_error_impls_std_error() {
263    // The blanket impl lets us box it as dyn Error.
264    fn take_err<E: std::error::Error>(_: &E) {}
265    let e = PostError::Processing("x".to_string());
266    take_err(&e);
267  }
268}