Skip to main content

nameparser/
format.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Port of Java `org.gbif.nameparser.util.NameFormatter` — renders a [`ParsedName`] back
4//! into a formatted scientific-name string.
5//!
6//! The Java class exposes a family of convenience methods (`canonical`,
7//! `canonicalWithoutAuthorship`, `canonicalMinimal`, `canonicalComplete`,
8//! `canonicalCompleteHtml`, `authorshipComplete`, `authorString`) that all delegate to one
9//! private `buildName(ParsedName, 16 booleans)`. This port keeps that exact shape: the 16
10//! positional booleans become a named [`Flags`] struct (safer to read than 16 positional
11//! `bool`s while preserving the same semantics), each public method fills the same flag
12//! values Java passes, and [`build_name`] mirrors the Java control flow statement for
13//! statement. The public entry points hang off [`ParsedName`] as methods so bindings can
14//! call e.g. `pn.canonical_name()`.
15//!
16//! Cross-validated byte-for-byte against Java `NameFormatter` over the full corpus by
17//! `tests/format_golden.rs` (the Java oracle emits the same five renderings per name).
18
19use std::sync::LazyLock;
20
21use regex::Regex;
22use unicode_normalization::UnicodeNormalization;
23
24use crate::model::enums::{NamePart, NameType, NomCode, Rank};
25use crate::model::name::{Authorship, CombinedAuthorship, ParsedName};
26use crate::model::Informal;
27use crate::unicode::java_trim;
28
29const HYBRID_MARKER: char = '×';
30const NOTHO_PREFIX: &str = "notho";
31const ET_AL: &str = "et al.";
32const ITALICS_OPEN: &str = "<i>";
33const ITALICS_CLOSE: &str = "</i>";
34
35/// Java `NameFormatter.AL` = `^al\.?$`, tested with `Matcher.find()`. Detects a trailing
36/// "al"/"al." author so `X, al.` renders with " et al." rather than " & al.". The `^…$`
37/// anchors make find() a whole-string test for every real author token; the one Java/Rust
38/// `$` difference (Java `$` also matches just before a trailing `\n`, Rust `$` = `\z` does
39/// not) is unreachable — author tokens never carry a trailing line terminator.
40static AL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^al\.?$").unwrap());
41
42/// Java `NameFormatter.PHRASE_SPECIES_MARKER` = `^(?:species|spec|sp)\b.*`
43/// (CASE_INSENSITIVE, tested with `Matcher.matches()`). Java's `\b` here is ASCII (no
44/// UNICODE_CHARACTER_CLASS flag on this pattern), so it is pinned to `(?-u:\b)`. Detects a
45/// phrase that already spells out the species marker as its leading word ("species 1"), so
46/// the formatter must not also synthesise an "sp." marker.
47static PHRASE_SPECIES_MARKER: LazyLock<Regex> =
48    LazyLock::new(|| Regex::new(r"(?i)^(?:species|spec|sp)(?-u:\b).*$").unwrap());
49
50/// Java's inline author-tail pattern `(?U)[\p{Lu}](?:\.[\p{Lu}])*\..+`, tested with
51/// `String.matches()` (full match → anchored `^…$` here). Recognises an author-shaped tail
52/// after a phrase's parenthesised collector reference (e.g. "…(D.Murfet 3190) R.J.Bates"),
53/// which canonical rendering drops. `\p{Lu}` is Unicode by default in the Rust `regex`
54/// crate, matching Java's `(?U)` flag. The `.`/`$` line-terminator set differs subtly from
55/// Java's (Rust `.` excludes only `\n`; Java's also excludes `\r`/U+0085/U+2028/U+2029), but
56/// the tail is `java_trim`'d and realistic author tails contain no embedded line terminators,
57/// so it is not observable. The sibling `PHRASE_SPECIES_MARKER` shares this caveat.
58static PHRASE_AUTHOR_TAIL: LazyLock<Regex> =
59    LazyLock::new(|| Regex::new(r"^[\p{Lu}](?:\.[\p{Lu}])*\..+$").unwrap());
60
61/// The 16 boolean knobs of Java `NameFormatter.buildName`, one named field per positional
62/// argument (declaration order matches Java's parameter order). See the Java Javadoc for
63/// each flag's meaning; the field docs below repeat the load-bearing ones.
64struct Flags {
65    /// include the hybrid marker (×) with the name if existing
66    hybrid_marker: bool,
67    /// include the infraspecific or infrageneric rank marker with the name if existing
68    rank_marker: bool,
69    /// include the name's authorship (author team and year)
70    authorship: bool,
71    /// show the genus for infrageneric names
72    genus_for_infrageneric: bool,
73    /// include the infrageneric name in brackets for species or infraspecies
74    infrageneric: bool,
75    /// decompose unicode ligatures into their ascii ones, e.g. æ becomes ae
76    decomposition: bool,
77    /// transform unicode letters into their ascii ones, e.g. ø becomes o and ü u
78    ascii_only: bool,
79    /// include the epithet qualifiers
80    show_qualifier: bool,
81    /// include the rank marker for incomplete determinations, e.g. Puma spec.
82    show_indet: bool,
83    /// include nomenclatural notes
84    nom_note: bool,
85    /// include the sensu/sec taxonomic note
86    show_sensu: bool,
87    /// include the cultivar epithet
88    show_cultivar: bool,
89    /// include the phrase name
90    show_phrase: bool,
91    /// include the strain (a non-phrase `phrase` value)
92    show_strain: bool,
93    /// render the genus author of an infrageneric name and the species author of a
94    /// below-species name
95    show_extra_authorship: bool,
96    /// add html `<i>` markup around the italicised parts
97    html: bool,
98}
99
100impl Informal {
101    /// The canonical string form of this informal name — e.g. `"Rhizobium sp. RMCC TR1811"`,
102    /// `"Ichneumonidae sp."`, `"Bartonella group"`. Mirrors Java `NameFormatter.canonical(Informal)`:
103    /// it rebuilds the equivalent `INFORMAL` [`ParsedName`] — the [`Informal::taxon`] in the genus
104    /// slot, or the uninomial slot for a non-genus anchor — and renders it through
105    /// [`ParsedName::canonical_name_without_authorship`], so the synthetic `sp.` marker and the
106    /// phrase land exactly where the parser would place them. Never empty: falls back to the bare
107    /// taxon should the rebuilt name render nothing. Named to parallel
108    /// [`ParsedName::canonical_name`] so bindings expose one method across both result variants.
109    pub fn canonical_name(&self) -> String {
110        let pn = ParsedName {
111            type_: NameType::Informal,
112            rank: self.rank,
113            code: self.code,
114            phrase: self.phrase.clone(),
115            genus: (self.taxon_rank == Rank::Genus).then(|| self.taxon.clone()),
116            uninomial: (self.taxon_rank != Rank::Genus).then(|| self.taxon.clone()),
117            ..ParsedName::default()
118        };
119        pn.canonical_name_without_authorship()
120            .unwrap_or_else(|| self.taxon.clone())
121    }
122}
123
124impl ParsedName {
125    /// Java `NameFormatter.canonical(ParsedName)`. A full scientific name with authorship in
126    /// its canonical form. Autonym authorship is placed per the nomenclatural code (after the
127    /// species epithet for botany, at the very end for zoology); subspecies use the `subsp.`
128    /// rank marker unless the name is zoological.
129    pub fn canonical_name(&self) -> Option<String> {
130        build_name(
131            self,
132            &Flags {
133                hybrid_marker: true,
134                rank_marker: true,
135                authorship: true,
136                genus_for_infrageneric: true,
137                infrageneric: false,
138                decomposition: false,
139                ascii_only: false,
140                show_qualifier: true,
141                show_indet: true,
142                nom_note: false,
143                show_sensu: false,
144                show_cultivar: true,
145                show_phrase: true,
146                show_strain: true,
147                show_extra_authorship: false,
148                html: false,
149            },
150        )
151    }
152
153    /// Java `NameFormatter.canonicalWithoutAuthorship(ParsedName)`. As [`Self::canonical_name`]
154    /// but omitting any authorship.
155    pub fn canonical_name_without_authorship(&self) -> Option<String> {
156        build_name(
157            self,
158            &Flags {
159                hybrid_marker: true,
160                rank_marker: true,
161                authorship: false,
162                genus_for_infrageneric: true,
163                infrageneric: false,
164                decomposition: false,
165                ascii_only: false,
166                show_qualifier: true,
167                show_indet: true,
168                nom_note: false,
169                show_sensu: false,
170                show_cultivar: true,
171                show_phrase: true,
172                show_strain: true,
173                show_extra_authorship: false,
174                html: false,
175            },
176        )
177    }
178
179    /// Java `NameFormatter.canonicalMinimal(ParsedName)`. Just the three main name parts
180    /// (genus, species, infraspecific) — no rank or hybrid markers, no authorship, cultivar
181    /// or strain. Infrageneric names are shown without a leading genus. Unicode characters
182    /// are folded to their ascii equivalents.
183    pub fn canonical_name_minimal(&self) -> Option<String> {
184        build_name(
185            self,
186            &Flags {
187                hybrid_marker: false,
188                rank_marker: false,
189                authorship: false,
190                genus_for_infrageneric: false,
191                infrageneric: false,
192                decomposition: true,
193                ascii_only: true,
194                show_qualifier: false,
195                show_indet: false,
196                nom_note: false,
197                show_sensu: false,
198                show_cultivar: false,
199                show_phrase: false,
200                show_strain: false,
201                show_extra_authorship: false,
202                html: false,
203            },
204        )
205    }
206
207    /// Java `NameFormatter.canonicalComplete(ParsedName)`. A full name with all details,
208    /// including non-code-compliant informal remarks (subgenus in brackets, strain, sensu,
209    /// nom. note, extra authorship). Unicode ligatures are decomposed.
210    pub fn canonical_name_complete(&self) -> Option<String> {
211        build_name(self, &complete_flags(false))
212    }
213
214    /// Java `NameFormatter.canonicalCompleteHtml(ParsedName)`. As
215    /// [`Self::canonical_name_complete`] but with `<i>…</i>` markup around the italicised
216    /// name parts.
217    pub fn canonical_name_complete_html(&self) -> Option<String> {
218        build_name(self, &complete_flags(true))
219    }
220
221    /// Java `NameFormatter.authorshipComplete(ParsedName)`. The full concatenated authorship
222    /// (basionym in brackets, combination, sanctioning author, years) using the name's own
223    /// nomenclatural code, or `None` when the name carries no authorship.
224    pub fn authorship_complete(&self) -> Option<String> {
225        let mut sb = String::new();
226        append_authorship_parts(
227            &mut sb,
228            &self.basionym_authorship,
229            &self.combination_authorship,
230            self.sanctioning_author.as_deref(),
231            true,
232            self.code,
233        );
234        if sb.is_empty() {
235            None
236        } else {
237            Some(sb)
238        }
239    }
240
241    // ---- ParsedName predicates the formatter relies on (Java `ParsedName` API) ----
242
243    /// Java `ParsedName.hasGenericAuthorship()`: the infrageneric genus author slot carries
244    /// an actual authorship.
245    pub fn has_generic_authorship(&self) -> bool {
246        self.generic_authorship
247            .as_ref()
248            .is_some_and(CombinedAuthorship::has_authorship)
249    }
250
251    /// Java `ParsedName.hasSpecificAuthorship()`: the below-species species-author slot
252    /// carries an actual authorship.
253    pub fn has_specific_authorship(&self) -> bool {
254        self.specific_authorship
255            .as_ref()
256            .is_some_and(CombinedAuthorship::has_authorship)
257    }
258
259    /// Java `ParsedName.hasEpithetQualifier(NamePart)`: a qualifier (cf./aff./…) is recorded
260    /// for the given name part.
261    pub fn has_epithet_qualifier(&self, part: NamePart) -> bool {
262        self.epithet_qualifier
263            .as_ref()
264            .is_some_and(|m| m.contains_key(&part))
265    }
266
267    /// Java `ParsedName.isHybridName()`: at least one part is marked notho- (a named hybrid).
268    pub fn is_hybrid_name(&self) -> bool {
269        self.notho.as_ref().is_some_and(|s| !s.is_empty())
270    }
271
272    /// Java `ParsedName.isPhraseName()`: the `phrase` field is set and non-empty.
273    pub fn is_phrase_name(&self) -> bool {
274        self.phrase.as_ref().is_some_and(|p| !p.is_empty())
275    }
276}
277
278/// Shared flag set for `canonicalComplete` / `canonicalCompleteHtml` — identical except for
279/// the trailing `html` knob.
280fn complete_flags(html: bool) -> Flags {
281    Flags {
282        hybrid_marker: true,
283        rank_marker: true,
284        authorship: true,
285        genus_for_infrageneric: true,
286        infrageneric: true,
287        decomposition: true,
288        ascii_only: false,
289        show_qualifier: true,
290        show_indet: true,
291        nom_note: true,
292        show_sensu: true,
293        show_cultivar: true,
294        show_phrase: true,
295        show_strain: true,
296        show_extra_authorship: true,
297        html,
298    }
299}
300
301/// Java `NameFormatter.hasNotho(ParsedName, NamePart)`.
302fn has_notho(n: &ParsedName, part: NamePart) -> bool {
303    n.notho.as_ref().is_some_and(|s| s.contains(&part))
304}
305
306/// Java `NameFormatter.isUnknown(Rank)` — `r == null || r.otherOrUnranked()`. Rank is never
307/// null in this port (defaults to `Unranked`), so it reduces to `other_or_unranked()`.
308fn is_unknown(r: Rank) -> bool {
309    r.other_or_unranked()
310}
311
312/// Java `NameFormatter.isInfraspecificMarker(Rank)`.
313fn is_infraspecific_marker(r: Rank) -> bool {
314    r.is_infraspecific() && !r.is_uncomparable()
315}
316
317fn append_in_italics(sb: &mut String, x: &str, html: bool) {
318    if html {
319        sb.push_str(ITALICS_OPEN);
320        sb.push_str(x);
321        sb.push_str(ITALICS_CLOSE);
322    } else {
323        sb.push_str(x);
324    }
325}
326
327/// Java `NameFormatter.appendIfNotEmpty(StringBuilder, String)` — append only when `sb` is
328/// already non-empty.
329fn append_if_not_empty(sb: &mut String, to_append: &str) {
330    if !sb.is_empty() {
331        sb.push_str(to_append);
332    }
333}
334
335/// Java `NameFormatter.phraseLeadsWithSpeciesMarker(ParsedName)`.
336fn phrase_leads_with_species_marker(n: &ParsedName) -> bool {
337    n.is_phrase_name()
338        && PHRASE_SPECIES_MARKER.is_match(java_trim(n.phrase.as_deref().unwrap_or("")))
339}
340
341/// gbif/name-parser-rust#16: true when an informal phrase already OPENS with this name's own
342/// rank marker, spelled out verbatim — "sect. 1" on a `SECTION_BOTANY`, "strain T101" on a
343/// `STRAIN`, "var 3" on a `VARIETY`. `StripAndStash::stash_trailing_rank_marker_code` keeps the
344/// source spelling of an indeterminate `Genus <marker> <code>` in the phrase, so synthesising the
345/// marker from the rank as well would double it ("Trachelomonas strain strain T101"). Compared
346/// dot-insensitively, since the marker is stored with its dot ("var.") and the source may write
347/// it without one.
348///
349/// The sibling [`phrase_leads_with_species_marker`] stays separate rather than folding into this:
350/// it matches the SPELLED-OUT species markers ("species 1", "spec 3"), none of which equal
351/// `Rank::Species`'s own marker "sp.", and it is a faithful port of a Java pattern.
352fn phrase_leads_with_rank_marker(n: &ParsedName) -> bool {
353    let Some(marker) = n.rank.marker() else {
354        return false;
355    };
356    let phrase = java_trim(n.phrase.as_deref().unwrap_or(""));
357    let Some(lead) = phrase.split_whitespace().next() else {
358        return false;
359    };
360    lead.trim_end_matches('.')
361        .eq_ignore_ascii_case(marker.trim_end_matches('.'))
362}
363
364/// Java `NameFormatter.appendRankMarker(sb, rank, ifRank, nothoPrefix)` (both the 3- and
365/// 4-arg overloads; the 3-arg one passes `if_rank = None`). Returns true if a marker was
366/// appended.
367fn append_rank_marker(
368    sb: &mut String,
369    rank: Rank,
370    if_rank: Option<fn(Rank) -> bool>,
371    notho_prefix: bool,
372) -> bool {
373    if let Some(marker) = rank.marker() {
374        if if_rank.is_none_or(|f| f(rank)) {
375            if notho_prefix {
376                sb.push_str(NOTHO_PREFIX);
377            }
378            sb.push_str(marker);
379            return true;
380        }
381    }
382    false
383}
384
385/// Java `NameFormatter.appendGenus(sb, n, hybridMarker, showQualifier, html)`.
386fn append_genus(
387    sb: &mut String,
388    n: &ParsedName,
389    hybrid_marker: bool,
390    show_qualifier: bool,
391    html: bool,
392) {
393    if show_qualifier && n.has_epithet_qualifier(NamePart::Generic) {
394        sb.push_str(qualifier(n, NamePart::Generic));
395        sb.push(' ');
396    }
397    if hybrid_marker && has_notho(n, NamePart::Generic) {
398        sb.push(HYBRID_MARKER);
399        sb.push(' ');
400    }
401    // In every call site the genus is Some (guarded by the caller), matching Java's
402    // unconditional n.getGenus() dereference here.
403    append_in_italics(sb, n.genus.as_deref().unwrap_or(""), html);
404}
405
406/// Java `NameFormatter.appendInfraspecific(...)`.
407fn append_infraspecific(
408    sb: &mut String,
409    n: &ParsedName,
410    hybrid_marker: bool,
411    show_qualifier: bool,
412    rank_marker: bool,
413    force_rank_marker: bool,
414    html: bool,
415) {
416    sb.push(' ');
417    if show_qualifier && n.has_epithet_qualifier(NamePart::Infraspecific) {
418        sb.push_str(qualifier(n, NamePart::Infraspecific));
419        sb.push(' ');
420    }
421    if hybrid_marker && has_notho(n, NamePart::Infraspecific) {
422        if rank_marker && is_infraspecific_marker(n.rank) {
423            sb.push_str("notho");
424        } else {
425            sb.push(HYBRID_MARKER);
426            sb.push(' ');
427        }
428    }
429    // Render the infraspecific rank marker. Other ranks always show it; the subspecies
430    // marker is hidden only for zoological names (ICZN trinomials carry no marker).
431    // Kept as Java's two nested `if`s (not collapsed) because the inner condition's
432    // `append_rank_marker` has a side effect (it appends the marker) — folding it into the
433    // outer guard would bury that write inside a compound boolean.
434    #[allow(clippy::collapsible_if)]
435    if force_rank_marker
436        || (rank_marker
437            && (n.code != Some(NomCode::Zoological)
438                || n.rank != Rank::Subspecies
439                || n.is_hybrid_name()))
440    {
441        if append_rank_marker(sb, n.rank, Some(is_infraspecific_marker), false)
442            && n.infraspecific_epithet.is_some()
443        {
444            sb.push(' ');
445        }
446    }
447    if let Some(ie) = &n.infraspecific_epithet {
448        append_in_italics(sb, ie, html);
449    }
450}
451
452/// Fetch an epithet qualifier known to exist (caller guards with `has_epithet_qualifier`).
453fn qualifier(n: &ParsedName, part: NamePart) -> &str {
454    n.epithet_qualifier
455        .as_ref()
456        .and_then(|m| m.get(&part))
457        .map(String::as_str)
458        .unwrap_or("")
459}
460
461/// Java `NameFormatter.joinAuthors(List<String>, Integer maxAuthors)`.
462fn join_authors(authors: &[String], max_authors: Option<usize>) -> String {
463    if let Some(max) = max_authors {
464        if authors.len() > max {
465            return format!("{} {}", authors[0], ET_AL);
466        }
467    }
468    if authors.len() > 1 {
469        let last = &authors[authors.len() - 1];
470        let end = if AL.is_match(last) {
471            format!(" {ET_AL}")
472        } else {
473            format!(" & {last}")
474        };
475        return format!("{}{}", authors[..authors.len() - 1].join(", "), end);
476    }
477    authors.join(", ")
478}
479
480/// Java `NameFormatter.appendAuthorship(StringBuilder, Authorship, boolean, NomCode)`.
481fn append_authorship(
482    sb: &mut String,
483    auth: &Authorship,
484    include_year: bool,
485    code: Option<NomCode>,
486) {
487    if !auth.exists() {
488        return;
489    }
490    let mut authors_appended = false;
491    let max = if code == Some(NomCode::Bacterial) {
492        Some(2)
493    } else {
494        None
495    };
496    if !auth.ex_authors.is_empty() {
497        sb.push_str(&join_authors(&auth.ex_authors, max));
498        sb.push_str(" ex ");
499        authors_appended = true;
500    }
501    if !auth.authors.is_empty() {
502        sb.push_str(&join_authors(&auth.authors, max));
503        authors_appended = true;
504    }
505    if include_year {
506        if let Some(year) = &auth.year {
507            if authors_appended {
508                if code != Some(NomCode::Bacterial) {
509                    sb.push(',');
510                }
511                sb.push(' ');
512            }
513            sb.push_str(year);
514        }
515        if let Some(iy) = &auth.imprint_year {
516            sb.push_str(" [");
517            sb.push_str(iy);
518            sb.push(']');
519        }
520    }
521}
522
523/// Java `NameFormatter.appendAuthorship(StringBuilder, CombinedAuthorshipIF, boolean,
524/// NomCode)` — used both for a name's own authorship (its flattened
525/// combination/basionym/sanctioning fields) and for the nested
526/// generic/specific `CombinedAuthorship` slots.
527fn append_authorship_parts(
528    sb: &mut String,
529    basionym: &Authorship,
530    combination: &Authorship,
531    sanctioning: Option<&str>,
532    include_year: bool,
533    code: Option<NomCode>,
534) {
535    let orig_len = sb.len();
536    if basionym.exists() {
537        sb.push('(');
538        append_authorship(sb, basionym, include_year, code);
539        sb.push(')');
540    }
541    if combination.exists() {
542        if orig_len < sb.len() {
543            sb.push(' ');
544        }
545        append_authorship(sb, combination, include_year, code);
546        if let Some(sanct) = sanctioning {
547            sb.push_str(" : ");
548            sb.push_str(sanct);
549        }
550    }
551}
552
553/// Append the name's OWN authorship — Java `appendAuthorship(sb, n, includeYear, code)`
554/// where `n` (a `ParsedName`) is the `CombinedAuthorshipIF`.
555fn append_name_authorship(sb: &mut String, n: &ParsedName, include_year: bool) {
556    append_authorship_parts(
557        sb,
558        &n.basionym_authorship,
559        &n.combination_authorship,
560        n.sanctioning_author.as_deref(),
561        include_year,
562        n.code,
563    );
564}
565
566/// Append a nested `CombinedAuthorship` slot (generic or specific authorship).
567fn append_combined_authorship(
568    sb: &mut String,
569    c: &CombinedAuthorship,
570    include_year: bool,
571    code: Option<NomCode>,
572) {
573    append_authorship_parts(
574        sb,
575        &c.basionym_authorship,
576        &c.combination_authorship,
577        c.sanctioning_author.as_deref(),
578        include_year,
579        code,
580    );
581}
582
583/// Java `UnicodeUtils.decompose(String)` — expands the fixed set of two-letter ligatures.
584/// Every search key is a single unicode scalar and no replacement contains a search key, so
585/// a single char-by-char pass reproduces `StringUtils.replaceEach` exactly.
586fn decompose(x: &str) -> String {
587    let mut out = String::with_capacity(x.len());
588    for c in x.chars() {
589        match c {
590            'æ' => out.push_str("ae"),
591            'Æ' => out.push_str("Ae"),
592            'œ' => out.push_str("oe"),
593            'Œ' => out.push_str("Oe"),
594            'IJ' => out.push_str("Ij"),
595            'ij' => out.push_str("ij"),
596            'Lj' => out.push_str("Lj"),
597            'lj' => out.push_str("lj"),
598            'ȸ' => out.push_str("db"),
599            'ȹ' => out.push_str("qp"),
600            'ß' => out.push_str("ss"),
601            'st' => out.push_str("st"),
602            'ſt' => out.push_str("ft"),
603            'ff' => out.push_str("ff"),
604            'fi' => out.push_str("fi"),
605            'fl' => out.push_str("fl"),
606            'ffi' => out.push_str("ffi"),
607            'ffl' => out.push_str("ffl"),
608            other => out.push(other),
609        }
610    }
611    out
612}
613
614/// Java `UnicodeUtils.replaceSpecialCases(String)` — cases the java Normalizer misses.
615fn replace_special_cases(x: &str) -> String {
616    let mut out = String::with_capacity(x.len());
617    for c in x.chars() {
618        match c {
619            'ß' => out.push_str("ss"),
620            'ſ' => out.push('s'),
621            'Æ' => out.push_str("AE"),
622            'æ' => out.push_str("ae"),
623            'Ð' => out.push('D'),
624            'đ' => out.push('d'),
625            'ð' => out.push('d'),
626            'Ø' => out.push('O'),
627            'ø' => out.push('o'),
628            'Œ' => out.push_str("OE"),
629            'œ' => out.push_str("oe"),
630            'Ŧ' => out.push('T'),
631            'ŧ' => out.push('t'),
632            'Ł' => out.push('L'),
633            'ł' => out.push('l'),
634            other => out.push(other),
635        }
636    }
637    out
638}
639
640/// Java `UnicodeUtils.MARKER` = `Pattern.compile("\\p{M}")` — the Unicode general category
641/// Mark (Mn/Mc/Me). The `regex` crate's `\p{M}` is the same category, so this reproduces
642/// Java's `MARKER.matcher(x).replaceAll("")` byte-for-byte (no hand-rolled range set).
643static MARK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\p{M}").unwrap());
644
645/// Java `UnicodeUtils.foldToAscii(String)` — `replaceSpecialCases`, then Unicode NFD (which
646/// splits accented letters into base + combining mark), then drop all `\p{M}` marks, leaving
647/// the ascii base letters.
648fn fold_to_ascii(x: &str) -> String {
649    let x = replace_special_cases(x);
650    let nfd: String = x.nfd().collect();
651    MARK.replace_all(&nfd, "").into_owned()
652}
653
654/// Java `NameFormatter.buildName(ParsedName, 16 booleans)` — the core renderer every public
655/// method delegates to. Ported statement-for-statement; see the field docs on [`Flags`] for
656/// each knob.
657fn build_name(n: &ParsedName, f: &Flags) -> Option<String> {
658    let mut sb = String::new();
659
660    // `html`/`authorship` are reassigned below (Candidatus turns html off; several indet
661    // branches turn authorship off), so shadow them as locals like Java's mutable params.
662    let mut html = f.html;
663    let mut authorship = f.authorship;
664
665    let mut candidate_italics = false;
666    if n.candidatus {
667        sb.push('"');
668        if html {
669            sb.push_str(ITALICS_OPEN);
670            candidate_italics = true;
671            // the entire name goes in italics, so turn off per-part html
672            html = false;
673        }
674        sb.push_str("Candidatus ");
675    }
676
677    if let Some(uninomial) = &n.uninomial {
678        // higher rank names being just a uninomial!
679        if f.hybrid_marker && has_notho(n, NamePart::Generic) {
680            sb.push(HYBRID_MARKER);
681            sb.push(' ');
682        }
683        append_in_italics(&mut sb, uninomial, html);
684    } else {
685        // bi- or trinomials or infrageneric names
686        if let Some(infrageneric_epithet) = &n.infrageneric_epithet {
687            if (is_unknown(n.rank) && n.specific_epithet.is_none())
688                || n.rank.is_infrageneric_strictly()
689            {
690                let mut show_infra_gen = true;
691                // the infrageneric is the terminal rank. Always show it and wrap it with its
692                // genus if requested
693                if n.genus.is_some() && f.genus_for_infrageneric {
694                    append_genus(&mut sb, n, f.hybrid_marker, f.show_qualifier, html);
695                    // The genus author of an infrageneric name sits between the genus and the
696                    // rank marker ("Cordia (Adans.) Kuntze sect. Salimori").
697                    if f.show_extra_authorship && n.has_generic_authorship() {
698                        sb.push(' ');
699                        append_combined_authorship(
700                            &mut sb,
701                            n.generic_authorship.as_ref().unwrap(),
702                            true,
703                            n.code,
704                        );
705                    }
706                    sb.push(' ');
707                    // we show zoological infragenerics in brackets, but use rank markers for
708                    // botanical names (unless its no defined rank)
709                    if n.code == Some(NomCode::Zoological) {
710                        sb.push('(');
711                        if f.hybrid_marker && has_notho(n, NamePart::Infrageneric) {
712                            sb.push(HYBRID_MARKER);
713                            sb.push(' ');
714                        }
715                        append_in_italics(&mut sb, infrageneric_epithet, html);
716                        sb.push(')');
717                        show_infra_gen = false;
718                    }
719                }
720                if show_infra_gen {
721                    if f.rank_marker {
722                        // If we know the rank we use explicit rank markers — this is how
723                        // botanical infrageneric names are formed, see
724                        // http://www.iapt-taxon.org/nomen/main.php?page=art21
725                        if append_rank_marker(
726                            &mut sb,
727                            n.rank,
728                            None,
729                            f.hybrid_marker && has_notho(n, NamePart::Infrageneric),
730                        ) {
731                            sb.push(' ');
732                        }
733                    }
734                    append_in_italics(&mut sb, infrageneric_epithet, html);
735                }
736            } else {
737                if n.genus.is_some() {
738                    append_genus(&mut sb, n, f.hybrid_marker, f.show_qualifier, html);
739                }
740                if f.infrageneric {
741                    // additional subgenus shown for binomial. Always shown in brackets
742                    sb.push_str(" (");
743                    append_in_italics(&mut sb, infrageneric_epithet, html);
744                    sb.push(')');
745                }
746            }
747        } else if n.genus.is_some() {
748            append_genus(&mut sb, n, f.hybrid_marker, f.show_qualifier, html);
749        }
750
751        if n.specific_epithet.is_none() {
752            if (f.show_indet && n.genus.is_some() && n.cultivar_epithet.is_none())
753                || (f.show_phrase && n.is_phrase_name())
754            {
755                if n.rank.is_species_or_below() {
756                    // no species epithet given, indetermined!
757                    if n.rank.is_infraspecific() {
758                        // maybe we have an infraspecific epithet? force to show the rank marker —
759                        // unless the phrase already spells that marker out ("strain T101"), in
760                        // which case synthesising it would double it.
761                        if !phrase_leads_with_rank_marker(n) {
762                            append_infraspecific(
763                                &mut sb,
764                                n,
765                                f.hybrid_marker,
766                                f.show_qualifier,
767                                f.rank_marker,
768                                true,
769                                html,
770                            );
771                        }
772                    } else if !phrase_leads_with_species_marker(n) {
773                        // Skip the synthetic "sp." when an informal phrase already spells out
774                        // the species marker verbatim ("Allium species 1") — the phrase
775                        // carries it.
776                        sb.push(' ');
777                        // Java `sb.append(n.getRank().getMarker())`. Here the rank is
778                        // species-or-below-but-not-infraspecific (SPECIES / SPECIES_AGGREGATE),
779                        // both of which always have a marker, so the default is never taken; unlike
780                        // line 757 there is no null-marker rank to mirror Java's "null" for.
781                        sb.push_str(n.rank.marker().unwrap_or(""));
782                    }
783                    authorship = false;
784                }
785            } else if n.infraspecific_epithet.is_some() {
786                append_infraspecific(
787                    &mut sb,
788                    n,
789                    f.hybrid_marker,
790                    f.show_qualifier,
791                    f.rank_marker,
792                    false,
793                    html,
794                );
795            }
796        } else {
797            // species part
798            sb.push(' ');
799            if f.show_qualifier && n.has_epithet_qualifier(NamePart::Specific) {
800                sb.push_str(qualifier(n, NamePart::Specific));
801                sb.push(' ');
802            }
803            if f.hybrid_marker && has_notho(n, NamePart::Specific) {
804                sb.push(HYBRID_MARKER);
805                sb.push(' ');
806            }
807            append_in_italics(&mut sb, n.specific_epithet.as_deref().unwrap_or(""), html);
808            // The species author of a below-species name (cultivar / trinomial) sits right
809            // after the species epithet ("Acer campestre L. 'Elsrijk' Broerse").
810            if f.show_extra_authorship && n.has_specific_authorship() {
811                sb.push(' ');
812                append_combined_authorship(
813                    &mut sb,
814                    n.specific_authorship.as_ref().unwrap(),
815                    true,
816                    n.code,
817                );
818            }
819
820            if n.infraspecific_epithet.is_none() {
821                // Indetermined infraspecies? Only show indet cultivar marker if no cultivar
822                // epithet exists
823                if f.show_indet
824                    && n.rank.is_infraspecific()
825                    && (n.rank.is_restricted_to_code() != Some(NomCode::Cultivars)
826                        || n.cultivar_epithet.is_none())
827                {
828                    // no infraspecific epitheton given, but rank below species. Indetermined!
829                    // use ssp. for subspecies in case of indetermined names
830                    if n.rank == Rank::Subspecies {
831                        sb.push_str(" ssp.");
832                    } else {
833                        sb.push(' ');
834                        // Faithful to Java `sb.append(n.getRank().getMarker())`: when the marker
835                        // is null Java's `StringBuilder.append((String) null)` appends the literal
836                        // "null". The only infraspecific rank with a null marker is CULTIVAR_GROUP
837                        // (which reaches here only for a specific-but-no-infraspecific, no-cultivar
838                        // name — not producible by `parse()`, but the formatter is public API over
839                        // any hand-built ParsedName), so mirror the "null" rather than dropping it.
840                        sb.push_str(n.rank.marker().unwrap_or("null"));
841                    }
842                    authorship = false;
843                }
844            } else {
845                // Autonym authorship placement follows the codes. The autonym's final epithet
846                // never carries an author of its own; the author shown is the species author.
847                //   ICN Art. 22.1/26.1 (botany): cite it right after the species epithet.
848                //   ICZN (zoology): cite it at the very end of the trinomen.
849                // Only an explicit botanical code triggers the after-species placement;
850                // zoological and unknown-code autonyms keep the author in its default end
851                // position below.
852                if n.is_autonym() && n.code == Some(NomCode::Botanical) {
853                    if authorship && n.has_authorship() {
854                        sb.push(' ');
855                        append_name_authorship(&mut sb, n, true);
856                    }
857                    authorship = false;
858                }
859                // infraspecific part
860                append_infraspecific(
861                    &mut sb,
862                    n,
863                    f.hybrid_marker,
864                    f.show_qualifier,
865                    f.rank_marker,
866                    false,
867                    html,
868                );
869            }
870        }
871    }
872
873    // closing quotes for Candidatus names
874    if n.candidatus {
875        if candidate_italics {
876            sb.push_str(ITALICS_CLOSE);
877        }
878        sb.push('"');
879    }
880
881    // uninomial, genus, infragen, species or infraspecies authorship. For a cultivar the
882    // name's authorship IS the cultivar author, rendered AFTER the cultivar epithet below,
883    // so it is suppressed here.
884    let cultivar_shown = f.show_cultivar && n.cultivar_epithet.is_some();
885    if authorship && n.has_authorship() && !cultivar_shown {
886        sb.push(' ');
887        append_name_authorship(&mut sb, n, true);
888    }
889
890    // add strain name (phrase names get special treatment)
891    if f.show_strain && n.phrase.is_some() && !n.is_phrase_name() {
892        sb.push(' ');
893        sb.push_str(n.phrase.as_deref().unwrap_or(""));
894    }
895
896    // add cultivar name
897    if f.show_cultivar {
898        if let Some(cultivar) = &n.cultivar_epithet {
899            if n.rank == Rank::CultivarGroup {
900                sb.push(' ');
901                sb.push_str(cultivar);
902                sb.push_str(" Group");
903            } else if n.rank == Rank::Grex {
904                sb.push(' ');
905                sb.push_str(cultivar);
906                sb.push_str(" gx");
907            } else {
908                sb.push_str(" '");
909                sb.push_str(cultivar);
910                sb.push('\'');
911            }
912            // The cultivar author follows the cultivar epithet ("Acer campestre 'Elsrijk'
913            // Broerse").
914            if authorship && n.has_authorship() {
915                sb.push(' ');
916                append_name_authorship(&mut sb, n, true);
917            }
918        }
919    }
920
921    // Add phrase name. Phrase values may include a trailing author span after the collector
922    // parenthesised reference ("Sandheath (D.Murfet 3190) R.J.Bates"); for canonical
923    // rendering we drop that author-shaped tail so the output stays clean while the stored
924    // phrase keeps the full annotation. A non-author suffix (e.g. "NT Herbarium") is kept.
925    if f.show_phrase && n.is_phrase_name() {
926        let phrase_full = n.phrase.as_deref().unwrap_or("");
927        let mut phrase = phrase_full;
928        if let Some(last_close) = phrase_full.rfind(')') {
929            // ')' is ASCII (1 byte), so the byte comparison matches Java's char check for
930            // "is there content after the last ')'".
931            if last_close < phrase_full.len() - 1 {
932                let tail = java_trim(&phrase_full[last_close + 1..]);
933                // Author-shaped tail: initials with dots (e.g. "R.J.Bates").
934                if PHRASE_AUTHOR_TAIL.is_match(tail) {
935                    phrase = &phrase_full[..last_close + 1];
936                }
937            }
938        }
939        append_if_not_empty(&mut sb, " ");
940        sb.push_str(phrase);
941    }
942
943    // add sensu/sec reference
944    if f.show_sensu {
945        if let Some(tn) = &n.taxonomic_note {
946            append_if_not_empty(&mut sb, " ");
947            sb.push_str(tn);
948        }
949    }
950
951    // add nom status
952    if f.nom_note {
953        if let Some(nn) = &n.nomenclatural_note {
954            append_if_not_empty(&mut sb, ", ");
955            sb.push_str(nn);
956        }
957    }
958
959    // final char transformations
960    let mut name = java_trim(&sb).to_string();
961    if f.decomposition {
962        name = decompose(&name);
963    }
964    if f.ascii_only {
965        name = fold_to_ascii(&name);
966    }
967    // Java StringUtils.trimToNull: trim again, null if empty.
968    let name = java_trim(&name);
969    if name.is_empty() {
970        None
971    } else {
972        Some(name.to_string())
973    }
974}
975
976#[cfg(test)]
977mod tests {
978    //! Always-on formatter regression guards. Every `expect_*` value here is
979    //! **Java-authoritative** — produced by running the input through the real Java
980    //! `NameFormatter` (via the `FormatOracle`, same tool `tests/format_golden.rs` uses), not
981    //! hand-derived — so these pin the exact Java behaviour for the structural rendering
982    //! paths (autonym placement, infrageneric markers, notho/hybrid spacing, Candidatus
983    //! quoting, sanctioning author, cultivar, ascii folding, html) without needing the oracle
984    //! present at test time.
985
986    use crate::parse_name as parse;
987
988    /// Parse with the default (no hints) entry point; panics if the name is unparsable — every
989    /// input below is a parseable name chosen precisely to exercise a formatter path.
990    fn p(input: &str) -> crate::model::ParsedName {
991        parse(input, None, None, None).unwrap_or_else(|_| panic!("should parse: {input:?}"))
992    }
993
994    #[test]
995    fn informal_canonical_rebuilds_the_parser_rendering() {
996        use crate::model::enums::Rank;
997        use crate::model::Informal;
998        let inf = |taxon: &str, taxon_rank, rank, phrase: Option<&str>| Informal {
999            taxon: taxon.into(),
1000            taxon_rank,
1001            rank,
1002            phrase: phrase.map(str::to_string),
1003            code: None,
1004        };
1005        // genus-anchored provisional species with a captured phrase tag
1006        assert_eq!(
1007            inf(
1008                "Rhizobium",
1009                Rank::Genus,
1010                Rank::Species,
1011                Some("sp. RMCC TR1811")
1012            )
1013            .canonical_name(),
1014            "Rhizobium sp. RMCC TR1811"
1015        );
1016        // numbered placeholder
1017        assert_eq!(
1018            inf("Allium", Rank::Genus, Rank::Species, Some("1")).canonical_name(),
1019            "Allium sp. 1"
1020        );
1021        // bare "Genus sp." — no phrase (a higher-taxon anchor still sits in the genus slot)
1022        assert_eq!(
1023            inf("Ichneumonidae", Rank::Genus, Rank::Species, None).canonical_name(),
1024            "Ichneumonidae sp."
1025        );
1026        // informal group — UNRANKED, the phrase carries the designation (no synthetic sp.)
1027        assert_eq!(
1028            inf("Bartonella", Rank::Genus, Rank::Unranked, Some("group")).canonical_name(),
1029            "Bartonella group"
1030        );
1031    }
1032
1033    #[test]
1034    fn basic_binomial_with_author() {
1035        let n = p("Abies alba Mill.");
1036        assert_eq!(n.canonical_name().as_deref(), Some("Abies alba Mill."));
1037        assert_eq!(
1038            n.canonical_name_without_authorship().as_deref(),
1039            Some("Abies alba")
1040        );
1041        assert_eq!(n.canonical_name_minimal().as_deref(), Some("Abies alba"));
1042        assert_eq!(
1043            n.canonical_name_complete().as_deref(),
1044            Some("Abies alba Mill.")
1045        );
1046        assert_eq!(n.authorship_complete().as_deref(), Some("Mill."));
1047    }
1048
1049    #[test]
1050    fn authorless_name_has_no_authorship_string() {
1051        let n = p("Abies alba");
1052        assert_eq!(n.canonical_name().as_deref(), Some("Abies alba"));
1053        assert_eq!(n.authorship_complete(), None);
1054    }
1055
1056    #[test]
1057    fn zoological_subspecies_shows_no_rank_marker() {
1058        // ICZN trinomials carry no infraspecific marker.
1059        let n = p("Vulpes vulpes silaceus Miller, 1907");
1060        assert_eq!(
1061            n.canonical_name().as_deref(),
1062            Some("Vulpes vulpes silaceus Miller, 1907")
1063        );
1064        assert_eq!(
1065            n.canonical_name_without_authorship().as_deref(),
1066            Some("Vulpes vulpes silaceus")
1067        );
1068        assert_eq!(n.authorship_complete().as_deref(), Some("Miller, 1907"));
1069    }
1070
1071    #[test]
1072    fn botanical_autonym_keeps_marker_but_minimal_drops_it() {
1073        let n = p("Acer rubrum var. rubrum");
1074        assert_eq!(
1075            n.canonical_name().as_deref(),
1076            Some("Acer rubrum var. rubrum")
1077        );
1078        // canonicalMinimal drops the rank marker: three bare epithets.
1079        assert_eq!(
1080            n.canonical_name_minimal().as_deref(),
1081            Some("Acer rubrum rubrum")
1082        );
1083    }
1084
1085    #[test]
1086    fn botanical_autonym_places_author_after_species_epithet() {
1087        // ICN Art. 22.1/26.1: the species author sits before the (repeated) rank marker.
1088        let n = p("Trimezia spathata (Klatt) Baker subsp. spathata");
1089        assert_eq!(
1090            n.canonical_name().as_deref(),
1091            Some("Trimezia spathata (Klatt) Baker subsp. spathata")
1092        );
1093        assert_eq!(
1094            n.canonical_name_without_authorship().as_deref(),
1095            Some("Trimezia spathata subsp. spathata")
1096        );
1097        assert_eq!(n.authorship_complete().as_deref(), Some("(Klatt) Baker"));
1098    }
1099
1100    #[test]
1101    fn infrageneric_botanical_uses_rank_marker_and_minimal_drops_genus() {
1102        // "subg." normalises to the "subgen." marker; minimal shows only the terminal epithet.
1103        let n = p("Astragalus subg. Cercidothrix");
1104        assert_eq!(
1105            n.canonical_name().as_deref(),
1106            Some("Astragalus subgen. Cercidothrix")
1107        );
1108        assert_eq!(n.canonical_name_minimal().as_deref(), Some("Cercidothrix"));
1109    }
1110
1111    #[test]
1112    fn basionym_and_combination_authorship() {
1113        let n = p("Baeomyces rufus (Huds.) Rebent.");
1114        assert_eq!(
1115            n.canonical_name().as_deref(),
1116            Some("Baeomyces rufus (Huds.) Rebent.")
1117        );
1118        assert_eq!(
1119            n.canonical_name_without_authorship().as_deref(),
1120            Some("Baeomyces rufus")
1121        );
1122        assert_eq!(n.authorship_complete().as_deref(), Some("(Huds.) Rebent."));
1123    }
1124
1125    #[test]
1126    fn basionym_parens_with_year() {
1127        let n = p("Oenanthe oenanthe (Linnaeus, 1758)");
1128        assert_eq!(
1129            n.canonical_name().as_deref(),
1130            Some("Oenanthe oenanthe (Linnaeus, 1758)")
1131        );
1132        assert_eq!(n.authorship_complete().as_deref(), Some("(Linnaeus, 1758)"));
1133    }
1134
1135    #[test]
1136    fn sanctioning_author_rendered_with_colon() {
1137        // http://www.iapt-taxon.org/nomen/main.php?page=r50E — sanctioning author after " : ".
1138        let n = p("Agaricus campestris L. : Fr.");
1139        assert_eq!(
1140            n.canonical_name().as_deref(),
1141            Some("Agaricus campestris L. : Fr.")
1142        );
1143        assert_eq!(n.authorship_complete().as_deref(), Some("L. : Fr."));
1144    }
1145
1146    #[test]
1147    fn notho_genus_hybrid_marker_with_space() {
1148        let n = p("×Agropogon littoralis");
1149        assert_eq!(
1150            n.canonical_name().as_deref(),
1151            Some("× Agropogon littoralis")
1152        );
1153        // minimal drops the hybrid marker.
1154        assert_eq!(
1155            n.canonical_name_minimal().as_deref(),
1156            Some("Agropogon littoralis")
1157        );
1158    }
1159
1160    #[test]
1161    fn notho_species_hybrid_marker() {
1162        let n = p("Salix ×capreola Andersson");
1163        assert_eq!(
1164            n.canonical_name().as_deref(),
1165            Some("Salix × capreola Andersson")
1166        );
1167        assert_eq!(
1168            n.canonical_name_minimal().as_deref(),
1169            Some("Salix capreola")
1170        );
1171    }
1172
1173    #[test]
1174    fn cultivar_epithet_in_single_quotes_and_minimal_drops_it() {
1175        let n = p("Acer campestre 'Elsrijk'");
1176        assert_eq!(
1177            n.canonical_name().as_deref(),
1178            Some("Acer campestre 'Elsrijk'")
1179        );
1180        assert_eq!(
1181            n.canonical_name_minimal().as_deref(),
1182            Some("Acer campestre")
1183        );
1184    }
1185
1186    #[test]
1187    fn candidatus_wraps_in_quotes_with_bacterial_comma_less_year() {
1188        // Candidatus implies the bacterial code: the year carries no comma, and the whole
1189        // name is wrapped in double quotes.
1190        let n = p("Candidatus Nanopelagicus abundans Ghai, 2013");
1191        assert_eq!(
1192            n.canonical_name().as_deref(),
1193            Some("\"Candidatus Nanopelagicus abundans\" Ghai 2013")
1194        );
1195        assert_eq!(n.authorship_complete().as_deref(), Some("Ghai 2013"));
1196    }
1197
1198    #[test]
1199    fn minimal_folds_ligatures_and_diacritics_to_ascii() {
1200        // decompose expands the "æ" ligature; foldToAscii's NFD strips the "ü" umlaut.
1201        assert_eq!(
1202            p("Læptura").canonical_name_minimal().as_deref(),
1203            Some("Laeptura")
1204        );
1205        assert_eq!(
1206            p("Rübsaamenia excelsa").canonical_name_minimal().as_deref(),
1207            Some("Rubsaamenia excelsa")
1208        );
1209        // ...but the non-minimal renderings keep the original unicode.
1210        assert_eq!(p("Læptura").canonical_name().as_deref(), Some("Læptura"));
1211    }
1212
1213    #[test]
1214    fn cultivar_group_indet_mirrors_javas_null_marker_append() {
1215        // Latent faithfulness case flagged by review, unreachable via parse(): a CULTIVAR_GROUP
1216        // name with a specific but no infraspecific/cultivar epithet. CULTIVAR_GROUP is
1217        // infraspecific yet has a null rank marker, so Java's
1218        // `sb.append(n.getRank().getMarker())` appends the literal "null"
1219        // (`StringBuilder.append((String) null)`). Java-verified: `canonical(pn)` == "Aaa bbb
1220        // null". The formatter is public API over any hand-built ParsedName, so we mirror it.
1221        use crate::model::{ParsedName, Rank};
1222        let pn = ParsedName {
1223            rank: Rank::CultivarGroup,
1224            genus: Some("Aaa".to_string()),
1225            specific_epithet: Some("bbb".to_string()),
1226            ..Default::default()
1227        };
1228        assert_eq!(pn.canonical_name().as_deref(), Some("Aaa bbb null"));
1229        assert_eq!(
1230            pn.canonical_name_complete().as_deref(),
1231            Some("Aaa bbb null")
1232        );
1233    }
1234
1235    #[test]
1236    fn complete_html_italicises_name_parts() {
1237        assert_eq!(
1238            p("Abies alba Mill.")
1239                .canonical_name_complete_html()
1240                .as_deref(),
1241            Some("<i>Abies</i> <i>alba</i> Mill.")
1242        );
1243        // notho marker sits (un-italicised) between the italic parts.
1244        assert_eq!(
1245            p("Salix ×capreola Andersson")
1246                .canonical_name_complete_html()
1247                .as_deref(),
1248            Some("<i>Salix</i> × <i>capreola</i> Andersson")
1249        );
1250        assert_eq!(
1251            p("Astragalus subg. Cercidothrix")
1252                .canonical_name_complete_html()
1253                .as_deref(),
1254            Some("<i>Astragalus</i> subgen. <i>Cercidothrix</i>")
1255        );
1256    }
1257}