1use std::{
9 cell::{OnceCell, RefCell},
10 collections::VecDeque,
11 rc::Rc,
12 sync::LazyLock,
13};
14
15use latexml_core::common::xml::name_is;
16use libxml::tree::{Node, NodeType};
17use regex::Regex;
18use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
19
20use crate::{
21 document::{NodeData, PostDocument, get_xml_id},
22 object_db::{Entry, ObjectDB, Value},
23 processor::{ProcessResult, Processor},
24 scan::{title_node_text, title_text_content},
25};
26
27const NORMAL_TOC_TYPES: &[&str] = &[
34 "ltx:document",
35 "ltx:part",
36 "ltx:chapter",
37 "ltx:section",
38 "ltx:subsection",
39 "ltx:subsubsection",
40 "ltx:paragraph",
41 "ltx:subparagraph",
42 "ltx:index",
43 "ltx:bibliography",
44 "ltx:glossary",
45 "ltx:appendix",
46];
47
48struct ChildPages {
53 ids: Vec<String>,
54 index_of: HashMap<String, usize>,
55 related: OnceCell<Vec<(&'static str, String)>>,
58}
59
60const KEPT_RELATIONS: &[&str] = &["bibliography", "index", "glossary"];
65
66fn ref_fallbacks(key: &str) -> &'static [&'static str] {
68 match key {
69 "typerefnum" => &["refnum"],
70 "creflabel" => &["refnum"],
72 "toctitle" => &["title", "toccaption"],
73 "title" => &["toccaption"],
74 "rawtoctitle" => &["toctitle", "title", "toccaption"],
75 "rawtitle" => &["title", "toccaption"],
76 _ => &[],
77 }
78}
79
80fn tag_text(doc: &PostDocument, val: &Value) -> String {
83 match val {
84 Value::Xml(_) => value_text(doc, val),
85 other => other.to_string(),
86 }
87}
88
89fn value_text(doc: &PostDocument, val: &Value) -> String {
99 let raw = match val {
100 Value::Xml(node) if node.get_type() == Some(NodeType::ElementNode) => {
101 title_node_text(doc, node)
102 },
103 Value::Xml(node) => title_text_content(doc, node),
104 other => other.to_string(),
105 };
106 raw.split_whitespace().collect::<Vec<_>>().join(" ")
109}
110
111fn ref_content_children(val: &Value) -> Vec<NodeData> {
121 match val {
122 Value::Xml(node) => trim_child_data(child_nodes_data(node)),
123 other => vec![NodeData::Text(other.to_string())],
124 }
125}
126
127fn trim_child_data(mut out: Vec<NodeData>) -> Vec<NodeData> {
130 if let Some(NodeData::Text(s)) = out.first_mut() {
131 let t = s.trim_start().to_string();
132 if t.is_empty() {
133 out.remove(0);
134 } else {
135 *s = t;
136 }
137 }
138 if let Some(NodeData::Text(s)) = out.last_mut() {
139 let t = s.trim_end().to_string();
140 if t.is_empty() {
141 out.pop();
142 } else {
143 *s = t;
144 }
145 }
146 out
147}
148
149fn strip_ref_display_fragids(doc: &PostDocument) {
161 for mut n in doc.findnodes("//ltx:ref//*[@fragid]") {
162 let _ = n.remove_attribute("fragid");
163 }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub enum UrlStyle {
171 File,
174 Server,
177 Negotiated,
180}
181
182impl UrlStyle {
183 pub fn from_cli(s: &str) -> Option<Self> {
186 match s {
187 "file" => Some(UrlStyle::File),
188 "server" => Some(UrlStyle::Server),
189 "negotiated" => Some(UrlStyle::Negotiated),
190 _ => None,
191 }
192 }
193
194 pub fn as_cli(self) -> &'static str {
197 match self {
198 UrlStyle::File => "file",
199 UrlStyle::Server => "server",
200 UrlStyle::Negotiated => "negotiated",
201 }
202 }
203}
204
205fn apply_url_style(url: &str, style: UrlStyle, extension: &str) -> String {
211 match style {
212 UrlStyle::Server => {
214 let index_suffix = format!("index.{extension}");
215 if let Some(prefix) = url.strip_suffix(&index_suffix) {
216 if prefix.is_empty() {
217 return "./".to_string(); } else if prefix.ends_with('/') {
219 return prefix.to_string(); } }
222 url.to_string()
223 },
224 UrlStyle::Negotiated => {
226 let stripped = url.strip_suffix(&format!(".{extension}")).unwrap_or(url);
227 if stripped == "index" {
228 String::new() } else if let Some(prefix) = stripped.strip_suffix("index") {
230 if prefix.ends_with('/') {
231 prefix.to_string() } else {
233 stripped.to_string() }
235 } else {
236 stripped.to_string()
237 }
238 },
239 UrlStyle::File => url.to_string(),
240 }
241}
242
243type RefMemoEntry = (String, bool, Vec<NodeData>);
245
246type TitleMemoEntry = (String, Option<String>);
250
251const MAX_MEMO_IDS: usize = 16_384;
255
256pub struct CrossRef {
260 name: String,
261 pub db: ObjectDB,
263 url_style: UrlStyle,
265 extension: String,
267 toc_show: String,
269 ref_show: String,
271 min_ref_length: usize,
273 ref_join: String,
275 navigation_toc: Option<String>,
277 missing: HashMap<String, HashMap<String, HashMap<String, u32>>>,
279 child_pages: RefCell<HashMap<String, Rc<ChildPages>>>,
285 filling: RefCell<Vec<String>>,
289 title_memo: RefCell<HashMap<String, Vec<TitleMemoEntry>>>,
292 ref_memo: RefCell<HashMap<String, Vec<RefMemoEntry>>>,
295}
296
297struct BibciteDatum {
301 key: String,
302 authors: Vec<NodeData>,
303 fullauthors: Vec<NodeData>,
304 authortext: String,
308 year: Vec<NodeData>,
309 rawyear: Option<String>,
312 suffix: Option<String>,
313 number: Vec<NodeData>,
314 refnum: Vec<NodeData>,
315 title: Vec<NodeData>,
316 fullentry: Vec<NodeData>,
319 attr: HashMap<String, String>,
320 missing: bool,
323 nameless: bool,
326}
327
328impl BibciteDatum {
329 fn entry_number(&self) -> Option<u64> {
332 let text = self.sort_label()?;
333 (!text.is_empty() && text.bytes().all(|b| b.is_ascii_digit()))
334 .then(|| text.parse().ok())
335 .flatten()
336 }
337
338 fn cite_sty_key(&self) -> Option<u64> { cite_sty_sort_key(&self.sort_label()?) }
341
342 fn sort_label(&self) -> Option<String> {
344 if self.missing {
345 return None;
346 }
347 let label = if self.number.is_empty() {
348 &self.refnum
349 } else {
350 &self.number
351 };
352 Some(text_content(label).trim().to_string())
353 }
354}
355
356fn cite_sty_sort_key(label: &str) -> Option<u64> {
362 let chars: Vec<char> = label.chars().collect();
363 if chars.is_empty() {
364 return None;
365 }
366 if chars.iter().all(char::is_ascii_digit) {
367 return label.parse::<u64>().ok().map(|n| n * 256);
368 }
369 let (prefix, rest) = if chars[0].is_ascii_digit() {
370 (0, &chars[..])
371 } else {
372 (u64::from(u32::from(chars[0])), &chars[1..])
373 };
374 let digits = rest.iter().take_while(|c| c.is_ascii_digit()).count();
375 if digits == 0 {
376 return None;
377 }
378 let number: u64 = rest[..digits].iter().collect::<String>().parse().ok()?;
379 let mut key = (prefix * 16384 + number) * 256;
380 let Some((mark, tail)) = rest[digits..].split_first() else {
381 return Some(key);
382 };
383 key += u64::from(u32::from(*mark));
384 if tail.is_empty() {
385 return Some(key);
386 }
387 if tail.iter().all(char::is_ascii_digit) && key < 262144 {
388 let last: u64 = tail.iter().collect::<String>().parse().ok()?;
389 return Some(key * 4096 + last);
390 }
391 None
392}
393
394fn trim_child_nodes(val: Option<&Value>) -> Vec<NodeData> {
399 match val {
400 None | Some(Value::Null) => Vec::new(),
401 Some(v @ Value::Xml(_)) => ref_content_children(v),
402 Some(v) => {
403 let s = v.to_string();
404 let t = s.trim();
405 if t.is_empty() {
406 Vec::new()
407 } else {
408 vec![NodeData::Text(t.to_string())]
409 }
410 },
411 }
412}
413
414fn full_entry(bibitem: &Node, dropped_year: Option<&str>) -> Vec<NodeData> {
423 let mut text = Vec::new();
424 let blocks = crate::document::element_children(bibitem)
425 .into_iter()
426 .filter(|block| {
427 name_is(block, "bibblock")
428 && !block
429 .get_attribute("class")
430 .is_some_and(|class| class.split_whitespace().any(|c| c == "ltx_bib_cited"))
431 });
432 let mut dropped_year = dropped_year;
433 for (i, block) in blocks.enumerate() {
434 if i > 0 {
435 text.push(NodeData::Text(" ".to_string()));
436 }
437 text.extend(child_nodes_data(&block));
438 if !crate::document::element_children(&block).is_empty()
440 && let Some(year) = dropped_year.take()
441 {
442 text.push(NodeData::Element {
443 tag: "ltx:text".to_string(),
444 attributes: Some(HashMap::from_iter([(
445 "class".to_string(),
446 "ltx_bib_year".to_string(),
447 )])),
448 children: vec![NodeData::Text(year.to_string())],
449 });
450 }
451 }
452 if matches!(text.last(), Some(NodeData::Text(last)) if last.trim() == ".") {
453 text.pop();
454 }
455 text
456}
457
458fn child_nodes_data(node: &Node) -> Vec<NodeData> {
462 let mut out: Vec<NodeData> = Vec::new();
463 let mut child = node.get_first_child();
464 while let Some(c) = child {
465 match c.get_type() {
466 Some(NodeType::TextNode) => out.push(NodeData::Text(c.get_content())),
467 Some(NodeType::ElementNode) => out.push(NodeData::XmlNode(c.clone())),
468 _ => {},
469 }
470 child = c.get_next_sibling();
471 }
472 out
473}
474
475fn needs_fill_in(node: &Node) -> bool {
480 let mut child = node.get_first_child();
481 while let Some(c) = child {
482 if c.get_type() == Some(NodeType::ElementNode) {
483 match c.get_name().as_str() {
484 "ref" if is_unfilled_ref(&c) => return true,
485 "break" => return true,
486 "Math" => {},
487 _ if needs_fill_in(&c) => return true,
488 _ => {},
489 }
490 }
491 child = c.get_next_sibling();
492 }
493 false
494}
495
496fn value_reads_page(val: &Value) -> bool {
499 fn holds_math(node: &Node) -> bool {
500 let mut child = node.get_first_child();
501 while let Some(c) = child {
502 if c.get_type() == Some(NodeType::ElementNode) && (c.get_name() == "Math" || holds_math(&c)) {
503 return true;
504 }
505 child = c.get_next_sibling();
506 }
507 false
508 }
509 match val {
510 Value::Xml(node) => {
511 (node.get_type() == Some(NodeType::ElementNode) && node.get_name() == "Math")
512 || holds_math(node)
513 || needs_fill_in(node)
514 },
515 _ => false,
516 }
517}
518
519fn is_unfilled_ref(node: &Node) -> bool {
522 (node.has_attribute("idref") || node.has_attribute("labelref")) && node.get_content().is_empty()
523}
524
525fn node_data_text(doc: &PostDocument, data: &[NodeData]) -> String {
528 let mut out = String::new();
529 for datum in data {
530 match datum {
531 NodeData::Text(text) => out.push_str(text),
532 NodeData::XmlNode(node) => out.push_str(&title_node_text(doc, node)),
533 NodeData::Element { tag, attributes, children } => {
534 let attr = |key: &str| {
535 attributes
536 .as_ref()
537 .and_then(|attributes| attributes.get(key))
538 .map_or("", String::as_str)
539 };
540 let tagged = tag == "ltx:tag";
541 if tagged {
542 out.push_str(attr("open"));
543 }
544 out.push_str(&node_data_text(doc, children));
545 if tagged {
546 out.push_str(attr("close"));
547 }
548 },
549 }
550 }
551 out
552}
553
554fn bib_ref(attr: &HashMap<String, String>, children: Vec<NodeData>) -> NodeData {
556 NodeData::Element {
557 tag: "ltx:ref".to_string(),
558 attributes: Some(attr.clone()),
559 children,
560 }
561}
562
563fn bibcite_show_walk(
574 saveshow: &str,
575 datum: &BibciteDatum,
576 data: &mut VecDeque<BibciteDatum>,
577 preformatted: &[NodeData],
578 phrases: &[Node],
579 yysep: &str,
580 checkdups: bool,
581) -> (Vec<NodeData>, bool, Option<bool>) {
582 static YEAR_DELIM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)(\w)year").unwrap());
583 static PHRASE_DELIM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)(\w)phrase").unwrap());
584 static PHRASE_NUM_DELIM: LazyLock<Regex> =
585 LazyLock::new(|| Regex::new(r"(?i)phrase(\d)(\w)").unwrap());
586 static ROLE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\w+").unwrap());
587 static LITERAL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\{([^}]*)\}").unwrap());
588 static SPACES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s+").unwrap());
589 static PUNCT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\W+").unwrap());
590 static EMPTY_YEAR_PHRASE2: LazyLock<Regex> =
591 LazyLock::new(|| Regex::new(r"(?i)^\{\}year\{\}phrase2").unwrap());
592
593 let mut didref = false;
594 let mut numeric: Option<bool> = None;
596 let mut stuff: Vec<NodeData> = Vec::new();
597 let mut show = saveshow;
598 if show == "none" && !preformatted.is_empty() {
599 stuff = preformatted.to_vec();
600 numeric = Some(false);
601 show = "";
602 } else if datum.missing {
603 stuff = vec![bib_ref(&datum.attr, vec![NodeData::Text(
604 datum.key.clone(),
605 )])];
606 didref = true;
607 show = "";
608 }
609 let show = YEAR_DELIM.replace_all(show, "${1}{}year");
611 let show = PHRASE_DELIM.replace_all(&show, "${1}{}phrase");
612 let show = PHRASE_NUM_DELIM.replace_all(&show, "phrase${1}{}${2}");
613 let mut rest: &str = &show;
614 let same_authors = |data: &VecDeque<BibciteDatum>| {
617 data
618 .front()
619 .is_some_and(|n| n.authortext == datum.authortext)
620 };
621 while !rest.is_empty() {
622 if let Some(m) = ROLE.find(rest) {
623 let mut role = m.as_str().to_lowercase();
624 rest = &rest[m.end()..];
625 if role.ends_with('s') {
626 role.pop();
627 }
628 match role.as_str() {
629 "refnum" | "number" | "super" => numeric = Some(numeric.unwrap_or(true)),
630 "author" | "fullauthor" | "title" | "fullentry" | "year" => numeric = Some(false),
631 _ => {},
632 }
633 match role.as_str() {
634 "author" => stuff.extend(datum.authors.iter().cloned()),
635 "fullauthor" => stuff.extend(datum.fullauthors.iter().cloned()),
636 "title" => stuff.extend(datum.title.iter().cloned()),
637 "refnum" => stuff.extend(datum.refnum.iter().cloned()),
638 "fullentry" if datum.fullentry.is_empty() => {
640 stuff.push(bib_ref(&datum.attr, datum.refnum.clone()));
641 didref = true;
642 },
643 "fullentry" => {
644 stuff.extend(datum.fullentry.iter().cloned());
645 didref = true;
646 },
647 "year" => {
648 if !datum.year.is_empty() {
651 stuff.push(bib_ref(&datum.attr, datum.year.clone()));
652 didref = true;
653 while checkdups && same_authors(data) {
654 let next = data.pop_front().unwrap();
655 stuff.push(NodeData::Text(yysep.to_string()));
656 stuff.push(NodeData::Text(" ".to_string()));
657 let same_year = datum.rawyear.as_deref().unwrap_or("no_year_1")
658 == next.rawyear.as_deref().unwrap_or("no_year_2");
659 match next.suffix {
660 Some(ref suffix) if same_year => {
661 stuff.push(bib_ref(&next.attr, vec![NodeData::Text(suffix.clone())]))
662 },
663 _ => stuff.push(bib_ref(&next.attr, next.year.clone())),
664 }
665 }
666 }
667 },
668 "number" | "super" => {
669 let mut r = vec![bib_ref(&datum.attr, datum.number.clone())];
670 didref = true;
671 while checkdups && same_authors(data) {
672 let next = data.pop_front().unwrap();
673 r.push(NodeData::Text(yysep.to_string()));
674 r.push(NodeData::Text(" ".to_string()));
675 r.push(bib_ref(&next.attr, next.number.clone()));
676 }
677 if role == "super" {
678 stuff.push(NodeData::Element {
679 tag: "ltx:sup".to_string(),
680 attributes: None,
681 children: r,
682 });
683 } else {
684 stuff.extend(r);
685 }
686 },
687 _ => match role.strip_prefix("phrase").and_then(|d| {
688 let mut ds = d.chars();
689 ds.next()
690 .and_then(|c| c.to_digit(10))
691 .filter(|_| ds.next().is_none())
692 }) {
693 Some(n) => {
696 let short = |i: usize| {
697 phrases
698 .get(i)
699 .is_none_or(|p| p.get_content().chars().count() <= 1)
700 };
701 if n == 1
702 && datum.year.is_empty()
703 && short(0)
704 && short(1)
705 && let Some(m) = EMPTY_YEAR_PHRASE2.find(rest)
706 {
707 rest = &rest[m.end()..];
708 } else {
709 let phrase = match n {
711 0 => phrases.last(),
712 n => phrases.get(n as usize - 1),
713 };
714 if let Some(phrase) = phrase {
715 stuff.extend(child_nodes_data(phrase));
716 }
717 }
718 },
719 None => Info!("unexpected", role, "CITE ignoring show key '{}'", role),
720 },
721 }
722 } else if let Some(c) = LITERAL.captures(rest) {
723 if !c[1].is_empty() {
725 stuff.push(NodeData::Text(c[1].to_string()));
726 }
727 rest = &rest[c[0].len()..];
728 } else if let Some(r) = rest.strip_prefix('~') {
729 if !stuff.is_empty() {
730 stuff.push(NodeData::Text("\u{A0}".to_string()));
731 }
732 rest = r;
733 } else if let Some(m) = SPACES.find(rest) {
734 if !stuff.is_empty() {
735 stuff.push(NodeData::Text(m.as_str().to_string()));
736 }
737 rest = &rest[m.end()..];
738 } else if let Some(m) = PUNCT.find(rest) {
739 stuff.push(NodeData::Text(m.as_str().to_string()));
740 rest = &rest[m.end()..];
741 } else {
742 break;
744 }
745 }
746 (stuff, didref, numeric)
747}
748
749impl CrossRef {
750 pub fn new(db: ObjectDB, url_style: UrlStyle, number_sections: bool) -> Self {
751 CrossRef {
752 name: "CrossRef".to_string(),
753 db,
754 url_style,
755 extension: "xml".to_string(),
756 toc_show: "toctitle".to_string(),
757 ref_show: if number_sections {
758 "refnum".to_string()
759 } else {
760 "title".to_string()
761 },
762 min_ref_length: 1,
763 ref_join: " \u{2023} ".to_string(), navigation_toc: None,
765 missing: HashMap::default(),
766 child_pages: RefCell::new(HashMap::default()),
767 filling: RefCell::new(Vec::new()),
768 title_memo: RefCell::new(HashMap::default()),
769 ref_memo: RefCell::new(HashMap::default()),
770 }
771 }
772
773 pub fn set_extension(&mut self, ext: &str) { self.extension = ext.to_string(); }
775
776 pub fn set_navigation_toc(&mut self, format: &str) {
778 self.navigation_toc = Some(format.to_string());
779 }
780
781 fn note_missing(&mut self, severity: &str, ref_type: &str, key: &str) {
783 self
784 .missing
785 .entry(severity.to_string())
786 .or_default()
787 .entry(ref_type.to_string())
788 .or_default()
789 .entry(key.to_string())
790 .and_modify(|c| *c += 1)
791 .or_insert(1);
792 }
793
794 fn generate_url(&mut self, doc: &PostDocument, id: &str) -> Option<String> {
798 let entry = self.db.lookup(&format!("ID:{}", id))?;
799 let location = entry.get_string("location")?;
800
801 let doc_location = doc.site_relative_destination().unwrap_or_default();
802 let mut url = relative_url(location, &doc_location);
803
804 url = apply_url_style(&url, self.url_style, &self.extension);
805
806 if url.is_empty() {
807 url = ".".to_string();
808 }
809
810 let fragid = entry.get_string("fragid").map(String::from);
812 let loc = location.to_string();
813 if let Some(fid) = fragid {
814 if url == "." || loc == doc_location {
815 url.clear();
816 }
817 url = format!("{}#{}", url, fid);
818 } else if loc == doc_location {
819 url.clear();
820 }
821
822 Some(url)
823 }
824
825 fn generate_title(&self, doc: &PostDocument, id: &str, shown: &str) -> Option<String> {
829 if let Some(title) = self.title_memo.borrow().get(id).and_then(|by_shown| {
830 by_shown
831 .iter()
832 .find(|(s, _)| s == shown)
833 .map(|(_, t)| t.clone())
834 }) {
835 return title;
836 }
837 let (title, reads_page) = self.generate_title_uncached(doc, id, shown);
838 if !reads_page {
839 let mut memo = self.title_memo.borrow_mut();
840 if memo.len() >= MAX_MEMO_IDS && !memo.contains_key(id) {
841 memo.clear();
842 }
843 let by_shown = memo.entry(id.to_string()).or_default();
844 by_shown.push((shown.to_string(), title.clone()));
845 }
846 title
847 }
848
849 fn generate_title_uncached(
852 &self,
853 doc: &PostDocument,
854 id: &str,
855 shown: &str,
856 ) -> (Option<String>, bool) {
857 let mut reads_page = false;
858 let mut current_id = id.to_string();
859 let mut result = String::new();
860 let mut prefix = String::new();
861 let mut shown_so_far = shown.to_string();
862
863 while let Some(entry) = self.db.lookup(&format!("ID:{}", current_id)) {
864 let mut pieces = Vec::new();
865 let mut is_dup = false;
866
867 if let Some(title_val) = entry.get_value("title") {
869 if title_val.is_truthy() {
870 is_dup = shown_so_far.contains("title");
871 reads_page |= value_reads_page(title_val);
875 pieces.push(self.filled_value_text(doc, ¤t_id, title_val));
876 }
877 }
878 if pieces.is_empty() {
879 let has_type = entry
880 .get_value("tag:creftypecap")
881 .or_else(|| entry.get_value("tag:creftype"));
882 let has_refnum = entry.get_value("refnum");
883 let shows_refnum = shown_so_far.contains("refnum") || shown_so_far.contains("creflabel");
885 if has_type.is_some() && has_refnum.is_some() {
886 is_dup = shown_so_far.contains("type") && shows_refnum;
887 if let Some(t) = has_type {
888 reads_page |= value_reads_page(t);
889 pieces.push(tag_text(doc, t));
890 }
891 if let Some(r) = has_refnum {
892 reads_page |= value_reads_page(r);
893 pieces.push(tag_text(doc, r));
894 }
895 } else if let Some(tr) = entry.get_value("typerefnum") {
896 is_dup = shown_so_far.contains("type") && shows_refnum;
897 reads_page |= value_reads_page(tr);
898 pieces.push(tag_text(doc, tr));
899 } else if let Some(r) = has_refnum {
900 is_dup = shows_refnum;
901 reads_page |= value_reads_page(r);
902 pieces.push(tag_text(doc, r));
903 }
904 }
905
906 if is_dup {
907 prefix = "In ".to_string();
908 shown_so_far.clear();
909 } else {
910 let title = pieces.join(" ");
911 let title = title.trim();
912 if !title.is_empty() {
913 result.push_str(&prefix);
914 prefix = self.ref_join.clone();
915 result.push_str(title);
916 }
917 }
918
919 match entry.get_string("parent").map(String::from) {
921 Some(pid) => current_id = pid,
922 None => break,
923 }
924 }
925
926 let title = if result.is_empty() {
927 None
928 } else {
929 Some(result)
930 };
931 (title, reads_page)
932 }
933
934 fn generate_document_title(&self, doc: &PostDocument) -> Option<String> {
938 if let Some(docid) = doc.get_document_element().as_ref().and_then(get_xml_id) {
942 let title = self.generate_title(doc, &docid, "");
949 if title.as_ref().map(|t| !t.is_empty()).unwrap_or(false) {
950 return title;
951 }
952 }
953 if let Some(node) =
955 doc.findnode("//ltx:title | //ltx:toctitle | //ltx:caption | //ltx:toccaption")
956 {
957 let text = get_text_content_node(&node);
958 if !text.is_empty() {
959 return Some(text);
960 }
961 }
962 None
963 }
964
965 fn generate_glossary_ref_title(&self, entry_key: &str, show: &str) -> Vec<NodeData> {
973 let Some(entry) = self.db.lookup(entry_key) else {
974 return vec![];
975 };
976 let wrap = |children: Vec<NodeData>| {
977 vec![NodeData::Element {
978 tag: "ltx:text".to_string(),
979 attributes: Some(HashMap::from_iter([(
980 "class".to_string(),
981 format!("ltx_glossary_{show}"),
982 )])),
983 children,
984 }]
985 };
986 if let Some(val) = entry.get_value(&format!("phrase:{show}")) {
987 return wrap(self.entry_text_children(entry_key, val, false));
988 }
989 if let Some(base) = show.strip_suffix("-plural")
990 && let Some(val) = entry.get_value(&format!("phrase:{base}"))
991 {
992 let mut children = self.entry_text_children(entry_key, val, false);
993 children.push(NodeData::Text("s".to_string()));
994 return wrap(children);
995 }
996 if let Some(base) = show.strip_suffix("-indefinite")
997 && let Some(val) = entry.get_value(&format!("phrase:{base}"))
998 {
999 let article = if val
1001 .as_string()
1002 .starts_with(|c: char| "aeiouAEIOU".contains(c))
1003 {
1004 "an "
1005 } else {
1006 "a "
1007 };
1008 let mut children = vec![NodeData::Text(article.to_string())];
1009 children.extend(self.entry_text_children(entry_key, val, false));
1010 return wrap(children);
1011 }
1012 vec![]
1013 }
1014
1015 fn copy_resources(&self, doc: &PostDocument) {
1019 let refs = doc.findnodes("//ltx:ref[@href and not(@idref) and not(@labelref)]");
1020 for ref_node in &refs {
1021 if let Some(url) = ref_node.get_attribute("href") {
1022 if !url.contains("://") && !url.starts_with('/') {
1024 log::trace!("CrossRef: would copy resource '{}'", url);
1026 }
1027 }
1028 }
1029 }
1030
1031 fn entry_text_children(&self, id: &str, val: &Value, is_nameref: bool) -> Vec<NodeData> {
1036 trim_child_data(self.entry_children(id, val, is_nameref))
1037 }
1038
1039 fn entry_children(&self, id: &str, val: &Value, is_nameref: bool) -> Vec<NodeData> {
1043 let Value::Xml(node) = val else {
1044 return ref_content_children(val);
1045 };
1046 let mut out =
1048 if needs_fill_in(node) && !self.filling.borrow().iter().any(|filling| filling == id) {
1049 self.filling.borrow_mut().push(id.to_string());
1050 let filled = self.filled_children(node);
1051 self.filling.borrow_mut().pop();
1052 filled
1053 } else {
1054 child_nodes_data(node)
1055 };
1056 if is_nameref
1057 && let Some(at) = out
1058 .iter()
1059 .position(|datum| !matches!(datum, NodeData::Text(_)))
1060 && matches!(&out[at], NodeData::XmlNode(first) if name_is(first, "tag"))
1061 {
1062 out.remove(at);
1063 }
1064 out
1065 }
1066
1067 fn filled_children(&self, node: &Node) -> Vec<NodeData> {
1074 let mut out = Vec::new();
1075 let mut child = node.get_first_child();
1076 while let Some(c) = child {
1077 match c.get_type() {
1078 Some(NodeType::TextNode) => out.push(NodeData::Text(c.get_content())),
1079 Some(NodeType::ElementNode) => out.extend(self.filled_node(&c)),
1080 _ => {},
1081 }
1082 child = c.get_next_sibling();
1083 }
1084 out
1085 }
1086
1087 fn filled_node(&self, node: &Node) -> Vec<NodeData> {
1089 let in_ltx = node
1090 .get_namespace()
1091 .is_some_and(|ns| ns.get_href() == crate::document::LTX_NSURI);
1092 match node.get_name().as_str() {
1093 "ref" if in_ltx && is_unfilled_ref(node) => {
1094 let target = match node.get_attribute("idref") {
1095 Some(id) => Some(id),
1096 None => node.get_attribute("labelref").and_then(|label| {
1097 self
1098 .db
1099 .lookup(&label)
1100 .and_then(|entry| entry.get_string("id").map(String::from))
1101 }),
1102 };
1103 match target.filter(|id| self.db.lookup(&format!("ID:{id}")).is_some()) {
1104 Some(id) => {
1105 let show = node
1106 .get_attribute("show")
1107 .filter(|show| !show.is_empty())
1108 .unwrap_or_else(|| self.ref_show.clone());
1109 let is_nameref = node
1112 .get_attribute("class")
1113 .is_some_and(|class| class.contains("ltx_refmacro_nameref"));
1114 self.generate_ref_aux(&id, &show, is_nameref)
1115 },
1116 None => vec![NodeData::XmlNode(node.clone())],
1117 }
1118 },
1119 "break" if in_ltx => vec![NodeData::Element {
1120 tag: "ltx:text".to_string(),
1121 attributes: None,
1122 children: vec![NodeData::Text(" ".to_string())],
1123 }],
1124 "Math" => vec![NodeData::XmlNode(node.clone())],
1125 name if in_ltx && needs_fill_in(node) => {
1126 let xml_ns = latexml_core::common::xml::XML_NS;
1129 let attributes: HashMap<String, String> = node
1130 .get_properties()
1131 .into_iter()
1132 .filter(|(k, _)| k != "fragid" && k != "labels")
1133 .filter_map(|(k, v)| match node.get_attribute_ns(&k, xml_ns) {
1134 Some(_) if k == "id" => None,
1135 Some(_) => Some((format!("xml:{k}"), v)),
1136 None => Some((k, v)),
1137 })
1138 .collect();
1139 vec![NodeData::Element {
1140 tag: format!("ltx:{name}"),
1141 attributes: Some(attributes),
1142 children: self.filled_children(node),
1143 }]
1144 },
1145 _ => vec![NodeData::XmlNode(node.clone())],
1146 }
1147 }
1148
1149 fn filled_value_text(&self, doc: &PostDocument, id: &str, val: &Value) -> String {
1151 match val {
1152 Value::Xml(node) if needs_fill_in(node) => {
1153 let children = self.entry_text_children(id, val, false);
1154 node_data_text(doc, &children)
1155 .split_whitespace()
1156 .collect::<Vec<_>>()
1157 .join(" ")
1158 },
1159 _ => value_text(doc, val),
1160 }
1161 }
1162
1163 fn generate_ref(
1168 &mut self,
1169 _doc: &PostDocument,
1170 req_id: &str,
1171 req_show: &str,
1172 is_nameref: bool,
1173 ) -> Vec<NodeData> {
1174 if let Some(stuff) = self.ref_memo.borrow().get(req_id).and_then(|by_show| {
1175 by_show
1176 .iter()
1177 .find(|(show, nameref, _)| show == req_show && *nameref == is_nameref)
1178 .map(|(_, _, stuff)| stuff.clone())
1179 }) {
1180 return stuff;
1181 }
1182 match self.generate_ref_uncached(req_id, req_show, is_nameref) {
1183 Some(stuff) => {
1184 let mut memo = self.ref_memo.borrow_mut();
1185 if memo.len() >= MAX_MEMO_IDS && !memo.contains_key(req_id) {
1186 memo.clear();
1187 }
1188 let by_show = memo.entry(req_id.to_string()).or_default();
1189 by_show.push((req_show.to_string(), is_nameref, stuff.clone()));
1190 stuff
1191 },
1192 None => {
1194 self.note_missing("info", "Usable title for ID", req_id);
1195 vec![NodeData::Text(req_id.to_string())]
1196 },
1197 }
1198 }
1199
1200 fn generate_ref_uncached(
1202 &self,
1203 req_id: &str,
1204 req_show: &str,
1205 is_nameref: bool,
1206 ) -> Option<Vec<NodeData>> {
1207 let alternatives = show_alternatives(req_show);
1213 if let Some((_default, formats)) = alternatives.split_last() {
1214 for format in formats {
1215 let stuff = self.generate_ref_aux(req_id, format, is_nameref);
1216 if !stuff.is_empty() {
1217 return Some(stuff);
1218 }
1219 }
1220 }
1221 let show_options = if !req_show.contains("title") {
1222 vec![req_show.to_string(), "title".to_string()]
1223 } else {
1224 vec![req_show.to_string(), "refnum".to_string()]
1225 };
1226
1227 for show in &show_options {
1228 let mut stuff = Vec::new();
1229 let mut id = req_id.to_string();
1230 let mut pending = String::new();
1231 loop {
1232 let entry_exists = self.db.lookup(&format!("ID:{}", id)).is_some();
1233 if !entry_exists {
1234 break;
1235 }
1236 let s = self.generate_ref_aux(&id, show, is_nameref);
1237 if !s.is_empty() {
1238 if !pending.is_empty() {
1239 stuff.push(NodeData::Text(pending.clone()));
1240 }
1241 stuff.extend(s);
1242 if self.check_ref_content(&stuff) {
1243 return Some(stuff);
1244 }
1245 pending = self.ref_join.clone();
1246 }
1247 let parent = self
1248 .db
1249 .lookup(&format!("ID:{}", id))
1250 .and_then(|e| e.get_string("parent").map(String::from));
1251 match parent {
1252 Some(pid) => id = pid,
1253 None => break,
1254 }
1255 }
1256 if !stuff.is_empty() {
1257 return Some(stuff);
1258 }
1259 }
1260 None
1261 }
1262
1263 fn generate_ref_aux(&self, id: &str, show: &str, is_nameref: bool) -> Vec<NodeData> {
1267 let alternatives = show_alternatives(show);
1268 if alternatives.len() > 1 {
1269 return alternatives
1270 .into_iter()
1271 .map(|alternative| self.generate_ref_aux(id, alternative, is_nameref))
1272 .find(|stuff| !stuff.is_empty())
1273 .unwrap_or_default();
1274 }
1275 let entry = match self.db.lookup(&format!("ID:{}", id)) {
1276 Some(e) => e,
1277 None => return vec![],
1278 };
1279
1280 let mut stuff = Vec::new();
1281 let mut ok = false;
1282 let mut remaining = show.to_string();
1283
1284 while !remaining.is_empty() {
1285 if remaining.starts_with(|c: char| c.is_alphanumeric()) {
1286 let keyword: String = remaining
1287 .chars()
1288 .take_while(|c| c.is_alphanumeric())
1289 .collect();
1290 remaining = remaining[keyword.len()..].to_string();
1291 let key = keyword.to_lowercase();
1292 let class = if key.contains("title") {
1293 "ltx_ref_title"
1294 } else {
1295 "ltx_ref_tag"
1296 };
1297
1298 let mut keys_to_try = vec![key.clone(), format!("tag:{}", key)];
1299 keys_to_try.extend(ref_fallbacks(&key).iter().map(|s| s.to_string()));
1300
1301 for k in &keys_to_try {
1302 if let Some(val) = entry.get_value(k) {
1303 if val.is_truthy() {
1304 ok = true;
1305 stuff.push(NodeData::Element {
1313 tag: "ltx:text".to_string(),
1314 attributes: Some(HashMap::from_iter([(
1315 "class".to_string(),
1316 class.to_string(),
1317 )])),
1318 children: if k.starts_with("tag:") || k.ends_with("refnum") {
1319 self.entry_children(id, val, is_nameref)
1320 } else {
1321 self.entry_text_children(id, val, is_nameref)
1322 },
1323 });
1324 break;
1325 }
1326 }
1327 }
1328 } else if remaining.starts_with('{') {
1329 if let Some(end) = remaining[1..].find('}') {
1330 let literal = &remaining[1..1 + end];
1331 if !literal.is_empty() {
1332 stuff.push(NodeData::Text(literal.to_string()));
1333 }
1334 remaining = remaining[2 + end..].to_string();
1335 } else {
1336 remaining.clear();
1337 }
1338 } else if remaining.starts_with('~') {
1339 remaining = remaining[1..].to_string();
1340 if !stuff.is_empty() {
1341 stuff.push(NodeData::Text("\u{00A0}".to_string()));
1342 }
1343 } else if remaining.starts_with(|c: char| c.is_whitespace()) {
1344 let ws: String = remaining
1345 .chars()
1346 .take_while(|c| c.is_whitespace())
1347 .collect();
1348 remaining = remaining[ws.len()..].to_string();
1349 if !stuff.is_empty() {
1350 stuff.push(NodeData::Text(ws));
1351 }
1352 } else {
1353 let sym: String = remaining
1354 .chars()
1355 .take_while(|c| !c.is_alphanumeric() && *c != '{' && *c != '~')
1356 .collect();
1357 remaining = remaining[sym.len()..].to_string();
1358 stuff.push(NodeData::Text(sym));
1359 }
1360 }
1361
1362 if ok { stuff } else { vec![] }
1363 }
1364
1365 fn check_ref_content(&self, stuff: &[NodeData]) -> bool {
1367 let text = text_content(stuff);
1368 let cleaned = text.replace("in ", "");
1369 cleaned.chars().any(|c| c.is_alphanumeric())
1370 }
1371
1372 fn fill_in_relations(&mut self, doc: &mut PostDocument) {
1376 let page_id = match doc.get_document_element().as_ref().and_then(get_xml_id) {
1380 Some(id) => id,
1381 None => return,
1382 };
1383
1384 let mut current_id = page_id.clone();
1386 let mut rel = "up".to_string();
1387 let mut topmost = current_id.clone();
1388 loop {
1389 let parent_id = self
1390 .db
1391 .lookup(&format!("ID:{}", current_id))
1392 .and_then(|e| e.get_string("parent").map(String::from));
1393 match parent_id {
1394 Some(pid) => {
1395 let has_title = self
1396 .db
1397 .lookup(&format!("ID:{}", pid))
1398 .and_then(|e| e.get_value("title"))
1399 .map(|v| v.is_truthy())
1400 .unwrap_or(false);
1401 if has_title {
1402 doc.add_navigation(&rel, &pid);
1403 rel = format!("{} up", rel);
1404 }
1405 current_id = pid.clone();
1406 topmost = pid;
1407 },
1408 None => break,
1409 }
1410 }
1411
1412 if topmost != page_id {
1414 if let Some(top_pageid) = self
1415 .db
1416 .lookup(&format!("ID:{}", topmost))
1417 .and_then(|e| e.get_string("pageid").map(String::from))
1418 {
1419 doc.add_navigation("start", &top_pageid);
1420 }
1421 }
1422
1423 if let Some(prev) = self.find_previous_page_id(&page_id) {
1425 doc.add_navigation("prev", &prev);
1426 }
1427 if let Some(next) = self.find_next_page_id(&page_id) {
1428 doc.add_navigation("next", &next);
1429 }
1430
1431 let mut xentry = page_id.clone();
1437 while let Some(parent) = self.get_parent_page_id(&xentry) {
1438 for (rel, sib) in self.related_pages(&parent) {
1439 if sib != page_id {
1440 doc.add_navigation(rel, &sib);
1441 }
1442 }
1443 xentry = parent;
1444 }
1445 for (rel, child) in self.related_pages(&page_id) {
1446 doc.add_navigation(rel, &child);
1447 }
1448 }
1449
1450 fn related_pages(&self, entry_id: &str) -> Vec<(&'static str, String)> {
1454 let pages = self.child_pages(entry_id);
1455 let related = pages.related.get_or_init(|| {
1456 let mut related = Vec::new();
1457 for id in pages.ids.iter() {
1458 if !self.is_primary_page(id) {
1459 continue; }
1461 let typ = self
1462 .db
1463 .lookup(&format!("ID:{}", id))
1464 .and_then(|e| e.get_string("type").map(String::from));
1465 let name = typ.as_deref().map(|t| t.rsplit(':').next().unwrap_or(t));
1466 if let Some(rel) = name.and_then(|n| KEPT_RELATIONS.iter().find(|k| **k == n)) {
1467 related.push((*rel, id.clone()));
1468 }
1469 }
1470 related
1471 });
1472 related.clone()
1473 }
1474
1475 fn is_primary_page(&self, page_id: &str) -> bool {
1478 self
1479 .db
1480 .lookup(&format!("ID:{}", page_id))
1481 .and_then(|e| e.get_value("primary"))
1482 .map(|v| v.is_truthy())
1483 .unwrap_or(false)
1484 }
1485
1486 fn get_parent_page_id(&self, entry_id: &str) -> Option<String> {
1489 let entry = self.db.lookup(&format!("ID:{}", entry_id))?;
1490 let pageid = entry.get_string("pageid")?.to_string();
1491 let page_entry = self.db.lookup(&format!("ID:{}", pageid))?;
1492 let parent_id = page_entry.get_string("parent")?.to_string();
1493 let parent_entry = self.db.lookup(&format!("ID:{}", parent_id))?;
1494 Some(parent_entry.get_string("pageid")?.to_string())
1495 }
1496
1497 fn child_pages(&self, entry_id: &str) -> Rc<ChildPages> {
1502 if let Some(cached) = self.child_pages.borrow().get(entry_id) {
1503 return cached.clone();
1504 }
1505 let ids = self.compute_child_page_ids(entry_id);
1506 let mut index_of = HashMap::default();
1507 for (i, id) in ids.iter().enumerate() {
1509 index_of.insert(id.clone(), i);
1510 }
1511 let rc = Rc::new(ChildPages {
1512 ids,
1513 index_of,
1514 related: OnceCell::new(),
1515 });
1516 self
1517 .child_pages
1518 .borrow_mut()
1519 .insert(entry_id.to_string(), rc.clone());
1520 rc
1521 }
1522
1523 fn compute_child_page_ids(&self, entry_id: &str) -> Vec<String> {
1527 let entry = match self.db.lookup(&format!("ID:{}", entry_id)) {
1528 Some(e) => e,
1529 None => return Vec::new(),
1530 };
1531 let here_pageid = entry.get_string("pageid").map(String::from);
1532 let children = entry.get_children();
1533 let mut out = Vec::new();
1534 for ch in children {
1535 let ch_entry = match self.db.lookup(&format!("ID:{}", ch)) {
1536 Some(e) => e,
1537 None => continue,
1538 };
1539 let ch_pageid = match ch_entry.get_string("pageid") {
1540 Some(p) => p.to_string(),
1541 None => continue,
1542 };
1543 if here_pageid.as_deref() != Some(&ch_pageid) {
1544 out.push(ch_pageid);
1545 } else {
1546 out.extend(self.child_pages(&ch).ids.iter().cloned());
1547 }
1548 }
1549 out
1550 }
1551
1552 fn find_previous_page_id(&self, page_id: &str) -> Option<String> {
1556 let parent_id = self.get_parent_page_id(page_id)?;
1557 let siblings = self.child_pages(&parent_id);
1558 let pos = *siblings.index_of.get(page_id)?;
1560 let mut current = match siblings.ids[..pos]
1566 .iter()
1567 .rev()
1568 .find(|s| self.is_primary_page(s))
1569 {
1570 Some(sib) => sib.clone(),
1571 None => return Some(parent_id),
1572 };
1573 loop {
1575 let kids = self.child_pages(¤t);
1576 match kids.ids.iter().rev().find(|s| self.is_primary_page(s)) {
1577 Some(deepest) => current = deepest.clone(),
1578 None => break,
1579 }
1580 }
1581 Some(current)
1582 }
1583
1584 fn find_next_page_id(&self, page_id: &str) -> Option<String> {
1588 if let Some(first) = self
1590 .child_pages(page_id)
1591 .ids
1592 .iter()
1593 .find(|s| self.is_primary_page(s))
1594 {
1595 return Some(first.clone());
1596 }
1597 let mut current = page_id.to_string();
1598 loop {
1599 let parent = self.get_parent_page_id(¤t)?;
1600 let siblings = self.child_pages(&parent);
1601 let pos = *siblings.index_of.get(¤t)?;
1603 if let Some(first) = siblings.ids[pos + 1..]
1605 .iter()
1606 .find(|s| self.is_primary_page(s))
1607 {
1608 return Some(first.clone());
1609 }
1610 current = parent;
1611 }
1612 }
1613
1614 fn fill_in_tocs(&mut self, doc: &mut PostDocument) {
1615 let tocs = match doc.get_document_element() {
1622 Some(root) => doc.findnodes_at("descendant::ltx:TOC[not(ltx:toclist)]", Some(&root)),
1623 None => Vec::new(),
1624 };
1625 for toc in &tocs {
1626 let mut id = doc
1631 .get_document_element()
1632 .as_ref()
1633 .and_then(get_xml_id)
1634 .unwrap_or_default();
1635 let scope = toc.get_attribute("scope").unwrap_or_default();
1643 let unit = match scope.as_str() {
1644 "global" => {
1645 id = self.get_root_page_id(&id);
1646 None
1647 },
1648 "" | "current" => None,
1649 unit => Some(unit),
1650 };
1651 let show = toc
1652 .get_attribute("show")
1653 .unwrap_or_else(|| self.toc_show.clone());
1654
1655 let select_attr = toc.get_attribute("select");
1661 let types: Option<HashSet<&str>> = select_attr.as_deref().map(|s| {
1662 s.split('|')
1663 .map(str::trim)
1664 .filter(|t| !t.is_empty())
1665 .collect()
1666 });
1667 let lists_attr = toc.get_attribute("lists");
1668 let lists: HashSet<&str> = match lists_attr.as_deref() {
1669 Some(l) => l.split_whitespace().collect(),
1670 None => HashSet::from_iter(["toc"]),
1671 };
1672
1673 let format = toc.get_attribute("format").unwrap_or_default();
1678 let list = if let Some(unit) = unit {
1679 let children = self
1680 .db
1681 .lookup(&format!("ID:{unit}"))
1682 .map(|e| e.get_children().to_vec());
1683 children
1684 .unwrap_or_default()
1685 .iter()
1686 .flat_map(|child| self.gen_toc(child, &show, types.as_ref(), &lists, None, None))
1687 .collect()
1688 } else if format.is_empty() || format.starts_with("normal") {
1689 self.gen_toc(&id, &show, types.as_ref(), &lists, None, None)
1690 } else if format == "context" {
1691 let toc_lists: HashSet<&str> = HashSet::from_iter(["toc"]);
1692 self.gen_toc_context(&id, &show, types.as_ref(), &toc_lists)
1693 } else {
1694 Vec::new()
1695 };
1696 if !list.is_empty() {
1697 let toclist = NodeData::Element {
1698 tag: "ltx:toclist".to_string(),
1699 attributes: None,
1700 children: list,
1701 };
1702 let mut toc_mut = toc.clone();
1703 doc.add_nodes(&mut toc_mut, &[toclist]);
1704 }
1705 }
1706 }
1707
1708 fn get_root_page_id(&self, start_id: &str) -> String {
1713 let mut root_id = start_id.to_string();
1714 let mut cursor = start_id.to_string();
1715 while let Some(page_id) = self.parent_page_of(&cursor) {
1716 root_id = page_id.clone();
1717 cursor = page_id;
1718 }
1719 self
1721 .db
1722 .lookup(&format!("ID:{}", root_id))
1723 .and_then(|e| e.get_string("pageid"))
1724 .map(String::from)
1725 .unwrap_or(root_id)
1726 }
1727
1728 fn parent_page_of(&self, id: &str) -> Option<String> {
1731 let parent_id = self
1733 .db
1734 .lookup(&format!("ID:{}", id))
1735 .and_then(|e| e.get_string("parent"))
1736 .filter(|s| !s.is_empty())?;
1737 let page_id = self
1739 .db
1740 .lookup(&format!("ID:{}", parent_id))
1741 .and_then(|e| e.get_string("pageid"))
1742 .filter(|s| !s.is_empty())?
1743 .to_string();
1744 self.db.lookup(&format!("ID:{}", page_id)).map(|_| page_id)
1746 }
1747
1748 fn gen_toc(
1754 &self,
1755 id: &str,
1756 show: &str,
1757 types: Option<&HashSet<&str>>,
1758 lists: &HashSet<&str>,
1759 localto: Option<&str>,
1760 selfid: Option<&str>,
1761 ) -> Vec<NodeData> {
1762 let entry = match self.db.lookup(&format!("ID:{}", id)) {
1763 Some(e) => e,
1764 None => return vec![],
1765 };
1766
1767 let recurse = match localto {
1770 None => true,
1771 Some(target) => entry.get_string("location").unwrap_or("") == target,
1772 };
1773 let kids: Vec<NodeData> = if recurse {
1774 entry
1775 .get_children()
1776 .iter()
1777 .flat_map(|child_id| self.gen_toc(child_id, show, types, lists, localto, selfid))
1778 .collect()
1779 } else {
1780 Vec::new()
1781 };
1782
1783 let entry_type = entry.get_string("type").unwrap_or("");
1784 let type_ok = types.map(|t| t.contains(entry_type)).unwrap_or(true);
1789 let in_toc = entry
1790 .get_value("inlist")
1791 .map(|v| match v {
1792 Value::Hash(h) => lists.iter().any(|l| h.contains_key(*l)),
1793 _ => false,
1794 })
1795 .unwrap_or(false);
1796
1797 if type_ok && in_toc {
1798 vec![self.gen_tocentry(entry, selfid, show, kids)]
1799 } else {
1800 kids
1801 }
1802 }
1803
1804 fn gen_tocentry(
1809 &self,
1810 entry: &Entry,
1811 selfid: Option<&str>,
1812 show: &str,
1813 children: Vec<NodeData>,
1814 ) -> NodeData {
1815 let id = entry
1816 .get_string("id")
1817 .or_else(|| entry.get_key().strip_prefix("ID:"))
1818 .unwrap_or("")
1819 .to_string();
1820 let entry_type = entry.get_string("type").unwrap_or("");
1821 let type_name = entry_type.strip_prefix("ltx:").unwrap_or(entry_type);
1822
1823 let (mut before, mut after): (Option<&str>, Option<&str>) = (None, None);
1825 let mut show_mid = show;
1826 if let Some((b, rest)) = show_mid.split_once('<') {
1827 before = Some(b);
1828 show_mid = rest;
1829 }
1830 if let Some((mid, a)) = show_mid.split_once('>') {
1831 show_mid = mid;
1832 after = Some(a);
1833 }
1834
1835 let self_class = if selfid == Some(id.as_str()) {
1836 " ltx_ref_self"
1837 } else {
1838 ""
1839 };
1840
1841 let mut kids: Vec<NodeData> = Vec::new();
1842 if let Some(b) = before.filter(|b| !b.is_empty()) {
1843 kids.extend(self.generate_ref_simple(&id, b));
1844 }
1845 kids.push(NodeData::Element {
1846 tag: "ltx:ref".to_string(),
1847 attributes: Some(HashMap::from_iter([
1848 ("show".to_string(), show_mid.to_string()),
1849 ("idref".to_string(), id.clone()),
1850 ])),
1851 children: vec![],
1852 });
1853 if let Some(a) = after.filter(|a| !a.is_empty()) {
1854 kids.extend(self.generate_ref_simple(&id, a));
1855 }
1856 if !children.is_empty() {
1857 kids.push(NodeData::Element {
1858 tag: "ltx:toclist".to_string(),
1859 attributes: Some(HashMap::from_iter([(
1860 "class".to_string(),
1861 format!("ltx_toclist_{}", type_name),
1862 )])),
1863 children,
1864 });
1865 }
1866
1867 NodeData::Element {
1868 tag: "ltx:tocentry".to_string(),
1869 attributes: Some(HashMap::from_iter([(
1870 "class".to_string(),
1871 format!("ltx_tocentry_{}{}", type_name, self_class),
1872 )])),
1873 children: kids,
1874 }
1875 }
1876
1877 fn generate_ref_simple(&self, req_id: &str, req_show: &str) -> Vec<NodeData> {
1880 if !req_show.is_empty()
1881 && !req_id.is_empty()
1882 && self.db.lookup(&format!("ID:{}", req_id)).is_some()
1883 {
1884 self.generate_ref_aux(req_id, req_show, false)
1885 } else {
1886 Vec::new()
1887 }
1888 }
1889
1890 fn gen_toc_context(
1894 &self,
1895 id: &str,
1896 show: &str,
1897 types: Option<&HashSet<&str>>,
1898 lists: &HashSet<&str>,
1899 ) -> Vec<NodeData> {
1900 let start = match self.db.lookup(&format!("ID:{}", id)) {
1901 Some(e) => e,
1902 None => return vec![],
1903 };
1904
1905 let location = start.get_string("location").unwrap_or("").to_string();
1908 let mut navtoc = self.gen_toc(id, show, types, lists, Some(&location), Some(id));
1909
1910 let mut came_from = id.to_string();
1914 let mut parent_id = start.get_string("parent").map(String::from);
1915
1916 while let Some(pid) = parent_id {
1917 let parent = match self.db.lookup(&format!("ID:{}", pid)) {
1918 Some(e) => e,
1919 None => break,
1920 };
1921
1922 let mut row: Vec<NodeData> = Vec::new();
1925 for child_id in parent.get_children() {
1926 let child = match self.db.lookup(&format!("ID:{}", child_id)) {
1927 Some(e) => e,
1928 None => continue,
1929 };
1930 if !NORMAL_TOC_TYPES.contains(&child.get_string("type").unwrap_or("")) {
1931 continue;
1932 }
1933 let child_id_val = child.get_string("id").unwrap_or(&child_id);
1934 if child_id_val == came_from {
1935 row.append(&mut navtoc);
1936 } else {
1937 row.push(self.gen_tocentry(child, None, show, Vec::new()));
1938 }
1939 }
1940 navtoc = row;
1941
1942 let parent_type = parent.get_string("type").unwrap_or("");
1946 let parent_ok = types.map(|t| t.contains(parent_type)).unwrap_or(true);
1947 let parent_has_parent = parent
1948 .get_string("parent")
1949 .map(|s| !s.is_empty())
1950 .unwrap_or(false);
1951 if parent_ok && parent_has_parent {
1952 navtoc = vec![self.gen_tocentry(parent, None, show, navtoc)];
1953 }
1954
1955 came_from = pid;
1956 parent_id = parent.get_string("parent").map(String::from);
1957 }
1958
1959 navtoc
1960 }
1961
1962 fn fill_in_frags(&self, doc: &PostDocument) {
1963 if doc.idcache_len() <= self.db.len() {
1973 for (id, node) in doc.idcache_iter() {
1975 if let Some(entry) = self.db.lookup(&format!("ID:{}", id)) {
1976 if let Some(fragid) = entry.get_string("fragid") {
1977 let mut n = node.clone();
1978 n.set_attribute("fragid", fragid).ok();
1979 }
1980 }
1981 }
1982 } else {
1983 for key in self.db.keys_iter() {
1986 let id = match key.strip_prefix("ID:") {
1987 Some(rest) => rest,
1988 None => continue,
1989 };
1990 let entry = match self.db.lookup(key) {
1991 Some(e) => e,
1992 None => continue,
1993 };
1994 let fragid = match entry.get_string("fragid") {
1995 Some(f) => f,
1996 None => continue,
1997 };
1998 if let Some(node) = doc.find_node_by_id(id) {
1999 let mut n = node.clone();
2000 n.set_attribute("fragid", fragid).ok();
2001 }
2002 }
2003 }
2004 }
2005
2006 fn fill_in_refs(&mut self, doc: &mut PostDocument) {
2007 let mut refs = doc.findnodes("//*[@idref]");
2008 refs.extend(doc.findnodes("//*[@labelref]"));
2009 for ref_node in &refs {
2010 let tag = doc.get_qname(ref_node).unwrap_or_default();
2011 if tag == "ltx:XMRef" || tag == "ltx:note" {
2014 continue;
2015 }
2016
2017 let mut ref_mut = ref_node.clone();
2018 let mut id = ref_node.get_attribute("idref");
2019 let show = ref_node
2020 .get_attribute("show")
2021 .unwrap_or_else(|| self.ref_show.clone());
2022
2023 if id.is_none() {
2024 if let Some(label) = ref_node.get_attribute("labelref") {
2025 if let Some(entry) = self.db.lookup(&label) {
2026 if let Some(resolved_id) = entry.get_string("id") {
2027 ref_mut.set_attribute("idref", resolved_id).ok();
2028 id = Some(resolved_id.to_string());
2029 }
2030 }
2031 let classes = ref_node.get_attribute("class").unwrap_or_default();
2036 let external = classes
2037 .split_whitespace()
2038 .any(|class| class == "ltx_ref_external");
2039 if id.is_none() && !external {
2040 self.note_missing("warn", "Target for Label", &label);
2041 PostDocument::add_class(&mut ref_mut, "ltx_missing_label");
2042 if ref_mut.get_content().is_empty() {
2045 doc.add_nodes(&mut ref_mut, &[NodeData::Text(label.clone())]);
2046 ref_mut.set_attribute("broken", "1").ok();
2047 }
2048 } else if id.is_some() && external {
2049 let kept: Vec<&str> = classes
2050 .split_whitespace()
2051 .filter(|class| *class != "ltx_ref_external")
2052 .collect();
2053 if kept.is_empty() {
2054 ref_mut.remove_attribute("class").ok();
2055 } else {
2056 ref_mut.set_attribute("class", &kept.join(" ")).ok();
2057 }
2058 ref_mut.remove_attribute("href").ok();
2059 let children: Vec<Node> = ref_mut.get_child_nodes();
2060 doc.remove_nodes(&children);
2061 }
2062 }
2063 }
2064
2065 if let Some(ref id_str) = id {
2066 if !ref_mut.has_attribute("href") {
2067 if let Some(url) = self.generate_url(doc, id_str) {
2068 ref_mut.set_attribute("href", &url).ok();
2069 }
2070 }
2071 if !ref_mut.has_attribute("title") {
2072 if let Some(titlestring) = self.generate_title(doc, id_str, &show) {
2073 ref_mut.set_attribute("title", &titlestring).ok();
2074 }
2075 if let Some(rel) = ref_mut.get_attribute("rel") {
2083 if !rel.is_empty() {
2084 if let Some(fulltitle) = self.generate_title(doc, id_str, "") {
2085 ref_mut.set_attribute("fulltitle", &fulltitle).ok();
2086 }
2087 }
2088 }
2089 }
2090 if ref_mut.get_first_child().is_none() && tag != "ltx:graphics" && tag != "ltx:picture" {
2091 let is_nameref = ref_node
2093 .get_attribute("class")
2094 .is_some_and(|class| class.contains("ltx_refmacro_nameref"));
2095 let content = self.generate_ref(doc, id_str, &show, is_nameref);
2096 doc.add_nodes(&mut ref_mut, &content);
2097 }
2098 }
2099 }
2100 }
2101
2102 fn settle_cref_conjunctions(&mut self, doc: &mut PostDocument) {
2106 for conjunction in
2107 doc.findnodes("//ltx:text[contains(concat(' ', @class, ' '), ' ltx_cref_conjunction ')]")
2108 {
2109 let mut next = conjunction.get_next_sibling();
2110 while let Some(node) = next.as_ref().filter(|node| {
2111 node.get_type() == Some(NodeType::TextNode) && node.get_content().trim().is_empty()
2112 }) {
2113 next = node.get_next_sibling();
2114 }
2115 let formatted = next
2116 .filter(|node| name_is(node, "ref"))
2117 .and_then(|node| Some((node.get_attribute("idref")?, node.get_attribute("show")?)))
2118 .is_some_and(|(id, show)| {
2119 let alternatives = show_alternatives(&show);
2120 alternatives.len() > 1
2121 && !self
2122 .generate_ref_aux(&id, alternatives[0], false)
2123 .is_empty()
2124 });
2125 if formatted {
2126 doc.remove_nodes(&[conjunction]);
2127 } else {
2128 doc.unwrap_node(&conjunction);
2129 }
2130 }
2131 }
2132
2133 fn fill_in_glossaryrefs(&mut self, doc: &mut PostDocument) {
2134 for ref_node in &doc.findnodes("descendant::ltx:glossaryref") {
2141 let mut ref_mut = ref_node.clone();
2142 let key = ref_node.get_attribute("key").unwrap_or_default();
2143 let list = ref_node.get_attribute("inlist").unwrap_or_default();
2144 let show = ref_node
2145 .get_attribute("show")
2146 .filter(|s| !s.is_empty())
2147 .unwrap_or_else(|| "name".to_string());
2148 if show == "none" {
2152 continue;
2153 }
2154 let is_empty = |n: &Node| n.get_content().is_empty() && n.get_first_element_child().is_none();
2155
2156 let gkey = format!("GLOSSARY:{}:{}", list, key);
2157 let found = self.db.lookup(&gkey).map(|entry| {
2158 let title = entry
2164 .get_value("phrase:definition")
2165 .or_else(|| entry.get_value("phrase:description"))
2166 .map(|val| value_text(doc, val))
2167 .filter(|t| !t.is_empty());
2168 (title, entry.get_string("id").map(str::to_string))
2169 });
2170 if let Some((title, id)) = found {
2171 if !ref_mut.has_attribute("title")
2172 && let Some(title) = title
2173 {
2174 ref_mut.set_attribute("title", &title).ok();
2175 }
2176 if let Some(id) = id {
2177 ref_mut.set_attribute("idref", &id).ok();
2178 }
2179 if is_empty(&ref_mut) {
2180 let stuff = self.generate_glossary_ref_title(&gkey, &show);
2181 if stuff.is_empty() {
2182 self.note_missing("warn", &format!("Glossary contents ({show}) for key"), &key);
2183 doc.add_nodes(&mut ref_mut, &[NodeData::Text(key.clone())]);
2184 PostDocument::add_class(&mut ref_mut, "ltx_missing");
2185 } else {
2186 doc.add_nodes(&mut ref_mut, &stuff);
2187 }
2188 }
2189 } else {
2190 self.note_missing("warn", "Glossary Entry for key", &key);
2191 }
2192
2193 if is_empty(&ref_mut) {
2194 doc.add_nodes(&mut ref_mut, &[NodeData::Text(key.clone())]);
2195 PostDocument::add_class(&mut ref_mut, "ltx_missing");
2196 }
2197 }
2198 }
2199
2200 fn fill_in_rdfa_refs(&mut self, doc: &mut PostDocument) {
2228 for key in ["about", "resource"] {
2229 let refs = doc.findnodes(&format!("//*[@{key}idref or @{key}labelref]"));
2232 for ref_node in &refs {
2233 let mut ref_mut = ref_node.clone();
2234 let idref_attr = format!("{key}idref");
2235 let mut id = ref_node
2238 .get_attribute(&idref_attr)
2239 .filter(|v| !v.is_empty());
2240
2241 if id.is_none()
2245 && let Some(label) = ref_node.get_attribute(&format!("{key}labelref"))
2246 {
2247 if let Some(entry) = self.db.lookup(&label)
2248 && let Some(resolved) = entry.get_string("id")
2249 {
2250 ref_mut.set_attribute(&idref_attr, resolved).ok();
2251 id = Some(resolved.to_string());
2252 }
2253 if id.is_none() {
2254 self.note_missing("warn", &format!("Target for {key} Label"), &label);
2255 }
2256 }
2257
2258 if let Some(ref id_str) = id
2260 && ref_mut.get_attribute(key).is_none()
2261 {
2262 let value = if self.db.lookup(&format!("ID:{id_str}")).is_some() {
2263 self.generate_url(doc, id_str)
2264 } else {
2265 Some(format!("#{id_str}"))
2266 };
2267 if let Some(value) = value {
2268 ref_mut.set_attribute(key, &value).ok();
2269 }
2270 }
2271 }
2272 }
2273 }
2274
2275 fn fill_in_bibrefs(&mut self, doc: &mut PostDocument) {
2282 for _ in 0..3 {
2285 let bibrefs = doc.findnodes("//ltx:bibref");
2286 if bibrefs.is_empty() {
2287 return;
2288 }
2289 let mut cites: HashMap<usize, (Node, bool)> = HashMap::default();
2290 let mut keyless_cites: Vec<(Node, [String; 2])> = Vec::new();
2291 for bibref in &bibrefs {
2292 let keyless = bibref
2293 .get_attribute("bibrefs")
2294 .unwrap_or_default()
2295 .split(',')
2296 .all(str::is_empty);
2297 let separators = bibref_separators(bibref);
2298 let (cite, numeric) = self.make_bibcite(doc, bibref);
2299 let mut ancestor = bibref.get_parent();
2301 while let Some(node) = ancestor.as_ref()
2302 && doc.get_qname(node).as_deref() != Some("ltx:cite")
2303 {
2304 ancestor = node.get_parent();
2305 }
2306 if let Some(parent) = ancestor {
2307 if keyless {
2308 keyless_cites.push((parent.clone(), separators));
2309 }
2310 cites
2311 .entry(parent.to_hashable())
2312 .or_insert((parent, true))
2313 .1 &= numeric;
2314 }
2315 doc.replace_node(bibref, &cite);
2316 }
2317 for (mut parent, _) in cites.into_values().filter(|(_, numeric)| *numeric) {
2318 PostDocument::add_class(&mut parent, "ltx_cite_numeric");
2319 }
2320 for (cite, separators) in keyless_cites {
2322 if !carries_a_note(&child_nodes_data(&cite), &separators) {
2323 for mut text in cite.get_child_nodes() {
2324 text.unlink_node();
2325 }
2326 }
2327 }
2328 }
2329 let left = doc.findnodes("//ltx:bibref").len();
2330 if left > 0 {
2331 Warn!(
2332 "unexpected",
2333 "bibref",
2334 "{left} citation(s) inside copied bibliography entries left unfilled (entries that print each other whole)"
2335 );
2336 }
2337 }
2338
2339 fn make_bibcite(&mut self, doc: &PostDocument, bibref: &Node) -> (Vec<NodeData>, bool) {
2346 let keys_str = bibref.get_attribute("bibrefs").unwrap_or_default();
2347 let keys: Vec<&str> = keys_str.split(',').filter(|k| !k.is_empty()).collect();
2348 let preformatted = child_nodes_data(bibref);
2349 let mut show = bibref
2350 .get_attribute("show")
2351 .filter(|s| !s.is_empty())
2352 .unwrap_or_else(|| "refnum".to_string());
2353 if show == "none" && preformatted.is_empty() {
2354 show = "refnum".to_string();
2355 }
2356 if show == "nothing" {
2362 return (Vec::new(), false);
2363 }
2364 let [sep, yysep] = bibref_separators(bibref);
2365 let phrases = crate::document::element_children(bibref);
2367 if keys.is_empty() {
2370 return (keyless_phrases(&show, &phrases, &[sep, yysep]), false);
2371 }
2372 let inlist = bibref.get_attribute("inlist").unwrap_or_default();
2389 let mut lists: Vec<&str> = inlist.split_whitespace().collect();
2390 if !lists.contains(&"bibliography") {
2391 lists.push("bibliography");
2392 }
2393 let ids: Vec<Option<String>> = keys
2395 .iter()
2396 .map(|key| {
2397 lists.iter().find_map(|list| {
2398 self
2399 .db
2400 .lookup(&format!("BIBLABEL:{}:{}", list, key))
2401 .and_then(|be| be.get_string("id"))
2402 .map(String::from)
2403 })
2404 })
2405 .collect();
2406 let show_wants_ay = show.contains("Author") || show.contains("Year");
2418 let force_numeric = show_wants_ay
2419 && !ids.is_empty()
2420 && ids.iter().all(|id| {
2421 let Some(id) = id else {
2422 return false;
2423 };
2424 match self.db.lookup(&format!("ID:{}", id)) {
2425 Some(e) => {
2426 let nonempty = |k: &str| {
2427 e.get_value(k)
2428 .is_some_and(|v| !v.to_string().trim().is_empty())
2429 };
2430 !nonempty("authors")
2431 && !nonempty("fullauthors")
2432 && !nonempty("year")
2433 && (nonempty("number") || nonempty("refnum"))
2434 },
2435 None => false,
2436 }
2437 });
2438 let internal_delims = show
2443 .find("Year")
2444 .is_some_and(|yp| show[yp + "Year".len()..].contains("Phrase"));
2445
2446 let wants_fullentry = show.to_ascii_lowercase().contains("fullentry");
2447 static SUFFIXED_YEAR: LazyLock<Regex> =
2449 LazyLock::new(|| Regex::new(r"^(\d\d\d\d)(\w)$").unwrap());
2450 let mut data: Vec<BibciteDatum> = Vec::new();
2451 for (key, id) in keys.iter().zip(ids) {
2452 let found = id.and_then(|id| {
2453 let entry = self.db.lookup(&format!("ID:{}", id))?;
2454 let val = |k: &str| entry.get_value(k).filter(|v| !matches!(v, Value::Null));
2455 let (authors, fauthors, keytag) = (val("authors"), val("fullauthors"), val("keytag"));
2456 let (year, typetag, title) = (val("year"), val("typetag"), val("title"));
2457 let titlestring = title
2458 .map(|t| {
2459 t.to_string()
2460 .split_whitespace()
2461 .collect::<Vec<_>>()
2462 .join(" ")
2463 })
2464 .filter(|s| !s.is_empty());
2465 let (rawyear, suffix) = year
2466 .and_then(|y| {
2467 let text = y.to_string();
2468 SUFFIXED_YEAR
2469 .captures(&text)
2470 .map(|c| (Some(c[1].to_string()), Some(c[2].to_string())))
2471 })
2472 .unwrap_or_default();
2473 let nameless = !(show == "none"
2485 || show.eq_ignore_ascii_case("fullentry")
2486 || authors.is_some()
2487 || fauthors.is_some()
2488 || keytag.is_some());
2489 if nameless && nameless_numeric_show(&show).is_none() {
2490 show = "refnum".to_string();
2491 }
2492 let mut attr = HashMap::default();
2493 attr.insert("idref".to_string(), id.clone());
2494 if let Some(title) = titlestring {
2495 attr.insert("title".to_string(), title);
2496 }
2497 let fullentry = if wants_fullentry {
2499 let dropped_year = val("droppedyear").map(Value::to_string);
2500 match val("fullentry") {
2501 Some(Value::Xml(bibitem)) => full_entry(bibitem, dropped_year.as_deref()),
2502 _ => doc
2503 .find_node_by_id(&id)
2504 .map(|bibitem| full_entry(bibitem, dropped_year.as_deref()))
2505 .unwrap_or_default(),
2506 }
2507 } else {
2508 Vec::new()
2509 };
2510 Some((id, BibciteDatum {
2511 key: key.to_string(),
2512 authors: trim_child_nodes(authors.or(fauthors).or(keytag)),
2513 fullauthors: trim_child_nodes(fauthors.or(authors).or(keytag)),
2514 authortext: authors
2515 .or(fauthors)
2516 .map(Value::to_string)
2517 .unwrap_or_default(),
2518 year: trim_child_nodes(year.or(typetag)),
2519 rawyear,
2520 suffix,
2521 number: trim_child_nodes(val("number")),
2522 refnum: trim_child_nodes(val("refnum")),
2523 title: trim_child_nodes(title.or(keytag)),
2524 fullentry,
2525 attr,
2526 missing: false,
2527 nameless,
2528 }))
2529 });
2530 match found {
2531 Some((id, mut datum)) => {
2532 if let Some(url) = self.generate_url(doc, &id) {
2533 datum.attr.insert("href".to_string(), url);
2534 }
2535 data.push(datum);
2536 },
2537 None => {
2538 self.note_missing("warn", "Entry for citation", key);
2539 data.push(BibciteDatum {
2540 key: key.to_string(),
2541 authors: Vec::new(),
2542 fullauthors: Vec::new(),
2543 authortext: String::new(),
2544 year: Vec::new(),
2545 rawyear: None,
2546 suffix: None,
2547 number: Vec::new(),
2548 refnum: vec![NodeData::Text(key.to_string())],
2549 title: vec![NodeData::Text(key.to_string())],
2550 fullentry: vec![NodeData::Text(key.to_string())],
2551 attr: HashMap::from_iter([
2552 ("idref".to_string(), key.to_string()),
2553 ("title".to_string(), key.to_string()),
2554 ("class".to_string(), "ltx_missing_citation".to_string()),
2555 ]),
2556 missing: true,
2557 nameless: false,
2558 });
2559 },
2560 }
2561 }
2562
2563 let order_classes = bibref.get_attribute("class").unwrap_or_default();
2569 let has_class = |name: &str| order_classes.split_whitespace().any(|c| c == name);
2570 let cite_sty = has_class("ltx_cite_unsorted_first");
2575 let sort_key = |datum: &BibciteDatum| {
2576 if cite_sty {
2577 datum.cite_sty_key()
2578 } else {
2579 datum.entry_number()
2580 }
2581 };
2582 let steps: &[u64] = if cite_sty { &[256, 1] } else { &[1] };
2583 if has_class("ltx_cite_sort") {
2584 let unsorted = if has_class("ltx_cite_unsorted_first") {
2585 0
2586 } else {
2587 2
2588 };
2589 data.sort_by_key(|datum| sort_key(datum).map_or((unsorted, 0), |n| (1, n)));
2590 }
2591 let bare_number = matches!(
2592 show.to_ascii_lowercase().as_str(),
2593 "number" | "refnum" | "super"
2594 );
2595 let joints = if has_class("ltx_cite_compress") && (force_numeric || bare_number) {
2596 compressed_joints(&data.iter().map(sort_key).collect::<Vec<_>>(), steps)
2597 } else {
2598 vec![CiteJoint::Separator; data.len()]
2599 };
2600 let mut refs: Vec<NodeData> = Vec::new();
2601 if force_numeric {
2602 for (datum, joint) in data.iter().zip(&joints) {
2606 let label = [&datum.number, &datum.refnum]
2607 .into_iter()
2608 .find(|l| !l.is_empty())
2609 .cloned()
2610 .unwrap_or_else(|| vec![NodeData::Text(datum.key.clone())]);
2611 let item = vec![bib_ref(&datum.attr, label)];
2612 match joint {
2613 CiteJoint::Covered => {},
2614 CiteJoint::RangeEnd => append_range_end(&mut refs, item),
2615 CiteJoint::Separator => {
2616 if !refs.is_empty() {
2617 refs.push(NodeData::Text(", ".to_string()));
2618 }
2619 refs.extend(item);
2620 },
2621 }
2622 }
2623 if internal_delims && !refs.is_empty() {
2624 refs.insert(0, NodeData::Text("[".to_string()));
2625 refs.push(NodeData::Text("]".to_string()));
2626 }
2627 return (refs, true);
2628 }
2629 let lower = show.to_lowercase();
2630 let checkdups =
2631 lower.contains("author") && (lower.contains("year") || lower.contains("number"));
2632 let mut data: VecDeque<BibciteDatum> = data.into();
2633 let mut joints = joints.into_iter();
2635 let mut forms: Vec<Option<bool>> = Vec::new();
2636 while let Some(datum) = data.pop_front() {
2637 let joint = joints.next().unwrap_or(CiteJoint::Separator);
2638 if joint == CiteJoint::Covered {
2639 continue;
2640 }
2641 let nameless_show = datum
2642 .nameless
2643 .then(|| nameless_numeric_show(&show))
2644 .flatten();
2645 let (stuff, didref, numeric) = bibcite_show_walk(
2646 nameless_show.as_deref().unwrap_or(&show),
2647 &datum,
2648 &mut data,
2649 &preformatted,
2650 &phrases,
2651 &yysep,
2652 checkdups && !datum.nameless,
2654 );
2655 forms.push(numeric);
2656 let item = if didref {
2657 stuff
2658 } else {
2659 vec![bib_ref(&datum.attr, stuff)]
2660 };
2661 if joint == CiteJoint::RangeEnd {
2662 append_range_end(&mut refs, item);
2663 continue;
2664 }
2665 if !refs.is_empty() {
2666 refs.push(NodeData::Text(sep.clone()));
2667 refs.push(NodeData::Text(" ".to_string()));
2668 }
2669 refs.extend(item);
2670 }
2671 let numeric = forms.contains(&Some(true)) && !forms.contains(&Some(false));
2672 (refs, numeric)
2673 }
2674
2675 fn fill_in_mathlinks(&mut self, doc: &PostDocument) {
2676 for sym in &doc.findnodes("descendant::*[@decl_id or @meaning]") {
2677 let tag = doc.get_qname(sym).unwrap_or_default();
2678 if tag == "ltx:XMRef" || sym.has_attribute("href") {
2679 continue;
2680 }
2681 let entry_key = sym
2682 .get_attribute("decl_id")
2683 .map(|did| format!("DECLARATION:local:{}", did))
2684 .or_else(|| {
2685 sym
2686 .get_attribute("meaning")
2687 .map(|m| format!("DECLARATION:global:{}", m))
2688 });
2689 let parent_id = entry_key
2690 .as_ref()
2691 .and_then(|ek| self.db.lookup(ek))
2692 .and_then(|entry| entry.get_string("parent").map(String::from));
2693 if let Some(pid) = parent_id {
2694 if let Some(url) = self.generate_url(doc, &pid) {
2695 let mut sym_mut = sym.clone();
2696 sym_mut.set_attribute("href", &url).ok();
2697 }
2698 }
2699 }
2700 }
2701
2702 fn report_missing(&self) {
2706 for severity in ["error", "warn", "info"] {
2707 let Some(types) = self.missing.get(severity) else {
2708 continue;
2709 };
2710 let mut type_names: Vec<&String> = types.keys().collect();
2711 type_names.sort_unstable();
2712 for ref_type in type_names {
2713 let mut keys: Vec<&str> = types[ref_type].keys().map(String::as_str).collect();
2714 keys.sort_unstable();
2715 let msg = format!("Missing {}: {}", ref_type, keys.join(","));
2716 match severity {
2719 "error" => Error!("expected", "ids", "{}", msg),
2720 "warn" => Warn!("expected", "ids", "{}", msg),
2721 _ => Info!("expected", "ids", "{}", msg),
2722 }
2723 }
2724 }
2725 }
2726}
2727
2728impl Processor for CrossRef {
2729 fn get_name(&self) -> &str { &self.name }
2730
2731 fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
2732 match doc.get_document_element() {
2733 Some(el) => vec![el],
2734 None => vec![],
2735 }
2736 }
2737
2738 fn process(&mut self, mut doc: PostDocument, _nodes: Vec<Node>) -> ProcessResult {
2739 self.missing.clear();
2740
2741 let doc_title = self.generate_document_title(&doc);
2743 let navtoc = self.navigation_toc.clone();
2744
2745 let mut nav = if navtoc.is_some() || doc_title.is_some() {
2746 match doc.findnode("//ltx:navigation") {
2747 Some(existing) => Some(existing),
2748 None => {
2749 if let Some(mut root) = doc.get_document_element() {
2750 doc.add_nodes(&mut root, &[NodeData::Element {
2751 tag: "ltx:navigation".to_string(),
2752 attributes: None,
2753 children: vec![],
2754 }]);
2755 }
2756 doc.findnode("//ltx:navigation")
2757 },
2758 }
2759 } else {
2760 None
2761 };
2762 if let Some(ref format) = navtoc
2763 && let Some(ref mut nav_node) = nav
2764 {
2765 doc.add_nodes(nav_node, &[NodeData::Element {
2772 tag: "ltx:TOC".to_string(),
2773 attributes: Some(HashMap::from_iter([("format".to_string(), format.clone())])),
2774 children: vec![],
2775 }]);
2776 }
2777 if let Some(ref title) = doc_title
2778 && let Some(ref mut nav_node) = nav
2779 {
2780 doc.add_nodes(nav_node, &[NodeData::Element {
2781 tag: "ltx:title".to_string(),
2782 attributes: None,
2783 children: vec![NodeData::Text(title.clone())],
2784 }]);
2785 }
2786
2787 self.fill_in_relations(&mut doc);
2788 self.fill_in_tocs(&mut doc);
2789 self.fill_in_frags(&doc);
2790 self.fill_in_glossaryrefs(&mut doc);
2791 self.fill_in_refs(&mut doc);
2792 self.settle_cref_conjunctions(&mut doc);
2793 self.fill_in_rdfa_refs(&mut doc);
2794 self.fill_in_bibrefs(&mut doc);
2795 self.fill_in_mathlinks(&doc);
2796 self.copy_resources(&doc);
2797 strip_ref_display_fragids(&doc);
2798 self.report_missing();
2799 Ok(vec![doc])
2800 }
2801}
2802
2803fn relative_url(target: &str, base: &str) -> String {
2807 if target == base {
2808 return ".".to_string();
2809 }
2810 let target_parts: Vec<&str> = target.split('/').collect();
2811 let base_parts: Vec<&str> = base.split('/').collect();
2812 let common = target_parts
2813 .iter()
2814 .zip(base_parts.iter())
2815 .take_while(|(a, b)| a == b)
2816 .count();
2817 let mut result = String::new();
2818 for _ in common..base_parts.len().saturating_sub(1) {
2819 result.push_str("../");
2820 }
2821 result.push_str(&target_parts[common..].join("/"));
2822 if result.is_empty() {
2823 ".".to_string()
2824 } else {
2825 result
2826 }
2827}
2828
2829fn get_text_content_node(node: &Node) -> String {
2833 let text = node.get_content();
2834 let trimmed = text.trim();
2835 trimmed.split_whitespace().collect::<Vec<_>>().join(" ")
2837}
2838
2839fn keyless_phrases(show: &str, phrases: &[Node], separators: &[String]) -> Vec<NodeData> {
2842 static PHRASE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)phrase(\d)").unwrap());
2843 let stuff: Vec<NodeData> = PHRASE
2844 .captures_iter(show)
2845 .filter_map(|c| match c[1].parse::<usize>() {
2846 Ok(0) => phrases.last(),
2847 Ok(n) => phrases.get(n - 1),
2848 Err(_) => None,
2849 })
2850 .flat_map(child_nodes_data)
2851 .collect();
2852 if carries_a_note(&stuff, separators) {
2853 stuff
2854 } else {
2855 Vec::new()
2856 }
2857}
2858
2859fn bibref_separators(bibref: &Node) -> [String; 2] {
2861 ["separator", "yyseparator"].map(|name| {
2862 bibref
2863 .get_attribute(name)
2864 .filter(|s| !s.is_empty())
2865 .unwrap_or_else(|| ",".to_string())
2866 })
2867}
2868
2869fn carries_a_note(nodes: &[NodeData], separators: &[String]) -> bool {
2872 if nodes.iter().any(|n| !matches!(n, NodeData::Text(_))) {
2873 return true;
2874 }
2875 let text = separators
2876 .iter()
2877 .map(|sep| sep.trim())
2878 .filter(|sep| !sep.is_empty())
2879 .fold(text_content(nodes), |text, sep| text.replace(sep, " "));
2880 text
2881 .chars()
2882 .any(|c| !c.is_whitespace() && !"()[]{}<>,;".contains(c))
2883}
2884
2885fn text_content(nodes: &[NodeData]) -> String {
2886 nodes
2887 .iter()
2888 .map(|n| match n {
2889 NodeData::Text(s) => s.clone(),
2890 NodeData::Element { children, .. } => text_content(children),
2891 NodeData::XmlNode(n) => n.get_content(),
2892 })
2893 .collect::<Vec<_>>()
2894 .join("")
2895}
2896
2897fn show_alternatives(show: &str) -> Vec<&str> {
2899 let mut alternatives = Vec::new();
2900 let (mut depth, mut start) = (0usize, 0);
2901 for (at, c) in show.char_indices() {
2902 match c {
2903 '{' => depth += 1,
2904 '}' => depth = depth.saturating_sub(1),
2905 '|' if depth == 0 => {
2906 alternatives.push(&show[start..at]);
2907 start = at + 1;
2908 },
2909 _ => {},
2910 }
2911 }
2912 alternatives.push(&show[start..]);
2913 alternatives
2914}
2915
2916#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2918enum CiteJoint {
2919 Separator,
2921 Covered,
2923 RangeEnd,
2925}
2926
2927fn compressed_joints(numbers: &[Option<u64>], steps: &[u64]) -> Vec<CiteJoint> {
2931 let mut joints = vec![CiteJoint::Separator; numbers.len()];
2932 let follows = |at: usize, step: u64| matches!((numbers[at], numbers.get(at + 1).copied().flatten()), (Some(a), Some(b)) if b == a + step);
2933 let mut start = 0;
2934 while start < numbers.len() {
2935 let mut end = start;
2936 if let Some(&step) = steps.iter().find(|&&step| follows(start, step)) {
2938 while end + 1 < numbers.len() && follows(end, step) {
2939 end += 1;
2940 }
2941 }
2942 if end >= start + 2 {
2943 joints[start + 1..end].fill(CiteJoint::Covered);
2944 joints[end] = CiteJoint::RangeEnd;
2945 }
2946 start = end + 1;
2947 }
2948 joints
2949}
2950
2951fn append_range_end(refs: &mut Vec<NodeData>, mut item: Vec<NodeData>) {
2954 let is_sup = |node: &NodeData| matches!(node, NodeData::Element { tag, .. } if tag == "ltx:sup");
2955 if item.len() == 1
2956 && is_sup(&item[0])
2957 && let Some(NodeData::Element { children, .. }) = refs.last_mut().filter(|last| is_sup(last))
2958 {
2959 if let Some(NodeData::Element { children: inner, .. }) = item.pop() {
2960 children.push(NodeData::Text("\u{2013}".to_string()));
2961 children.extend(inner);
2962 }
2963 return;
2964 }
2965 refs.push(NodeData::Text("\u{2013}".to_string()));
2966 refs.extend(item);
2967}
2968
2969fn nameless_numeric_show(show: &str) -> Option<String> {
2973 let lower = show.to_ascii_lowercase();
2974 let after_full = lower.strip_prefix("full").unwrap_or(&lower);
2975 let rest = after_full
2976 .strip_prefix("authors")
2977 .or_else(|| after_full.strip_prefix("author"))
2978 .map(|rest| show[show.len() - rest.len()..].trim_start())?;
2979 let rest_lower = rest.to_ascii_lowercase();
2980 (rest_lower.contains("number") && rest_lower.contains("phrase") && !rest_lower.contains("author"))
2981 .then(|| rest.to_string())
2982}
2983
2984#[cfg(test)]
2985mod tests {
2986 use super::*;
2987
2988 #[test]
2989 fn relative_url_identical_paths_is_dot() {
2990 assert_eq!(relative_url("a/b.html", "a/b.html"), ".");
2991 }
2992
2993 #[test]
2994 fn relative_url_same_dir() {
2995 assert_eq!(relative_url("a/other.html", "a/index.html"), "other.html");
2997 }
2998
2999 #[test]
3000 fn relative_url_sibling_dir() {
3001 assert_eq!(relative_url("b/x.html", "a/index.html"), "../b/x.html");
3003 }
3004
3005 #[test]
3006 fn relative_url_deeply_nested_base() {
3007 assert_eq!(
3009 relative_url("top/sibling.html", "top/deep/nested/page.html"),
3010 "../../sibling.html"
3011 );
3012 }
3013
3014 #[test]
3015 fn relative_url_same_prefix_different_file() {
3016 assert_eq!(
3017 relative_url("a/b/c/target.html", "a/b/c/source.html"),
3018 "target.html"
3019 );
3020 }
3021
3022 #[test]
3023 fn ref_fallbacks_typerefnum_goes_to_refnum() {
3024 assert_eq!(ref_fallbacks("typerefnum"), &["refnum"]);
3025 assert_eq!(ref_fallbacks("creflabel"), &["refnum"]);
3026 }
3027
3028 #[test]
3029 fn compressed_joints_join_runs_of_three() {
3030 use CiteJoint::{Covered as C, RangeEnd as R, Separator as S};
3031 let joints = |numbers: &[Option<u64>]| compressed_joints(numbers, &[1]);
3032 assert_eq!(joints(&[Some(1), Some(2), Some(3)]), [S, C, R]);
3033 assert_eq!(joints(&[Some(1), Some(2)]), [S, S]);
3034 assert_eq!(
3035 joints(&[
3036 Some(1),
3037 Some(2),
3038 Some(3),
3039 Some(5),
3040 Some(6),
3041 Some(7),
3042 Some(8)
3043 ]),
3044 [S, C, R, S, C, C, R]
3045 );
3046 assert_eq!(joints(&[Some(1), Some(2), None, Some(3)]), [S, S, S, S]);
3047 }
3048
3049 #[test]
3050 fn cite_sty_sort_keys_and_runs() {
3051 use CiteJoint::{Covered as C, RangeEnd as R, Separator as S};
3052 assert_eq!(cite_sty_sort_key("7"), Some(7 * 256));
3054 assert_eq!(cite_sty_sort_key("2a"), Some(2 * 256 + 97));
3055 assert_eq!(cite_sty_sort_key("a2"), Some((97 * 16384 + 2) * 256));
3056 assert_eq!(cite_sty_sort_key("1.2"), Some((256 + 46) * 4096 + 2));
3057 assert_eq!(cite_sty_sort_key("Knu84"), None);
3058 assert_eq!(cite_sty_sort_key("2ab"), None);
3059 let mut labels = ["7", "2a", "1"];
3060 labels.sort_by_key(|label| cite_sty_sort_key(label));
3061 assert_eq!(labels, ["1", "2a", "7"]);
3062 let keys = |labels: &[&str]| {
3064 labels
3065 .iter()
3066 .map(|label| cite_sty_sort_key(label))
3067 .collect::<Vec<_>>()
3068 };
3069 assert_eq!(compressed_joints(&keys(&["1", "2", "3"]), &[256, 1]), [
3070 S, C, R
3071 ]);
3072 assert_eq!(compressed_joints(&keys(&["4a", "4b", "4c"]), &[256, 1]), [
3073 S, C, R
3074 ]);
3075 assert_eq!(compressed_joints(&keys(&["2a", "3", "4"]), &[256, 1]), [
3076 S, S, S
3077 ]);
3078 }
3079
3080 #[test]
3081 fn ref_fallbacks_title_chain() {
3082 assert_eq!(ref_fallbacks("title"), &["toccaption"]);
3083 assert_eq!(ref_fallbacks("toctitle"), &["title", "toccaption"]);
3084 assert_eq!(ref_fallbacks("rawtoctitle"), &[
3085 "toctitle",
3086 "title",
3087 "toccaption"
3088 ]);
3089 assert_eq!(ref_fallbacks("rawtitle"), &["title", "toccaption"]);
3090 }
3091
3092 #[test]
3093 fn ref_fallbacks_unknown_key_is_empty() {
3094 let empty: &[&str] = &[];
3095 assert_eq!(ref_fallbacks("nonexistent"), empty);
3096 assert_eq!(ref_fallbacks(""), empty);
3097 }
3098
3099 #[test]
3100 fn text_content_flattens_text() {
3101 let nodes = vec![
3102 NodeData::Text("hello ".to_string()),
3103 NodeData::Text("world".to_string()),
3104 ];
3105 assert_eq!(text_content(&nodes), "hello world");
3106 }
3107
3108 #[test]
3109 fn text_content_recurses_into_elements() {
3110 let nodes = vec![NodeData::Element {
3111 tag: "span".to_string(),
3112 attributes: None,
3113 children: vec![
3114 NodeData::Text("inner ".to_string()),
3115 NodeData::Text("text".to_string()),
3116 ],
3117 }];
3118 assert_eq!(text_content(&nodes), "inner text");
3119 }
3120
3121 #[test]
3122 fn text_content_empty_list_is_empty_string() {
3123 assert_eq!(text_content(&[]), "");
3124 }
3125
3126 #[test]
3127 fn text_content_mixed_text_and_nested_element() {
3128 let nodes = vec![
3129 NodeData::Text("outer ".to_string()),
3130 NodeData::Element {
3131 tag: "em".to_string(),
3132 attributes: None,
3133 children: vec![NodeData::Text("inner".to_string())],
3134 },
3135 NodeData::Text(" tail".to_string()),
3136 ];
3137 assert_eq!(text_content(&nodes), "outer inner tail");
3138 }
3139
3140 #[test]
3143 fn url_style_file_is_identity() {
3144 for url in ["a/b.html", "index.html", "sub/index.html", "index", ""] {
3146 assert_eq!(apply_url_style(url, UrlStyle::File, "html"), url);
3147 }
3148 }
3149
3150 #[test]
3151 fn url_style_server_strips_trailing_index() {
3152 assert_eq!(
3154 apply_url_style("index.html", UrlStyle::Server, "html"),
3155 "./"
3156 );
3157 assert_eq!(
3158 apply_url_style("dir/index.html", UrlStyle::Server, "html"),
3159 "dir/"
3160 );
3161 assert_eq!(
3162 apply_url_style("a/b/index.html", UrlStyle::Server, "html"),
3163 "a/b/"
3164 );
3165 assert_eq!(
3167 apply_url_style("dir/page.html", UrlStyle::Server, "html"),
3168 "dir/page.html"
3169 );
3170 assert_eq!(
3173 apply_url_style("myindex.html", UrlStyle::Server, "html"),
3174 "myindex.html"
3175 );
3176 }
3177
3178 #[test]
3179 fn url_style_negotiated_strips_extension_and_index() {
3180 assert_eq!(
3182 apply_url_style("dir/page.html", UrlStyle::Negotiated, "html"),
3183 "dir/page"
3184 );
3185 assert_eq!(
3187 apply_url_style("index.html", UrlStyle::Negotiated, "html"),
3188 ""
3189 );
3190 assert_eq!(
3191 apply_url_style("dir/index.html", UrlStyle::Negotiated, "html"),
3192 "dir/"
3193 );
3194 assert_eq!(
3196 apply_url_style("myindex.html", UrlStyle::Negotiated, "html"),
3197 "myindex"
3198 );
3199 assert_eq!(
3201 apply_url_style("dir/index.xml", UrlStyle::Negotiated, "xml"),
3202 "dir/"
3203 );
3204 }
3205}