latexml_post/
processor.rs1use std::path::PathBuf;
7
8use libxml::tree::Node;
9use rustc_hash::FxHashMap as HashMap;
10
11use crate::document::PostDocument;
12
13#[derive(Debug, Default, Clone)]
15pub struct ProcessorOptions {
16 pub resource_directory: Option<String>,
17 pub resource_prefix: Option<String>,
18}
19
20pub type ProcessResult = Result<Vec<PostDocument>, PostError>;
22
23#[derive(Debug)]
25pub enum PostError {
26 Processing(String),
28 Io(std::io::Error),
30 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
50pub trait Processor {
56 fn get_name(&self) -> &str;
58
59 fn resource_directory(&self) -> Option<&str> { None }
61
62 fn resource_prefix(&self) -> Option<&str> { None }
64
65 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 fn process(&mut self, doc: PostDocument, nodes: Vec<Node>) -> ProcessResult;
78
79 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#[derive(Debug, Clone)]
93pub struct ClassInfo {
94 pub name: String,
95 pub options: String,
96 pub oldstyle: Option<String>,
97}
98
99#[derive(Debug, Clone)]
101pub struct PackageInfo {
102 pub name: String,
103 pub options: String,
104}
105
106pub 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 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
162pub 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
183pub 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 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 fn take_err<E: std::error::Error>(_: &E) {}
265 let e = PostError::Processing("x".to_string());
266 take_err(&e);
267 }
268}