Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/src/csl/person.rs

7.5 KiB, 3 runs

created by r1870400018:73631, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Ported from hayagriva 0.10.1, Copyright (c) Martin Haug and the hayagriva contributors,
2//! MIT OR Apache-2.0 (`src/types/persons.rs`, `src/lang/name.rs`, `src/lang/en.rs`'s articles and
3//! `src/lang/mod.rs`'s `is_cjk`).
4//!
5//! hayagriva's model is BibTeX's, not CSL's: `family` may carry a non-dropping particle ("van der
6//! Berg" read from `{van der Berg}`), found again by [`Person::particle_in_family`], and
7//! `particle` is BibTeX's "von" part, which CSL would call the dropping particle. A person with
8//! no given name, particle or suffix is institutional (CSL's literal name).
9use crate::unicode::segment::graphemes;
10
11use std::fmt::Write;
12
13
14/// A name as hayagriva holds it.
15#[derive(Clone, Debug, Default, PartialEq, Eq)]
16pub struct Person {
17 pub family: String,
18 pub given: Option<String>,
19 pub particle: Option<String>, // BibTeX's "von" part
20 pub suffix: Option<String>,
21 pub comma_suffix: bool, // a comma before the suffix in given-first order
22}
23
24// Sorted, searched by bisection; the repeats are hayagriva's.
25const NAME_PARTICLES: [&str; 115] = [
26 "'t", "a", "ab", "af", "al", "am", "and", "ap", "auf", "auf der", "bar", "ben", "bin", "d'",
27 "da", "dai", "dal", "dall'", "dalla", "dalle", "de", "de", "de", "de la", "de las", "de los",
28 "de'", "degli", "dei", "del", "dela", "dell'", "della", "delle", "dello", "den", "den", "der",
29 "der", "des", "di", "do", "dos", "du", "e", "el", "en", "et", "fan", "filho", "fitz", "grosse",
30 "große", "i", "ibn", "in", "l'", "la", "las", "le", "li", "lo", "los", "m'", "mac", "mc", "n'",
31 "no", "ní", "o", "och", "of", "op de", "saint", "sainte", "san", "sant", "santa", "santo",
32 "st", "ste", "t'", "te", "ten", "ten", "ter", "ter", "thoe", "tot", "und", "und der", "van",
33 "van", "van de", "van den", "van der", "van het", "vande", "vanden", "vander", "ver", "vom",
34 "von", "von den", "von der", "von und zu", "y", "z", "ze", "zu", "zum", "zur", "à", "é", "ó",
35];
36
37const ARTICLES: [&str; 8] = ["A", "AN", "An", "THE", "The", "a", "an", "the"];
38
39/// Is the character a CJK ideograph? Names holding one are written family first, unspaced.
40pub fn is_cjk(c: char) -> bool {
41 let cp = c as u32;
42 (0x4E00..=0x9FFF).contains(&cp)
43 || (0x3400..=0x4DBF).contains(&cp)
44 || (0x20000..=0x2A6DF).contains(&cp)
45 || (0x2A700..=0x2B73F).contains(&cp)
46 || (0x2B740..=0x2B81F).contains(&cp)
47 || (0x2B820..=0x2CEAF).contains(&cp)
48 || (0xF900..=0xFAFF).contains(&cp)
49 || (0x2F800..=0x2FA1F).contains(&cp)
50}
51
52impl Person {
53
54 pub fn new(family: &str, given: Option<&str>) -> Self {
55 Self { family: family.to_string(), given: given.map(str::to_string), ..Self::default() }
56 }
57
58 /// An institutional name, written as it stands.
59 pub fn literal(name: &str) -> Self {
60 Self::new(name, None)
61 }
62
63 pub fn with_particle(mut self, p: &str) -> Self {
64 self.particle = Some(p.to_string());
65 self
66 }
67
68 pub fn with_suffix(mut self, s: &str) -> Self {
69 self.suffix = Some(s.to_string());
70 self
71 }
72
73 pub fn is_institutional(&self) -> bool {
74 self.given.is_none() && self.suffix.is_none() && self.particle.is_none()
75 }
76
77 pub fn is_cjk(&self) -> bool {
78 self.family.chars().any(is_cjk) || self.given.as_ref().map_or(false, |g| g.chars().any(is_cjk))
79 }
80
81 /// The non-dropping particle at the start of the family name: the longest leading run of
82 /// words, ending before a space, that is a known particle.
83 pub fn particle_in_family(&self) -> Option<&str> {
84 for (i, c) in self.family.char_indices().rev() {
85 if c != ' ' {
86 continue;
87 }
88 let p = &self.family[..i];
89 if NAME_PARTICLES.binary_search(&p.to_lowercase().as_str()).is_ok() {
90 return Some(p);
91 }
92 }
93 None
94 }
95
96 pub fn family_without_particle(&self) -> &str {
97 match self.particle_in_family() {
98 Some(p) => self.family[p.len()..].trim_start(),
99 None => &self.family,
100 }
101 }
102
103 /// The family name less a leading English article, for sorting an institution.
104 pub fn family_without_article(&self) -> &str {
105 match self.family.find(' ') {
106 Some(i) if i + 1 != self.family.len() && ARTICLES.binary_search(&&self.family[..i]).is_ok() =>
107 &self.family[i + 1..],
108 _ => &self.family,
109 }
110 }
111
112 /// Writes the given name's initials, each followed by `delim`. A lower-case word ("de") is
113 /// written whole, and with `hyphen` a hyphenated name keeps its hyphen ("H.-P.").
114 pub fn initials<W: Write>(&self, w: &mut W, delim: Option<&str>, hyphen: bool) -> std::fmt::Result {
115 let given = match &self.given {
116 Some(g) => g,
117 None => return Ok(()),
118 };
119 let mut collect = true;
120 let mut non_empty = false;
121 let mut start_of_word = true;
122 let mut last_was_lower = false;
123 let delim_ends_ws = delim.and_then(|d| d.chars().last()).map_or(false, char::is_whitespace);
124 for gr in graphemes(given) {
125 if let Some(c) = gr.chars().next() {
126 if c.is_whitespace() || c == '-' {
127 if last_was_lower {
128 collect = false;
129 }
130 if !collect {
131 let hyphenate = hyphen && c == '-';
132 if !last_was_lower {
133 if let Some(d) = delim {
134 let _ = w.write_str(if hyphenate { d.trim_end() } else { d });
135 }
136 }
137 collect = true;
138 start_of_word = true;
139 if hyphenate {
140 let _ = w.write_char('-');
141 } else if last_was_lower {
142 let _ = w.write_char(' ');
143 }
144 }
145 continue;
146 }
147 }
148 if collect {
149 if gr.to_lowercase() != gr {
150 collect = false;
151 last_was_lower = false;
152 } else if start_of_word {
153 last_was_lower = true;
154 }
155 if last_was_lower && start_of_word {
156 start_of_word = false;
157 if !delim_ends_ws {
158 let _ = w.write_char(' ');
159 }
160 }
161 let _ = w.write_str(gr);
162 non_empty = true;
163 }
164 }
165 if non_empty && !collect {
166 if let Some(d) = delim {
167 let _ = w.write_str(d.trim_end());
168 }
169 }
170 Ok(())
171 }
172
173 /// Writes the given name with `delim` after each single-letter word, which is how hayagriva
174 /// honours `initialize-with` when `initialize` is false.
175 pub fn given_with_delimiter<W: Write>(&self, w: &mut W, delim: Option<&str>) -> std::fmt::Result {
176 let given = match &self.given {
177 Some(g) => g,
178 None => return Ok(()),
179 };
180 for (i, word) in given.split(' ').enumerate() {
181 if i > 0 {
182 let _ = w.write_char(' ');
183 }
184 let _ = w.write_str(word);
185 if let Some(d) = delim {
186 if graphemes(word).len() == 1 {
187 let _ = w.write_str(d);
188 }
189 }
190 }
191 Ok(())
192 }
193
194 /// The particles before the family name: the dropping one, then the non-dropping one.
195 pub fn particles(&self) -> Option<String> {
196 match (&self.particle, self.particle_in_family()) {
197 (Some(d), Some(n)) => Some(format!("{} {}", d, n)),
198 (Some(d), None) => Some(d.clone()),
199 (None, Some(n)) => Some(n.to_string()),
200 (None, None) => None,
201 }
202 }
203
204 /// hayagriva's `csl_cmp` in the long form: CJK names last, then the family name (without its
205 /// particle when demoting), the particle, the given name and the suffix, each lower-cased.
206 pub fn sort_cmp(&self, other: &Self, demote: bool) -> std::cmp::Ordering {
207 let low = |s: &Option<String>| s.as_ref().map(|x| x.to_lowercase());
208 let (ca, cb) = (self.is_cjk(), other.is_cjk());
209 if ca != cb {
210 return ca.cmp(&cb);
211 }
212 let fam = self.family.to_lowercase().cmp(&other.family.to_lowercase());
213 if ca {
214 return fam.then_with(|| low(&self.given).cmp(&low(&other.given)));
215 }
216 let ord = match demote {
217 true => self.family_without_particle().to_lowercase()
218 .cmp(&other.family_without_particle().to_lowercase())
219 .then_with(|| low(&self.particles()).cmp(&low(&other.particles()))),
220 false => fam.then_with(|| low(&self.particle).cmp(&low(&other.particle))),
221 };
222 ord.then_with(|| low(&self.given).cmp(&low(&other.given)))
223 .then_with(|| low(&self.suffix).cmp(&low(&other.suffix)))
224 }
225}