1use latexml_core::common::{cleaners::substr, xml::name_is};
18use libxml::tree::Node;
19use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
20
21use crate::{
22 document::{NodeData, PostDocument, PostDocumentOptions},
23 object_db::ObjectDB,
24 processor::{ProcessResult, Processor, find_documentclass_and_packages},
25 radix::radix_alpha,
26};
27
28#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum RawBibSource {
39 Path(String),
41 Literal(String),
43}
44
45#[derive(Debug, Clone)]
50pub struct BibConversionRequest {
51 pub sources: Vec<RawBibSource>,
53 pub search_paths: Vec<String>,
55 pub preloads: Vec<String>,
60 pub wanted_keys: Option<Vec<String>>,
67}
68
69pub type BibConverterFn = fn(&BibConversionRequest) -> Option<PostDocument>;
76
77thread_local! {
78 static BIB_CONVERTER: std::cell::Cell<Option<BibConverterFn>> =
79 const { std::cell::Cell::new(None) };
80 static URLS_AS_TEXT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
83 static GIVEN_NAME_FORM: std::cell::Cell<GivenNameForm> =
86 const { std::cell::Cell::new(GivenNameForm::Initials) };
87 static PERIOD_RULE: std::cell::Cell<PeriodRule> =
90 const { std::cell::Cell::new(PeriodRule::AddPeriod) };
91 static BIBLATEX_BIBLIOGRAPHY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105enum PeriodRule {
106 AddPeriod,
110 Tracker,
112}
113
114fn is_biblatex_bibliography() -> bool { BIBLATEX_BIBLIOGRAPHY.with(std::cell::Cell::get) }
116
117fn label_editors(tail: &str, find: impl Fn(&str) -> Vec<Node>) -> Vec<Node> {
127 if is_biblatex_bibliography() {
128 let host = find(&format!(
129 "ltx:bib-related[@role='host']/ltx:bib-name[@role='editor']{tail}"
130 ));
131 if !host.is_empty() {
132 return host;
133 }
134 }
135 find(&format!("ltx:bib-name[@role='editor']{tail}"))
136}
137
138impl PeriodRule {
139 fn of_style(bibstyle: Option<&str>) -> Self {
143 if bibstyle.is_some_and(|style| style.starts_with("biblatex")) {
144 PeriodRule::Tracker
145 } else {
146 PeriodRule::AddPeriod
147 }
148 }
149
150 fn absorbs_period(self, text: &str) -> bool {
152 match self {
153 PeriodRule::AddPeriod => text.trim_end().ends_with(['.', '?', '!']),
154 PeriodRule::Tracker => ends_with_punctuation(text),
155 }
156 }
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169enum GivenNameForm {
170 Initials,
174 Full,
176}
177
178pub fn set_bib_converter(convert: BibConverterFn) {
180 BIB_CONVERTER.with(|slot| slot.set(Some(convert)));
181}
182
183fn bib_converter() -> Option<BibConverterFn> { BIB_CONVERTER.with(|slot| slot.get()) }
184
185#[derive(Debug, Clone, PartialEq)]
187pub enum CitationStyle {
188 Numbers,
190 AuthorYear,
192 Alpha,
194}
195
196#[derive(Debug)]
200struct BibEntryData {
201 bib_key: String,
202 cited_key: Option<String>,
203 sort_key: String,
204 initial: String,
205 author_year: String,
206 suffix: Option<String>,
207 sort_names: String,
209 year: String,
210 entry_type: String,
212 number: u32,
214 label_number: Option<u32>,
216 referrers: HashSet<String>,
218 bibreferrers: HashSet<String>,
220 citations: Vec<String>,
222 bibentry: Option<Node>,
224 db_index: usize,
227}
228
229impl BibEntryData {
230 fn bib_type(&self) -> &str {
232 if self.entry_type.is_empty() {
233 "misc"
234 } else {
235 &self.entry_type
236 }
237 }
238
239 fn format_type(&self) -> &str {
243 match self.entry_type.as_str() {
244 "article" => "article",
245 "book" | "periodical" | "collection" | "proceedings" | "manual" | "misc" | "unpublished"
246 | "booklet" => "book",
247 "incollection"
248 | "collection.article"
249 | "proceedings.article"
250 | "inproceedings"
251 | "inbook" => "incollection",
252 "report" | "techreport" => "report",
253 "thesis" | "mastersthesis" | "phdthesis" => "thesis",
254 "website" | "online" => "website",
255 "software" => "software",
256 _ => "book", }
258 }
259}
260
261pub struct MakeBibliography {
265 name: String,
266 pub db: ObjectDB,
267 split: bool,
268 bibliographies: Vec<String>,
269 dropped_years: std::cell::RefCell<HashMap<String, String>>,
272}
273
274impl MakeBibliography {
275 pub fn new(db: ObjectDB, split: bool) -> Self {
276 MakeBibliography {
277 name: "MakeBibliography".to_string(),
278 db,
279 split,
280 bibliographies: Vec::new(),
281 dropped_years: Default::default(),
282 }
283 }
284
285 pub fn set_bibliographies(&mut self, bibs: Vec<String>) { self.bibliographies = bibs; }
286
287 fn get_bibliographies(
297 &self,
298 doc: &PostDocument,
299 bib_node: &Node,
300 wanted_keys: Option<&Vec<String>>,
301 ) -> Vec<PostDocument> {
302 let mut bibnames: Vec<String> = Vec::new();
303 let mut from_bibliography = false;
304
305 if !self.bibliographies.is_empty() {
307 bibnames = self.bibliographies.clone();
308 } else {
309 let files_of = |node: &Node| node.get_attribute("files").filter(|f| !f.is_empty());
323 let files = files_of(bib_node)
324 .or_else(|| bib_node.get_parent().as_ref().and_then(files_of))
325 .or_else(|| {
326 if !doc.findnodes_at("ltx:biblist", Some(bib_node)).is_empty() {
327 return None;
328 }
329 doc
330 .findnodes("//ltx:bibliography[@files]")
331 .iter()
332 .find_map(files_of)
333 });
334 if let Some(f) = files {
335 from_bibliography = true;
336 bibnames = f.split(',').map(|s| s.trim().to_string()).collect();
337 }
338 }
339
340 let search_paths = doc.get_search_paths();
341 let mut bibs: Vec<PostDocument> = Vec::new();
342 let mut rawbibs: Vec<RawBibSource> = Vec::new();
347
348 for bib in &bibnames {
349 let mut loaded = false;
350 let is_bib_style = bib.ends_with(".bib") || bib.ends_with(".bib.xml") || from_bibliography;
356
357 if let Some(data) = bib.strip_prefix("literal:") {
359 rawbibs.push(RawBibSource::Literal(data.to_string()));
360 continue;
361 }
362
363 if bib.ends_with(".xml") {
365 if let Some(path) = find_file(bib, search_paths) {
366 match PostDocument::new_from_file(&path, PostDocumentOptions {
367 source_directory: Some(".".to_string()),
368 ..PostDocumentOptions::default()
369 }) {
370 Ok(bibdoc) => {
371 bibs.push(bibdoc);
372 loaded = true;
373 },
374 Err(e) => Warn!("I/O", bib, "Failed to load bibliography '{}': {}", bib, e),
375 }
376 }
377 }
378 else if is_bib_style {
380 let xmlbib = if from_bibliography && !bib.ends_with(".bib") {
381 format!("{}.bib", bib)
382 } else {
383 bib.clone()
384 };
385 let xml_candidate = if xmlbib.ends_with(".xml") {
387 xmlbib.clone()
388 } else {
389 format!("{}.xml", xmlbib)
390 };
391 if let Some(path) = find_file(&xml_candidate, search_paths) {
392 match PostDocument::new_from_file(&path, PostDocumentOptions {
393 source_directory: Some(".".to_string()),
394 ..PostDocumentOptions::default()
395 }) {
396 Ok(bibdoc) => {
397 bibs.push(bibdoc);
398 loaded = true;
399 },
400 Err(e) => Warn!("I/O", path, "Failed to load bibliography '{}': {}", path, e),
401 }
402 }
403 }
404
405 if !loaded {
411 let bib_file = if from_bibliography && !bib.ends_with(".bib") {
412 format!("{}.bib", bib)
413 } else {
414 bib.clone()
415 };
416 if let Some(contents) = latexml_core::binding::virtual_files::vfs_read(&bib_file) {
424 rawbibs.push(RawBibSource::Literal(contents));
425 loaded = true;
426 } else if let Some(bib_path) =
427 latexml_core::util::pathname::requested_as(&bib_file, || {
429 bib_lookup_candidates(&bib_file).iter().find_map(|c| {
430 find_file(c, search_paths)
431 .or_else(|| latexml_core::util::pathname::kpsewhich(&[c.as_str()]))
432 })
433 })
434 {
435 rawbibs.push(RawBibSource::Path(bib_path));
436 loaded = true;
437 } else if is_bib_style {
438 Error!(
447 "missing_file",
448 bib,
449 "Couldn't find Bibliography '{}'\nSearchpaths were {}",
450 bib,
451 search_paths.join(",")
452 );
453 }
454 }
455
456 if !loaded {
457 Info!(
458 "bibliography",
459 "missing",
460 "Couldn't find usable bibliography for '{}'",
461 bib
462 );
463 }
464 }
465
466 if !rawbibs.is_empty() {
469 match bib_converter() {
470 Some(convert) => {
471 let (class, packages) = find_documentclass_and_packages(doc);
472 let mut preloads = Vec::with_capacity(1 + packages.len());
474 preloads.push(if class.options.is_empty() {
475 format!("{}.cls", class.name)
476 } else {
477 format!("[{}]{}.cls", class.options, class.name)
478 });
479 for pkg in &packages {
480 preloads.push(if pkg.options.is_empty() {
481 format!("{}.sty", pkg.name)
482 } else {
483 format!("[{}]{}.sty", pkg.options, pkg.name)
484 });
485 }
486 let request = BibConversionRequest {
487 sources: rawbibs,
488 search_paths: search_paths.to_vec(),
489 preloads,
490 wanted_keys: wanted_keys.cloned(),
491 };
492 match convert(&request) {
493 Some(bibdoc) => bibs.push(bibdoc),
494 None => Error!(
495 "bibliography",
496 "convert",
497 "Recursive BibTeX conversion produced no bibliography"
498 ),
499 }
500 },
501 None => Error!(
505 "bibliography",
506 "converter",
507 "No BibTeX converter installed; cannot convert {} raw bibliography source(s) \
508 (call make_bibliography::set_bib_converter before post-processing)",
509 rawbibs.len()
510 ),
511 }
512 }
513
514 Info!(
515 "bibliography",
516 "using",
517 "MakeBibliography: using {} bibliographies",
518 bibs.len()
519 );
520 bibs
521 }
522
523 fn scan_bibentries(entries: &mut HashMap<String, BibEntryData>, srcdoc: &PostDocument) {
533 for bibentry in srcdoc.findnodes("//ltx:bibentry") {
534 let bibkey = match bibentry.get_attribute("key") {
535 Some(k) => k,
536 None => continue,
537 };
538 let lc_key = bibkey.to_lowercase();
539 let citations = Self::entry_citations(srcdoc, &bibentry);
540
541 if let Some(previous) = entries.get(&lc_key)
547 && previous.bib_key != bibkey
548 {
549 Error!(
550 "unexpected",
551 &bibkey,
552 "Bibliography entries '{}' and '{}' differ only in case: they share one key and the entry '{}' is replaced",
553 previous.bib_key,
554 bibkey,
555 previous.bib_key
556 );
557 }
558 let db_index = entries.get(&lc_key).map_or(entries.len(), |e| e.db_index);
559 entries.insert(lc_key, BibEntryData {
560 bib_key: bibkey,
561 cited_key: None,
562 sort_key: String::new(),
563 initial: String::new(),
564 author_year: String::new(),
565 suffix: None,
566 sort_names: String::new(),
567 year: String::new(),
568 entry_type: String::new(),
569 number: 0,
570 label_number: None,
571 referrers: HashSet::default(),
572 bibreferrers: HashSet::default(),
573 citations,
574 bibentry: Some(bibentry.clone()),
575 db_index,
576 });
577 }
578 }
579
580 fn entry_citations(srcdoc: &PostDocument, bibentry: &Node) -> Vec<String> {
582 srcdoc
583 .findnodes_at(".//@bibrefs", Some(bibentry))
584 .iter()
585 .filter_map(|n| {
586 let val = n.get_content();
587 if val.is_empty() { None } else { Some(val) }
588 })
589 .flat_map(|s| s.split(',').map(String::from).collect::<Vec<_>>())
590 .filter(|s| !s.is_empty())
591 .collect()
592 }
593
594 fn cited_keys(&self, lists: &[&str]) -> Option<Vec<String>> {
605 let mut keys: Vec<String> = Vec::new();
606 for db_key in self.db.get_keys() {
607 let Some(rest) = db_key.strip_prefix("BIBLABEL:") else {
608 continue;
609 };
610 let Some((list, bibkey)) = rest.split_once(':') else {
611 continue;
612 };
613 if !lists.contains(&list) {
614 continue;
615 }
616 if bibkey == "*" {
617 return None; }
619 keys.push(bibkey.to_string());
620 }
621 (!keys.is_empty()).then_some(keys)
622 }
623
624 fn get_bib_entries(
625 &self,
626 doc: &PostDocument,
627 bib_node: &Node,
628 ) -> (HashMap<String, BibEntryData>, Vec<PostDocument>) {
629 let lists_str = bib_node
630 .get_attribute("lists")
631 .unwrap_or_else(|| "bibliography".to_string());
632 let lists: Vec<&str> = lists_str.split_whitespace().collect();
633
634 let mut entries: HashMap<String, BibEntryData> = HashMap::default();
639 let bib_docs = self.get_bibliographies(doc, bib_node, self.cited_keys(&lists).as_ref());
640 for bibdoc in &bib_docs {
641 Self::scan_bibentries(&mut entries, bibdoc);
642 }
643 Self::scan_bibentries(&mut entries, doc);
658 for own in doc.findnodes_at(".//ltx:bibentry", Some(bib_node)) {
663 let Some(key) = own.get_attribute("key") else {
664 continue;
665 };
666 if let Some(entry) = entries.get_mut(&key.to_lowercase())
667 && entry.bib_key == key
668 {
669 entry.citations = Self::entry_citations(doc, &own);
670 entry.bibentry = Some(own);
671 }
672 }
673 let mut inline_keys: Vec<String> = doc
679 .findnodes_at(".//ltx:bibentry", Some(bib_node))
680 .iter()
681 .filter(|entry| {
682 !entry
683 .get_attribute("class")
684 .is_some_and(|class| class.split_whitespace().any(|c| c == "ltx_bib_library"))
685 })
686 .filter_map(|entry| entry.get_attribute("key"))
687 .collect();
688 inline_keys.sort();
689 let own_id = crate::document::get_xml_id(bib_node);
692 let foreign_keys: HashSet<String> = doc
693 .findnodes("//ltx:bibentry")
694 .iter()
695 .filter(|entry| {
696 let mut up = entry.get_parent();
697 while let Some(node) = up {
698 if name_is(&node, "bibliography") {
699 return crate::document::get_xml_id(&node) != own_id;
700 }
701 up = node.get_parent();
702 }
703 false
704 })
705 .filter_map(|entry| entry.get_attribute("key"))
706 .map(|key| key.to_lowercase())
707 .filter(|key| !inline_keys.iter().any(|own| own.to_lowercase() == *key))
708 .collect();
709
710 let cite_star = lists
713 .iter()
714 .any(|list| self.db.lookup(&format!("BIBLABEL:{}:*", list)).is_some());
715
716 let mut queue: Vec<String> = Vec::new();
717 for db_key in self.db.get_keys() {
718 if !db_key.starts_with("BIBLABEL:") {
719 continue;
720 }
721 let parts: Vec<&str> = db_key.splitn(3, ':').collect();
722 if parts.len() < 3 {
723 continue;
724 }
725 let (list, bibkey) = (parts[1], parts[2]);
726 if !lists.contains(&list) {
727 continue;
728 }
729
730 let lc_key = bibkey.to_lowercase();
731 if let Some(bentry) = self.db.lookup(db_key) {
732 let has_refs = bentry
733 .get_value("referrers")
734 .map(|v| v.is_truthy())
735 .unwrap_or(false);
736 if has_refs {
737 if let Some(crate::object_db::Value::Hash(refs)) = bentry.get_value("referrers") {
739 for ref_id in refs.keys() {
740 let mut rid = ref_id.clone();
741 let mut is_from_bib = false;
742 while let Some(entry) = self.db.lookup(&format!("ID:{}", rid)) {
743 let entry_type = entry.get_string("type").unwrap_or("");
744 if entry_type == "ltx:bibitem" {
745 is_from_bib = true;
746 break;
747 }
748 match entry.get_string("parent").map(String::from) {
749 Some(parent) => rid = parent,
750 None => break,
751 }
752 }
753 if !is_from_bib {
754 if let Some(existing) = entries.get(&lc_key) {
756 if let Some(ref prev_key) = existing.cited_key {
757 if prev_key != bibkey {
758 Warn!(
759 "bibliography",
760 "case_mismatch",
761 "Case mismatch in bib key '{}' vs '{}'",
762 prev_key,
763 bibkey
764 );
765 }
766 }
767 }
768 let entry = entries
769 .entry(lc_key.clone())
770 .or_insert_with(|| BibEntryData {
771 bib_key: bibkey.to_string(),
772 cited_key: None,
773 sort_key: String::new(),
774 initial: String::new(),
775 author_year: String::new(),
776 suffix: None,
777 sort_names: String::new(),
778 year: String::new(),
779 entry_type: String::new(),
780 number: 0,
781 label_number: None,
782 referrers: HashSet::default(),
783 bibreferrers: HashSet::default(),
784 citations: Vec::new(),
785 bibentry: None,
786 db_index: usize::MAX,
787 });
788 entry.cited_key = Some(bibkey.to_string());
789 entry.referrers.insert(ref_id.clone());
790 }
791 }
792 }
793 if entries
794 .get(&lc_key)
795 .map(|e| !e.referrers.is_empty())
796 .unwrap_or(false)
797 {
798 queue.push(bibkey.to_string());
799 }
800 }
801 }
802 }
803
804 if cite_star {
817 let mut all: Vec<String> = entries.values().map(|e| e.bib_key.clone()).collect();
818 all.sort();
819 queue.extend(all);
820 }
821 let queued: HashSet<String> = queue.iter().map(|key| key.to_lowercase()).collect();
823 queue.extend(
824 inline_keys
825 .into_iter()
826 .filter(|key| !queued.contains(&key.to_lowercase())),
827 );
828 if let Some(listing) = given_listing(doc, bib_node) {
833 let listed: HashSet<String> = listing.iter().map(|key| key.to_lowercase()).collect();
834 queue.retain(|key| listed.contains(&key.to_lowercase()));
835 queue.extend(listing);
836 }
837
838 let mut seen: HashSet<String> = HashSet::default();
841 let mut included: HashMap<String, BibEntryData> = HashMap::default();
842 let mut missing_keys: Vec<String> = Vec::new();
843
844 while let Some(bibkey) = queue.pop() {
845 if seen.contains(&bibkey) || bibkey == "*" || foreign_keys.contains(&bibkey.to_lowercase()) {
846 continue;
847 }
848 seen.insert(bibkey.clone());
849 let lc_key = bibkey.to_lowercase();
850
851 match entries.remove(&lc_key) {
852 Some(mut entry) => {
853 if let Some(ref bibentry) = entry.bibentry {
855 let (sort_names, short_names, _full_names) = extract_names(doc, bibentry);
863 entry.sort_names = sort_names.clone();
864
865 let date_content =
867 PostDocument::findnodes_foreign("ltx:bib-date[@role='publication']", bibentry)
868 .into_iter()
869 .next()
870 .map(|n| n.get_content())
871 .unwrap_or_default();
872 let year = extract_four_digit_year(&date_content);
873 entry.year = year.clone();
874
875 let title = PostDocument::findnodes_foreign("ltx:bib-title", bibentry)
888 .into_iter()
889 .next()
890 .map(|n| n.get_content())
891 .unwrap_or_default();
892
893 let entry_type = bibentry
895 .get_attribute("type")
896 .unwrap_or_else(|| "misc".to_string());
897 entry.entry_type = entry_type;
898
899 entry.author_year = format!("{}.{}", short_names, year);
906 entry.initial = PostDocument::initial(&short_names, true);
907
908 let sort_key = format!("{}.{}.{}.{}", sort_names, year, title, bibkey).to_lowercase();
910 entry.sort_key = sort_key.clone();
911
912 let citations = entry.citations.clone();
914 for c in &citations {
915 queue.push(c.clone());
916 }
917 included.insert(sort_key, entry);
918 } else {
919 missing_keys.push(bibkey);
929 }
930 },
931 _ => {
932 missing_keys.push(bibkey);
934 },
935 }
936 }
937
938 if !missing_keys.is_empty() {
939 Warn!(
940 "bibliography",
941 "missing_keys",
942 "Missing bibkeys: {}",
943 missing_keys.join(", ")
944 );
945 }
946
947 let citations_map: Vec<(String, Vec<String>)> = included
950 .values()
951 .map(|e| (e.bib_key.clone(), e.citations.clone()))
952 .collect();
953 for (bibkey, citations) in &citations_map {
954 for cited in citations {
955 let lc = cited.to_lowercase();
956 for entry in included.values_mut() {
958 if entry.bib_key.to_lowercase() == lc {
959 entry.bibreferrers.insert(bibkey.clone());
960 }
961 }
962 }
963 }
964
965 Info!(
966 "bibliography",
967 "count",
968 "MakeBibliography: {} bibentries, {} cited",
969 entries.len() + included.len(),
970 included.len()
971 );
972
973 let mut sorted_keys: Vec<String> = included.keys().cloned().collect();
976 unisort(&mut sorted_keys);
977
978 let mut ay_last: HashMap<String, String> = HashMap::default(); for key in &sorted_keys {
981 if let Some(entry) = included.get(key) {
982 let ay = entry.author_year.clone();
983 if let Some(prev_key) = ay_last.get(&ay) {
984 let prev_key = prev_key.clone();
985 if let Some(prev) = included.get_mut(&prev_key) {
987 if prev.suffix.is_none() {
988 prev.suffix = Some(radix_alpha(1));
989 }
990 }
991 let prev_counter = included
992 .get(&prev_key)
993 .and_then(|p| p.suffix.as_ref())
994 .map(|s| suffix_to_counter(s))
995 .unwrap_or(1);
996 if let Some(e) = included.get_mut(key) {
997 e.suffix = Some(radix_alpha(prev_counter + 1));
998 }
999 }
1000 ay_last.insert(ay, key.clone());
1001 }
1002 }
1003
1004 for entry in included.values() {
1006 if let Some(ref bibentry) = entry.bibentry {
1007 let sort_errors = PostDocument::findnodes_foreign(".//ltx:ERROR[@class='sort']", bibentry);
1008 for mut sortnode in sort_errors {
1009 sortnode.unlink();
1010 }
1011 }
1012 }
1013
1014 (included, bib_docs)
1020 }
1021
1022 fn make_bibliography_list(
1026 &self,
1027 doc: &PostDocument,
1028 bib_id: &str,
1029 initial: Option<&str>,
1030 entries: &HashMap<String, BibEntryData>,
1031 style: &CitationStyle,
1032 ) -> NodeData {
1033 let id = if let Some(init) = initial {
1034 format!("{}.L1.{}", bib_id, init)
1035 } else {
1036 format!("{}.L1", bib_id)
1037 };
1038
1039 let mut ordered: Vec<&BibEntryData> = entries.values().collect();
1046 ordered.sort_by_key(|e| e.number);
1047 let items: Vec<NodeData> = ordered
1050 .iter()
1051 .filter_map(|entry| {
1052 debug_assert!(
1053 entry.bibentry.is_some(),
1054 "included entry {} has no bibentry",
1055 entry.bib_key
1056 );
1057 let bibentry = entry.bibentry.as_ref()?;
1058 Some(self.format_bib_entry(doc, bib_id, entry, bibentry, style))
1059 })
1060 .collect();
1061
1062 NodeData::Element {
1063 tag: "ltx:biblist".to_string(),
1064 attributes: Some(HashMap::from_iter([("xml:id".to_string(), id)])),
1065 children: items,
1066 }
1067 }
1068
1069 fn format_bib_entry(
1073 &self,
1074 doc: &PostDocument,
1075 bib_id: &str,
1076 entry: &BibEntryData,
1077 bibentry: &Node,
1078 style: &CitationStyle,
1079 ) -> NodeData {
1080 let id = bibitem_id(bib_id, entry, bibentry);
1084
1085 let cited_key = entry.cited_key.as_deref().unwrap_or(&entry.bib_key);
1086 let mut children = Vec::new();
1087
1088 let mut tags = Vec::new();
1090
1091 let given_label = entry_given_label(entry, style);
1095 if given_label.is_none() {
1096 tags.push(NodeData::Element {
1097 tag: "ltx:tag".to_string(),
1098 attributes: Some(HashMap::from_iter([
1099 ("role".to_string(), "number".to_string()),
1100 ("class".to_string(), "ltx_bib_number".to_string()),
1101 ])),
1102 children: vec![NodeData::Text(entry.shown_number().to_string())],
1103 });
1104 }
1105
1106 let (author_tag_nodes, has_names, has_key, has_year, has_typetag) =
1108 self.build_author_year_tags(doc, entry, bibentry);
1109 tags.extend(author_tag_nodes);
1110
1111 let mut effective_style = style.clone();
1113 if !((has_names || has_key) && (has_year || has_typetag)) {
1115 effective_style = CitationStyle::Numbers;
1116 }
1117
1118 let mut skip_first_block = false;
1119 let mut drop_first_block_year = false;
1121 match effective_style {
1122 _ if given_label.is_some() => {
1123 tags.push(NodeData::Element {
1124 tag: "ltx:tag".to_string(),
1125 attributes: Some(HashMap::from_iter([
1126 ("role".to_string(), "refnum".to_string()),
1127 ("class".to_string(), "ltx_bib_abbrv".to_string()),
1128 ("open".to_string(), "[".to_string()),
1129 ("close".to_string(), "]".to_string()),
1130 ])),
1131 children: vec![NodeData::Text(given_label.unwrap_or_default())],
1132 });
1133 },
1134 CitationStyle::Numbers => {
1135 tags.push(NodeData::Element {
1136 tag: "ltx:tag".to_string(),
1137 attributes: Some(HashMap::from_iter([
1138 ("role".to_string(), "refnum".to_string()),
1139 ("class".to_string(), "ltx_bib_key".to_string()),
1140 ("open".to_string(), "[".to_string()),
1141 ("close".to_string(), "]".to_string()),
1142 ])),
1143 children: vec![NodeData::Text(entry.shown_number().to_string())],
1144 });
1145 },
1146 CitationStyle::Alpha => {
1147 let aa = self.make_alpha_label(doc, entry, bibentry);
1149 let yy = alpha_label_year(&entry.year);
1150 let suffix = entry.suffix.as_deref().unwrap_or("");
1151 tags.push(NodeData::Element {
1152 tag: "ltx:tag".to_string(),
1153 attributes: Some(HashMap::from_iter([
1154 ("role".to_string(), "refnum".to_string()),
1155 ("class".to_string(), "ltx_bib_abbrv".to_string()),
1156 ("open".to_string(), "[".to_string()),
1157 ("close".to_string(), "]".to_string()),
1158 ])),
1159 children: vec![NodeData::Text(format!("{aa}{yy}{suffix}"))],
1160 });
1161 },
1162 CitationStyle::AuthorYear => {
1163 skip_first_block = false;
1188 drop_first_block_year = true;
1189 let suffix = entry.suffix.as_deref().unwrap_or("");
1190 let authors = PostDocument::findnodes_foreign("ltx:bib-name[@role='author']", bibentry);
1191 let mut refnum_children: Vec<NodeData> = if !authors.is_empty() {
1192 do_names_short(authors)
1193 } else {
1194 let editors = label_editors("", |x| PostDocument::findnodes_foreign(x, bibentry));
1195 if !editors.is_empty() {
1196 do_editors_a(editors)
1197 } else {
1198 let key = PostDocument::findnodes_foreign("ltx:bib-key", bibentry)
1200 .into_iter()
1201 .next()
1202 .map(|k| k.get_content())
1203 .unwrap_or_else(|| entry.bib_key.clone());
1204 vec![NodeData::Text(key)]
1205 }
1206 };
1207 let year_text = if !entry.year.is_empty() {
1210 format!("{}{}", entry.year, suffix)
1211 } else {
1212 PostDocument::findnodes_foreign("ltx:bib-type", bibentry)
1213 .into_iter()
1214 .next()
1215 .map(|t| t.get_content())
1216 .unwrap_or_default()
1217 };
1218 refnum_children.push(NodeData::Text(format!(" ({})", year_text)));
1219 tags.push(NodeData::Element {
1220 tag: "ltx:tag".to_string(),
1221 attributes: Some(HashMap::from_iter([
1222 ("role".to_string(), "refnum".to_string()),
1223 ("class".to_string(), "ltx_bib_author-year".to_string()),
1224 ])),
1225 children: refnum_children,
1226 });
1227 },
1228 }
1229
1230 if !tags.is_empty() {
1231 children.push(NodeData::Element {
1232 tag: "ltx:tags".to_string(),
1233 attributes: None,
1234 children: tags,
1235 });
1236 }
1237
1238 let mut dropped_year = None;
1240 let blocks = self.format_blocks(
1241 doc,
1242 entry,
1243 bibentry,
1244 skip_first_block,
1245 drop_first_block_year,
1246 &mut dropped_year,
1247 );
1248 if let Some(year) = dropped_year {
1249 self.dropped_years.borrow_mut().insert(id.clone(), year);
1250 }
1251 children.extend(blocks);
1252
1253 let mut citedby: Vec<NodeData> = Vec::new();
1255 let mut sorted_referrers: Vec<&String> = entry.referrers.iter().collect();
1256 sorted_referrers.sort();
1257 for ref_id in &sorted_referrers {
1258 citedby.push(NodeData::Element {
1259 tag: "ltx:ref".to_string(),
1260 attributes: Some(HashMap::from_iter([
1261 ("idref".to_string(), (*ref_id).clone()),
1262 ("show".to_string(), "typerefnum".to_string()),
1263 ])),
1264 children: vec![],
1265 });
1266 }
1267 if !entry.bibreferrers.is_empty() {
1268 let mut sorted_bibrefs: Vec<&String> = entry.bibreferrers.iter().collect();
1269 sorted_bibrefs.sort();
1270 citedby.push(NodeData::Element {
1271 tag: "ltx:bibref".to_string(),
1272 attributes: Some(HashMap::from_iter([
1273 (
1274 "bibrefs".to_string(),
1275 sorted_bibrefs
1276 .iter()
1277 .map(|s| s.as_str())
1278 .collect::<Vec<_>>()
1279 .join(","),
1280 ),
1281 ("show".to_string(), "refnum".to_string()),
1282 ])),
1283 children: vec![],
1284 });
1285 }
1286 if !citedby.is_empty() {
1287 let conjoined = PostDocument::conjoin(
1288 crate::document::Conjunction::Simple(",\n".to_string()),
1289 citedby,
1290 );
1291 let mut block_children = vec![NodeData::Text("Cited by: ".to_string())];
1292 block_children.extend(conjoined);
1293 block_children.push(NodeData::Text(".".to_string()));
1294 children.push(NodeData::Element {
1295 tag: "ltx:bibblock".to_string(),
1296 attributes: Some(HashMap::from_iter([(
1297 "class".to_string(),
1298 "ltx_bib_cited".to_string(),
1299 )])),
1300 children: block_children,
1301 });
1302 }
1303
1304 NodeData::Element {
1305 tag: "ltx:bibitem".to_string(),
1306 attributes: Some(HashMap::from_iter([
1307 ("xml:id".to_string(), id),
1308 ("key".to_string(), cited_key.to_string()),
1309 ("type".to_string(), entry.entry_type.clone()),
1310 ("class".to_string(), format!("ltx_bib_{}", entry.bib_type())),
1311 ])),
1312 children,
1313 }
1314 }
1315
1316 fn build_author_year_tags(
1320 &self,
1321 doc: &PostDocument,
1322 entry: &BibEntryData,
1323 bibentry: &Node,
1324 ) -> (Vec<NodeData>, bool, bool, bool, bool) {
1325 let mut tags = Vec::new();
1326 let mut has_names = false;
1327 let mut has_key = false;
1328 let mut has_year = false;
1329 let mut has_typetag = false;
1330
1331 let mut surnames: Vec<Node> =
1333 doc.findnodes_at("ltx:bib-name[@role='author']/ltx:surname", Some(bibentry));
1334 if surnames.is_empty() {
1335 surnames = label_editors("/ltx:surname", |x| doc.findnodes_at(x, Some(bibentry)));
1336 }
1337
1338 if surnames.len() > 2 {
1339 has_names = true;
1340 let first_text = surnames[0].get_content();
1342 tags.push(NodeData::Element {
1343 tag: "ltx:tag".to_string(),
1344 attributes: Some(HashMap::from_iter([
1345 ("role".to_string(), "authors".to_string()),
1346 ("class".to_string(), "ltx_bib_author".to_string()),
1347 ])),
1348 children: vec![NodeData::Text(first_text), NodeData::Element {
1349 tag: "ltx:text".to_string(),
1350 attributes: Some(HashMap::from_iter([(
1351 "class".to_string(),
1352 "ltx_bib_etal".to_string(),
1353 )])),
1354 children: vec![NodeData::Text(" et al.".to_string())],
1355 }],
1356 });
1357 let mut full_children: Vec<NodeData> = Vec::new();
1359 for (i, surname) in surnames.iter().enumerate() {
1360 if i > 0 && i < surnames.len() - 1 {
1361 full_children.push(NodeData::Text(", ".to_string()));
1362 } else if i == surnames.len() - 1 {
1363 full_children.push(NodeData::Text(" and ".to_string()));
1364 }
1365 full_children.push(NodeData::Text(surname.get_content()));
1366 }
1367 tags.push(NodeData::Element {
1368 tag: "ltx:tag".to_string(),
1369 attributes: Some(HashMap::from_iter([
1370 ("role".to_string(), "fullauthors".to_string()),
1371 ("class".to_string(), "ltx_bib_author".to_string()),
1372 ])),
1373 children: full_children,
1374 });
1375 } else if surnames.len() == 2 {
1376 has_names = true;
1377 tags.push(NodeData::Element {
1378 tag: "ltx:tag".to_string(),
1379 attributes: Some(HashMap::from_iter([
1380 ("role".to_string(), "authors".to_string()),
1381 ("class".to_string(), "ltx_bib_author".to_string()),
1382 ])),
1383 children: vec![
1384 NodeData::Text(surnames[0].get_content()),
1385 NodeData::Text(" and ".to_string()),
1386 NodeData::Text(surnames[1].get_content()),
1387 ],
1388 });
1389 } else if !surnames.is_empty() {
1390 has_names = true;
1391 tags.push(NodeData::Element {
1392 tag: "ltx:tag".to_string(),
1393 attributes: Some(HashMap::from_iter([
1394 ("role".to_string(), "authors".to_string()),
1395 ("class".to_string(), "ltx_bib_author".to_string()),
1396 ])),
1397 children: vec![NodeData::Text(surnames[0].get_content())],
1398 });
1399 }
1400
1401 if let Some(key_node) = PostDocument::findnodes_foreign("ltx:bib-key", bibentry)
1403 .into_iter()
1404 .next()
1405 {
1406 has_key = true;
1407 tags.push(NodeData::Element {
1408 tag: "ltx:tag".to_string(),
1409 attributes: Some(HashMap::from_iter([
1410 ("role".to_string(), "key".to_string()),
1411 ("class".to_string(), "ltx_bib_key".to_string()),
1412 ])),
1413 children: vec![NodeData::Text(key_node.get_content())],
1414 });
1415 }
1416
1417 if let Some(date_node) =
1419 PostDocument::findnodes_foreign("ltx:bib-date[@role='publication']", bibentry)
1420 .into_iter()
1421 .next()
1422 {
1423 has_year = true;
1424 let year_text = extract_four_digit_year(&date_node.get_content());
1425 let suffix = entry.suffix.as_deref().unwrap_or("");
1426 tags.push(NodeData::Element {
1427 tag: "ltx:tag".to_string(),
1428 attributes: Some(HashMap::from_iter([
1429 ("role".to_string(), "year".to_string()),
1430 ("class".to_string(), "ltx_bib_year".to_string()),
1431 ])),
1432 children: vec![NodeData::Text(format!("{}{}", year_text, suffix))],
1433 });
1434 }
1435
1436 if let Some(type_node) = PostDocument::findnodes_foreign("ltx:bib-type", bibentry)
1438 .into_iter()
1439 .next()
1440 {
1441 has_typetag = true;
1442 tags.push(NodeData::Element {
1443 tag: "ltx:tag".to_string(),
1444 attributes: Some(HashMap::from_iter([
1445 ("role".to_string(), "bibtype".to_string()),
1446 ("class".to_string(), "ltx_bib_type".to_string()),
1447 ])),
1448 children: vec![NodeData::Text(type_node.get_content())],
1449 });
1450 }
1451
1452 if let Some(title_node) = PostDocument::findnodes_foreign("ltx:bib-title", bibentry)
1454 .into_iter()
1455 .next()
1456 {
1457 tags.push(NodeData::Element {
1458 tag: "ltx:tag".to_string(),
1459 attributes: Some(HashMap::from_iter([
1460 ("role".to_string(), "title".to_string()),
1461 ("class".to_string(), "ltx_bib_title".to_string()),
1462 ])),
1463 children: vec![NodeData::Text(title_node.get_content())],
1464 });
1465 }
1466
1467 (tags, has_names, has_key, has_year, has_typetag)
1468 }
1469
1470 fn make_alpha_label(&self, doc: &PostDocument, entry: &BibEntryData, bibentry: &Node) -> String {
1474 let mut surnames: Vec<Node> =
1475 doc.findnodes_at("ltx:bib-name[@role='author']/ltx:surname", Some(bibentry));
1476 if surnames.is_empty() {
1477 surnames = label_editors("/ltx:surname", |x| doc.findnodes_at(x, Some(bibentry)));
1478 }
1479 if surnames.len() > 1 {
1480 let initials: Vec<char> = surnames
1488 .iter()
1489 .map(|n| n.get_content().chars().next().unwrap_or('?'))
1490 .collect();
1491 if initials.len() > 3 {
1492 format!("{}+", initials[..3].iter().collect::<String>())
1493 } else {
1494 initials.iter().collect::<String>()
1495 }
1496 } else if !surnames.is_empty() {
1497 let text = surnames[0].get_content();
1498 substr(&text, 0, 3).to_uppercase()
1499 } else {
1500 entry
1501 .bib_key
1502 .chars()
1503 .take(3)
1504 .collect::<String>()
1505 .to_uppercase()
1506 }
1507 }
1508
1509 fn format_blocks(
1513 &self,
1514 doc: &PostDocument,
1515 entry: &BibEntryData,
1516 bibentry: &Node,
1517 skip_first: bool,
1518 drop_first_year: bool,
1519 dropped_year: &mut Option<String>,
1520 ) -> Vec<NodeData> {
1521 let format_type = entry.format_type();
1522 let block_specs = get_fmt_spec(format_type);
1523 let mut blocks = Vec::new();
1524 let mut year_left_out: Option<String> = None;
1525
1526 for (i, block_spec) in block_specs.iter().enumerate() {
1527 if skip_first && i == 0 {
1528 continue;
1529 }
1530
1531 let mut items: Vec<NodeData> = Vec::new();
1532 for field_spec in block_spec {
1533 if drop_first_year && i == 0 && field_spec.class == "year" {
1541 let nodes = PostDocument::findnodes_foreign(
1542 field_spec.xpath.trim_start_matches('!').trim(),
1543 bibentry,
1544 );
1545 if !nodes.is_empty() {
1546 year_left_out = Some(node_data_text(&apply_formatter(
1547 doc,
1548 field_spec.formatter,
1549 &nodes,
1550 )));
1551 }
1552 continue;
1553 }
1554 let (nodes_found, negated) = {
1555 let xpath = field_spec.xpath.trim_start_matches('!').trim();
1556 let negated = field_spec.xpath.starts_with('!');
1557 if xpath == "true" {
1558 (true, false)
1559 } else {
1560 let found = !PostDocument::findnodes_foreign(xpath, bibentry).is_empty();
1561 (found, negated)
1562 }
1563 };
1564
1565 if field_spec.xpath != "true" {
1567 if negated {
1568 if nodes_found {
1569 continue;
1570 }
1571 } else {
1572 if !nodes_found {
1573 continue;
1574 }
1575 }
1576 }
1577
1578 if !field_spec.punct.is_empty() && !items.is_empty() {
1580 push_unit_text(&mut items, field_spec.punct);
1581 }
1582 if !field_spec.pre.is_empty() {
1584 items.push(NodeData::Text(field_spec.pre.to_string()));
1585 }
1586 if !field_spec.class.is_empty() {
1588 let xpath = field_spec.xpath.trim_start_matches('!').trim();
1589 let content = if xpath == "true" {
1590 Vec::new()
1591 } else {
1592 let nodes = PostDocument::findnodes_foreign(xpath, bibentry);
1593 apply_formatter(doc, field_spec.formatter, &nodes)
1594 };
1595 if !content.is_empty() {
1596 items.push(NodeData::Element {
1597 tag: "ltx:text".to_string(),
1598 attributes: Some(HashMap::from_iter([(
1599 "class".to_string(),
1600 format!("ltx_bib_{}", field_spec.class),
1601 )])),
1602 children: content,
1603 });
1604 }
1605 }
1606 if !field_spec.post.is_empty() {
1608 push_unit_text(&mut items, field_spec.post);
1609 }
1610 }
1611
1612 if !items.is_empty() {
1613 blocks.push(make_bibblock("", &items));
1614 if dropped_year.is_none()
1617 && items
1618 .iter()
1619 .any(|item| matches!(item, NodeData::Element { .. }))
1620 {
1621 *dropped_year = year_left_out.take();
1622 }
1623 }
1624 }
1625
1626 blocks
1632 }
1633}
1634
1635impl Processor for MakeBibliography {
1636 fn get_name(&self) -> &str { &self.name }
1637
1638 fn to_process(&self, doc: &PostDocument) -> Vec<Node> { doc.findnodes("//ltx:bibliography") }
1639
1640 fn process(&mut self, mut doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
1641 for mut entry in doc.findnodes("//ltx:bibentry[@xml:id]") {
1651 doc.release_id(&mut entry);
1652 }
1653 for bib in &nodes {
1654 let biblatex = bib
1656 .get_attribute("bibstyle")
1657 .is_some_and(|style| style.starts_with("biblatex"));
1658 BIBLATEX_BIBLIOGRAPHY.with(|flag| flag.set(biblatex));
1659 if !doc.findnodes_at(".//ltx:bibitem", Some(bib)).is_empty() {
1661 continue;
1662 }
1663
1664 let citestyle_str = bib
1674 .get_attribute("citestyle")
1675 .filter(|s| !s.is_empty())
1676 .unwrap_or_else(|| "numbers".to_string());
1677 let style = match citestyle_str.as_str() {
1687 "numbers" => CitationStyle::Numbers,
1688 "AY" => CitationStyle::Alpha,
1689 _ => CitationStyle::AuthorYear,
1690 };
1691
1692 let (mut entries, _bib_docs) = self.get_bib_entries(&doc, bib);
1694 if entries.is_empty() {
1695 Info!(
1696 "bibliography",
1697 "empty",
1698 "MakeBibliography: no entries to process"
1699 );
1700 continue;
1701 }
1702
1703 let bib_id = crate::document::get_xml_id(bib)
1707 .or_else(|| {
1708 doc
1709 .get_document_element()
1710 .as_ref()
1711 .and_then(crate::document::get_xml_id)
1712 })
1713 .unwrap_or_else(|| "bib".to_string());
1714
1715 let mut number = 0u32;
1731 let mut shown = 0u32;
1733
1734 let is_numeric = bib
1750 .get_attribute("citestyle")
1751 .as_deref()
1752 .map(|s| s.is_empty() || s == "numbers")
1753 .unwrap_or(true);
1754 let unsorted_style = bib.with_attribute(c"sort", |v| v == "false") == Some(true);
1755 let cite_order = (is_numeric && unsorted_style).then(|| citation_order(&doc));
1756 let cite_order = given_listing(&doc, bib)
1759 .or_else(|| inline_listing(&doc, bib))
1760 .map(|listing| {
1761 let mut order: HashMap<String, usize> = HashMap::default();
1762 for key in listing {
1763 let next = order.len();
1764 order.entry(key.to_lowercase()).or_insert(next);
1765 }
1766 order
1767 })
1768 .or(cite_order);
1769 let prints_urls = bib
1770 .get_attribute("bibstyle")
1771 .as_deref()
1772 .is_some_and(style_prints_urls);
1773 URLS_AS_TEXT.with(|flag| flag.set(prints_urls));
1774 let given_names = bib
1775 .get_attribute("bibstyle")
1776 .map_or(GivenNameForm::Initials, |style| {
1777 style_given_name_form(&style, doc.get_search_paths())
1778 });
1779 GIVEN_NAME_FORM.with(|form| form.set(given_names));
1780 let period_rule = PeriodRule::of_style(bib.get_attribute("bibstyle").as_deref());
1781 PERIOD_RULE.with(|rule| rule.set(period_rule));
1782
1783 if self.split {
1784 let mut by_initial: HashMap<String, Vec<String>> = HashMap::default();
1786 for (key, entry) in &entries {
1787 by_initial
1788 .entry(entry.initial.clone())
1789 .or_default()
1790 .push(key.clone());
1791 }
1792 let mut initials: Vec<String> = by_initial.keys().cloned().collect();
1793 initials.sort();
1794 for group in by_initial.values_mut() {
1795 unisort(group);
1796 }
1797 for initial in &initials {
1798 for key in &by_initial[initial] {
1806 debug_assert!(entries.contains_key(key), "grouped key {key} left entries");
1807 if let Some(entry) = entries.get_mut(key) {
1808 number_entry(entry, &mut number, &mut shown, &style);
1809 }
1810 }
1811 let subset: HashMap<String, BibEntryData> = by_initial[initial]
1813 .iter()
1814 .filter_map(|k| entries.get(k).map(|e| (k.clone(), clone_entry(e))))
1815 .collect();
1816 let biblist = self.make_bibliography_list(&doc, &bib_id, Some(initial), &subset, &style);
1817 let mut bib_mut = bib.clone();
1818 doc.add_nodes(&mut bib_mut, &[biblist]);
1819 }
1820 } else {
1821 let sorted_keys = order_entry_keys(&entries, cite_order.as_ref());
1822 for key in &sorted_keys {
1823 debug_assert!(entries.contains_key(key), "sorted key {key} left entries");
1824 if let Some(entry) = entries.get_mut(key) {
1825 number_entry(entry, &mut number, &mut shown, &style);
1826 }
1827 }
1828 let biblist = self.make_bibliography_list(&doc, &bib_id, None, &entries, &style);
1829 let mut bib_mut = bib.clone();
1830 doc.add_nodes(&mut bib_mut, &[biblist]);
1831 }
1832
1833 Info!(
1834 "bibliography",
1835 "formatted",
1836 "MakeBibliography: formatted {} entries",
1837 entries.len()
1838 );
1839
1840 let lists_str = bib
1844 .get_attribute("lists")
1845 .unwrap_or_else(|| "bibliography".to_string());
1846 for entry in entries.values() {
1847 let cited_key = entry.cited_key.as_deref().unwrap_or(&entry.bib_key);
1848 debug_assert!(
1850 entry.bibentry.is_some(),
1851 "included entry {} has no bibentry",
1852 entry.bib_key
1853 );
1854 let Some(bibentry) = entry.bibentry.as_ref() else {
1855 continue;
1856 };
1857 let bibitem_id = bibitem_id(&bib_id, entry, bibentry);
1858
1859 for list in lists_str.split_whitespace() {
1861 let label_key = format!("BIBLABEL:{}:{}", list, cited_key);
1862 self.db.register(&label_key, vec![(
1863 "id",
1864 crate::object_db::Value::from(bibitem_id.as_str()),
1865 )]);
1866 }
1867
1868 let location = doc.site_relative_destination().unwrap_or_default();
1873 let mut values = vec![
1874 ("type", crate::object_db::Value::from("ltx:bibitem")),
1875 ("location", crate::object_db::Value::from(location.as_str())),
1876 ("fragid", crate::object_db::Value::from(bibitem_id.as_str())),
1877 ];
1878 if entry_given_label(entry, &style).is_none() {
1880 values.push((
1881 "number",
1882 crate::object_db::Value::from(entry.shown_number().to_string().as_str()),
1883 ));
1884 }
1885 self.db.register(&format!("ID:{}", bibitem_id), values);
1886 }
1887 }
1888
1889 let location = doc.site_relative_destination().unwrap_or_default();
1914 for node in doc.findnodes("//ltx:bibliography//*[@xml:id]") {
1915 let Some(id) = crate::document::get_xml_id(&node) else {
1916 continue;
1917 };
1918 let key = format!("ID:{}", id);
1919 let qname = doc
1920 .get_qname(&node)
1921 .unwrap_or_else(|| "ltx:text".to_string());
1922 if qname == "ltx:bibitem" {
1923 let props = crate::scan::bibitem_tag_props(&doc, &node);
1933 let copy = if self.db.lookup("FULLENTRY").is_some() {
1937 self.db.adopt_xml(&node)
1938 } else {
1939 None
1940 };
1941 let year = self.dropped_years.borrow_mut().remove(&id);
1942 if !props.is_empty() || copy.is_some() {
1943 let entry = self.db.register(&key, vec![]);
1944 for (k, v) in props {
1945 entry.set_value(&k, v);
1946 }
1947 if let Some(copy) = copy {
1948 entry.set_value("fullentry", copy);
1949 }
1950 if let Some(year) = year {
1951 entry.set_value("droppedyear", crate::object_db::Value::from(year.as_str()));
1952 }
1953 }
1954 } else if self.db.lookup(&key).is_none() {
1955 self.db.register(&key, vec![
1959 ("type", crate::object_db::Value::from(qname.as_str())),
1960 ("location", crate::object_db::Value::from(location.as_str())),
1961 ("fragid", crate::object_db::Value::from(id.as_str())),
1962 ]);
1963 }
1964 }
1965
1966 let bibentries = doc.findnodes("//ltx:bibentry");
1968 if !bibentries.is_empty() {
1969 doc.remove_nodes(&bibentries);
1970 }
1971
1972 let biblists = doc.findnodes("//ltx:biblist");
1974 let empty_lists: Vec<Node> = biblists
1975 .into_iter()
1976 .filter(|n| {
1977 n.get_first_child()
1978 .map(|c| {
1979 let mut has_element = false;
1980 let mut current = Some(c);
1981 while let Some(ref node) = current {
1982 if node.get_type() == Some(libxml::tree::NodeType::ElementNode) {
1983 has_element = true;
1984 break;
1985 }
1986 current = node.get_next_sibling();
1987 }
1988 !has_element
1989 })
1990 .unwrap_or(true)
1991 })
1992 .collect();
1993 if !empty_lists.is_empty() {
1994 doc.remove_nodes(&empty_lists);
1995 }
1996
1997 Ok(vec![doc])
1998 }
1999}
2000
2001#[derive(Clone)]
2010struct FieldSpec {
2011 xpath: &'static str,
2013 punct: &'static str,
2015 pre: &'static str,
2017 class: &'static str,
2019 formatter: Formatter,
2021 post: &'static str,
2023}
2024
2025#[derive(Clone, Copy)]
2026enum Formatter {
2027 Any,
2028 Units,
2038 Authors,
2039 EditorsA,
2040 EditorsB,
2041 OtherNames,
2042 Year,
2043 Type,
2044 Title,
2045 ThesisType,
2046 Edition,
2047 Pages,
2048 CrossRef,
2049 Links,
2050 None,
2051}
2052
2053fn get_fmt_spec(format_type: &str) -> Vec<Vec<FieldSpec>> {
2055 let meta_block: Vec<Vec<FieldSpec>> = vec![
2056 vec![FieldSpec {
2061 xpath: "ltx:bib-name[@role='translator']",
2062 punct: "",
2063 pre: "Translated by ",
2064 class: "translator",
2065 formatter: Formatter::Authors,
2066 post: "",
2067 }],
2068 vec![FieldSpec {
2073 xpath: "ltx:bib-name",
2074 punct: "",
2075 pre: "",
2076 class: "editor",
2077 formatter: Formatter::OtherNames,
2078 post: "",
2079 }],
2080 vec![
2084 FieldSpec {
2085 xpath: "ltx:bib-related[@type='event']/ltx:bib-title",
2086 punct: "",
2087 pre: "",
2088 class: "event",
2089 formatter: Formatter::Title,
2090 post: "",
2091 },
2092 FieldSpec {
2093 xpath: "ltx:bib-related[@type='event']/ltx:bib-subtitle",
2094 punct: ". ",
2095 pre: "",
2096 class: "subtitle",
2097 formatter: Formatter::Units,
2098 post: "",
2099 },
2100 FieldSpec {
2101 xpath: "ltx:bib-related[@type='event']/ltx:bib-place",
2102 punct: " ",
2103 pre: "(",
2104 class: "place",
2105 formatter: Formatter::Any,
2106 post: ")",
2107 },
2108 FieldSpec {
2109 xpath: "ltx:bib-related[@type='event']/ltx:bib-date",
2110 punct: ", ",
2111 pre: "",
2112 class: "date",
2113 formatter: Formatter::Any,
2114 post: "",
2115 },
2116 FieldSpec {
2117 xpath: "true",
2118 punct: ".",
2119 pre: "",
2120 class: "",
2121 formatter: Formatter::None,
2122 post: "",
2123 },
2124 ],
2125 vec![
2127 FieldSpec {
2128 xpath: "ltx:bib-related[@type='issue']/ltx:bib-title",
2129 punct: "",
2130 pre: "",
2131 class: "issuetitle",
2132 formatter: Formatter::Title,
2133 post: "",
2134 },
2135 FieldSpec {
2136 xpath: "ltx:bib-related[@type='issue']/ltx:bib-subtitle",
2137 punct: ". ",
2138 pre: "",
2139 class: "subtitle",
2140 formatter: Formatter::Units,
2141 post: "",
2142 },
2143 FieldSpec {
2144 xpath: "true",
2145 punct: ".",
2146 pre: "",
2147 class: "",
2148 formatter: Formatter::None,
2149 post: "",
2150 },
2151 ],
2152 vec![FieldSpec {
2159 xpath: "ltx:bib-note",
2160 punct: "",
2161 pre: "Note: ",
2162 class: "note",
2163 formatter: Formatter::Units,
2164 post: "",
2165 }],
2166 vec![FieldSpec {
2168 xpath: "ltx:bib-date[@role='accessed']",
2169 punct: "",
2170 pre: "Accessed: ",
2171 class: "accessed",
2172 formatter: Formatter::Any,
2173 post: "",
2174 }],
2175 vec![FieldSpec {
2176 xpath: "ltx:bib-links | ltx:bib-review | ltx:bib-identifier | ltx:bib-url",
2177 punct: "",
2178 pre: "External Links: ",
2179 class: "links",
2180 formatter: Formatter::Links,
2181 post: "",
2182 }],
2183 ];
2184
2185 let mut blocks = match format_type {
2186 "article" => vec![
2187 vec![
2189 FieldSpec {
2190 xpath: "ltx:bib-name[@role='author']",
2191 punct: "",
2192 pre: "",
2193 class: "author",
2194 formatter: Formatter::Authors,
2195 post: "",
2196 },
2197 FieldSpec {
2198 xpath: "ltx:bib-date[@role='publication']",
2199 punct: "",
2200 pre: "",
2201 class: "year",
2202 formatter: Formatter::Year,
2203 post: "",
2204 },
2205 ],
2206 vec![
2208 FieldSpec {
2209 xpath: "ltx:bib-title",
2210 punct: "",
2211 pre: "",
2212 class: "title",
2213 formatter: Formatter::Title,
2214 post: ".",
2215 },
2216 FieldSpec {
2217 xpath: "ltx:bib-subtitle",
2218 punct: " ",
2219 pre: "",
2220 class: "subtitle",
2221 formatter: Formatter::Units,
2222 post: ".",
2223 },
2224 ],
2225 vec![
2227 FieldSpec {
2228 xpath: "ltx:bib-part[@role='part']",
2229 punct: "",
2230 pre: "",
2231 class: "part",
2232 formatter: Formatter::Any,
2233 post: "",
2234 },
2235 FieldSpec {
2239 xpath: "ltx:bib-related[@type='journal']/ltx:bib-title",
2240 punct: ", ",
2241 pre: "",
2242 class: "journal",
2243 formatter: Formatter::Any,
2244 post: "",
2245 },
2246 FieldSpec {
2247 xpath: "ltx:bib-part[@role='volume']",
2248 punct: " ",
2249 pre: "",
2250 class: "volume",
2251 formatter: Formatter::Any,
2252 post: "",
2253 },
2254 FieldSpec {
2255 xpath: "ltx:bib-part[@role='number']",
2256 punct: " ",
2257 pre: "(",
2258 class: "number",
2259 formatter: Formatter::Any,
2260 post: ")",
2261 },
2262 FieldSpec {
2265 xpath: "ltx:bib-related/ltx:bib-related[@type='issue']/ltx:bib-title",
2266 punct: ": ",
2267 pre: "",
2268 class: "issuetitle",
2269 formatter: Formatter::Title,
2270 post: "",
2271 },
2272 FieldSpec {
2273 xpath: "ltx:bib-related/ltx:bib-related[@type='issue']/ltx:bib-subtitle",
2274 punct: ". ",
2275 pre: "",
2276 class: "subtitle",
2277 formatter: Formatter::Units,
2278 post: "",
2279 },
2280 FieldSpec {
2281 xpath: "ltx:bib-status",
2282 punct: ", ",
2283 pre: "(",
2284 class: "status",
2285 formatter: Formatter::Any,
2286 post: ")",
2287 },
2288 FieldSpec {
2289 xpath: "ltx:bib-part[@role='pages']",
2290 punct: ", ",
2291 pre: "",
2292 class: "pages",
2293 formatter: Formatter::Pages,
2294 post: "",
2295 },
2296 FieldSpec {
2297 xpath: "ltx:bib-language",
2298 punct: " ",
2299 pre: "(",
2300 class: "language",
2301 formatter: Formatter::Any,
2302 post: ")",
2303 },
2304 FieldSpec {
2305 xpath: "true",
2306 punct: ".",
2307 pre: "",
2308 class: "",
2309 formatter: Formatter::None,
2310 post: "",
2311 },
2312 ],
2313 ],
2314 "book" => vec![
2315 vec![
2316 FieldSpec {
2317 xpath: "ltx:bib-name[@role='author']",
2318 punct: "",
2319 pre: "",
2320 class: "author",
2321 formatter: Formatter::Authors,
2322 post: "",
2323 },
2324 FieldSpec {
2329 xpath: "ltx:bib-name[@role='editor']",
2330 punct: ", ",
2331 pre: "",
2332 class: "editor",
2333 formatter: Formatter::EditorsA,
2334 post: "",
2335 },
2336 FieldSpec {
2337 xpath: "ltx:bib-date[@role='publication']",
2338 punct: "",
2339 pre: "",
2340 class: "year",
2341 formatter: Formatter::Year,
2342 post: "",
2343 },
2344 ],
2345 vec![
2346 FieldSpec {
2347 xpath: "ltx:bib-title",
2348 punct: "",
2349 pre: "",
2350 class: "title",
2351 formatter: Formatter::Title,
2352 post: ".",
2353 },
2354 FieldSpec {
2355 xpath: "ltx:bib-subtitle",
2356 punct: " ",
2357 pre: "",
2358 class: "subtitle",
2359 formatter: Formatter::Units,
2360 post: ".",
2361 },
2362 ],
2363 vec![
2364 FieldSpec {
2365 xpath: "ltx:bib-type",
2366 punct: "",
2367 pre: "",
2368 class: "type",
2369 formatter: Formatter::Any,
2370 post: "",
2371 },
2372 FieldSpec {
2373 xpath: "ltx:bib-edition",
2374 punct: ", ",
2375 pre: "",
2376 class: "edition",
2377 formatter: Formatter::Edition,
2378 post: "",
2379 },
2380 FieldSpec {
2381 xpath: "ltx:bib-part[@role='series']",
2382 punct: ", ",
2383 pre: "",
2384 class: "series",
2385 formatter: Formatter::Any,
2386 post: "",
2387 },
2388 FieldSpec {
2389 xpath: "ltx:bib-part[@role='volume']",
2390 punct: ", ",
2391 pre: "Vol. ",
2392 class: "volume",
2393 formatter: Formatter::Any,
2394 post: "",
2395 },
2396 FieldSpec {
2397 xpath: "ltx:bib-part[@role='part']",
2398 punct: ", ",
2399 pre: "Part ",
2400 class: "part",
2401 formatter: Formatter::Any,
2402 post: "",
2403 },
2404 FieldSpec {
2405 xpath: "ltx:bib-publisher",
2406 punct: ", ",
2407 pre: " ",
2408 class: "publisher",
2409 formatter: Formatter::Any,
2410 post: "",
2411 },
2412 FieldSpec {
2413 xpath: "ltx:bib-organization",
2414 punct: ", ",
2415 pre: " ",
2416 class: "publisher",
2417 formatter: Formatter::Any,
2418 post: "",
2419 },
2420 FieldSpec {
2421 xpath: "ltx:bib-place",
2422 punct: ", ",
2423 pre: "",
2424 class: "place",
2425 formatter: Formatter::Any,
2426 post: "",
2427 },
2428 FieldSpec {
2429 xpath: "ltx:bib-status",
2430 punct: " ",
2431 pre: "(",
2432 class: "status",
2433 formatter: Formatter::Any,
2434 post: ")",
2435 },
2436 FieldSpec {
2437 xpath: "ltx:bib-language",
2438 punct: " ",
2439 pre: "(",
2440 class: "language",
2441 formatter: Formatter::Any,
2442 post: ")",
2443 },
2444 FieldSpec {
2445 xpath: "true",
2446 punct: ".",
2447 pre: "",
2448 class: "",
2449 formatter: Formatter::None,
2450 post: "",
2451 },
2452 ],
2453 ],
2454 "incollection" => vec![
2455 vec![
2456 FieldSpec {
2457 xpath: "ltx:bib-name[@role='author']",
2458 punct: "",
2459 pre: "",
2460 class: "author",
2461 formatter: Formatter::Authors,
2462 post: "",
2463 },
2464 FieldSpec {
2465 xpath: "ltx:bib-date[@role='publication']",
2466 punct: "",
2467 pre: "",
2468 class: "year",
2469 formatter: Formatter::Year,
2470 post: "",
2471 },
2472 ],
2473 vec![
2474 FieldSpec {
2475 xpath: "ltx:bib-title",
2476 punct: "",
2477 pre: "",
2478 class: "title",
2479 formatter: Formatter::Title,
2480 post: ".",
2481 },
2482 FieldSpec {
2483 xpath: "ltx:bib-subtitle",
2484 punct: " ",
2485 pre: "",
2486 class: "subtitle",
2487 formatter: Formatter::Units,
2488 post: ".",
2489 },
2490 ],
2491 vec![
2492 FieldSpec {
2493 xpath: "ltx:bib-type",
2494 punct: "",
2495 pre: "",
2496 class: "type",
2497 formatter: Formatter::Any,
2498 post: "",
2499 },
2500 FieldSpec {
2501 xpath: "ltx:bib-related[@bibrefs]",
2502 punct: " ",
2503 pre: "See ",
2504 class: "crossref",
2505 formatter: Formatter::CrossRef,
2506 post: ",",
2507 },
2508 FieldSpec {
2515 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-title",
2516 punct: " ",
2517 pre: "In ",
2518 class: "",
2519 formatter: Formatter::None,
2520 post: "",
2521 },
2522 FieldSpec {
2523 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@role='host']/ltx:bib-title",
2524 punct: "",
2525 pre: "",
2526 class: "maintitle",
2527 formatter: Formatter::Title,
2528 post: ". ",
2529 },
2530 FieldSpec {
2531 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@role='host']/ltx:bib-subtitle",
2532 punct: "",
2533 pre: "",
2534 class: "subtitle",
2535 formatter: Formatter::Units,
2536 post: ". ",
2537 },
2538 FieldSpec {
2539 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-title",
2540 punct: "",
2541 pre: "",
2542 class: "inbook",
2543 formatter: Formatter::Title,
2544 post: ",",
2545 },
2546 FieldSpec {
2549 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-subtitle",
2550 punct: " ",
2551 pre: "",
2552 class: "subtitle",
2553 formatter: Formatter::Units,
2554 post: ",",
2555 },
2556 FieldSpec {
2561 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@type='event']/ltx:bib-title",
2562 punct: " ",
2563 pre: "",
2564 class: "event",
2565 formatter: Formatter::Title,
2566 post: "",
2567 },
2568 FieldSpec {
2569 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@type='event']/ltx:bib-subtitle",
2570 punct: ". ",
2571 pre: "",
2572 class: "subtitle",
2573 formatter: Formatter::Units,
2574 post: "",
2575 },
2576 FieldSpec {
2577 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@type='event']/ltx:bib-place",
2578 punct: " ",
2579 pre: "(",
2580 class: "place",
2581 formatter: Formatter::Any,
2582 post: ")",
2583 },
2584 FieldSpec {
2585 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-related[@type='event']/ltx:bib-date",
2586 punct: ", ",
2587 pre: "",
2588 class: "date",
2589 formatter: Formatter::Any,
2590 post: "",
2591 },
2592 FieldSpec {
2593 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-name[@role='editor']",
2594 punct: " ",
2595 pre: " ",
2596 class: "editor",
2597 formatter: Formatter::EditorsA,
2598 post: ",",
2599 },
2600 ],
2601 vec![
2602 FieldSpec {
2608 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-edition",
2609 punct: "",
2610 pre: "",
2611 class: "edition",
2612 formatter: Formatter::Edition,
2613 post: "",
2614 },
2615 FieldSpec {
2616 xpath: "ltx:bib-edition",
2617 punct: "",
2618 pre: "",
2619 class: "edition",
2620 formatter: Formatter::Edition,
2621 post: "",
2622 },
2623 FieldSpec {
2624 xpath: "ltx:bib-name[@role='editor']",
2625 punct: ", ",
2626 pre: "",
2627 class: "editor",
2628 formatter: Formatter::EditorsB,
2629 post: "",
2630 },
2631 FieldSpec {
2632 xpath: "ltx:bib-related/ltx:bib-part[@role='series']",
2633 punct: ", ",
2634 pre: "",
2635 class: "series",
2636 formatter: Formatter::Any,
2637 post: "",
2638 },
2639 FieldSpec {
2640 xpath: "ltx:bib-related/ltx:bib-part[@role='volume']",
2641 punct: ", ",
2642 pre: "Vol. ",
2643 class: "volume",
2644 formatter: Formatter::Any,
2645 post: "",
2646 },
2647 FieldSpec {
2648 xpath: "ltx:bib-related/ltx:bib-part[@role='part']",
2649 punct: ", ",
2650 pre: "Part ",
2651 class: "part",
2652 formatter: Formatter::Any,
2653 post: "",
2654 },
2655 FieldSpec {
2656 xpath: "ltx:bib-publisher",
2657 punct: ", ",
2658 pre: " ",
2659 class: "publisher",
2660 formatter: Formatter::Any,
2661 post: "",
2662 },
2663 FieldSpec {
2673 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-publisher",
2674 punct: ", ",
2675 pre: " ",
2676 class: "publisher",
2677 formatter: Formatter::Any,
2678 post: "",
2679 },
2680 FieldSpec {
2681 xpath: "ltx:bib-organization",
2682 punct: ", ",
2683 pre: "",
2684 class: "publisher",
2685 formatter: Formatter::Any,
2686 post: "",
2687 },
2688 FieldSpec {
2689 xpath: "ltx:bib-place",
2690 punct: ", ",
2691 pre: "",
2692 class: "place",
2693 formatter: Formatter::Any,
2694 post: "",
2695 },
2696 FieldSpec {
2697 xpath: "ltx:bib-related[@type][not(../ltx:bib-related[@bibrefs])]/ltx:bib-place",
2698 punct: ", ",
2699 pre: "",
2700 class: "place",
2701 formatter: Formatter::Any,
2702 post: "",
2703 },
2704 FieldSpec {
2705 xpath: "ltx:bib-part[@role='pages']",
2706 punct: ", ",
2707 pre: "",
2708 class: "pages",
2709 formatter: Formatter::Pages,
2710 post: "",
2711 },
2712 FieldSpec {
2713 xpath: "ltx:bib-status",
2714 punct: " ",
2715 pre: "(",
2716 class: "status",
2717 formatter: Formatter::Any,
2718 post: ")",
2719 },
2720 FieldSpec {
2721 xpath: "ltx:bib-language",
2722 punct: " ",
2723 pre: "(",
2724 class: "language",
2725 formatter: Formatter::Any,
2726 post: ")",
2727 },
2728 FieldSpec {
2729 xpath: "true",
2730 punct: ".",
2731 pre: "",
2732 class: "",
2733 formatter: Formatter::None,
2734 post: "",
2735 },
2736 ],
2737 ],
2738 "report" => vec![
2739 vec![
2740 FieldSpec {
2741 xpath: "ltx:bib-name[@role='author']",
2742 punct: "",
2743 pre: "",
2744 class: "author",
2745 formatter: Formatter::Authors,
2746 post: "",
2747 },
2748 FieldSpec {
2753 xpath: "ltx:bib-name[@role='editor']",
2754 punct: ", ",
2755 pre: "",
2756 class: "editor",
2757 formatter: Formatter::EditorsA,
2758 post: "",
2759 },
2760 FieldSpec {
2761 xpath: "ltx:bib-date[@role='publication']",
2762 punct: "",
2763 pre: "",
2764 class: "year",
2765 formatter: Formatter::Year,
2766 post: "",
2767 },
2768 ],
2769 vec![
2770 FieldSpec {
2771 xpath: "ltx:bib-title",
2772 punct: "",
2773 pre: "",
2774 class: "title",
2775 formatter: Formatter::Title,
2776 post: ".",
2777 },
2778 FieldSpec {
2779 xpath: "ltx:bib-subtitle",
2780 punct: " ",
2781 pre: "",
2782 class: "subtitle",
2783 formatter: Formatter::Units,
2784 post: ".",
2785 },
2786 ],
2787 vec![FieldSpec {
2788 xpath: "ltx:bib-type",
2789 punct: "",
2790 pre: "",
2791 class: "type",
2792 formatter: Formatter::Any,
2793 post: "",
2794 }],
2795 vec![
2796 FieldSpec {
2797 xpath: "ltx:bib-part[@role='number']",
2798 punct: "",
2799 pre: "Technical Report ",
2800 class: "number",
2801 formatter: Formatter::Any,
2802 post: "",
2803 },
2804 FieldSpec {
2805 xpath: "ltx:bib-part[@role='series']",
2806 punct: ", ",
2807 pre: "",
2808 class: "series",
2809 formatter: Formatter::Any,
2810 post: "",
2811 },
2812 FieldSpec {
2813 xpath: "ltx:bib-part[@role='volume']",
2814 punct: ", ",
2815 pre: "Vol. ",
2816 class: "volume",
2817 formatter: Formatter::Any,
2818 post: "",
2819 },
2820 FieldSpec {
2821 xpath: "ltx:bib-part[@role='part']",
2822 punct: ", ",
2823 pre: "Part ",
2824 class: "part",
2825 formatter: Formatter::Any,
2826 post: "",
2827 },
2828 FieldSpec {
2829 xpath: "ltx:bib-publisher",
2830 punct: ", ",
2831 pre: " ",
2832 class: "publisher",
2833 formatter: Formatter::Any,
2834 post: "",
2835 },
2836 FieldSpec {
2837 xpath: "ltx:bib-organization",
2838 punct: ", ",
2839 pre: " ",
2840 class: "publisher",
2841 formatter: Formatter::Any,
2842 post: "",
2843 },
2844 FieldSpec {
2845 xpath: "ltx:bib-place",
2846 punct: ", ",
2847 pre: " ",
2848 class: "place",
2849 formatter: Formatter::Any,
2850 post: "",
2851 },
2852 FieldSpec {
2853 xpath: "ltx:bib-status",
2854 punct: ", ",
2855 pre: "(",
2856 class: "status",
2857 formatter: Formatter::Any,
2858 post: ")",
2859 },
2860 FieldSpec {
2861 xpath: "ltx:bib-language",
2862 punct: " ",
2863 pre: "(",
2864 class: "language",
2865 formatter: Formatter::Any,
2866 post: ")",
2867 },
2868 FieldSpec {
2869 xpath: "true",
2870 punct: ".",
2871 pre: "",
2872 class: "",
2873 formatter: Formatter::None,
2874 post: "",
2875 },
2876 ],
2877 ],
2878 "thesis" => vec![
2879 vec![
2880 FieldSpec {
2881 xpath: "ltx:bib-name[@role='author']",
2882 punct: "",
2883 pre: "",
2884 class: "author",
2885 formatter: Formatter::Authors,
2886 post: "",
2887 },
2888 FieldSpec {
2893 xpath: "ltx:bib-name[@role='editor']",
2894 punct: ", ",
2895 pre: "",
2896 class: "editor",
2897 formatter: Formatter::EditorsA,
2898 post: "",
2899 },
2900 FieldSpec {
2901 xpath: "ltx:bib-date[@role='publication']",
2902 punct: "",
2903 pre: "",
2904 class: "year",
2905 formatter: Formatter::Year,
2906 post: "",
2907 },
2908 ],
2909 vec![
2910 FieldSpec {
2911 xpath: "ltx:bib-title",
2912 punct: "",
2913 pre: "",
2914 class: "title",
2915 formatter: Formatter::Title,
2916 post: ".",
2917 },
2918 FieldSpec {
2919 xpath: "ltx:bib-subtitle",
2920 punct: " ",
2921 pre: "",
2922 class: "subtitle",
2923 formatter: Formatter::Units,
2924 post: ".",
2925 },
2926 ],
2927 vec![
2928 FieldSpec {
2929 xpath: "ltx:bib-type",
2930 punct: " ",
2931 pre: "",
2932 class: "type",
2933 formatter: Formatter::ThesisType,
2934 post: "",
2935 },
2936 FieldSpec {
2937 xpath: "ltx:bib-part[@role='part']",
2938 punct: ", ",
2939 pre: "Part ",
2940 class: "part",
2941 formatter: Formatter::Any,
2942 post: "",
2943 },
2944 FieldSpec {
2945 xpath: "ltx:bib-publisher",
2946 punct: ", ",
2947 pre: "",
2948 class: "publisher",
2949 formatter: Formatter::Any,
2950 post: "",
2951 },
2952 FieldSpec {
2953 xpath: "ltx:bib-organization",
2954 punct: ", ",
2955 pre: "",
2956 class: "publisher",
2957 formatter: Formatter::Any,
2958 post: "",
2959 },
2960 FieldSpec {
2961 xpath: "ltx:bib-place",
2962 punct: ", ",
2963 pre: "",
2964 class: "place",
2965 formatter: Formatter::Any,
2966 post: "",
2967 },
2968 FieldSpec {
2969 xpath: "ltx:bib-status",
2970 punct: ", ",
2971 pre: "(",
2972 class: "status",
2973 formatter: Formatter::Any,
2974 post: ")",
2975 },
2976 FieldSpec {
2977 xpath: "ltx:bib-language",
2978 punct: ", ",
2979 pre: "(",
2980 class: "language",
2981 formatter: Formatter::Any,
2982 post: ")",
2983 },
2984 FieldSpec {
2985 xpath: "true",
2986 punct: ".",
2987 pre: "",
2988 class: "",
2989 formatter: Formatter::None,
2990 post: "",
2991 },
2992 ],
2993 ],
2994 "website" => vec![
2995 vec![
2996 FieldSpec {
2997 xpath: "ltx:bib-name[@role='author']",
2998 punct: "",
2999 pre: "",
3000 class: "author",
3001 formatter: Formatter::Authors,
3002 post: "",
3003 },
3004 FieldSpec {
3009 xpath: "ltx:bib-name[@role='editor']",
3010 punct: ", ",
3011 pre: "",
3012 class: "editor",
3013 formatter: Formatter::EditorsA,
3014 post: "",
3015 },
3016 FieldSpec {
3017 xpath: "ltx:bib-date[@role='publication']",
3018 punct: "",
3019 pre: "",
3020 class: "year",
3021 formatter: Formatter::Year,
3022 post: "",
3023 },
3024 FieldSpec {
3032 xpath: "ltx:bib-title",
3033 punct: " ",
3034 pre: "",
3035 class: "title",
3036 formatter: Formatter::Any,
3037 post: "",
3038 },
3039 FieldSpec {
3040 xpath: "ltx:bib-subtitle",
3041 punct: " ",
3042 pre: "",
3043 class: "subtitle",
3044 formatter: Formatter::Units,
3045 post: "",
3046 },
3047 FieldSpec {
3048 xpath: "ltx:bib-type",
3049 punct: " ",
3050 pre: "",
3051 class: "type",
3052 formatter: Formatter::Any,
3053 post: "",
3054 },
3055 FieldSpec {
3056 xpath: "! ltx:bib-type",
3057 punct: " ",
3058 pre: "",
3059 class: "type",
3060 formatter: Formatter::None,
3061 post: "(Website)",
3062 },
3063 ],
3064 vec![
3065 FieldSpec {
3066 xpath: "ltx:bib-organization",
3067 punct: ", ",
3068 pre: " ",
3069 class: "publisher",
3070 formatter: Formatter::Any,
3071 post: "",
3072 },
3073 FieldSpec {
3074 xpath: "ltx:bib-place",
3075 punct: ", ",
3076 pre: "",
3077 class: "place",
3078 formatter: Formatter::Any,
3079 post: "",
3080 },
3081 FieldSpec {
3082 xpath: "true",
3083 punct: ".",
3084 pre: "",
3085 class: "",
3086 formatter: Formatter::None,
3087 post: "",
3088 },
3089 ],
3090 ],
3091 "software" => vec![
3092 vec![
3093 FieldSpec {
3094 xpath: "ltx:bib-key",
3095 punct: "",
3096 pre: "",
3097 class: "key",
3098 formatter: Formatter::Any,
3099 post: "",
3100 },
3101 FieldSpec {
3104 xpath: "ltx:bib-type",
3105 punct: " ",
3106 pre: "",
3107 class: "type",
3108 formatter: Formatter::Type,
3109 post: "",
3110 },
3111 ],
3112 vec![
3113 FieldSpec {
3114 xpath: "ltx:bib-title",
3115 punct: "",
3116 pre: "",
3117 class: "title",
3118 formatter: Formatter::Any,
3119 post: "",
3120 },
3121 FieldSpec {
3122 xpath: "ltx:bib-subtitle",
3123 punct: " ",
3124 pre: "",
3125 class: "subtitle",
3126 formatter: Formatter::Units,
3127 post: "",
3128 },
3129 ],
3130 vec![
3131 FieldSpec {
3132 xpath: "ltx:bib-organization",
3133 punct: ", ",
3134 pre: " ",
3135 class: "publisher",
3136 formatter: Formatter::Any,
3137 post: "",
3138 },
3139 FieldSpec {
3140 xpath: "ltx:bib-place",
3141 punct: ", ",
3142 pre: "",
3143 class: "place",
3144 formatter: Formatter::Any,
3145 post: "",
3146 },
3147 FieldSpec {
3148 xpath: "true",
3149 punct: ".",
3150 pre: "",
3151 class: "",
3152 formatter: Formatter::None,
3153 post: "",
3154 },
3155 ],
3156 ],
3157 _ => vec![
3158 vec![
3160 FieldSpec {
3161 xpath: "ltx:bib-name[@role='author']",
3162 punct: "",
3163 pre: "",
3164 class: "author",
3165 formatter: Formatter::Authors,
3166 post: "",
3167 },
3168 FieldSpec {
3169 xpath: "ltx:bib-date[@role='publication']",
3170 punct: "",
3171 pre: "",
3172 class: "year",
3173 formatter: Formatter::Year,
3174 post: "",
3175 },
3176 ],
3177 vec![
3178 FieldSpec {
3179 xpath: "ltx:bib-title",
3180 punct: "",
3181 pre: "",
3182 class: "title",
3183 formatter: Formatter::Title,
3184 post: ".",
3185 },
3186 FieldSpec {
3187 xpath: "ltx:bib-subtitle",
3188 punct: " ",
3189 pre: "",
3190 class: "subtitle",
3191 formatter: Formatter::Units,
3192 post: ".",
3193 },
3194 ],
3195 ],
3196 };
3197 for block in &mut blocks {
3202 if let Some(at) = block.iter().position(|spec| spec.xpath == "ltx:bib-title") {
3203 let main_title = [
3204 FieldSpec {
3205 xpath: "ltx:bib-related[@type='mvbook']/ltx:bib-title",
3206 punct: "",
3207 pre: "",
3208 class: "maintitle",
3209 formatter: Formatter::Title,
3210 post: ". ",
3211 },
3212 FieldSpec {
3213 xpath: "ltx:bib-related[@type='mvbook']/ltx:bib-subtitle",
3214 punct: "",
3215 pre: "",
3216 class: "subtitle",
3217 formatter: Formatter::Units,
3218 post: ". ",
3219 },
3220 ];
3221 block.splice(at..at, main_title);
3222 break;
3223 }
3224 }
3225 if format_type == "article"
3231 && is_biblatex_bibliography()
3232 && let Some(block) = blocks.iter_mut().find(|block| {
3233 block
3234 .iter()
3235 .any(|f| f.xpath == "ltx:bib-part[@role='pages']")
3236 })
3237 && let Some(at) = block
3238 .iter()
3239 .position(|f| f.xpath == "ltx:bib-part[@role='pages']")
3240 {
3241 block.insert(at, FieldSpec {
3242 xpath: "ltx:bib-name[@role='editor']",
3243 punct: ". ",
3244 pre: "Edited by ",
3245 class: "editor",
3246 formatter: Formatter::Authors,
3247 post: "",
3248 });
3249 }
3250 blocks.extend(meta_block);
3251 blocks
3252}
3253
3254fn field_content(node: &Node) -> Vec<NodeData> {
3273 let mut children = Vec::new();
3274 let mut child = node.get_first_child();
3275 let mut has_element = false;
3276 while let Some(n) = child {
3277 has_element |= n.get_type() == Some(libxml::tree::NodeType::ElementNode);
3278 child = n.get_next_sibling();
3279 children.push(n);
3280 }
3281 if has_element {
3282 children.into_iter().map(NodeData::XmlNode).collect()
3283 } else {
3284 vec![NodeData::Text(node.get_content())]
3285 }
3286}
3287
3288fn ends_with_punctuation(text: &str) -> bool {
3296 text
3297 .trim_end()
3298 .trim_end_matches([')', ']', '>', '\'', '`', '’', '”', '"'])
3299 .ends_with(['.', '?', '!', ',', ';', ':', '…'])
3300}
3301
3302fn join_fields(nodes: &[Node], separator: &str) -> Vec<NodeData> {
3310 let space = separator.trim_start_matches(|c: char| !c.is_whitespace());
3311 let mut result = Vec::new();
3312 let mut previous: Option<bool> = None;
3314 for node in nodes {
3315 if node.get_content().trim().is_empty() && node.get_first_element_child().is_none() {
3316 continue;
3317 }
3318 if let Some(ends_in_mark) = previous {
3319 let joint = if ends_in_mark { space } else { separator };
3320 result.push(NodeData::Text(joint.to_string()));
3321 }
3322 result.extend(field_content(node));
3323 previous = Some(node_trailing_text(node).is_some_and(|text| ends_with_punctuation(&text)));
3324 }
3325 result
3326}
3327
3328fn push_unit_text(items: &mut Vec<NodeData>, text: &str) {
3332 let text = match text.strip_prefix('.') {
3333 Some(rest)
3334 if trailing_text(items)
3335 .is_some_and(|last| PERIOD_RULE.with(std::cell::Cell::get).absorbs_period(&last)) =>
3336 {
3337 rest
3338 },
3339 _ => text,
3340 };
3341 if !text.is_empty() {
3342 items.push(NodeData::Text(text.to_string()));
3343 }
3344}
3345
3346fn trailing_text(items: &[NodeData]) -> Option<String> {
3352 items.iter().rev().find_map(|item| match item {
3353 NodeData::Text(text) => (!text.trim().is_empty()).then(|| text.clone()),
3354 NodeData::Element { tag, children, .. } => {
3355 element_trailing_text(tag, || trailing_text(children))
3356 },
3357 NodeData::XmlNode(node) => node_trailing_text(node),
3358 })
3359}
3360
3361fn node_trailing_text(node: &Node) -> Option<String> {
3362 match node.get_type() {
3363 Some(libxml::tree::NodeType::ElementNode) => element_trailing_text(&node.get_name(), || {
3364 let mut child = node.get_last_child();
3365 while let Some(n) = child {
3366 if let Some(text) = node_trailing_text(&n) {
3367 return Some(text);
3368 }
3369 child = n.get_prev_sibling();
3370 }
3371 None
3372 }),
3373 Some(libxml::tree::NodeType::TextNode) | Some(libxml::tree::NodeType::CDataSectionNode) => {
3374 let text = node.get_content();
3375 (!text.trim().is_empty()).then_some(text)
3376 },
3377 _ => None,
3378 }
3379}
3380
3381fn element_trailing_text(
3384 tag: &str,
3385 children_text: impl FnOnce() -> Option<String>,
3386) -> Option<String> {
3387 match tag.rsplit(':').next().unwrap_or(tag) {
3388 "Math" => Some(String::new()),
3389 "ref" | "bibref" | "cite" => children_text().or(Some(String::new())),
3390 _ => children_text(),
3391 }
3392}
3393
3394fn apply_formatter(doc: &PostDocument, formatter: Formatter, nodes: &[Node]) -> Vec<NodeData> {
3398 match formatter {
3399 Formatter::Any => join_fields(nodes, ", "),
3405 Formatter::Units => join_fields(nodes, ". "),
3409 Formatter::Authors => do_names(nodes.to_vec()),
3410 Formatter::EditorsA => do_editors_a(nodes.to_vec()),
3411 Formatter::EditorsB => {
3412 let mut result = vec![NodeData::Text("(".to_string())];
3413 result.extend(do_names(nodes.to_vec()));
3414 let suffix = if nodes.len() > 1 { " Eds.)" } else { " Ed.)" };
3415 result.push(NodeData::Text(suffix.to_string()));
3416 result
3417 },
3418 Formatter::OtherNames => {
3419 let mut groups: Vec<(String, Vec<Node>)> = Vec::new();
3423 for node in nodes {
3424 let role = node.get_attribute("role").unwrap_or_default();
3425 if matches!(role.as_str(), "author" | "editor" | "translator") {
3426 continue;
3427 }
3428 match groups.iter_mut().find(|(r, _)| *r == role) {
3429 Some((_, group)) => group.push(node.clone()),
3430 None => groups.push((role, vec![node.clone()])),
3431 }
3432 }
3433 let mut result = Vec::new();
3434 for (role, names) in groups {
3435 if !result.is_empty() {
3436 result.push(NodeData::Text("; ".to_string()));
3437 }
3438 result.extend(do_names(names));
3439 if role != "none" {
3440 result.push(NodeData::Text(format!(" ({role})")));
3441 }
3442 }
3443 result
3444 },
3445 Formatter::Year => {
3446 let suffix = "";
3456 let content: Vec<NodeData> = nodes
3457 .iter()
3458 .map(|n| {
3459 let text = n.get_content();
3460 let year = extract_four_digit_year(&text);
3461 NodeData::Text(year)
3462 })
3463 .collect();
3464 let mut result = vec![NodeData::Text(" (".to_string())];
3465 result.extend(content);
3466 result.push(NodeData::Text(format!("{})", suffix)));
3467 result
3468 },
3469 Formatter::Type => {
3470 let mut result = vec![NodeData::Text("(".to_string())];
3471 result.extend(nodes.iter().flat_map(field_content));
3472 result.push(NodeData::Text(")".to_string()));
3473 result
3474 },
3475 Formatter::Title => nodes.iter().flat_map(field_content).collect(),
3476 Formatter::ThesisType => nodes.iter().flat_map(field_content).collect(),
3477 Formatter::Edition => {
3478 let mut result: Vec<NodeData> = nodes.iter().flat_map(field_content).collect();
3479 result.push(NodeData::Text(" edition".to_string()));
3480 result
3481 },
3482 Formatter::Pages => {
3483 let mut result = vec![NodeData::Text("pp.\u{00A0}".to_string())]; result.extend(nodes.iter().flat_map(field_content));
3485 result
3486 },
3487 Formatter::CrossRef => {
3488 if let Some(node) = nodes.first() {
3490 if let Some(bibrefs) = node.get_attribute("bibrefs") {
3491 return vec![NodeData::Element {
3492 tag: "ltx:cite".to_string(),
3493 attributes: None,
3494 children: vec![NodeData::Element {
3495 tag: "ltx:bibref".to_string(),
3496 attributes: Some(HashMap::from_iter([
3497 ("bibrefs".to_string(), bibrefs),
3498 ("show".to_string(), "title, author".to_string()),
3499 ])),
3500 children: vec![],
3501 }],
3502 }];
3503 }
3504 }
3505 Vec::new()
3506 },
3507 Formatter::Links => format_links(doc, nodes),
3508 Formatter::None => Vec::new(),
3509 }
3510}
3511
3512fn format_links(doc: &PostDocument, nodes: &[Node]) -> Vec<NodeData> {
3516 let mut links: Vec<NodeData> = Vec::new();
3517
3518 for node in nodes {
3519 let tag = doc.get_qname(node).unwrap_or_default();
3520 let scheme = node.get_attribute("scheme").unwrap_or_default();
3521 let href = node.get_attribute("href");
3522 let printed_url = href.as_deref().map(force_absolute_url);
3524 let content_text = node.get_content();
3525
3526 let href = href.map(|h| unescape_tex_url(&h));
3532 let href = match (&href, scheme.as_str()) {
3533 (None, "doi") if !content_text.trim().is_empty() && content_text.contains('/') => {
3534 Some(doi_href(&content_text))
3535 },
3536 (Some(h), "doi") if !h.contains("://") => Some(doi_href(h.trim_start_matches('/'))),
3537 (Some(h), _) => Some(force_absolute_url(h)),
3538 (None, _) => None,
3539 };
3540 let children: Vec<NodeData> = node
3550 .get_child_nodes()
3551 .into_iter()
3552 .map(NodeData::XmlNode)
3553 .collect();
3554 match tag.as_str() {
3555 "ltx:bib-identifier" | "ltx:bib-review" => {
3556 if let Some(href) = href {
3557 links.push(NodeData::Element {
3558 tag: "ltx:ref".to_string(),
3559 attributes: Some(HashMap::from_iter([
3560 ("href".to_string(), href),
3561 ("class".to_string(), format!("{} ltx_bib_external", scheme)),
3562 ])),
3563 children,
3564 });
3565 } else {
3566 links.push(NodeData::Element {
3567 tag: "ltx:text".to_string(),
3568 attributes: Some(HashMap::from_iter([(
3569 "class".to_string(),
3570 format!("{} ltx_bib_external", scheme),
3571 )])),
3572 children,
3573 });
3574 }
3575 },
3576 "ltx:bib-links" => {
3577 links.push(NodeData::Element {
3578 tag: "ltx:text".to_string(),
3579 attributes: Some(HashMap::from_iter([(
3580 "class".to_string(),
3581 "ltx_bib_external".to_string(),
3582 )])),
3583 children,
3584 });
3585 },
3586 "ltx:bib-url" => {
3587 if let Some(href) = href {
3588 let children = if URLS_AS_TEXT.with(|flag| flag.get()) && content_text.trim() == "Link" {
3593 vec![NodeData::Text(printed_url.unwrap_or_else(|| href.clone()))]
3594 } else {
3595 children
3596 };
3597 links.push(NodeData::Element {
3598 tag: "ltx:ref".to_string(),
3599 attributes: Some(HashMap::from_iter([
3600 ("href".to_string(), href),
3601 ("class".to_string(), "ltx_bib_external".to_string()),
3602 ])),
3603 children,
3604 });
3605 }
3606 },
3607 _ => {},
3608 }
3609 }
3610
3611 if links.len() > 1 {
3613 let mut result = Vec::new();
3614 for (i, link) in links.into_iter().enumerate() {
3615 if i > 0 {
3616 result.push(NodeData::Text(",\n".to_string()));
3617 }
3618 result.push(link);
3619 }
3620 result
3621 } else {
3622 links
3623 }
3624}
3625
3626fn unisort(keys: &mut [String]) {
3653 keys.sort_by_cached_key(|k| (collation_primary_key(k), k.clone()));
3654}
3655
3656fn style_prints_urls(bibstyle: &str) -> bool {
3665 bibstyle.starts_with("biblatex")
3666 || matches!(
3667 bibstyle,
3668 "plainnat" | "abbrvnat" | "unsrtnat" | "abntex2-num" | "abntex2-alf"
3669 )
3670}
3671
3672fn citation_order(doc: &PostDocument) -> HashMap<String, usize> {
3687 let mut order: HashMap<String, usize> = HashMap::default();
3688 let mut next = 0usize;
3689 for node in doc.findnodes("//ltx:bibref[not(ancestor::ltx:bibliography)]") {
3690 let Some(refs) = node.get_attribute("bibrefs") else {
3691 continue;
3692 };
3693 for key in refs.split(',') {
3694 let k = key.trim().to_lowercase();
3695 if k.is_empty() {
3696 continue;
3697 }
3698 order.entry(k).or_insert_with(|| {
3699 let i = next;
3700 next += 1;
3701 i
3702 });
3703 }
3704 }
3705 order
3706}
3707
3708fn order_entry_keys(
3719 entries: &HashMap<String, BibEntryData>,
3720 cite_order: Option<&HashMap<String, usize>>,
3721) -> Vec<String> {
3722 match cite_order {
3723 Some(order) => {
3724 let mut cited: Vec<(usize, String)> = Vec::new();
3725 let mut uncited: Vec<String> = Vec::new();
3726 for (sort_key, entry) in entries {
3727 match order.get(&entry.bib_key.to_lowercase()) {
3728 Some(&idx) => cited.push((idx, sort_key.clone())),
3729 None => uncited.push(sort_key.clone()),
3730 }
3731 }
3732 cited.sort_by_key(|(idx, _)| *idx);
3733 uncited.sort_by(|a, b| {
3734 entries[a]
3735 .db_index
3736 .cmp(&entries[b].db_index)
3737 .then_with(|| a.cmp(b))
3738 });
3739 cited.into_iter().map(|(_, k)| k).chain(uncited).collect()
3740 },
3741 None => {
3742 let mut keys: Vec<String> = entries.keys().cloned().collect();
3743 unisort(&mut keys);
3744 keys
3745 },
3746 }
3747}
3748
3749fn given_listing(doc: &PostDocument, bib: &Node) -> Option<Vec<String>> {
3757 if bib.with_attribute(c"sort", |v| v == "false") != Some(true)
3758 || !bib
3759 .get_attribute("bibstyle")
3760 .is_some_and(|style| style.starts_with("biblatex"))
3761 {
3762 return None;
3763 }
3764 entry_keys(doc, bib)
3765}
3766
3767fn inline_listing(doc: &PostDocument, bib: &Node) -> Option<Vec<String>> {
3773 if !bib.get_attribute("class").is_some_and(|class| {
3774 class
3775 .split_whitespace()
3776 .any(|c| c == "ltx_bibliography_inline")
3777 }) {
3778 return None;
3779 }
3780 entry_keys(doc, bib)
3781}
3782
3783fn entry_keys(doc: &PostDocument, bib: &Node) -> Option<Vec<String>> {
3785 let keys: Vec<String> = doc
3786 .findnodes_at(".//ltx:bibentry", Some(bib))
3787 .iter()
3788 .filter_map(|entry| entry.get_attribute("key"))
3789 .collect();
3790 (!keys.is_empty()).then_some(keys)
3791}
3792
3793fn given_label(bibentry: &Node) -> Option<String> {
3809 if !is_biblatex_bibliography() {
3810 return None;
3811 }
3812 let field = |role: &str| {
3813 PostDocument::findnodes_foreign(&format!("ltx:bib-data[@role='{role}']"), bibentry)
3814 .first()
3815 .map(|node| node.get_content().trim().to_string())
3816 .filter(|text| !text.is_empty())
3817 };
3818 if let Some(shorthand) = field("shorthand") {
3819 return Some(shorthand);
3820 }
3821 let mut label = field("labelalpha")?;
3822 if let Some(extra) = field("extraalpha").and_then(|n| n.parse::<u32>().ok()) {
3823 label.push_str(&mknumalph(extra));
3824 }
3825 Some(label)
3826}
3827
3828fn given_number(entry: &BibEntryData) -> Option<u32> {
3837 if !is_biblatex_bibliography() {
3838 return None;
3839 }
3840 let bibentry = entry.bibentry.as_ref()?;
3841 PostDocument::findnodes_foreign("ltx:bib-data[@role='labelnumber']", bibentry)
3842 .first()
3843 .and_then(|node| node.get_content().trim().parse().ok())
3844}
3845
3846fn number_entry(
3854 entry: &mut BibEntryData,
3855 number: &mut u32,
3856 shown: &mut u32,
3857 style: &CitationStyle,
3858) {
3859 *number += 1;
3860 entry.number = *number;
3861 entry.label_number = given_number(entry);
3862 if entry_given_label(entry, style).is_none() {
3863 *shown += 1;
3864 if entry.label_number.is_none() && *shown != *number {
3865 entry.label_number = Some(*shown);
3866 }
3867 }
3868}
3869
3870fn entry_given_label(entry: &BibEntryData, style: &CitationStyle) -> Option<String> {
3873 if matches!(style, CitationStyle::AuthorYear) {
3874 return None;
3875 }
3876 entry.bibentry.as_ref().and_then(given_label)
3877}
3878
3879fn mknumalph(n: u32) -> String {
3882 let letter = |i: u32| char::from(b'a' + (i - 1) as u8);
3883 match n {
3884 1..=26 => letter(n).to_string(),
3885 27..=702 => {
3886 let first = (n - 1) / 26;
3887 format!("{}{}", letter(first), letter(n - first * 26))
3888 },
3889 _ => n.to_string(),
3890 }
3891}
3892
3893fn collation_primary_key(s: &str) -> String {
3896 use unicode_normalization::{UnicodeNormalization, char::is_combining_mark};
3897 s.nfd()
3898 .filter(|c| !is_combining_mark(*c))
3899 .flat_map(char::to_lowercase)
3900 .collect()
3901}
3902
3903fn extract_names(doc: &PostDocument, bibentry: &Node) -> (String, String, String) {
3908 let mut name_nodes: Vec<Node> =
3909 PostDocument::findnodes_foreign("ltx:bib-name[@role='author']", bibentry);
3910 if name_nodes.is_empty() {
3911 name_nodes = label_editors("", |x| PostDocument::findnodes_foreign(x, bibentry));
3912 }
3913
3914 if name_nodes.is_empty() {
3915 if let Some(key_node) = PostDocument::findnodes_foreign("ltx:bib-key", bibentry)
3917 .into_iter()
3918 .next()
3919 {
3920 let text = key_node.get_content();
3921 return (text.clone(), text.clone(), text);
3922 }
3923 if let Some(title_node) = PostDocument::findnodes_foreign("ltx:bib-title", bibentry)
3925 .into_iter()
3926 .next()
3927 {
3928 let text = title_node.get_content();
3929 return (text.clone(), text.clone(), text);
3930 }
3931 return (String::new(), String::new(), String::new());
3932 }
3933
3934 let sort_names: String = name_nodes
3936 .iter()
3937 .map(|n| get_name_text(doc, n))
3938 .collect::<Vec<_>>()
3939 .join(" ");
3940
3941 let surnames: Vec<String> = name_nodes
3943 .iter()
3944 .filter_map(|n| {
3945 PostDocument::findnodes_foreign("ltx:surname", n)
3946 .into_iter()
3947 .next()
3948 .map(|s| s.get_content())
3949 })
3950 .collect();
3951
3952 let short_names = if surnames.len() > 2 {
3953 format!("{} et al", surnames[0])
3954 } else if surnames.len() == 2 {
3955 format!("{} and {}", surnames[0], surnames[1])
3956 } else if !surnames.is_empty() {
3957 surnames[0].clone()
3958 } else {
3959 String::new()
3960 };
3961
3962 let full_names = surnames.join(", ");
3963 (sort_names, short_names, full_names)
3964}
3965
3966fn do_name(given: Option<&str>, surname: &str) -> String {
3976 let mut out = String::new();
3977 if let Some(given) = given {
3978 match GIVEN_NAME_FORM.with(std::cell::Cell::get) {
3979 GivenNameForm::Full => {
3980 for word in given.split_whitespace() {
3981 out.push_str(word);
3982 out.push(' ');
3983 }
3984 },
3985 GivenNameForm::Initials => {
3986 for word in given.split_whitespace() {
3987 if word.ends_with('.') {
3988 out.push_str(word);
3989 out.push(' ');
3990 } else if let Some(c) = word.chars().next() {
3991 out.push(c);
3992 out.push_str(". ");
3993 }
3994 }
3995 },
3996 }
3997 }
3998 out.push_str(surname);
3999 out
4000}
4001
4002fn do_name_node(namenode: &Node) -> String {
4004 let first_text = |xpath: &str| {
4005 PostDocument::findnodes_foreign(xpath, namenode)
4006 .into_iter()
4007 .next()
4008 .map(|n| n.get_content())
4009 };
4010 let given = first_text("ltx:givenname");
4011 let surname = first_text("ltx:surname").unwrap_or_default();
4012 do_name(given.as_deref(), &surname)
4013}
4014
4015fn style_given_name_form(bibstyle: &str, search_paths: &[String]) -> GivenNameForm {
4022 match bibstyle {
4023 "biblatex" => GivenNameForm::Full,
4024 "biblatex-giveninits" => GivenNameForm::Initials,
4025 _ => {
4026 let bst = if bibstyle.ends_with(".bst") {
4027 bibstyle.to_string()
4028 } else {
4029 format!("{bibstyle}.bst")
4030 };
4031 find_file(&bst, search_paths)
4032 .or_else(|| latexml_core::util::pathname::kpsewhich(&[bst.as_str()]))
4033 .and_then(|path| std::fs::read(path).ok())
4034 .map_or(GivenNameForm::Initials, |bytes| {
4035 bst_given_name_form(&String::from_utf8_lossy(&bytes))
4036 })
4037 },
4038 }
4039}
4040
4041fn bst_given_name_form(bst: &str) -> GivenNameForm {
4063 let code: String = bst
4064 .lines()
4065 .map(strip_bst_comment)
4066 .collect::<Vec<_>>()
4067 .join("\n");
4068 for (at, _) in code.match_indices("'abnt.full.initials :=") {
4075 match code[..at].trim_end().rsplit(char::is_whitespace).next() {
4076 Some("#0") => return GivenNameForm::Initials,
4077 Some("#1") => return GivenNameForm::Full,
4078 _ => {},
4079 }
4080 }
4081 let mut rest = code.as_str();
4082 while let Some(at) = rest.find("format.name$") {
4083 let before = rest[..at].trim_end();
4084 rest = &rest[at + "format.name$".len()..];
4085 if rest.trim_start().starts_with("\"others\"") {
4089 continue;
4090 }
4091 let Some(open) = before.strip_suffix('"').and_then(|body| body.rfind('"')) else {
4093 return GivenNameForm::Initials;
4094 };
4095 let template = &before[open + 1..before.len() - 1];
4096 if let Some(form) = template_given_name_form(template) {
4097 return form;
4098 }
4099 }
4100 GivenNameForm::Initials
4101}
4102
4103fn strip_bst_comment(line: &str) -> &str {
4106 let mut in_string = false;
4107 for (i, c) in line.char_indices() {
4108 match c {
4109 '"' => in_string = !in_string,
4110 '%' if !in_string => return &line[..i],
4111 _ => {},
4112 }
4113 }
4114 line
4115}
4116
4117fn template_given_name_form(template: &str) -> Option<GivenNameForm> {
4121 let mut depth = 0usize;
4122 let mut letters = String::new();
4123 let mut read = false;
4125 for c in template.chars() {
4126 if depth == 1 && !read {
4127 if c.is_ascii_alphabetic() {
4128 letters.push(c);
4129 continue;
4130 }
4131 if !letters.is_empty() {
4132 read = true;
4133 if letters.starts_with('f') {
4134 return Some(if letters == "ff" {
4135 GivenNameForm::Full
4136 } else {
4137 GivenNameForm::Initials
4138 });
4139 }
4140 }
4141 }
4142 match c {
4143 '{' => {
4144 depth += 1;
4145 if depth == 1 {
4146 letters.clear();
4147 read = false;
4148 }
4149 },
4150 '}' => depth = depth.saturating_sub(1),
4151 _ => {},
4152 }
4153 }
4154 None
4155}
4156
4157fn do_names_short(mut names: Vec<Node>) -> Vec<NodeData> {
4171 let surname_text = |n: &Node| -> String {
4172 PostDocument::findnodes_foreign("ltx:surname", n)
4173 .into_iter()
4174 .next()
4175 .map(|s| s.get_content())
4176 .unwrap_or_else(|| n.get_content())
4177 .trim()
4178 .to_string()
4179 };
4180 let mut etal = names
4181 .last()
4182 .map(|n| n.get_content().trim() == "others")
4183 .unwrap_or(false);
4184 if etal {
4185 names.pop();
4186 }
4187 if names.len() > 2 {
4188 etal = true;
4189 }
4190 let etal_span = || NodeData::Element {
4191 tag: "ltx:text".to_string(),
4192 attributes: Some(HashMap::from_iter([(
4193 "class".to_string(),
4194 "ltx_bib_etal".to_string(),
4195 )])),
4196 children: vec![NodeData::Text("et al.".to_string())],
4197 };
4198 match (names.len(), etal) {
4199 (0, _) => Vec::new(),
4200 (_, true) => vec![
4201 NodeData::Text(surname_text(&names[0])),
4202 NodeData::Text(" ".to_string()),
4203 etal_span(),
4204 ],
4205 (1, false) => vec![NodeData::Text(surname_text(&names[0]))],
4206 (_, false) => vec![
4207 NodeData::Text(surname_text(&names[0])),
4208 NodeData::Text(" and ".to_string()),
4209 NodeData::Text(surname_text(&names[1])),
4210 ],
4211 }
4212}
4213
4214fn do_names(mut names: Vec<Node>) -> Vec<NodeData> {
4220 let sep = if names.len() > 2 { ", " } else { " " };
4221 let mut etal = false;
4222 if names
4223 .last()
4224 .map(|n| n.get_content().trim() == "others")
4225 .unwrap_or(false)
4226 {
4227 names.pop();
4228 etal = true;
4229 }
4230 let last = names.len().saturating_sub(1);
4231 let mut out: Vec<NodeData> = Vec::new();
4232 for (i, name) in names.iter().enumerate() {
4233 if !out.is_empty() {
4234 out.push(NodeData::Text(sep.to_string()));
4235 if !etal && i == last {
4236 out.push(NodeData::Text("and ".to_string()));
4237 }
4238 }
4239 out.push(NodeData::Text(do_name_node(name)));
4240 }
4241 if etal {
4242 out.push(NodeData::Text(sep.to_string()));
4243 out.push(NodeData::Element {
4244 tag: "ltx:text".to_string(),
4245 attributes: Some(HashMap::from_iter([(
4246 "class".to_string(),
4247 "ltx_bib_etal".to_string(),
4248 )])),
4249 children: vec![NodeData::Text("et al.".to_string())],
4250 });
4251 }
4252 out
4253}
4254
4255fn do_editors_a(names: Vec<Node>) -> Vec<NodeData> {
4258 let n = names.len();
4259 let mut out = do_names(names);
4260 if n > 1 {
4261 out.push(NodeData::Text(" (Eds.)".to_string()));
4262 } else if n == 1 {
4263 out.push(NodeData::Text(" (Ed.)".to_string()));
4264 }
4265 out
4266}
4267
4268fn get_name_text(_doc: &PostDocument, namenode: &Node) -> String {
4272 let surname = PostDocument::findnodes_foreign("ltx:surname", namenode)
4273 .into_iter()
4274 .next()
4275 .map(|n| n.get_content());
4276 let givenname = PostDocument::findnodes_foreign("ltx:givenname", namenode)
4277 .into_iter()
4278 .next()
4279 .map(|n| n.get_content());
4280 match (surname, givenname) {
4281 (Some(s), Some(g)) => format!("{} {}", s, g),
4282 (Some(s), None) => s,
4283 (None, Some(g)) => g,
4284 (None, None) => String::new(),
4285 }
4286}
4287
4288fn extract_four_digit_year(text: &str) -> String {
4290 if let Some(start) = text.find(|c: char| c.is_ascii_digit()) {
4291 let digits: String = text[start..]
4292 .chars()
4293 .take_while(|c| c.is_ascii_digit())
4294 .collect();
4295 if digits.len() >= 4 {
4296 return digits[..4].to_string();
4297 }
4298 }
4299 text.to_string()
4300}
4301
4302fn alpha_label_year(year: &str) -> String {
4308 let purified: Vec<char> = purify(year).chars().collect();
4309 purified[purified.len().saturating_sub(2)..]
4310 .iter()
4311 .collect()
4312}
4313
4314fn purify(text: &str) -> String {
4317 text
4318 .chars()
4319 .filter_map(|c| match c {
4320 c if c.is_alphanumeric() => Some(c),
4321 c if c.is_whitespace() || matches!(c, '-' | '~' | '\u{2010}'..='\u{2015}') => Some(' '),
4322 _ => None,
4323 })
4324 .collect()
4325}
4326
4327fn suffix_to_counter(suffix: &str) -> u32 {
4329 let mut n = 0u32;
4330 for c in suffix.chars() {
4331 n = n * 26 + (c as u32 - 'a' as u32 + 1);
4332 }
4333 n
4334}
4335
4336fn bibitem_id(bib_id: &str, entry: &BibEntryData, bibentry: &Node) -> String {
4340 let orig_id = crate::document::get_xml_id(bibentry).unwrap_or_default();
4341 if orig_id.is_empty() {
4342 format!("{}.bib{}", bib_id, entry.number)
4343 } else {
4344 let stripped = orig_id.strip_prefix("bib").unwrap_or(&orig_id);
4345 format!("{}{}", bib_id, stripped)
4346 }
4347}
4348
4349impl BibEntryData {
4350 fn shown_number(&self) -> u32 { self.label_number.unwrap_or(self.number) }
4352}
4353
4354fn clone_entry(e: &BibEntryData) -> BibEntryData {
4356 BibEntryData {
4357 bib_key: e.bib_key.clone(),
4358 cited_key: e.cited_key.clone(),
4359 sort_key: e.sort_key.clone(),
4360 initial: e.initial.clone(),
4361 author_year: e.author_year.clone(),
4362 suffix: e.suffix.clone(),
4363 sort_names: e.sort_names.clone(),
4364 year: e.year.clone(),
4365 entry_type: e.entry_type.clone(),
4366 number: e.number,
4367 label_number: e.label_number,
4368 referrers: e.referrers.clone(),
4369 bibreferrers: e.bibreferrers.clone(),
4370 citations: e.citations.clone(),
4371 bibentry: e.bibentry.clone(),
4372 db_index: e.db_index,
4373 }
4374}
4375
4376fn node_data_text(nodes: &[NodeData]) -> String {
4379 nodes
4380 .iter()
4381 .map(|node| match node {
4382 NodeData::Text(text) => text.clone(),
4383 NodeData::Element { children, .. } => node_data_text(children),
4384 NodeData::XmlNode(node) => node.get_content(),
4385 })
4386 .collect()
4387}
4388
4389fn make_bibblock(class: &str, content: &[NodeData]) -> NodeData {
4390 let mut attrs = HashMap::default();
4391 attrs.insert("xml:space".to_string(), "preserve".to_string());
4392 if !class.is_empty() {
4393 attrs.insert("class".to_string(), class.to_string());
4394 }
4395 NodeData::Element {
4396 tag: "ltx:bibblock".to_string(),
4397 attributes: Some(attrs),
4398 children: content.to_vec(),
4399 }
4400}
4401
4402fn find_file(name: &str, search_paths: &[String]) -> Option<String> {
4416 latexml_core::util::pathname::find(name, latexml_core::util::pathname::PathnameFindOptions {
4417 paths: Some(search_paths.to_vec()),
4418 ..Default::default()
4419 })
4420}
4421
4422fn doi_href(doi: &str) -> String {
4426 let mut href = String::from("https://doi.org/");
4427 for c in doi.trim().chars() {
4428 if c.is_ascii_alphanumeric() || matches!(c, '.' | '/' | '-' | '+') {
4429 href.push(c);
4430 } else {
4431 let mut buf = [0u8; 4];
4432 for &b in c.encode_utf8(&mut buf).as_bytes() {
4433 href.push_str(&format!("%{:02X}", b));
4434 }
4435 }
4436 }
4437 href
4438}
4439
4440fn unescape_tex_url(href: &str) -> String {
4444 let mut out = String::with_capacity(href.len());
4445 let mut rest = href;
4446 while let Some(at) = rest.find('\\') {
4447 out.push_str(&rest[..at]);
4448 rest = &rest[at + 1..];
4449 match rest.chars().next() {
4450 Some(c @ ('_' | '%' | '#' | '&' | '$' | '~' | '{' | '}')) => {
4451 out.push(c);
4452 rest = &rest[1..];
4453 if c == '~' {
4454 rest = rest.strip_prefix("{}").unwrap_or(rest);
4455 }
4456 },
4457 _ => out.push('\\'),
4458 }
4459 }
4460 out.push_str(rest);
4461 out
4462}
4463
4464fn force_absolute_url(url: &str) -> String {
4467 let u = url.trim();
4468 if u.is_empty() || u.contains("://") || u.starts_with("mailto:") {
4469 u.to_string()
4470 } else {
4471 format!("https://{}", u)
4472 }
4473}
4474
4475fn bib_lookup_candidates(bib_file: &str) -> Vec<String> {
4487 let mut out = vec![bib_file.to_string()];
4488 let base = latexml_core::util::pathname::file_name(bib_file);
4489 let extensionless = !base.contains('.');
4490 if extensionless {
4491 out.push(format!("{bib_file}.bib"));
4492 }
4493 if !base.is_empty() && base != bib_file && bib_file.contains('/') {
4494 out.push(base.clone());
4495 if extensionless {
4496 out.push(format!("{base}.bib"));
4497 }
4498 }
4499 out
4500}
4501
4502#[cfg(test)]
4503mod tests {
4504 use super::*;
4505
4506 #[test]
4508 fn unescape_tex_url_drops_only_tex_escapes() {
4509 for (raw, href) in [
4510 (
4511 r"https://x.org/a\_b\%20c\#f\&q=1\$\{\}",
4512 "https://x.org/a_b%20c#f&q=1${}",
4513 ),
4514 (r"https://x.org/\~{}u/\~v", "https://x.org/~u/~v"),
4515 (r"https://x.org/a_b%20c", "https://x.org/a_b%20c"),
4516 (r"C:\dir\file\", r"C:\dir\file\"),
4517 ] {
4518 assert_eq!(unescape_tex_url(raw), href, "{raw}");
4519 }
4520 }
4521
4522 #[test]
4526 fn join_fields_reads_the_printed_text() {
4527 let xml = r#"<r xmlns="http://dlmf.nist.gov/LaTeXML"><bib-note>Bounds on <Math><XMath><XMTok>n!.</XMTok></XMath></Math></bib-note><bib-note>See <bibref bibrefs="k"/></bib-note><bib-note>Ends.</bib-note><bib-note>Last</bib-note></r>"#;
4528 let doc = libxml::parser::Parser::default()
4529 .parse_string(xml)
4530 .expect("parse");
4531 let nodes = doc.get_root_element().expect("root").get_child_elements();
4532 let printed: String = join_fields(&nodes, ". ")
4533 .iter()
4534 .map(|item| match item {
4535 NodeData::Text(text) => text.clone(),
4536 NodeData::XmlNode(node) if node.get_type() == Some(libxml::tree::NodeType::ElementNode) => {
4537 format!("[{}]", node.get_name())
4538 },
4539 NodeData::XmlNode(node) => node.get_content(),
4540 NodeData::Element { tag, .. } => format!("[{tag}]"),
4541 })
4542 .collect();
4543 assert_eq!(printed, "Bounds on [Math]. See [bibref]. Ends. Last");
4544 }
4545
4546 #[test]
4547 fn test_extract_four_digit_year() {
4548 assert_eq!(extract_four_digit_year("2024"), "2024");
4549 assert_eq!(
4550 extract_four_digit_year("Published in 2024, January"),
4551 "2024"
4552 );
4553 assert_eq!(extract_four_digit_year("99"), "99");
4554 assert_eq!(extract_four_digit_year(""), "");
4555 }
4556
4557 #[test]
4558 fn test_find_file_case_insensitive_bib() {
4559 let dir = std::env::temp_dir().join("lxo_bib_case_test");
4565 let _ = std::fs::create_dir_all(&dir);
4566 let on_disk = dir.join("Evoflock.bib");
4567 std::fs::write(&on_disk, "@article{k, title={T}}\n").unwrap();
4568 let dirs = vec![dir.to_str().unwrap().to_string()];
4569 assert!(find_file("Evoflock.bib", &dirs).is_some());
4571 let hit = find_file("EvoFlock.bib", &dirs);
4573 assert!(
4574 hit.is_some(),
4575 "case-mismatched bib filename should resolve via the pathname fallback"
4576 );
4577 assert!(hit.unwrap().to_lowercase().ends_with("evoflock.bib"));
4578 assert!(find_file("NoSuchBib.bib", &dirs).is_none());
4580 let _ = std::fs::remove_dir_all(&dir);
4581 }
4582
4583 #[test]
4584 fn test_suffix_to_counter() {
4585 assert_eq!(suffix_to_counter("a"), 1);
4586 assert_eq!(suffix_to_counter("b"), 2);
4587 assert_eq!(suffix_to_counter("z"), 26);
4588 assert_eq!(suffix_to_counter("aa"), 27);
4589 }
4590
4591 #[test]
4592 fn test_period_rule() {
4593 use PeriodRule::{AddPeriod, Tracker};
4594 assert_eq!(PeriodRule::of_style(None), AddPeriod);
4595 assert_eq!(PeriodRule::of_style(Some("plainnat")), AddPeriod);
4596 assert_eq!(PeriodRule::of_style(Some("biblatex-giveninits")), Tracker);
4597 for text in ["What is X?", "Stop!", "Pub, Inc.", "Inc. "] {
4599 assert!(AddPeriod.absorbs_period(text), "{text}");
4600 }
4601 for text in ["Title", "Ends with colon:", "Second (2nd ed.)", "“Quoted.”"] {
4602 assert!(!AddPeriod.absorbs_period(text), "{text}");
4603 }
4604 for text in [
4606 "What is X?",
4607 "Ends with colon:",
4608 "Second (2nd ed.)",
4609 "“Quoted.”",
4610 ] {
4611 assert!(Tracker.absorbs_period(text), "{text}");
4612 }
4613 assert!(!Tracker.absorbs_period("Title"));
4614 let items = vec![
4616 NodeData::Text("Bounds on ".to_string()),
4617 NodeData::Element {
4618 tag: "ltx:Math".to_string(),
4619 attributes: None,
4620 children: vec![NodeData::Text("n!".to_string())],
4621 },
4622 ];
4623 assert_eq!(trailing_text(&items).as_deref(), Some(""));
4624 let items = vec![NodeData::Text("What?".to_string()), NodeData::Element {
4625 tag: "ltx:bibref".to_string(),
4626 attributes: None,
4627 children: vec![],
4628 }];
4629 assert_eq!(trailing_text(&items).as_deref(), Some(""));
4630 }
4631
4632 #[test]
4633 fn test_do_name() {
4634 assert_eq!(do_name(Some("John"), "Smith"), "J. Smith");
4635 assert_eq!(do_name(Some("J."), "Smith"), "J. Smith");
4636 assert_eq!(do_name(Some("John Robert"), "Smith"), "J. R. Smith");
4637 assert_eq!(do_name(None, "Smith"), "Smith");
4638 }
4639
4640 #[test]
4641 fn test_do_name_full_given_names() {
4642 GIVEN_NAME_FORM.with(|form| form.set(GivenNameForm::Full));
4643 assert_eq!(do_name(Some("John Robert"), "Smith"), "John Robert Smith");
4644 assert_eq!(do_name(Some("J."), "Smith"), "J. Smith");
4645 assert_eq!(do_name(None, "Smith"), "Smith");
4646 GIVEN_NAME_FORM.with(|form| form.set(GivenNameForm::Initials));
4647 assert_eq!(do_name(Some("John Robert"), "Smith"), "J. R. Smith");
4648 }
4649
4650 #[test]
4651 fn test_bst_given_name_form() {
4652 use GivenNameForm::{Full, Initials};
4653 let call = |template: &str| format!("{{ s nameptr \"{template}\" format.name$ 't := }}");
4654 assert_eq!(bst_given_name_form(&call("{ff~}{vv~}{ll}{, jj}")), Full);
4657 assert_eq!(bst_given_name_form(&call("{f.~}{vv~}{ll}{, jj}")), Initials);
4658 assert_eq!(
4659 bst_given_name_form(&call("{ff{ } }{vv{ } }{ll{ }}{, jj}")),
4660 Full
4661 );
4662 assert_eq!(bst_given_name_form(&call("{vv~}{ll}{, ff}{, jj}")), Full);
4663 assert_eq!(
4664 bst_given_name_form(&call("{vv~}{ll}{, jj}{, f.}")),
4665 Initials
4666 );
4667 assert_eq!(
4668 bst_given_name_form(&call("{vv~}{ll}{, jj}{, f{.}.}")),
4669 Initials
4670 );
4671 assert_eq!(bst_given_name_form(&call("{f}{ll}")), Initials);
4672 let abnt = |template: &str, default: &str| {
4676 format!(
4677 "{}\n{{ abnt-full-initials \"yes\" = 'abnt.full.initials := }}\n{{ {default} 'abnt.full.initials := }}",
4678 call(template)
4679 )
4680 };
4681 assert_eq!(
4682 bst_given_name_form(&abnt("{vv }{ll}{, jj}{, ff}", "#0")),
4683 Initials
4684 );
4685 assert_eq!(
4686 bst_given_name_form(&abnt("{vv }{ll}{, jj}{, f.}", "#1")),
4687 Full
4688 );
4689 let option_only = format!(
4690 "{}\n{{ abnt-full-initials \"yes\" = 'abnt.full.initials := }}",
4691 call("{f.~}{ll}")
4692 );
4693 assert_eq!(bst_given_name_form(&option_only), Initials);
4694 let label_first = format!("{}\n{}", call("{vv~}{ll}"), call("{ff~}{ll}"));
4696 assert_eq!(bst_given_name_form(&label_first), Full);
4697 let commented = format!("% \"{{ff~}}{{ll}}\" format.name$\n{}", call("{f.~}{ll}"));
4699 assert_eq!(bst_given_name_form(&commented), Initials);
4700 let variable = format!(
4703 "{{ s nameptr name.format.string format.name$ }}\n{}",
4704 call("{vv{ } }{ll{ }}{ ff{ }}{ jj{ }}")
4705 );
4706 assert_eq!(bst_given_name_form(&variable), Initials);
4707 assert_eq!(bst_given_name_form("ENTRY { author } {} {}"), Initials);
4708 let others_test = format!(
4710 "{{ names.str #2 \"{{ff }}{{vv }}{{ll}}{{ jj}}\" format.name$\n \"others\" = }}\n{}",
4711 call("{vv~}{ll}{,~f.}{,~jj}")
4712 );
4713 assert_eq!(bst_given_name_form(&others_test), Initials);
4714 }
4715
4716 #[test]
4717 fn test_fmt_spec_coverage() {
4718 for fmt in &[
4720 "article",
4721 "book",
4722 "incollection",
4723 "report",
4724 "thesis",
4725 "website",
4726 "software",
4727 ] {
4728 let specs = get_fmt_spec(fmt);
4729 assert!(
4730 !specs.is_empty(),
4731 "FMT_SPEC for '{}' should not be empty",
4732 fmt
4733 );
4734 }
4735 }
4736}