1use latexml_core::common::xml::name_is;
32use libxml::tree::Node;
33
34use crate::document::PostDocument;
35
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
47pub enum Whatsout {
48 #[default]
49 Document,
50 Fragment,
51 Math,
52 Archive,
53}
54
55impl Whatsout {
56 pub fn from_cli(s: &str) -> Option<Self> {
63 match s {
64 "document" => Some(Whatsout::Document),
65 "fragment" => Some(Whatsout::Fragment),
66 "math" => Some(Whatsout::Math),
67 _ if s.starts_with("archive") => Some(Whatsout::Archive),
68 _ => None,
69 }
70 }
71
72 pub fn as_cli(self) -> &'static str {
76 match self {
77 Whatsout::Document => "document",
78 Whatsout::Fragment => "fragment",
79 Whatsout::Math => "math",
80 Whatsout::Archive => "archive",
81 }
82 }
83
84 pub fn is_archive(self) -> bool { matches!(self, Whatsout::Archive) }
88
89 pub fn requires_post(self) -> bool { !matches!(self, Whatsout::Document) }
94}
95
96pub fn serialize_whatsout(doc: &PostDocument, mode: Whatsout) -> String {
104 match mode {
105 Whatsout::Document | Whatsout::Archive => doc.to_xml_string(),
108 Whatsout::Fragment => get_embeddable(doc)
109 .map(|n| doc.get_document().node_to_string(&n))
110 .unwrap_or_else(|| doc.to_xml_string()),
111 Whatsout::Math => get_math(doc)
112 .map(|n| doc.get_document().node_to_string(&n))
113 .unwrap_or_else(|| doc.to_xml_string()),
114 }
115}
116
117const MATH_XPATH: &str = "//*[local-name()='math' or local-name()='Math']";
121
122const MATH_IMG_XPATH: &str = "//*[local-name()='img' and contains(@class,'ltx_Math')]";
124
125const EMBEDDABLE_XPATH: &str = "//*[contains(@class,'ltx_document')]";
129
130const RDFA_ATTRS: &[&str] = &[
133 "prefix", "property", "content", "resource", "about", "typeof", "rel", "rev", "datatype",
134];
135
136fn is_unwrappable_div_class(class: &str) -> bool {
139 matches!(
140 class,
141 "ltx_page_main" | "ltx_page_content" | "ltx_document" | "ltx_para" | "ltx_header"
142 )
143}
144
145fn is_inline_child(name: &str) -> bool {
148 name.contains("math") || name.contains("text") || name.contains("span")
151}
152
153pub fn get_math(doc: &PostDocument) -> Option<Node> {
163 let math_nodes = doc.findnodes(MATH_XPATH);
164 let math_count = math_nodes.len();
165
166 if math_count == 0 {
167 let img_nodes = doc.findnodes(MATH_IMG_XPATH);
168 if img_nodes.is_empty() {
169 return get_embeddable(doc);
170 }
171 return img_nodes.into_iter().next();
172 }
173
174 let mut math = math_nodes.into_iter().next()?;
175 if math_count > 1 {
176 let descendant_math_xpath = format!(".{MATH_XPATH}");
181 let mut found = 0;
182 while found != math_count {
183 found = doc.findnodes_at(&descendant_math_xpath, Some(&math)).len();
184 if math.get_name().eq_ignore_ascii_case("math") {
185 found += 1;
186 }
187 if found != math_count {
188 match math.get_parent() {
189 Some(p) => math = p,
190 None => break,
191 }
192 }
193 }
194 while is_table_row_or_cell(&math.get_name()) {
197 match math.get_parent() {
198 Some(p) => math = p,
199 None => break,
200 }
201 }
202 }
203
204 Some(math)
205}
206
207pub fn get_embeddable(doc: &PostDocument) -> Option<Node> {
224 let root = doc.get_document_element()?;
225 let mut embeddable = doc
226 .findnodes(EMBEDDABLE_XPATH)
227 .into_iter()
228 .next()
229 .unwrap_or_else(|| root.clone());
230
231 loop {
233 if !name_is(&embeddable, "div") {
234 break;
235 }
236 let children = embeddable.get_child_nodes();
237 if children.len() != 1 {
238 break;
239 }
240 let class = embeddable.get_attribute("class").unwrap_or_default();
241 if !is_unwrappable_div_class(&class) {
242 break;
243 }
244 if embeddable.has_attribute("style") {
245 break;
246 }
247 match embeddable.get_first_child() {
248 Some(c) => embeddable = c,
249 None => break,
250 }
251 }
252
253 if name_is(&embeddable, "p") {
255 let children = embeddable.get_child_nodes();
256 if !children.is_empty() && children.iter().all(|c| is_inline_child(&c.get_name())) {
257 let _ = embeddable.set_name("span");
258 let _ = embeddable.set_attribute("class", "text");
259 }
260 }
261
262 for attr in RDFA_ATTRS {
264 if let Some(value) = root.get_attribute(attr) {
265 let _ = embeddable.set_attribute(attr, &value);
266 }
267 }
268
269 Some(embeddable)
270}
271
272fn is_table_row_or_cell(name: &str) -> bool { matches!(name, "tr" | "td" | "TR" | "TD") }
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277 use crate::document::PostDocumentOptions;
278
279 fn doc(xml: &str) -> PostDocument {
280 PostDocument::new_from_string(xml, PostDocumentOptions::default()).expect("parse test fixture")
281 }
282
283 #[test]
284 fn get_embeddable_returns_root_when_no_ltx_document() {
285 let d = doc("<html><body><p>hello</p></body></html>");
286 let node = get_embeddable(&d).expect("some node");
287 assert_eq!(node.get_name(), "html");
288 }
289
290 #[test]
297 fn get_embeddable_unwraps_single_child_wrappers_to_inline_span() {
298 let xml = r#"<html><body><div class="ltx_document"><div class="ltx_page_main"><p>Hello world</p></div></div></body></html>"#;
303 let d = doc(xml);
304 let node = get_embeddable(&d).expect("some node");
305 assert_eq!(node.get_name(), "span");
306 assert_eq!(node.get_attribute("class").as_deref(), Some("text"));
307 }
308
309 #[test]
310 fn get_embeddable_stops_at_multi_child() {
311 let xml =
313 r#"<html><body><div class="ltx_document"><p>first</p><p>second</p></div></body></html>"#;
314 let d = doc(xml);
315 let node = get_embeddable(&d).expect("some node");
316 assert_eq!(node.get_name(), "div");
317 assert_eq!(node.get_attribute("class").as_deref(), Some("ltx_document"));
318 }
319
320 #[test]
321 fn get_embeddable_keeps_p_when_child_is_non_inline_block() {
322 let xml = r#"<html><body><div class="ltx_document"><div class="ltx_para"><p><table>x</table></p></div></div></body></html>"#;
325 let d = doc(xml);
326 let node = get_embeddable(&d).expect("some node");
327 assert_eq!(node.get_name(), "p");
328 }
329
330 #[test]
331 fn get_math_returns_lone_math_node() {
332 let xml = r#"<html><body><p>some text</p><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>x</mi></math></body></html>"#;
333 let d = doc(xml);
334 let node = get_math(&d).expect("some node");
335 assert_eq!(node.get_name(), "math");
336 }
337
338 #[test]
339 fn get_math_returns_lca_for_multiple_math() {
340 let xml = r#"<html><body><div id="container"><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>a</mi></math><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>b</mi></math></div></body></html>"#;
341 let d = doc(xml);
342 let node = get_math(&d).expect("some node");
343 assert_eq!(node.get_name(), "div");
346 assert_eq!(node.get_attribute("id").as_deref(), Some("container"));
347 }
348
349 #[test]
350 fn get_math_falls_through_to_img_when_no_math_elements() {
351 let xml = r#"<html><body><p>before</p><img class="ltx_Math" alt="x"/></body></html>"#;
352 let d = doc(xml);
353 let node = get_math(&d).expect("some node");
354 assert_eq!(node.get_name(), "img");
355 }
356
357 #[test]
358 fn get_math_falls_through_to_embeddable_when_no_math_at_all() {
359 let xml = r#"<html><body><div class="ltx_document"><p>just prose</p></div></body></html>"#;
363 let d = doc(xml);
364 let node = get_math(&d).expect("some node");
365 assert_eq!(node.get_name(), "span");
366 }
367
368 #[test]
369 fn whatsout_from_cli_recognized() {
370 assert_eq!(Whatsout::from_cli("document"), Some(Whatsout::Document));
371 assert_eq!(Whatsout::from_cli("fragment"), Some(Whatsout::Fragment));
372 assert_eq!(Whatsout::from_cli("math"), Some(Whatsout::Math));
373 assert_eq!(Whatsout::from_cli("archive"), Some(Whatsout::Archive));
378 assert_eq!(Whatsout::from_cli("archive::zip"), Some(Whatsout::Archive));
379 assert_eq!(Whatsout::from_cli("nonsense"), None);
380 }
381
382 #[test]
383 fn whatsout_default_is_document() {
384 assert_eq!(Whatsout::default(), Whatsout::Document);
385 }
386
387 #[test]
388 fn whatsout_is_archive_predicate() {
389 assert!(Whatsout::Archive.is_archive());
390 assert!(!Whatsout::Document.is_archive());
391 assert!(!Whatsout::Fragment.is_archive());
392 assert!(!Whatsout::Math.is_archive());
393 }
394
395 #[test]
396 fn whatsout_requires_post_for_non_document() {
397 assert!(!Whatsout::Document.requires_post());
399 assert!(Whatsout::Fragment.requires_post());
400 assert!(Whatsout::Math.requires_post());
401 assert!(Whatsout::Archive.requires_post());
402 }
403
404 #[test]
405 fn serialize_whatsout_archive_returns_full_document() {
406 let xml = r#"<html><body><div class="ltx_document"><p>hi</p></div></body></html>"#;
411 let d = doc(xml);
412 let archive = serialize_whatsout(&d, Whatsout::Archive);
413 let full = serialize_whatsout(&d, Whatsout::Document);
414 assert_eq!(archive, full);
415 assert!(archive.contains("<html>") && archive.contains("</html>"));
416 }
417
418 #[test]
419 fn serialize_whatsout_document_matches_full_xml() {
420 let xml = r#"<html><body><div class="ltx_document"><p>hi</p></div></body></html>"#;
421 let d = doc(xml);
422 let full = serialize_whatsout(&d, Whatsout::Document);
423 assert!(full.contains("<html>") && full.contains("</html>"));
424 }
425
426 #[test]
427 fn serialize_whatsout_fragment_strips_html_wrapper() {
428 let xml = r#"<html><body><div class="ltx_document"><p>hi</p></div></body></html>"#;
429 let d = doc(xml);
430 let frag = serialize_whatsout(&d, Whatsout::Fragment);
431 assert!(
435 !frag.contains("<html>"),
436 "frag contains html wrapper: {frag}"
437 );
438 assert!(frag.contains("hi"));
439 }
440
441 #[test]
442 fn serialize_whatsout_math_returns_math_subtree() {
443 let xml = r#"<html><body><p>txt</p><math xmlns="http://www.w3.org/1998/Math/MathML"><mi>z</mi></math></body></html>"#;
444 let d = doc(xml);
445 let m = serialize_whatsout(&d, Whatsout::Math);
446 assert!(m.contains("<mi>z</mi>"));
447 assert!(!m.contains("<html>"), "math contains html wrapper: {m}");
448 assert!(
449 !m.contains("<p>txt</p>"),
450 "math contains unrelated text: {m}"
451 );
452 }
453
454 #[test]
455 fn get_embeddable_copies_rdfa_from_root() {
456 let xml = r#"<html prefix="dc: http://purl.org/dc/terms/" typeof="ScholarlyArticle"><body><div class="ltx_document"><p>text</p></div></body></html>"#;
457 let d = doc(xml);
458 let node = get_embeddable(&d).expect("some node");
459 assert_eq!(
462 node.get_attribute("prefix").as_deref(),
463 Some("dc: http://purl.org/dc/terms/")
464 );
465 assert_eq!(
466 node.get_attribute("typeof").as_deref(),
467 Some("ScholarlyArticle")
468 );
469 }
470
471 #[test]
472 fn whatsout_cli_tag_round_trips() {
473 for w in [
474 Whatsout::Document,
475 Whatsout::Fragment,
476 Whatsout::Math,
477 Whatsout::Archive,
478 ] {
479 assert_eq!(
480 Whatsout::from_cli(w.as_cli()),
481 Some(w),
482 "as_cli must round-trip through from_cli for {w:?}"
483 );
484 }
485 }
486}