Skip to main content

dima_core/
citations.rs

1//! Bibliographic references: the single source for every citation surface.
2//!
3//! CLI help, the JSON `run.references`, `dima cite`, the GUI's *Cite DiMA* dialog and tooltips,
4//! the documentation bibliography and `CITATION.cff` are all produced from this module, so a
5//! reference can never disagree between surfaces.
6//!
7//! References are ranked by the repository's citation policy (see `AGENTS.md`): domain venues
8//! first ([`Tier::Domain`]), then general statistics, mathematics (including numerical analysis),
9//! HCI or computer science only where they are the primary source of a number, algorithm or
10//! result ([`Tier::General`]), then standards and specifications, cited for what they define
11//! ([`Tier::Standard`]).
12//!
13//! # In-text labels
14//!
15//! In-text labels ([`Citation::short`]) are computed once over the whole registry, so a work has
16//! the same label on every surface (D114):
17//!
18//! 1. Family names and year: `Shannon 1948`, `Chao & Jost 2012`, `List et al. 2017`.
19//! 2. Works that share that label show as many names as needed to tell them apart, the same
20//!    number for each work of the group: `Grüning, Dale et al. 2018` and
21//!    `Grüning, Chilton et al. 2018`. "et al." always stands for two or more names, so a list at
22//!    most one name longer than shown is written in full (APA 7 §8.18; CSL 1.0.2
23//!    `disambiguate-add-names`; biblatex `uniquelist=minyear`).
24//! 3. Works whose names are still identical get year letters `a`, `b`, …, `z`, `aa`, … in title
25//!    order, ignoring a leading A, An or The (APA 7 §8.19 and §9.47; CSL 1.0.2
26//!    `disambiguate-add-year-suffix`).
27//!
28//! Letters appear in labels and in dima's own name-year reference lists
29//! ([`Citation::listed_text`]: the documentation pages and the Bibliography). They never appear
30//! in exported records ([`Citation::text`]: `run.references`, `dima cite`, BibTeX, RIS, CFF),
31//! because a citing document assigns its own.
32//!
33//! A standard whose publisher gives it a short name is labelled by that designation instead,
34//! without a year (D115): `RFC 8259` (RFC 7322, Section 3.5), `UAX #15` (the Unicode
35//! Consortium's abbreviated citations), `WCAG 2.2` (the W3C's reference tags). Designations are
36//! unique by construction and need no letters. dima's own reference lists start the entry with
37//! the designation, so the label leads to it; exported records do not carry it.
38
39use std::collections::{BTreeMap, BTreeSet, HashMap};
40use std::fmt::Write as _;
41use std::sync::OnceLock;
42
43#[path = "citations_data.rs"]
44mod data;
45
46/// Citation-policy tier of a reference (`AGENTS.md`, "Citation policy").
47#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
48pub enum Tier {
49    /// Peer-reviewed work in a bioinformatics, computational-biology, virology, ecology or
50    /// biostatistics venue.
51    Domain,
52    /// Peer-reviewed statistics, mathematics (including numerical analysis), HCI, visualisation or
53    /// computer-science work, cited only as the primary source of something no domain source
54    /// provides, or as a peer-reviewed statement of a classical mathematical result in the form
55    /// used.
56    General,
57    /// A standard or specification, cited for what it defines: a W3C, IETF, Unicode, ISO/IEC or
58    /// BIPM document, or a file or data format's specification by its maintainer (including a
59    /// database's or tool's definition of the symbols in the files it distributes, where no
60    /// peer-reviewed source documents them).
61    Standard,
62}
63
64impl Tier {
65    /// The label shown next to the reference on the docs *Design rationale* page.
66    #[must_use]
67    pub const fn label(self) -> &'static str {
68        match self {
69            Self::Domain => "",
70            Self::General => "[general]",
71            Self::Standard => "[standard]",
72        }
73    }
74}
75
76/// Publication type, used to choose the BibTeX/RIS/CFF entry type.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
78pub enum Kind {
79    /// Journal article.
80    Article,
81    /// Paper in conference proceedings.
82    Proceedings,
83    /// Chapter in an edited book or a lecture-notes volume.
84    Chapter,
85    /// A standard or specification (RFC, W3C recommendation, Unicode annex, SI Brochure, format
86    /// or symbol definition).
87    Standard,
88}
89
90/// One bibliographic reference.
91#[derive(Debug, PartialEq, Eq)]
92pub struct Citation {
93    /// Stable citation key (`familyYYYY`, lower-case ASCII).
94    pub key: &'static str,
95    /// Authors in publication order as `(family, given)`. A group author has an empty `given`.
96    pub authors: &'static [(&'static str, &'static str)],
97    /// Year of the issue (for the DiMA paper: 2025, although it was published online in 2024).
98    pub year: u16,
99    /// Title, sentence case as published.
100    pub title: &'static str,
101    /// Journal, proceedings, book or issuing body.
102    pub venue: &'static str,
103    /// Volume, if any.
104    pub volume: Option<&'static str>,
105    /// Issue, if any.
106    pub issue: Option<&'static str>,
107    /// Page range (`first-last`) or article number.
108    pub pages: Option<&'static str>,
109    /// DOI without the resolver prefix.
110    pub doi: Option<&'static str>,
111    /// Canonical URL, for references without a DOI.
112    pub url: Option<&'static str>,
113    /// Publication type.
114    pub kind: Kind,
115    /// Citation-policy tier.
116    pub tier: Tier,
117}
118
119/// Citation key of the DiMA paper (Tharanga et al. 2025).
120pub const DIMA_PAPER: &str = "tharanga2025";
121
122/// The DiMA paper: Tharanga et al., *Brief Bioinform* 2025;26(1):bbae607.
123#[must_use]
124pub fn dima_paper() -> &'static Citation {
125    by_key(DIMA_PAPER).expect("the DiMA paper is always present")
126}
127
128/// Authors of this software (`(family, given)`), as listed in `Cargo.toml`.
129pub const SOFTWARE_AUTHORS: &[(&str, &str)] = &[("Tharanga", "Shan")];
130
131/// Public source repository of this software.
132pub const SOFTWARE_REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
133
134/// The documentation this build links to (D113): that of its own version (`…/vX.Y/`) for a
135/// release build, that of the development version (`…/latest/`) otherwise.
136pub const DOCS_URL: &str = env!("DIMA_DOCS_URL");
137
138/// The documentation of a release of this software, e.g. `…/dima-perf/v1.0/` for 1.0.0.
139#[must_use]
140pub fn release_docs_url(version: &str) -> String {
141    let mut parts = version.split('.');
142    format!(
143        "{}v{}.{}/",
144        env!("CARGO_PKG_HOMEPAGE"),
145        parts.next().unwrap_or("0"),
146        parts.next().unwrap_or("0")
147    )
148}
149
150/// Keywords describing this software (CITATION.cff, .zenodo.json).
151pub const SOFTWARE_KEYWORDS: &[&str] = &[
152    "bioinformatics",
153    "virology",
154    "sequence diversity",
155    "Shannon entropy",
156    "k-mer",
157    "multiple sequence alignment",
158];
159
160/// Version of this software.
161pub const SOFTWARE_VERSION: &str = env!("CARGO_PKG_VERSION");
162
163/// References without a Crossref DOI (books, older papers, specifications). Sorted by key.
164static OTHER_CITATIONS: &[Citation] = &[
165    Citation {
166        key: "charmodnorm",
167        authors: &[("Phillips", "Addison")],
168        year: 2021,
169        title: "Character Model for the World Wide Web: String Matching",
170        venue: "W3C Working Group Note",
171        volume: None,
172        issue: None,
173        pages: None,
174        doi: None,
175        url: Some("https://www.w3.org/TR/2021/NOTE-charmod-norm-20210811/"),
176        kind: Kind::Standard,
177        tier: Tier::Standard,
178    },
179    Citation {
180        key: "dpubaria11",
181        authors: &[("Garrish", "Matt"), ("Siegman", "Tzviya")],
182        year: 2025,
183        title: "Digital Publishing WAI-ARIA Module 1.1",
184        venue: "W3C Recommendation",
185        volume: None,
186        issue: None,
187        pages: None,
188        doi: None,
189        url: Some("https://www.w3.org/TR/2025/REC-dpub-aria-1.1-20250612/"),
190        kind: Kind::Standard,
191        tier: Tier::Standard,
192    },
193    Citation {
194        key: "kuiken2003",
195        authors: &[
196            ("Kuiken", "Carla"),
197            ("Korber", "Bette"),
198            ("Shafer", "Robert W."),
199        ],
200        year: 2003,
201        title: "HIV sequence databases",
202        venue: "AIDS Reviews",
203        volume: Some("5"),
204        issue: Some("1"),
205        pages: Some("52-61"),
206        doi: None,
207        url: Some("https://europepmc.org/article/MED/12875108"),
208        kind: Kind::Article,
209        tier: Tier::Domain,
210    },
211    Citation {
212        key: "lanlcodes",
213        authors: &[("Los Alamos HIV Sequence Database", "")],
214        year: 2009,
215        title: "Codes and Symbols in Sequence Alignments",
216        venue: "Los Alamos National Laboratory",
217        volume: None,
218        issue: None,
219        pages: None,
220        doi: None,
221        url: Some("https://www.hiv.lanl.gov/content/sequence/HelpDocs/IUPAC.html"),
222        kind: Kind::Standard,
223        tier: Tier::Standard,
224    },
225    Citation {
226        key: "lanlgenecutter",
227        authors: &[("Los Alamos HIV Sequence Database", "")],
228        year: 2024,
229        title: "Gene Cutter Help and Explanation",
230        venue: "Los Alamos National Laboratory",
231        volume: None,
232        issue: None,
233        pages: None,
234        doi: None,
235        url: Some("https://www.hiv.lanl.gov/content/sequence/GENE_CUTTER/cutter-help.html"),
236        kind: Kind::Standard,
237        tier: Tier::Standard,
238    },
239    Citation {
240        key: "miller1955",
241        authors: &[("Miller", "George A.")],
242        year: 1955,
243        title: "Note on the bias of information estimates",
244        venue: "Information Theory in Psychology: Problems and Methods (Quastler H, ed.), Free Press, Glencoe, IL",
245        volume: None,
246        issue: None,
247        pages: Some("95-100"),
248        doi: None,
249        url: None,
250        kind: Kind::Chapter,
251        tier: Tier::General,
252    },
253    Citation {
254        key: "rao1945",
255        authors: &[("Rao", "C. Radhakrishna")],
256        year: 1945,
257        title: "Information and the accuracy attainable in the estimation of statistical parameters",
258        venue: "Bulletin of the Calcutta Mathematical Society",
259        volume: Some("37"),
260        issue: None,
261        pages: Some("81-91"),
262        doi: None,
263        url: None,
264        kind: Kind::Article,
265        tier: Tier::General,
266    },
267    Citation {
268        key: "uax15",
269        authors: &[("Whistler", "Ken")],
270        year: 2025,
271        title: "Unicode Standard Annex #15: Unicode Normalization Forms",
272        venue: "The Unicode Consortium",
273        volume: None,
274        issue: None,
275        pages: None,
276        doi: None,
277        url: Some("https://www.unicode.org/reports/tr15/tr15-57.html"),
278        kind: Kind::Standard,
279        tier: Tier::Standard,
280    },
281    Citation {
282        key: "uax44",
283        authors: &[("Unicode Consortium", "")],
284        year: 2025,
285        title: "Unicode Standard Annex #44: Unicode Character Database",
286        venue: "The Unicode Consortium",
287        volume: None,
288        issue: None,
289        pages: None,
290        doi: None,
291        url: Some("https://www.unicode.org/reports/tr44/tr44-36.html"),
292        kind: Kind::Standard,
293        tier: Tier::Standard,
294    },
295    Citation {
296        key: "wcag22",
297        authors: &[
298            ("Campbell", "Alastair"),
299            ("Adams", "Chuck"),
300            ("Bradley Montgomery", "Rachael"),
301            ("Cooper", "Michael"),
302            ("Kirkpatrick", "Andrew"),
303        ],
304        year: 2024,
305        title: "Web Content Accessibility Guidelines (WCAG) 2.2",
306        venue: "W3C Recommendation",
307        volume: None,
308        issue: None,
309        pages: None,
310        doi: None,
311        url: Some("https://www.w3.org/TR/2024/REC-WCAG22-20241212/"),
312        kind: Kind::Standard,
313        tier: Tier::Standard,
314    },
315    Citation {
316        key: "wcag2ict",
317        authors: &[("W3C Accessibility Guidelines Working Group", "")],
318        year: 2025,
319        title: "Guidance on Applying WCAG 2 to Non-Web Information and Communications Technologies (WCAG2ICT)",
320        venue: "W3C Group Note",
321        volume: None,
322        issue: None,
323        pages: None,
324        doi: None,
325        url: Some("https://www.w3.org/TR/2025/NOTE-wcag2ict-22-20251211/"),
326        kind: Kind::Standard,
327        tier: Tier::Standard,
328    },
329];
330
331/// The designations of standards labelled by them (see the module documentation), by key.
332/// Sorted by key.
333static DESIGNATIONS: &[(&str, &str)] = &[
334    ("bipm2019", "SI Brochure"),
335    ("dpubaria11", "DPUB-ARIA 1.1"),
336    ("rfc4180", "RFC 4180"),
337    ("rfc6596", "RFC 6596"),
338    ("rfc7322", "RFC 7322"),
339    ("rfc8259", "RFC 8259"),
340    ("rfc9309", "RFC 9309"),
341    ("uax15", "UAX #15"),
342    ("uax44", "UAX #44"),
343    ("wcag22", "WCAG 2.2"),
344    ("wcag2ict", "WCAG2ICT"),
345];
346
347/// Looks a reference up by key.
348#[must_use]
349pub fn by_key(key: &str) -> Option<&'static Citation> {
350    [data::DOI_CITATIONS, OTHER_CITATIONS]
351        .into_iter()
352        .find_map(|list| {
353            list.binary_search_by(|c| c.key.cmp(key))
354                .ok()
355                .map(|i| &list[i])
356        })
357}
358
359/// Every reference, sorted by key.
360#[must_use]
361pub fn all() -> &'static [&'static Citation] {
362    static ALL: OnceLock<Vec<&'static Citation>> = OnceLock::new();
363    ALL.get_or_init(|| {
364        let mut v: Vec<&'static Citation> =
365            data::DOI_CITATIONS.iter().chain(OTHER_CITATIONS).collect();
366        v.sort_unstable_by_key(|c| c.key);
367        v
368    })
369}
370
371/// A use of a reference, optionally pointing at a specific rule, figure or section
372/// (for example `Cite::new("list2017").at("Rule 5")`).
373#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
374pub struct Cite {
375    /// Citation key.
376    pub key: &'static str,
377    /// Location inside the work ("Rule 5", "Fig. 2", "SC 1.4.11").
378    pub locator: Option<&'static str>,
379}
380
381impl Cite {
382    /// A whole-work citation.
383    #[must_use]
384    pub const fn new(key: &'static str) -> Self {
385        Self { key, locator: None }
386    }
387
388    /// The same citation pointing at a specific location.
389    #[must_use]
390    pub const fn at(self, locator: &'static str) -> Self {
391        Self {
392            key: self.key,
393            locator: Some(locator),
394        }
395    }
396
397    /// The referenced work.
398    ///
399    /// # Panics
400    /// If the key is unknown; every key used in the code base is checked by a unit test.
401    #[must_use]
402    pub fn citation(self) -> &'static Citation {
403        by_key(self.key).unwrap_or_else(|| panic!("unknown citation key {:?}", self.key))
404    }
405
406    /// Short in-text form with locator, e.g. `List et al. 2017, Rule 5`.
407    #[must_use]
408    pub fn short(self) -> String {
409        let mut s = self.citation().short();
410        if let Some(loc) = self.locator {
411            s.push_str(", ");
412            s.push_str(loc);
413        }
414        s
415    }
416
417    /// Narrative in-text form, with the year and locator in parentheses, e.g.
418    /// `Tharanga et al. (2025, Fig. 2)`.
419    #[must_use]
420    pub fn narrative(self) -> String {
421        let c = self.citation();
422        if let Some(d) = c.designation() {
423            return self
424                .locator
425                .map_or_else(|| d.to_owned(), |loc| format!("{d} ({loc})"));
426        }
427        let mut s = format!("{} ({}", c.label_names(), c.listed_year());
428        if let Some(loc) = self.locator {
429            s.push_str(", ");
430            s.push_str(loc);
431        }
432        s.push(')');
433        s
434    }
435
436    /// Short form with locator and DOI (or URL), as used at the end of CLI long help,
437    /// e.g. `Chao et al. 2013, doi:10.1111/2041-210X.12108`.
438    #[must_use]
439    pub fn reference(self) -> String {
440        let c = self.citation();
441        let mut s = self.short();
442        if let Some(link) = c.link() {
443            s.push_str(", ");
444            s.push_str(&link);
445        }
446        s
447    }
448}
449
450/// Initials of a given name: the first letter of each space-, hyphen- or dot-separated part
451/// (`"Hans-Georg"` → `"HG"`, `"C. Titus"` → `"CT"`).
452fn initials(given: &str) -> String {
453    given
454        .split(|c: char| c.is_whitespace() || c == '-' || c == '.')
455        .filter_map(|part| part.chars().next())
456        .flat_map(char::to_uppercase)
457        .collect()
458}
459
460/// Escapes a BibTeX field value: LaTeX special characters are backslash-escaped and braces are
461/// balanced by escaping them too.
462pub(crate) fn bibtex_escape(s: &str) -> String {
463    let mut out = String::with_capacity(s.len());
464    for ch in s.chars() {
465        match ch {
466            '&' | '%' | '$' | '#' | '_' | '{' | '}' => {
467                out.push('\\');
468                out.push(ch);
469            }
470            '~' => out.push_str("\\textasciitilde{}"),
471            '^' => out.push_str("\\textasciicircum{}"),
472            '\\' => out.push_str("\\textbackslash{}"),
473            _ => out.push(ch),
474        }
475    }
476    out
477}
478
479/// Splits `first-last` into its two pages; an article number yields `(number, None)`.
480fn page_range(pages: &str) -> (&str, Option<&str>) {
481    match pages.split_once('-') {
482        Some((a, b)) if !a.is_empty() && !b.is_empty() => (a, Some(b)),
483        _ => (pages, None),
484    }
485}
486
487/// Upper bound on authors listed in full by [`Citation::text`] before `et al.` (APA 7 lists up to
488/// 20 authors; long consortium author lists would otherwise dominate the output).
489const TEXT_MAX_AUTHORS: usize = 20;
490
491/// The in-text label of a reference without its year: the family names (`names`) and the year
492/// letter that tells it apart from works with identical names and year (`suffix`, usually empty).
493#[derive(Debug, Clone, PartialEq, Eq)]
494struct Label {
495    names: String,
496    suffix: String,
497}
498
499/// The family names of an in-text label: the first `n`, then "et al.", which always stands for at
500/// least two names (APA 7 §8.18), so a list at most one name longer than `n` is written in full.
501/// A reference without authors is labelled by its issuing body.
502fn label_names(c: &Citation, n: usize) -> String {
503    let family: Vec<&str> = c.authors.iter().map(|&(f, _)| f).collect();
504    match family.as_slice() {
505        [] => c.venue.to_owned(),
506        [a] => (*a).to_owned(),
507        [rest @ .., last] if family.len() <= n + 1 => format!("{} & {last}", rest.join(", ")),
508        _ => format!("{} et al.", family[..n].join(", ")),
509    }
510}
511
512/// Year letter number `i` (from 0): `a` … `z`, `aa`, `ab`, … (CSL 1.0.2 year-suffix).
513fn year_suffix(mut i: usize) -> String {
514    let mut letters = Vec::new();
515    loop {
516        letters.push(char::from(b'a' + (i % 26) as u8));
517        if i < 26 {
518            break;
519        }
520        i = i / 26 - 1;
521    }
522    letters.iter().rev().collect()
523}
524
525/// The title order of APA 7 §9.47: case-insensitive, ignoring a leading A, An or The.
526fn title_order(title: &str) -> String {
527    let t = title.to_lowercase();
528    ["a ", "an ", "the "]
529        .iter()
530        .find_map(|article| t.strip_prefix(article))
531        .unwrap_or(&t)
532        .to_owned()
533}
534
535/// The labels of `cites` by key, by the rule in the module documentation.
536fn disambiguate<'a>(cites: &[&'a Citation]) -> HashMap<&'a str, Label> {
537    let mut groups: BTreeMap<(String, u16), Vec<&'a Citation>> = BTreeMap::new();
538    for &c in cites {
539        groups
540            .entry((label_names(c, 1), c.year))
541            .or_default()
542            .push(c);
543    }
544    let mut out = HashMap::with_capacity(cites.len());
545    for group in groups.into_values() {
546        let longest = group
547            .iter()
548            .map(|c| c.authors.len())
549            .max()
550            .unwrap_or(1)
551            .max(1);
552        let distinct = |n: usize| {
553            group
554                .iter()
555                .map(|c| label_names(c, n))
556                .collect::<BTreeSet<_>>()
557                .len()
558        };
559        let most = distinct(longest);
560        let n = (1..=longest)
561            .find(|&n| distinct(n) == most)
562            .unwrap_or(longest);
563        let mut same: BTreeMap<String, Vec<&'a Citation>> = BTreeMap::new();
564        for &c in &group {
565            same.entry(label_names(c, n)).or_default().push(c);
566        }
567        for (names, mut works) in same {
568            if let [only] = works.as_slice() {
569                out.insert(
570                    only.key,
571                    Label {
572                        names,
573                        suffix: String::new(),
574                    },
575                );
576                continue;
577            }
578            works.sort_by_cached_key(|c| (title_order(c.title), c.key));
579            for (i, c) in works.into_iter().enumerate() {
580                out.insert(
581                    c.key,
582                    Label {
583                        names: names.clone(),
584                        suffix: year_suffix(i),
585                    },
586                );
587            }
588        }
589    }
590    out
591}
592
593/// The name-year label of every reference in the registry without a designation, by key.
594fn labels() -> &'static HashMap<&'static str, Label> {
595    static LABELS: OnceLock<HashMap<&'static str, Label>> = OnceLock::new();
596    LABELS.get_or_init(|| {
597        let named: Vec<&'static Citation> = all()
598            .iter()
599            .copied()
600            .filter(|c| c.designation().is_none())
601            .collect();
602        disambiguate(&named)
603    })
604}
605
606impl Citation {
607    /// `true` if this is the registry's entry for its key.
608    fn in_registry(&self) -> bool {
609        by_key(self.key).is_some_and(|c| c == self)
610    }
611
612    /// The registry's name-year label of this reference, if it is the registry's entry for its
613    /// key and has no designation.
614    fn registry_label(&self) -> Option<&'static Label> {
615        labels().get(self.key).filter(|_| self.in_registry())
616    }
617
618    /// The short name its publisher gives this standard, used as its label: `RFC 8259`,
619    /// `UAX #15`, `WCAG 2.2`; `None` for every other reference.
620    #[must_use]
621    pub fn designation(&self) -> Option<&'static str> {
622        DESIGNATIONS
623            .binary_search_by(|&(k, _)| k.cmp(self.key))
624            .ok()
625            .map(|i| DESIGNATIONS[i].1)
626            .filter(|_| self.in_registry())
627    }
628
629    /// The family names of the in-text label: `Tharanga et al.`, `Grüning, Dale et al.`. A
630    /// reference outside the registry has the plain form.
631    fn label_names(&self) -> String {
632        self.registry_label()
633            .map_or_else(|| label_names(self, 1), |l| l.names.clone())
634    }
635
636    /// The in-text label, the same on every surface: `Tharanga et al. 2025`,
637    /// `Grüning, Dale et al. 2018`, `RFC 8259` (see the module documentation for the rule).
638    #[must_use]
639    pub fn short(&self) -> String {
640        match self.designation() {
641            Some(d) => d.to_owned(),
642            None => format!("{} {}", self.label_names(), self.listed_year()),
643        }
644    }
645
646    /// The year as dima's own name-year lists show it: `2018`, or `2024a` when a year letter
647    /// tells apart works with identical authors and year.
648    #[must_use]
649    pub fn listed_year(&self) -> String {
650        let suffix = self.registry_label().map_or("", |l| l.suffix.as_str());
651        format!("{}{suffix}", self.year)
652    }
653
654    /// `doi:…` if the reference has a DOI, else its URL.
655    #[must_use]
656    pub fn link(&self) -> Option<String> {
657        self.doi
658            .map(|d| format!("doi:{d}"))
659            .or_else(|| self.url.map(str::to_owned))
660    }
661
662    /// Resolvable URL: `https://doi.org/…` for a DOI, else the stored URL.
663    #[must_use]
664    pub fn href(&self) -> Option<String> {
665        self.doi
666            .map(|d| format!("https://doi.org/{d}"))
667            .or_else(|| self.url.map(str::to_owned))
668    }
669
670    /// One author in Vancouver form: `Tharanga S`; a group author verbatim.
671    fn vancouver_author((family, given): (&str, &str)) -> String {
672        let ini = initials(given);
673        if ini.is_empty() {
674            family.to_owned()
675        } else {
676            format!("{family} {ini}")
677        }
678    }
679
680    /// Full plain-text reference (Vancouver/NLM style), as exported (`run.references`,
681    /// `dima cite`), e.g.
682    /// `Tharanga S, Ünlü ES, … Khan AM. DiMA: sequence diversity dynamics analyser for viruses.
683    /// Briefings in Bioinformatics. 2025;26(1):bbae607. doi:10.1093/bib/bbae607`.
684    #[must_use]
685    pub fn text(&self) -> String {
686        self.render(&self.year.to_string())
687    }
688
689    /// [`Citation::text`] as dima's own reference lists show it (the documentation and its
690    /// Bibliography): led by the designation of a standard that has one, and with a year letter
691    /// where the label has one ([`Citation::listed_year`]).
692    #[must_use]
693    pub fn listed_text(&self) -> String {
694        let text = self.render(&self.listed_year());
695        match self.designation() {
696            Some(d) => format!("{d}. {text}"),
697            None => text,
698        }
699    }
700
701    /// The full reference with `year` as its year.
702    fn render(&self, year: &str) -> String {
703        let mut s = String::new();
704        let listed = self.authors.len().min(TEXT_MAX_AUTHORS);
705        for (i, &a) in self.authors[..listed].iter().enumerate() {
706            if i > 0 {
707                s.push_str(", ");
708            }
709            s.push_str(&Self::vancouver_author(a));
710        }
711        if self.authors.len() > listed {
712            s.push_str(", et al");
713        }
714        if !s.is_empty() {
715            s.push_str(". ");
716        }
717        s.push_str(self.title);
718        if !self.title.ends_with(['?', '!', '.']) {
719            s.push('.');
720        }
721        match self.kind {
722            Kind::Article => {
723                let _ = write!(s, " {}. {year}", self.venue);
724                if let Some(v) = self.volume {
725                    let _ = write!(s, ";{v}");
726                    if let Some(i) = self.issue {
727                        let _ = write!(s, "({i})");
728                    }
729                }
730                if let Some(p) = self.pages {
731                    let _ = write!(s, ":{p}");
732                }
733                s.push('.');
734            }
735            Kind::Proceedings | Kind::Chapter => {
736                let _ = write!(s, " In: {}. {year}", self.venue);
737                if let Some(v) = self.volume {
738                    let _ = write!(s, ";{v}");
739                }
740                if let Some(p) = self.pages {
741                    let _ = write!(s, ". p. {p}");
742                }
743                s.push('.');
744            }
745            Kind::Standard => {
746                let _ = write!(s, " {}; {year}.", self.venue);
747            }
748        }
749        if let Some(d) = self.doi {
750            let _ = write!(s, " doi:{d}");
751        } else if let Some(u) = self.url {
752            let _ = write!(s, " {u}");
753        }
754        s
755    }
756
757    /// BibTeX entry.
758    #[must_use]
759    pub fn bibtex(&self) -> String {
760        let (ty, venue_field) = match self.kind {
761            Kind::Article => ("article", "journal"),
762            Kind::Proceedings => ("inproceedings", "booktitle"),
763            Kind::Chapter => ("incollection", "booktitle"),
764            Kind::Standard => ("misc", "howpublished"),
765        };
766        let authors = self
767            .authors
768            .iter()
769            .map(|&(family, given)| {
770                if given.is_empty() {
771                    // Braces keep a group author from being parsed as "Last, First".
772                    format!("{{{}}}", bibtex_escape(family))
773                } else {
774                    format!("{{{}}}, {}", bibtex_escape(family), bibtex_escape(given))
775                }
776            })
777            .collect::<Vec<_>>()
778            .join(" and ");
779        let mut s = format!("@{ty}{{{},\n", self.key);
780        let mut field = |name: &str, value: &str| {
781            let _ = writeln!(s, "  {name:<9} = {{{value}}},");
782        };
783        if !authors.is_empty() {
784            field("author", &authors);
785        }
786        // Double braces preserve the published capitalisation.
787        field("title", &format!("{{{}}}", bibtex_escape(self.title)));
788        field(venue_field, &bibtex_escape(self.venue));
789        field("year", &self.year.to_string());
790        if let Some(v) = self.volume {
791            field("volume", &bibtex_escape(v));
792        }
793        if let Some(i) = self.issue {
794            field("number", &bibtex_escape(i));
795        }
796        if let Some(p) = self.pages {
797            match page_range(p) {
798                (a, Some(b)) => field("pages", &format!("{a}--{b}")),
799                (n, None) => field("pages", &bibtex_escape(n)),
800            }
801        }
802        if let Some(d) = self.doi {
803            field("doi", d);
804        }
805        if let Some(u) = self.url {
806            field("url", u);
807        }
808        s.push('}');
809        s
810    }
811
812    /// RIS record (one tag per line, terminated by `ER  -`).
813    #[must_use]
814    pub fn ris(&self) -> String {
815        let ty = match self.kind {
816            Kind::Article => "JOUR",
817            Kind::Proceedings => "CONF",
818            Kind::Chapter => "CHAP",
819            Kind::Standard => "STAND",
820        };
821        let mut s = String::new();
822        let mut tag = |t: &str, v: &str| {
823            let _ = writeln!(s, "{t}  - {v}");
824        };
825        tag("TY", ty);
826        for &(family, given) in self.authors {
827            if given.is_empty() {
828                tag("AU", family);
829            } else {
830                tag("AU", &format!("{family}, {given}"));
831            }
832        }
833        tag("TI", self.title);
834        tag("T2", self.venue);
835        tag("PY", &self.year.to_string());
836        if let Some(v) = self.volume {
837            tag("VL", v);
838        }
839        if let Some(i) = self.issue {
840            tag("IS", i);
841        }
842        if let Some(p) = self.pages {
843            let (a, b) = page_range(p);
844            tag("SP", a);
845            if let Some(b) = b {
846                tag("EP", b);
847            }
848        }
849        if let Some(d) = self.doi {
850            tag("DO", d);
851        }
852        if let Some(u) = self.href() {
853            tag("UR", &u);
854        }
855        tag("ER", "");
856        // RIS readers expect "ER  - " followed by end of line; keep the trailing space.
857        s
858    }
859
860    /// The reference as a CFF 1.2.0 `reference` object, as YAML lines indented by `indent`
861    /// spaces (the first line starts with `type:`).
862    #[must_use]
863    pub fn cff(&self, indent: usize) -> String {
864        let pad = " ".repeat(indent);
865        let q = |v: &str| serde_json::to_string(v).expect("strings always serialise");
866        let ty = match self.kind {
867            Kind::Article => "article",
868            Kind::Proceedings => "conference-paper",
869            Kind::Chapter => "book",
870            Kind::Standard => "standard",
871        };
872        let mut s = String::new();
873        let _ = writeln!(s, "{pad}type: {ty}");
874        let _ = writeln!(s, "{pad}authors:");
875        for &(family, given) in self.authors {
876            if given.is_empty() {
877                let _ = writeln!(s, "{pad}  - name: {}", q(family));
878            } else {
879                let _ = writeln!(s, "{pad}  - family-names: {}", q(family));
880                let _ = writeln!(s, "{pad}    given-names: {}", q(given));
881            }
882        }
883        let _ = writeln!(s, "{pad}title: {}", q(self.title));
884        let venue_key = match self.kind {
885            Kind::Article => "journal",
886            Kind::Proceedings => "conference",
887            Kind::Chapter => "collection-title",
888            Kind::Standard => "publisher",
889        };
890        if self.kind == Kind::Proceedings || self.kind == Kind::Standard {
891            let _ = writeln!(s, "{pad}{venue_key}:");
892            let _ = writeln!(s, "{pad}  name: {}", q(self.venue));
893        } else {
894            let _ = writeln!(s, "{pad}{venue_key}: {}", q(self.venue));
895        }
896        let _ = writeln!(s, "{pad}year: {}", self.year);
897        if let Some(v) = self.volume {
898            let _ = writeln!(s, "{pad}volume: {}", q(v));
899        }
900        if let Some(i) = self.issue {
901            let _ = writeln!(s, "{pad}issue: {}", q(i));
902        }
903        if let Some(p) = self.pages {
904            match page_range(p) {
905                (a, Some(b)) => {
906                    let _ = writeln!(s, "{pad}start: {}", q(a));
907                    let _ = writeln!(s, "{pad}end: {}", q(b));
908                }
909                (n, None) => {
910                    let _ = writeln!(s, "{pad}start: {}", q(n));
911                }
912            }
913        }
914        if let Some(d) = self.doi {
915            let _ = writeln!(s, "{pad}doi: {}", q(d));
916        }
917        if let Some(u) = self.url {
918            let _ = writeln!(s, "{pad}url: {}", q(u));
919        }
920        s
921    }
922}
923
924/// Plain-text citation of a release of this software (usually [`SOFTWARE_VERSION`]; the version
925/// recorded in a results file for `dima cite --from`), e.g.
926/// `Tharanga S. dima: sequence diversity dynamics analyser for viruses (Rust implementation),
927/// version 1.0.0. https://github.com/…`.
928#[must_use]
929pub fn software_text(version: &str) -> String {
930    let authors = SOFTWARE_AUTHORS
931        .iter()
932        .map(|&a| Citation::vancouver_author(a))
933        .collect::<Vec<_>>()
934        .join(", ");
935    format!("{authors}. {SOFTWARE_TITLE}, version {version} [software]. {SOFTWARE_REPOSITORY}")
936}
937
938/// Title of this software in citations.
939pub const SOFTWARE_TITLE: &str =
940    "dima: sequence diversity dynamics analyser for viruses (Rust implementation)";
941
942/// BibTeX entry for a release of this software.
943#[must_use]
944pub fn software_bibtex(version: &str) -> String {
945    let authors = SOFTWARE_AUTHORS
946        .iter()
947        .map(|&(f, g)| format!("{{{f}}}, {g}"))
948        .collect::<Vec<_>>()
949        .join(" and ");
950    let key = format!("dima_rs_{}", version.replace(['.', '-', '+'], "_"));
951    let title = bibtex_escape(SOFTWARE_TITLE);
952    format!(
953        "@software{{{key},\n  author    = {{{authors}}},\n  title     = {{{{{title}}}}},\n  \
954         version   = {{{version}}},\n  url       = {{{SOFTWARE_REPOSITORY}}},\n  \
955         note      = {{Implements the method of Tharanga et al. 2025, doi:10.1093/bib/bbae607}},\n}}"
956    )
957}
958
959/// RIS record for a release of this software.
960#[must_use]
961pub fn software_ris(version: &str) -> String {
962    let mut s = String::from("TY  - COMP\n");
963    for &(f, g) in SOFTWARE_AUTHORS {
964        let _ = writeln!(s, "AU  - {f}, {g}");
965    }
966    let _ = writeln!(s, "TI  - {SOFTWARE_TITLE}");
967    let _ = writeln!(s, "ET  - {version}");
968    let _ = writeln!(s, "UR  - {SOFTWARE_REPOSITORY}");
969    s.push_str("ER  - \n");
970    s
971}
972
973/// A CFF 1.2.0 document describing a release of this software, with the DiMA paper as
974/// `preferred-citation` and `extra` as additional `references` (the content of `CITATION.cff`,
975/// which `cargo xtask gen` prefixes with a generated-file comment).
976#[must_use]
977pub fn cff_document(version: &str, extra: &[&Citation]) -> String {
978    let q = |v: &str| serde_json::to_string(v).expect("strings always serialise");
979    let mut s = String::new();
980    s.push_str("cff-version: 1.2.0\n");
981    s.push_str("message: \"If you use DiMA, please cite the DiMA paper (preferred-citation) and the software version you used.\"\n");
982    s.push_str("type: software\n");
983    let _ = writeln!(s, "title: {}", q(SOFTWARE_TITLE));
984    let _ = writeln!(s, "version: {}", q(version));
985    s.push_str("license: MIT\n");
986    let _ = writeln!(s, "repository-code: {}", q(SOFTWARE_REPOSITORY));
987    let _ = writeln!(s, "url: {}", q(&release_docs_url(version)));
988    s.push_str("authors:\n");
989    for &(f, g) in SOFTWARE_AUTHORS {
990        let _ = writeln!(s, "  - family-names: {}\n    given-names: {}", q(f), q(g));
991    }
992    s.push_str("keywords:\n");
993    for k in SOFTWARE_KEYWORDS {
994        let _ = writeln!(s, "  - {}", q(k));
995    }
996    s.push_str("preferred-citation:\n");
997    s.push_str(&dima_paper().cff(2));
998    if !extra.is_empty() {
999        s.push_str("references:\n");
1000        for c in extra {
1001            let body = c.cff(4);
1002            // First line becomes the list item.
1003            let body = body.replacen("    type:", "  - type:", 1);
1004            s.push_str(&body);
1005        }
1006    }
1007    s
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use super::*;
1013
1014    #[test]
1015    fn keys_are_sorted_unique_and_well_formed() {
1016        for list in [data::DOI_CITATIONS, OTHER_CITATIONS] {
1017            for w in list.windows(2) {
1018                assert!(w[0].key < w[1].key, "{} !< {}", w[0].key, w[1].key);
1019            }
1020        }
1021        let mut keys: Vec<_> = all().iter().map(|c| c.key).collect();
1022        let n = keys.len();
1023        keys.dedup();
1024        assert_eq!(keys.len(), n, "duplicate keys across the two lists");
1025        for c in all() {
1026            assert!(
1027                c.key
1028                    .bytes()
1029                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()),
1030                "{}",
1031                c.key
1032            );
1033            assert!(by_key(c.key).is_some());
1034        }
1035        assert!(by_key("nope1900").is_none());
1036    }
1037
1038    #[test]
1039    fn records_are_complete() {
1040        for c in all() {
1041            assert!(!c.title.trim().is_empty(), "{}", c.key);
1042            assert!(!c.venue.trim().is_empty(), "{}", c.key);
1043            assert!(!c.authors.is_empty(), "{}", c.key);
1044            assert!(
1045                c.doi.is_some() || c.url.is_some() || c.kind != Kind::Standard,
1046                "{}",
1047                c.key
1048            );
1049            assert!((1900..=2100).contains(&c.year), "{}", c.key);
1050            for &(f, g) in c.authors {
1051                assert!(!f.trim().is_empty(), "{}", c.key);
1052                assert_eq!(f.trim(), f, "{}", c.key);
1053                assert_eq!(g.trim(), g, "{}", c.key);
1054            }
1055            for s in [c.title, c.venue] {
1056                assert!(
1057                    !s.contains('<') && !s.contains("&amp;") && !s.contains("  "),
1058                    "{}",
1059                    c.key
1060                );
1061            }
1062            if let Some(d) = c.doi {
1063                assert!(d.starts_with("10.") && d.contains('/'), "{}", c.key);
1064                assert!(!d.contains(char::is_whitespace), "{}", c.key);
1065            }
1066            if let Some(u) = c.url {
1067                assert!(u.starts_with("https://"), "{}", c.key);
1068            }
1069            if c.tier == Tier::Standard {
1070                assert_eq!(c.kind, Kind::Standard, "{}", c.key);
1071            }
1072        }
1073    }
1074
1075    #[test]
1076    fn dima_paper_is_exact() {
1077        let p = dima_paper();
1078        assert_eq!(p.doi, Some("10.1093/bib/bbae607"));
1079        assert_eq!(p.year, 2025);
1080        assert_eq!(p.short(), "Tharanga et al. 2025");
1081        assert_eq!(
1082            p.text(),
1083            "Tharanga S, Ünlü ES, Hu Y, Sjaugi MF, Çelik MA, Hekimoğlu H, Miotto O, Öncel MM, \
1084             Khan AM. DiMA: sequence diversity dynamics analyser for viruses. Briefings in \
1085             Bioinformatics. 2025;26(1):bbae607. doi:10.1093/bib/bbae607"
1086        );
1087    }
1088
1089    #[test]
1090    fn short_forms() {
1091        assert_eq!(by_key("shannon1948").unwrap().short(), "Shannon 1948");
1092        assert_eq!(by_key("chao2012").unwrap().short(), "Chao & Jost 2012");
1093        assert_eq!(
1094            Cite::new("list2017").at("Rule 5").short(),
1095            "List et al. 2017, Rule 5"
1096        );
1097        assert_eq!(
1098            Cite::new("chao2013").reference(),
1099            "Chao et al. 2013, doi:10.1111/2041-210X.12108"
1100        );
1101        assert_eq!(
1102            Cite::new("wcag22").at("SC 1.4.11").reference(),
1103            "WCAG 2.2, SC 1.4.11, https://www.w3.org/TR/2024/REC-WCAG22-20241212/"
1104        );
1105        assert_eq!(
1106            Cite::new("rfc6596").at("Section 3").narrative(),
1107            "RFC 6596 (Section 3)"
1108        );
1109        assert_eq!(by_key("uax15").unwrap().short(), "UAX #15");
1110    }
1111
1112    #[test]
1113    fn labels_are_unique() {
1114        let mut seen = HashMap::new();
1115        for c in all() {
1116            if let Some(other) = seen.insert(c.short(), c.key) {
1117                panic!("{} and {} share the label {:?}", other, c.key, c.short());
1118            }
1119        }
1120    }
1121
1122    #[test]
1123    fn colliding_works_add_names() {
1124        for (key, label) in [
1125            ("gruning2018bioconda", "Grüning, Dale et al. 2018"),
1126            ("gruning2018repro", "Grüning, Chilton et al. 2018"),
1127            ("mangul2019bench", "Mangul, Martin et al. 2019"),
1128            ("mangul2019install", "Mangul, Mosqueiro et al. 2019"),
1129        ] {
1130            assert_eq!(by_key(key).unwrap().short(), label);
1131        }
1132        assert_eq!(
1133            Cite::new("gruning2018repro").at("Box 1").narrative(),
1134            "Grüning, Chilton et al. (2018, Box 1)"
1135        );
1136        assert_eq!(
1137            Cite::new("tharanga2025").at("Fig. 2").narrative(),
1138            "Tharanga et al. (2025, Fig. 2)"
1139        );
1140    }
1141
1142    #[test]
1143    fn designations_label_standards_only() {
1144        for w in DESIGNATIONS.windows(2) {
1145            assert!(w[0].0 < w[1].0, "{} !< {}", w[0].0, w[1].0);
1146        }
1147        for &(key, d) in DESIGNATIONS {
1148            let c = by_key(key).unwrap_or_else(|| panic!("{key} is not in the registry"));
1149            assert_eq!(c.tier, Tier::Standard, "{key}");
1150            assert!(
1151                !d.is_empty() && d.trim() == d && d.is_ascii(),
1152                "{key}: {d:?}"
1153            );
1154            assert_eq!(c.short(), d);
1155            assert!(
1156                labels().get(key).is_none(),
1157                "{key} also has a name-year label"
1158            );
1159            assert_eq!(c.listed_text(), format!("{d}. {}", c.text()));
1160            assert!(
1161                !c.text().starts_with(d),
1162                "{key}: exported text carries the designation"
1163            );
1164        }
1165    }
1166
1167    #[test]
1168    fn et_al_stands_for_at_least_two_names() {
1169        for c in all() {
1170            let Some(label) = labels().get(c.key) else {
1171                continue;
1172            };
1173            if let Some(shown) = label.names.strip_suffix(" et al.") {
1174                let names = shown.split(", ").count();
1175                assert!(c.authors.len() >= names + 2, "{}: {:?}", c.key, label);
1176            }
1177        }
1178    }
1179
1180    #[test]
1181    fn year_letters_only_for_identical_authors() {
1182        // Different people with the same family names would need initials (APA 7 §8.20), not
1183        // letters, which say "the same authors".
1184        let mut lettered: BTreeMap<(&str, u16), Vec<&Citation>> = BTreeMap::new();
1185        for c in all() {
1186            let Some(label) = labels().get(c.key) else {
1187                continue;
1188            };
1189            if !label.suffix.is_empty() {
1190                lettered
1191                    .entry((label.names.as_str(), c.year))
1192                    .or_default()
1193                    .push(c);
1194            }
1195        }
1196        for works in lettered.values() {
1197            let people = |c: &Citation| -> Vec<(String, String)> {
1198                c.authors
1199                    .iter()
1200                    .map(|&(f, g)| (f.to_owned(), initials(g)))
1201                    .collect()
1202            };
1203            assert!(
1204                works.iter().all(|c| people(c) == people(works[0])),
1205                "different people share a label: add initials (APA 7 §8.20): {:?}",
1206                works.iter().map(|c| c.key).collect::<Vec<_>>()
1207            );
1208        }
1209        // No year letter reaches the exported text.
1210        for c in all() {
1211            assert!(c.text().contains(&c.year.to_string()), "{}", c.key);
1212            if c.designation().is_none() && labels()[c.key].suffix.is_empty() {
1213                assert_eq!(c.listed_text(), c.text(), "{}", c.key);
1214            }
1215        }
1216    }
1217
1218    fn fixture(
1219        key: &'static str,
1220        authors: &'static [(&'static str, &'static str)],
1221        title: &'static str,
1222    ) -> Citation {
1223        Citation {
1224            key,
1225            authors,
1226            year: 2018,
1227            title,
1228            venue: "Venue",
1229            volume: None,
1230            issue: None,
1231            pages: None,
1232            doi: None,
1233            url: None,
1234            kind: Kind::Article,
1235            tier: Tier::Domain,
1236        }
1237    }
1238
1239    fn fixture_labels(fixtures: &[Citation]) -> Vec<String> {
1240        let refs: Vec<&Citation> = fixtures.iter().collect();
1241        let labels = disambiguate(&refs);
1242        fixtures
1243            .iter()
1244            .map(|c| {
1245                let l = &labels[c.key];
1246                format!("{} {}{}", l.names, c.year, l.suffix)
1247            })
1248            .collect()
1249    }
1250
1251    #[test]
1252    fn references_outside_the_registry_have_plain_labels() {
1253        let outside = fixture(
1254            "gruning2018repro",
1255            &[("Grüning", "B"), ("Other", "A"), ("Third", "C")],
1256            "Elsewhere",
1257        );
1258        assert_eq!(outside.short(), "Grüning et al. 2018");
1259        assert_eq!(outside.listed_text(), outside.text());
1260        let unknown = fixture("nope2018", &[("Doe", "J")], "Unknown");
1261        assert_eq!(unknown.short(), "Doe 2018");
1262    }
1263
1264    #[test]
1265    fn label_rule_on_fixtures() {
1266        // APA 7 §8.18: names until the lists differ.
1267        let kapoor = [
1268            fixture(
1269                "k1",
1270                &[
1271                    ("Kapoor", "A"),
1272                    ("Bloom", "B"),
1273                    ("Montez", "C"),
1274                    ("Lee", "D"),
1275                    ("Ng", "E"),
1276                ],
1277                "One",
1278            ),
1279            fixture(
1280                "k2",
1281                &[
1282                    ("Kapoor", "A"),
1283                    ("Bloom", "B"),
1284                    ("Zucker", "C"),
1285                    ("Ng", "D"),
1286                    ("Lee", "E"),
1287                ],
1288                "Two",
1289            ),
1290        ];
1291        assert_eq!(
1292            fixture_labels(&kapoor),
1293            [
1294                "Kapoor, Bloom, Montez et al. 2018",
1295                "Kapoor, Bloom, Zucker et al. 2018"
1296            ]
1297        );
1298        // Only the last name differs: "et al." cannot stand for one name, so all are written.
1299        let hasan = [
1300            fixture(
1301                "h1",
1302                &[
1303                    ("Hasan", "A"),
1304                    ("Liang", "B"),
1305                    ("Kahn", "C"),
1306                    ("Jones-Miller", "D"),
1307                ],
1308                "One",
1309            ),
1310            fixture(
1311                "h2",
1312                &[
1313                    ("Hasan", "A"),
1314                    ("Liang", "B"),
1315                    ("Kahn", "C"),
1316                    ("Weintraub", "D"),
1317                ],
1318                "Two",
1319            ),
1320        ];
1321        assert_eq!(
1322            fixture_labels(&hasan),
1323            [
1324                "Hasan, Liang, Kahn & Jones-Miller 2018",
1325                "Hasan, Liang, Kahn & Weintraub 2018"
1326            ]
1327        );
1328        // One list is a prefix of the other.
1329        let prefix = [
1330            fixture("p1", &[("X", "A"), ("Y", "B"), ("Z", "C")], "One"),
1331            fixture(
1332                "p2",
1333                &[("X", "A"), ("Y", "B"), ("Z", "C"), ("W", "D")],
1334                "Two",
1335            ),
1336        ];
1337        assert_eq!(
1338            fixture_labels(&prefix),
1339            ["X, Y & Z 2018", "X, Y et al. 2018"]
1340        );
1341        // Identical lists get letters in title order, ignoring a leading article; a work with
1342        // a different list in the same group gets names only.
1343        let mixed = [
1344            fixture("m1", &[("G", "A"), ("D", "B"), ("S", "C")], "The zebra"),
1345            fixture("m2", &[("G", "A"), ("D", "B"), ("S", "C")], "Apples"),
1346            fixture("m3", &[("G", "A"), ("C", "B"), ("K", "C")], "Middle"),
1347        ];
1348        assert_eq!(
1349            fixture_labels(&mixed),
1350            ["G, D & S 2018b", "G, D & S 2018a", "G, C & K 2018"]
1351        );
1352        // A group author with identical works; a lone work keeps its plain label.
1353        let group = [
1354            fixture(
1355                "g1",
1356                &[("Los Alamos HIV Sequence Database", "")],
1357                "Landmarks",
1358            ),
1359            fixture(
1360                "g2",
1361                &[("Los Alamos HIV Sequence Database", "")],
1362                "Gene Cutter help",
1363            ),
1364            fixture("g3", &[("Shannon", "C")], "A mathematical theory"),
1365        ];
1366        assert_eq!(
1367            fixture_labels(&group),
1368            [
1369                "Los Alamos HIV Sequence Database 2018b",
1370                "Los Alamos HIV Sequence Database 2018a",
1371                "Shannon 2018",
1372            ]
1373        );
1374        assert_eq!(year_suffix(0), "a");
1375        assert_eq!(year_suffix(25), "z");
1376        assert_eq!(year_suffix(26), "aa");
1377        assert_eq!(year_suffix(27), "ab");
1378        assert_eq!(year_suffix(26 + 26 * 26), "aaa");
1379        assert_eq!(title_order("An Example"), "example");
1380        assert_eq!(title_order("Another"), "another");
1381    }
1382
1383    #[test]
1384    fn initials_handle_compound_and_dotted_names() {
1385        assert_eq!(initials("Hans-Georg"), "HG");
1386        assert_eq!(initials("C. Titus"), "CT");
1387        assert_eq!(initials("Justin J. J."), "JJJ");
1388        assert_eq!(initials("Eyyüb Selim"), "ES");
1389        assert_eq!(initials(""), "");
1390    }
1391
1392    #[test]
1393    fn group_authors_and_long_lists() {
1394        let g = by_key("goecks2010").unwrap();
1395        assert!(
1396            g.text()
1397                .starts_with("Goecks J, Nekrutenko A, Taylor J, Galaxy Team. Galaxy:")
1398        );
1399        assert!(g.bibtex().contains("{Taylor}, James and {Galaxy Team}"));
1400        let b = by_key("bolyen2019").unwrap();
1401        assert!(b.authors.len() > TEXT_MAX_AUTHORS);
1402        assert!(b.text().contains(", et al. Reproducible"));
1403        let bib = b.bibtex();
1404        let author_line = bib
1405            .lines()
1406            .find(|l| l.trim_start().starts_with("author"))
1407            .unwrap();
1408        assert_eq!(author_line.matches(" and ").count(), b.authors.len() - 1);
1409    }
1410
1411    #[test]
1412    fn bibtex_is_balanced_and_escaped() {
1413        for c in all() {
1414            let b = c.bibtex();
1415            let mut depth = 0i32;
1416            let mut prev = '\0';
1417            for ch in b.chars() {
1418                if prev != '\\' {
1419                    match ch {
1420                        '{' => depth += 1,
1421                        '}' => depth -= 1,
1422                        _ => {}
1423                    }
1424                }
1425                assert!(depth >= 0, "{}", c.key);
1426                prev = ch;
1427            }
1428            assert_eq!(depth, 0, "{}", c.key);
1429            assert!(b.starts_with('@') && b.ends_with('}'), "{}", c.key);
1430        }
1431        let m = by_key("maceachren2012").unwrap().bibtex();
1432        assert!(m.contains("Visual Semiotics \\& Uncertainty"));
1433        assert!(
1434            by_key("brown2001")
1435                .unwrap()
1436                .bibtex()
1437                .contains("pages     = {101--133}")
1438        );
1439    }
1440
1441    #[test]
1442    fn ris_records() {
1443        let r = dima_paper().ris();
1444        assert!(r.starts_with("TY  - JOUR\nAU  - Tharanga, Shan\n"));
1445        assert!(r.contains("SP  - bbae607\n"));
1446        assert!(!r.contains("EP  -"));
1447        assert!(r.ends_with("ER  - \n"));
1448        let r = by_key("brown2001").unwrap().ris();
1449        assert!(r.contains("SP  - 101\nEP  - 133\n"));
1450    }
1451
1452    #[test]
1453    fn cff_document_shape() {
1454        let doc = cff_document(SOFTWARE_VERSION, &[by_key("chao2013").unwrap()]);
1455        assert!(doc.contains("cff-version: 1.2.0\n"));
1456        assert!(doc.contains(&format!("version: \"{SOFTWARE_VERSION}\"\n")));
1457        assert!(doc.contains("preferred-citation:\n  type: article\n  authors:\n    - family-names: \"Tharanga\"\n      given-names: \"Shan\"\n"));
1458        assert!(doc.contains("  doi: \"10.1093/bib/bbae607\"\n"));
1459        assert!(doc.contains("references:\n  - type: article\n    authors:\n"));
1460        // Every line is either a comment, a top-level key, or indented by an even number of spaces.
1461        for line in doc.lines() {
1462            let indent = line.len() - line.trim_start().len();
1463            assert_eq!(indent % 2, 0, "{line}");
1464        }
1465    }
1466
1467    #[test]
1468    fn software_citations() {
1469        let t = software_text("0.9.1");
1470        assert!(t.starts_with("Tharanga S. dima: sequence diversity dynamics analyser"));
1471        assert!(t.contains(", version 0.9.1 [software]. "));
1472        let b = software_bibtex("0.9.1");
1473        assert!(b.starts_with("@software{dima_rs_0_9_1,\n"));
1474        assert!(b.contains("version   = {0.9.1}"));
1475        let r = software_ris("0.9.1");
1476        assert!(r.contains("ET  - 0.9.1\n") && r.ends_with("ER  - \n"));
1477        let cff = cff_document("0.9.1", &[]);
1478        assert!(cff.contains("version: \"0.9.1\"\n"));
1479        assert!(cff.contains("url: \"https://shanweera.github.io/dima-perf/v0.9/\"\n"));
1480        assert!(
1481            DOCS_URL.ends_with("/latest/") || DOCS_URL == release_docs_url(SOFTWARE_VERSION),
1482            "{DOCS_URL}"
1483        );
1484        assert!(env!("CARGO_PKG_AUTHORS").starts_with("Shan Tharanga"));
1485    }
1486}