oxedyne/fe2o3/fe2o3_text/src/csl/cite.rs
26.0 KiB, 57 runs
created by r1870400018:73853, 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/csl/mod.rs` (`BibliographyDriver::finish`, `do_citation`, |
| 3 | //! `do_bibliography`) and `src/csl/sort.rs`. |
| 4 | //! |
| 5 | //! hayagriva collates text keys with ICU for the style's locale. `collate` approximates the |
| 6 | //! root collation's primary level (spaces, then punctuation, digits and letters, with accents and |
| 7 | //! case set aside) and breaks ties by code point. |
| 8 | use crate::unicode::norm::{ |
| 9 | combining_class, |
| 10 | nfd, |
| 11 | }; |
| 12 | use crate::csl::{ |
| 13 | item::{ |
| 14 | var_kind, |
| 15 | DateVal, |
| 16 | Item, |
| 17 | NumVal, |
| 18 | Numeric, |
| 19 | VarKind, |
| 20 | }, |
| 21 | locale::Chain, |
| 22 | page::PageVal, |
| 23 | node::{ |
| 24 | self, |
| 25 | Formatting, |
| 26 | Meta, |
| 27 | Node, |
| 28 | }, |
| 29 | render::{ |
| 30 | self, |
| 31 | Cite, |
| 32 | Ctx, |
| 33 | Disamb, |
| 34 | Ibid, |
| 35 | NForm, |
| 36 | NameDisamb, |
| 37 | Sorting, |
| 38 | Special, |
| 39 | }, |
| 40 | person::Person, |
| 41 | style::{ |
| 42 | Collapse, |
| 43 | Demote, |
| 44 | GivenRule, |
| 45 | NameOpts, |
| 46 | Sort, |
| 47 | SortKey, |
| 48 | SortSrc, |
| 49 | Style, |
| 50 | VarForm, |
| 51 | }, |
| 52 | }; |
| 53 | |
| 54 | use std::cmp::Ordering; |
| 55 | |
| 56 | |
| 57 | /// Typst's citation forms, hayagriva's `CitePurpose`; `Normal` is the style's own. |
| 58 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 59 | pub enum CiteForm { #[default] Normal, Author, Year, Full, Prose } |
| 60 | |
| 61 | /// One reference within a citation, to an entry by its index in the item slice. |
| 62 | #[derive(Clone, Debug, Default)] |
| 63 | pub struct CiteRef { |
| 64 | pub entry: usize, |
| 65 | pub locator: Option<(String, NumVal)>, // kind (`page`, `custom`) and value |
| 66 | pub form: CiteForm, |
| 67 | pub hidden: bool, // listed in the bibliography, never printed |
| 68 | } |
| 69 | |
| 70 | #[derive(Clone, Debug, Default)] |
| 71 | pub struct Citation { |
| 72 | pub refs: Vec<CiteRef>, |
| 73 | pub note: Option<usize>, // the footnote number, for note styles |
| 74 | } |
| 75 | |
| 76 | /// A bibliography entry: second-field-align's first field, then the rest. |
| 77 | pub type BibEntry = (Option<Node>, Vec<Node>); |
| 78 | |
| 79 | /// One cite as the driver carries it between rounds. |
| 80 | #[derive(Clone, Debug)] |
| 81 | struct Pending { |
| 82 | entry: usize, |
| 83 | initial: usize, // its index in the citation as written |
| 84 | locator: Option<(String, NumVal)>, |
| 85 | form: CiteForm, |
| 86 | hidden: bool, |
| 87 | cite: Cite, |
| 88 | checked_disamb: bool, |
| 89 | first_name: Option<NameDisamb>, // the first `names` element's forms, as first rendered |
| 90 | delim: Option<String>, // the delimiter before it, when grouping sets one |
| 91 | group: Option<usize>, // its cite group, numbered from 1 |
| 92 | special: Option<Special>, // what collapsing leaves of it |
| 93 | nodes: Vec<Node>, |
| 94 | } |
| 95 | |
| 96 | /// What every citation in a document decides together: the bibliography's order, each entry's |
| 97 | /// citation number, and every citation's final rendering. Built once from all the document's |
| 98 | /// citations, in order, as hayagriva's `BibliographyDriver::finish` is. |
| 99 | #[derive(Clone, Debug, Default)] |
| 100 | pub struct CiteState { |
| 101 | order: Vec<usize>, // entry indices in bibliography order |
| 102 | number: Vec<usize>, // per entry, from 1; 0 when uncited |
| 103 | bib: Vec<Option<Cite>>, // per entry, what its bibliography entry inherits |
| 104 | cites: Vec<Vec<Node>>, // each citation, rendered |
| 105 | } |
| 106 | |
| 107 | impl CiteState { |
| 108 | |
| 109 | pub fn new<'a, I: Item>( |
| 110 | style: &'a Style, |
| 111 | chain: &'a Chain<'a>, |
| 112 | lang: Option<&'a str>, |
| 113 | items: &'a [I], |
| 114 | cites: &[Citation], |
| 115 | ) |
| 116 | -> Self |
| 117 | { |
| 118 | // Each entry once, in the order it is first cited. |
| 119 | let mut seen = vec![false; items.len()]; |
| 120 | let mut order = Vec::new(); |
| 121 | for r in cites.iter().flat_map(|c| c.refs.iter()) { |
| 122 | if r.entry < items.len() && !seen[r.entry] { |
| 123 | seen[r.entry] = true; |
| 124 | order.push(r.entry); |
| 125 | } |
| 126 | } |
| 127 | let bib_sort = style.bibliography.as_ref().and_then(|b| b.sort.as_ref()); |
| 128 | let nil: Vec<usize> = vec![0; items.len()]; |
| 129 | sort(style, chain, lang, items, &mut order, |&e| e, bib_sort, &nil); |
| 130 | let mut number = vec![0; items.len()]; |
| 131 | for (i, &e) in order.iter().enumerate() { |
| 132 | number[e] = i + 1; |
| 133 | } |
| 134 | |
| 135 | // 1. Sort each citation, decide its cites' positions and render them without locators. |
| 136 | let mut seen = vec![false; items.len()]; |
| 137 | let mut res: Vec<(Option<usize>, Vec<Pending>)> = Vec::new(); |
| 138 | let mut last: Option<(usize, Option<(String, NumVal)>, bool)> = None; |
| 139 | for c in cites { |
| 140 | let mut refs: Vec<(usize, &CiteRef)> = c.refs.iter().enumerate() |
| 141 | .filter(|(_, r)| r.entry < items.len()) |
| 142 | .collect(); |
| 143 | sort(style, chain, lang, items, &mut refs, |(_, r)| r.entry, style.citation.sort.as_ref(), &number); |
| 144 | let mut ps = Vec::new(); |
| 145 | for (initial, r) in refs { |
| 146 | let e = r.entry; |
| 147 | let near_note = c.note.is_some() && res.iter().rev() |
| 148 | .take(style.citation.near_note_distance as usize) |
| 149 | .any(|(n, ps)| n.is_some() && ps.iter().any(|p| p.entry == e)); |
| 150 | let first_note = c.note.map(|n| res.iter() |
| 151 | .find_map(|(m, ps)| m.filter(|_| ps.iter().any(|p| p.entry == e))) |
| 152 | .unwrap_or(n)); |
| 153 | let first = !seen[e]; |
| 154 | seen[e] = true; |
| 155 | let cite = Cite { |
| 156 | number: Some(number[e]), |
| 157 | first_note, |
| 158 | first, |
| 159 | ibid: ibid(e, &r.locator, last.as_ref()), |
| 160 | near_note, |
| 161 | ..Cite::default() |
| 162 | }; |
| 163 | last = Some((e, r.locator.clone(), r.hidden)); |
| 164 | let mut p = Pending { |
| 165 | entry: e, |
| 166 | initial, |
| 167 | locator: r.locator.clone(), |
| 168 | form: r.form, |
| 169 | hidden: r.hidden, |
| 170 | cite, |
| 171 | checked_disamb: false, |
| 172 | first_name: None, |
| 173 | delim: None, |
| 174 | group: None, |
| 175 | special: None, |
| 176 | nodes: Vec::new(), |
| 177 | }; |
| 178 | let out = render::citation_entry(style, chain, &items[e], &p.cite, lang, None); |
| 179 | p.checked_disamb = out.checked_disamb; |
| 180 | p.first_name = out.first_name; |
| 181 | p.nodes = out.nodes; |
| 182 | ps.push(p); |
| 183 | } |
| 184 | res.push((c.note, ps)); |
| 185 | } |
| 186 | |
| 187 | // 2. Up to three rounds of disambiguation. Each set of cites that read alike tries names, |
| 188 | // then `choose`, then a year-suffix, and each entry takes the furthest state its cites |
| 189 | // reached. |
| 190 | for _ in 0..3 { |
| 191 | let sets = ambiguous(&res); |
| 192 | if sets.is_empty() { |
| 193 | break; |
| 194 | } |
| 195 | let mut marks: Vec<Option<Disamb>> = vec![None; items.len()]; |
| 196 | for set in &sets { |
| 197 | let mut found = disamb_names(style, &res, set); |
| 198 | if found.is_empty() && marks.iter().all(Option::is_none) { |
| 199 | found = disamb_choose(&res, set); |
| 200 | } |
| 201 | if found.is_empty() && marks.iter().all(Option::is_none) { |
| 202 | found = disamb_year_suffix(style, items, &res, set); |
| 203 | } |
| 204 | for (e, d) in found { |
| 205 | marks[e] = Some(match marks[e].take() { |
| 206 | Some(m) => m.max(d), |
| 207 | None => d, |
| 208 | }); |
| 209 | } |
| 210 | } |
| 211 | if marks.iter().all(Option::is_none) { |
| 212 | break; |
| 213 | } |
| 214 | for p in res.iter_mut().flat_map(|(_, ps)| ps.iter_mut()) { |
| 215 | if let Some(d) = &marks[p.entry] { |
| 216 | p.cite.disamb = d.clone(); |
| 217 | p.nodes = render::citation_entry(style, chain, &items[p.entry], &p.cite, lang, None).nodes; |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | // 3. Cites with equal names gather behind the first of them. |
| 223 | let layout = &style.citation.layout; |
| 224 | let group_delim = style.citation.cite_group_delimiter.clone() |
| 225 | .or_else(|| layout.delimiter.clone().filter(|_| style.citation.collapse.is_some())); |
| 226 | if let Some(delim) = group_delim { |
| 227 | for (_, ps) in res.iter_mut() { |
| 228 | group(ps, &delim); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // 4. Final positions on the final order, and the locators. |
| 233 | let mut prev: Option<(usize, Option<(String, NumVal)>, bool)> = None; |
| 234 | for (_, ps) in res.iter_mut() { |
| 235 | for p in ps.iter_mut() { |
| 236 | p.cite.ibid = ibid(p.entry, &p.locator, prev.as_ref()); |
| 237 | p.cite.locator = p.locator.clone(); |
| 238 | prev = Some((p.entry, p.locator.clone(), false)); |
| 239 | } |
| 240 | } |
| 241 | // Without a bibliography sort, numbers follow the cites as they now stand. |
| 242 | if bib_sort.is_none() { |
| 243 | let mut n = vec![0; items.len()]; |
| 244 | let mut next = 1; |
| 245 | for p in res.iter_mut().flat_map(|(_, ps)| ps.iter_mut()) { |
| 246 | if n[p.entry] == 0 { |
| 247 | n[p.entry] = next; |
| 248 | next += 1; |
| 249 | } |
| 250 | p.cite.number = Some(n[p.entry]); |
| 251 | } |
| 252 | number = n; |
| 253 | } |
| 254 | |
| 255 | // The bibliography inherits each entry's first cite. |
| 256 | let mut bib: Vec<Option<Cite>> = vec![None; items.len()]; |
| 257 | for p in res.iter().flat_map(|(_, ps)| ps.iter()) { |
| 258 | if bib[p.entry].is_none() { |
| 259 | bib[p.entry] = Some(Cite { locator: None, ..p.cite.clone() }); |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | // 5-6. Collapsing, the final render of each cite, then the citation's affixes and |
| 264 | // delimiters. |
| 265 | let fmt = Formatting::default().apply(&layout.look.fmt); |
| 266 | let mut out = Vec::with_capacity(res.len()); |
| 267 | for (_, ps) in res.iter_mut() { |
| 268 | if ps.iter().all(|p| p.form == CiteForm::Normal) { |
| 269 | collapse(style, ps); |
| 270 | } |
| 271 | for p in ps.iter_mut() { |
| 272 | p.nodes = render::citation_entry(style, chain, &items[p.entry], &p.cite, lang, p.special.clone()).nodes; |
| 273 | } |
| 274 | if ps.iter().all(|p| p.hidden) { |
| 275 | out.push(Vec::new()); |
| 276 | continue; |
| 277 | } |
| 278 | let affix = ps.iter().all(|p| p.form == CiteForm::Normal); |
| 279 | let mut nodes = Vec::new(); |
| 280 | if let (true, Some(pre)) = (affix, layout.look.prefix.as_ref()) { |
| 281 | nodes.push(Node::Text(pre.clone(), fmt)); |
| 282 | } |
| 283 | for (i, p) in ps.iter().enumerate() { |
| 284 | if p.hidden { |
| 285 | continue; |
| 286 | } |
| 287 | if i != 0 { |
| 288 | if let Some(d) = p.delim.as_ref().or(layout.delimiter.as_ref()) { |
| 289 | nodes.push(Node::Text(d.clone(), fmt)); |
| 290 | } |
| 291 | } |
| 292 | nodes.push(Node::Elem(node::Elem { |
| 293 | children: p.nodes.clone(), |
| 294 | display: None, |
| 295 | meta: Some(Meta::Entry(p.initial)), |
| 296 | })); |
| 297 | } |
| 298 | if let (true, Some(suf)) = (affix, layout.look.suffix.as_ref()) { |
| 299 | if !node::last_text(&nodes).map_or(false, |t| t.ends_with(suf.as_str())) { |
| 300 | nodes.push(Node::Text(suf.clone(), fmt)); |
| 301 | } |
| 302 | } |
| 303 | out.push(node::simplify(nodes)); |
| 304 | } |
| 305 | Self { order, number, bib, cites: out } |
| 306 | } |
| 307 | |
| 308 | /// The entries in bibliography order. |
| 309 | pub fn order(&self) -> &[usize] { |
| 310 | &self.order |
| 311 | } |
| 312 | |
| 313 | pub fn number(&self, entry: usize) -> Option<usize> { |
| 314 | self.number.get(entry).copied().filter(|&n| n > 0) |
| 315 | } |
| 316 | |
| 317 | /// The `i`th citation as given to [`CiteState::new`], rendered; empty when every cite in it is |
| 318 | /// hidden. |
| 319 | pub fn citation(&self, i: usize) -> &[Node] { |
| 320 | self.cites.get(i).map_or(&[], |c| c.as_slice()) |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | // Disambiguation |
| 325 | |
| 326 | type Set = Vec<(usize, usize)>; // cites by citation and place in it |
| 327 | type Res = [(Option<usize>, Vec<Pending>)]; |
| 328 | |
| 329 | /// The sets of cites, still open to a year-suffix, that render alike though their entries differ. |
| 330 | fn ambiguous(res: &Res) -> Vec<Set> { |
| 331 | let mut keys: Vec<(String, Option<usize>, (usize, usize))> = Vec::new(); // key, its set, first cite |
| 332 | let mut sets: Vec<Set> = Vec::new(); |
| 333 | for (i, (_, ps)) in res.iter().enumerate() { |
| 334 | for (j, p) in ps.iter().enumerate() { |
| 335 | if !p.cite.disamb.may_year_suffix() { |
| 336 | continue; |
| 337 | } |
| 338 | let key = node::styled(&p.nodes); |
| 339 | match keys.iter_mut().find(|(k, _, _)| *k == key) { |
| 340 | Some((_, Some(set), _)) => sets[*set].push((i, j)), |
| 341 | Some((_, set, first)) => { |
| 342 | *set = Some(sets.len()); |
| 343 | sets.push(vec![*first, (i, j)]); |
| 344 | } |
| 345 | None => keys.push((key, None, (i, j))), |
| 346 | } |
| 347 | } |
| 348 | } |
| 349 | sets.into_iter().filter(|set| { |
| 350 | let first = set.first().map(|&(i, j)| res[i].1[j].entry); |
| 351 | set.iter().any(|&(i, j)| Some(res[i].1[j].entry) != first) |
| 352 | }).collect() |
| 353 | } |
| 354 | |
| 355 | /// Every person a cite's `names` elements hold, written or not. |
| 356 | fn names_of(nodes: &[Node], out: &mut Vec<Person>) { |
| 357 | for n in nodes { |
| 358 | if let Node::Elem(e) = n { |
| 359 | if let Some(Meta::Names(ns)) = &e.meta { |
| 360 | out.extend(ns.iter().flat_map(|(ps, _)| ps.iter()).cloned()); |
| 361 | } |
| 362 | names_of(&e.children, out); |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | /// One cite of an ambiguous set, with its people. |
| 368 | struct DisambData<'r> { |
| 369 | at: (usize, usize), |
| 370 | names: Vec<Person>, |
| 371 | p: &'r Pending, |
| 372 | } |
| 373 | |
| 374 | /// Do the first `n` names, as the given-name rule compares them, tell `x` from the rest? |
| 375 | fn is_disambiguated(n: usize, xs: &[DisambData], x: &DisambData, rule: Option<GivenRule>) -> bool { |
| 376 | let init = |p: &Person| { |
| 377 | let mut g = String::new(); |
| 378 | let _ = p.initials(&mut g, None, false); |
| 379 | Person { given: Some(g), ..p.clone() } |
| 380 | }; |
| 381 | let bare = |p: &Person| Person { given: None, ..p.clone() }; |
| 382 | let parts = |d: &DisambData| -> Vec<Person> { |
| 383 | d.names.iter().take(n).enumerate().map(|(i, p)| match rule { |
| 384 | Some(GivenRule::AllNames | GivenRule::ByCite) => p.clone(), |
| 385 | Some(GivenRule::AllNamesWithInitials) => init(p), |
| 386 | Some(GivenRule::PrimaryName) if i == 0 => p.clone(), |
| 387 | Some(GivenRule::PrimaryNameWithInitials) if i == 0 => init(p), |
| 388 | Some(GivenRule::PrimaryName | GivenRule::PrimaryNameWithInitials) | None => bare(p), |
| 389 | }).collect() |
| 390 | }; |
| 391 | let mine = parts(x); |
| 392 | xs.iter().all(|y| y.at == x.at || parts(y) != mine) |
| 393 | } |
| 394 | |
| 395 | /// hayagriva's `disamb_cite_add_given_name`: a namesake with other initials needs the initial, one |
| 396 | /// with the same initials the full given name. |
| 397 | fn add_given(x: &Person, xs: &[&Person], form: &mut NForm) -> bool { |
| 398 | if *form == NForm::Count || *form == NForm::LongFull { |
| 399 | return false; |
| 400 | } |
| 401 | let mut changed = false; |
| 402 | for p in xs { |
| 403 | if x == *p || x.family != p.family { |
| 404 | continue; |
| 405 | } |
| 406 | let (mut xi, mut pi) = (String::new(), String::new()); |
| 407 | let _ = x.initials(&mut xi, None, false); |
| 408 | let _ = p.initials(&mut pi, None, false); |
| 409 | if xi == pi { |
| 410 | *form = NForm::LongFull; |
| 411 | return true; |
| 412 | } |
| 413 | if *form != NForm::LongInit { |
| 414 | *form = NForm::LongInit; |
| 415 | changed = true; |
| 416 | } |
| 417 | } |
| 418 | changed |
| 419 | } |
| 420 | |
| 421 | /// hayagriva's `disambiguate_names`: show more names, one more each pass, and under the by-cite |
| 422 | /// rule widen the forms of namesakes, until each cite stands apart. |
| 423 | fn disamb_names(style: &Style, res: &Res, set: &Set) -> Vec<(usize, Disamb)> { |
| 424 | let group: Vec<DisambData> = set.iter().map(|&(i, j)| { |
| 425 | let mut names = Vec::new(); |
| 426 | names_of(&res[i].1[j].nodes, &mut names); |
| 427 | DisambData { at: (i, j), names, p: &res[i].1[j] } |
| 428 | }).collect(); |
| 429 | let max = match style.citation.add_names { |
| 430 | true => group.iter().map(|d| d.names.len()).max().unwrap_or(0), |
| 431 | false => 1, |
| 432 | }; |
| 433 | let rule = match style.citation.add_givenname { |
| 434 | true => Some(style.citation.givenname_rule), |
| 435 | false => None, |
| 436 | }; |
| 437 | let mut changed: Vec<((usize, usize), NameDisamb)> = Vec::new(); |
| 438 | let slot = |changed: &Vec<((usize, usize), NameDisamb)>, d: &DisambData| -> Option<NameDisamb> { |
| 439 | match changed.iter().find(|(at, _)| *at == d.at) { |
| 440 | Some((_, n)) => Some(n.clone()), |
| 441 | None => match &d.p.cite.disamb { |
| 442 | Disamb::Names(n) => Some(n.clone()), |
| 443 | _ => d.p.first_name.clone(), |
| 444 | }, |
| 445 | } |
| 446 | }; |
| 447 | let put = |changed: &mut Vec<((usize, usize), NameDisamb)>, at: (usize, usize), n: NameDisamb| { |
| 448 | match changed.iter_mut().find(|(a, _)| *a == at) { |
| 449 | Some((_, old)) => *old = n, |
| 450 | None => changed.push((at, n)), |
| 451 | } |
| 452 | }; |
| 453 | let mut done: Vec<(usize, usize)> = Vec::new(); |
| 454 | for i in 1..=max { |
| 455 | let before = done.len(); |
| 456 | if before == group.len() { |
| 457 | break; |
| 458 | } |
| 459 | for d in &group { |
| 460 | if done.contains(&d.at) || !d.p.cite.disamb.may_names() || !is_disambiguated(i, &group, d, rule) { |
| 461 | continue; |
| 462 | } |
| 463 | done.push(d.at); |
| 464 | if rule != Some(GivenRule::ByCite) { |
| 465 | continue; |
| 466 | } |
| 467 | if let (Some(mut props), Some(x)) = (slot(&changed, d), d.names.get(i - 1)) { |
| 468 | let others: Vec<&Person> = group.iter() |
| 469 | .filter(|o| o.at != d.at) |
| 470 | .flat_map(|o| o.names.iter()) |
| 471 | .collect(); |
| 472 | if add_given(x, &others, props.form_mut(i - 1)) { |
| 473 | put(&mut changed, d.at, props); |
| 474 | } |
| 475 | } |
| 476 | } |
| 477 | if done.len() > before { |
| 478 | for d in &group { |
| 479 | if let Some(mut s) = slot(&changed, d) { |
| 480 | s.add_name(i); |
| 481 | put(&mut changed, d.at, s); |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 | changed.into_iter().map(|((i, j), n)| (res[i].1[j].entry, Disamb::Names(n))).collect() |
| 487 | } |
| 488 | |
| 489 | /// hayagriva's `disambiguate_with_choose`: every cite that asked `disambiguate`, but the first, |
| 490 | /// takes the `choose` branch. |
| 491 | fn disamb_choose(res: &Res, set: &Set) -> Vec<(usize, Disamb)> { |
| 492 | let ps: Vec<&Pending> = set.iter().map(|&(i, j)| &res[i].1[j]).collect(); |
| 493 | if !ps.iter().any(|p| p.checked_disamb && p.cite.disamb.may_choose()) { |
| 494 | return Vec::new(); |
| 495 | } |
| 496 | ps.iter().filter(|p| p.checked_disamb).skip(1).map(|p| (p.entry, Disamb::Choose)).collect() |
| 497 | } |
| 498 | |
| 499 | /// hayagriva's `disambiguate_year_suffix`: when some cite writes a date and the style allows it, |
| 500 | /// each entry of the set takes a suffix in the order it first appears. |
| 501 | fn disamb_year_suffix<I: Item>(style: &Style, items: &[I], res: &Res, set: &Set) -> Vec<(usize, Disamb)> { |
| 502 | const DATES: [&str; 6] = ["issued", "accessed", "available-date", "event-date", "submitted", "original-date"]; |
| 503 | let dated = res.iter().flat_map(|(_, ps)| ps.iter()).any(|p| { |
| 504 | let has = DATES.iter().any(|v| items[p.entry].date(v).is_some()); |
| 505 | node::find_elem(&p.nodes, &|e| e.meta == Some(Meta::Date) || (has && e.meta == Some(Meta::CitationLabel))).is_some() |
| 506 | }); |
| 507 | let open = |&(i, j): &(usize, usize)| res[i].1[j].cite.disamb.may_year_suffix(); |
| 508 | if !dated || !style.citation.add_year_suffix || !set.iter().any(open) { |
| 509 | return Vec::new(); |
| 510 | } |
| 511 | let mut entries: Vec<usize> = Vec::new(); |
| 512 | for at in set.iter().filter(|at| open(at)) { |
| 513 | let e = res[at.0].1[at.1].entry; |
| 514 | if !entries.contains(&e) { |
| 515 | entries.push(e); |
| 516 | } |
| 517 | } |
| 518 | entries.into_iter().enumerate().map(|(i, e)| (e, Disamb::YearSuffix(i as u8))).collect() |
| 519 | } |
| 520 | |
| 521 | // Grouping and collapsing |
| 522 | |
| 523 | /// hayagriva's grouping: each cite whose first `names` element equals an earlier one's moves up |
| 524 | /// behind the last of them and takes `delim` before it, which the one it follows gives up. As in |
| 525 | /// hayagriva, the group number recorded is the count of groups so far, and the indices kept for |
| 526 | /// earlier groups are not shifted by a later move. |
| 527 | fn group(ps: &mut [Pending], delim: &str) { |
| 528 | let mut map: Vec<(node::Elem, usize)> = Vec::new(); // a names element, the last index with it |
| 529 | let mut count = 0; |
| 530 | for i in 0..ps.len() { |
| 531 | let names = match node::find_elem(&ps[i].nodes, &|e| matches!(e.meta, Some(Meta::Names(_)))) { |
| 532 | Some(e) => e.clone(), |
| 533 | None => continue, |
| 534 | }; |
| 535 | let mut prev = None; |
| 536 | let target = match map.iter_mut().find(|(n, _)| *n == names) { |
| 537 | Some((_, last)) => { |
| 538 | prev = Some(*last); |
| 539 | *last += 1; |
| 540 | *last |
| 541 | } |
| 542 | None => { |
| 543 | count += 1; |
| 544 | map.push((names, i)); |
| 545 | i |
| 546 | } |
| 547 | }; |
| 548 | let mut pos = i; |
| 549 | while target < pos { |
| 550 | ps.swap(pos, pos - 1); |
| 551 | pos -= 1; |
| 552 | } |
| 553 | ps[target].delim = Some(delim.to_string()); |
| 554 | ps[target].group = Some(count); |
| 555 | if let Some(p) = prev { |
| 556 | ps[p].delim = None; |
| 557 | } |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | /// hayagriva's `collapse_items`: runs of three or more consecutive citation numbers become a |
| 562 | /// range, and a group's later cites keep only their year, or only their year-suffix. |
| 563 | fn collapse(style: &Style, ps: &mut [Pending]) { |
| 564 | let c = &style.citation; |
| 565 | let after = c.after_collapse_delimiter.clone().or_else(|| c.layout.delimiter.clone()); |
| 566 | let group_delim = c.cite_group_delimiter.clone(); |
| 567 | let suffix_delim = c.year_suffix_delimiter.clone().or_else(|| group_delim.clone()); |
| 568 | match c.collapse { |
| 569 | Some(Collapse::CitationNumber) => { |
| 570 | let mut range: Option<(usize, usize)> = None; // its first and last index |
| 571 | let mut just = false; // the last range collapsed |
| 572 | let end_range = |ps: &mut [Pending], range: &mut Option<(usize, usize)>, just: &mut bool| { |
| 573 | let use_after = *just; |
| 574 | *just = false; |
| 575 | if let Some((start, end)) = *range { |
| 576 | if use_after { |
| 577 | ps[start].delim = after.clone(); |
| 578 | } |
| 579 | if start + 1 < end { |
| 580 | ps[end].delim = Some("–".to_string()); |
| 581 | for p in &mut ps[start + 1..end] { |
| 582 | p.hidden = true; |
| 583 | } |
| 584 | *just = true; |
| 585 | } |
| 586 | } |
| 587 | *range = None; |
| 588 | }; |
| 589 | for i in 0..ps.len() { |
| 590 | let numbered = node::find_elem(&ps[i].nodes, &|e| e.meta == Some(Meta::CitationNumber)).is_some(); |
| 591 | if ps[i].hidden || !numbered { |
| 592 | end_range(ps, &mut range, &mut just); |
| 593 | continue; |
| 594 | } |
| 595 | let n = ps[i].cite.number; |
| 596 | match range { |
| 597 | Some((start, end)) if end + 1 == i && ps[end].cite.number.map(|m| m + 1) == n => { |
| 598 | range = Some((start, i)); |
| 599 | } |
| 600 | _ => { |
| 601 | end_range(ps, &mut range, &mut just); |
| 602 | range = Some((i, i)); |
| 603 | } |
| 604 | } |
| 605 | } |
| 606 | end_range(ps, &mut range, &mut just); |
| 607 | } |
| 608 | Some(kind @ (Collapse::Year | Collapse::YearSuffix | Collapse::YearSuffixRanged)) => { |
| 609 | let mut cur: Option<(usize, usize)> = None; // where the group began, and its number |
| 610 | for i in 0..ps.len() { |
| 611 | match cur { |
| 612 | Some((_, g)) if Some(g) == ps[i].group => { |
| 613 | let suffixed = matches!(ps[i].cite.disamb, render::Disamb::YearSuffix(s) if s > 0); |
| 614 | if kind == Collapse::YearSuffix && suffixed { |
| 615 | ps[i].delim = suffix_delim.clone(); |
| 616 | ps[i].special = Some(Special::OnlyYearSuffix); |
| 617 | continue; |
| 618 | } |
| 619 | ps[i].delim = group_delim.clone(); |
| 620 | ps[i].special = Some(Special::OnlyFirstDate); |
| 621 | } |
| 622 | Some((start, _)) if start + 1 < i => { |
| 623 | ps[i].delim = after.clone(); |
| 624 | cur = ps[i].group.map(|g| (i, g)); |
| 625 | } |
| 626 | _ => cur = ps[i].group.map(|g| (i, g)), |
| 627 | } |
| 628 | } |
| 629 | } |
| 630 | None => {} |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | /// hayagriva's `IbidState::with_last`: the same entry as the last cite, when that was printed, is |
| 635 | /// ibid with an equal locator, and ibid-with-locator when only this one has a locator or they |
| 636 | /// differ; without a locator after one with it, it is only subsequent. |
| 637 | fn ibid( |
| 638 | entry: usize, |
| 639 | loc: &Option<(String, NumVal)>, |
| 640 | last: Option<&(usize, Option<(String, NumVal)>, bool)>, |
| 641 | ) |
| 642 | -> Ibid |
| 643 | { |
| 644 | match last { |
| 645 | Some((e, l, hidden)) if *e == entry && !*hidden => match (l == loc, loc.is_none()) { |
| 646 | (true, _) => Ibid::Ibid, |
| 647 | (false, true) => Ibid::No, |
| 648 | (false, false) => Ibid::WithLocator, |
| 649 | }, |
| 650 | _ => Ibid::No, |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | /// Renders the bibliography: every cited entry in the style's order, each split into its first |
| 655 | /// field and the rest when the style asks for `second-field-align`. Empty when the style has no |
| 656 | /// bibliography. |
| 657 | pub fn render_bibliography<'a, I: Item>( |
| 658 | style: &'a Style, |
| 659 | chain: &'a Chain<'a>, |
| 660 | lang: Option<&'a str>, |
| 661 | items: &'a [I], |
| 662 | state: &CiteState, |
| 663 | ) |
| 664 | -> Vec<BibEntry> |
| 665 | { |
| 666 | let align = style.bibliography.as_ref().map_or(false, |b| b.second_field_align.is_some()); |
| 667 | let mut out = Vec::new(); |
| 668 | for &e in &state.order { |
| 669 | let cite = match state.bib.get(e).cloned().flatten() { |
| 670 | Some(c) => Cite { number: state.number(e), ..c }, |
| 671 | None => Cite { number: state.number(e), first: true, ..Cite::default() }, |
| 672 | }; |
| 673 | let mut body = match render::bibliography_entry(style, chain, &items[e], &cite, lang) { |
| 674 | Some(n) => node::simplify(n), |
| 675 | None => return Vec::new(), |
| 676 | }; |
| 677 | let prefix = match align { |
| 678 | true => node::remove_any_meta(&mut body), |
| 679 | false => None, |
| 680 | }; |
| 681 | out.push((prefix, body)); |
| 682 | } |
| 683 | out |
| 684 | } |
| 685 | |
| 686 | // Sorting |
| 687 | |
| 688 | /// Sorts cites, each naming its entry through `ent`, by a style's keys, stably. `num` gives each entry's citation number for a |
| 689 | /// `citation-number` key. |
| 690 | fn sort<'a, I: Item, T>( |
| 691 | style: &'a Style, |
| 692 | chain: &'a Chain<'a>, |
| 693 | lang: Option<&'a str>, |
| 694 | items: &'a [I], |
| 695 | idx: &mut [T], |
| 696 | ent: impl Fn(&T) -> usize, |
| 697 | keys: Option<&'a Sort>, |
| 698 | num: &[usize], |
| 699 | ) { |
| 700 | let keys = match keys { |
| 701 | Some(k) => k, |
| 702 | None => return, |
| 703 | }; |
| 704 | idx.sort_by(|a, b| { |
| 705 | let (a, b) = (ent(a), ent(b)); |
| 706 | for k in &keys.keys { |
| 707 | let o = cmp_key(style, chain, lang, (&items[a], num[a]), (&items[b], num[b]), k); |
| 708 | if o != Ordering::Equal { |
| 709 | return o; |
| 710 | } |
| 711 | } |
| 712 | Ordering::Equal |
| 713 | }); |
| 714 | } |
| 715 | |
| 716 | /// One key's order. As in hayagriva, a key that one side lacks reverses the order as a |
| 717 | /// descending key does, which puts the entry without the value last. |
| 718 | fn cmp_key<'a, I: Item>( |
| 719 | style: &'a Style, |
| 720 | chain: &'a Chain<'a>, |
| 721 | lang: Option<&'a str>, |
| 722 | (a, an): (&'a I, usize), |
| 723 | (b, bn): (&'a I, usize), |
| 724 | key: &'a SortKey, |
| 725 | ) |
| 726 | -> Ordering |
| 727 | { |
| 728 | fn opt<T>(a: Option<T>, b: Option<T>, f: impl Fn(&T, &T) -> Ordering) -> (Ordering, bool) { |
| 729 | match (a, b) { |
| 730 | (Some(a), Some(b)) => (f(&a, &b), false), |
| 731 | (Some(_), None) => (Ordering::Greater, true), |
| 732 | (None, Some(_)) => (Ordering::Less, true), |
| 733 | (None, None) => (Ordering::Equal, true), |
| 734 | } |
| 735 | } |
| 736 | let (ord, empty) = match &key.src { |
| 737 | SortSrc::Var(v) => match var_kind(v) { |
| 738 | VarKind::Standard => { |
| 739 | let f = |i: &I| i.text(v, VarForm::Long).map(|c| c.to_string().to_lowercase()); |
| 740 | opt(f(a), f(b), |x, y| collate(x, y)) |
| 741 | } |
| 742 | VarKind::Date => opt(a.date(v), b.date(v), date_cmp), |
| 743 | VarKind::Name => { |
| 744 | let demote = style.demote_particle != Demote::Never; |
| 745 | let (pa, pb) = (a.names(v), b.names(v)); |
| 746 | for (x, y) in pa.iter().zip(pb.iter()) { |
| 747 | let o = x.sort_cmp(y, demote); |
| 748 | if o != Ordering::Equal { |
| 749 | return o; |
| 750 | } |
| 751 | } |
| 752 | (pa.len().cmp(&pb.len()), false) |
| 753 | } |
| 754 | VarKind::Number => { |
| 755 | let f = |i: &I, n: usize| match v.as_str() { |
| 756 | "citation-number" => Some(n.to_string()), |
| 757 | _ => i.number(v), |
| 758 | }; |
| 759 | opt(f(a, an), f(b, bn), |x, y| num_cmp(x, y)) |
| 760 | } |
| 761 | VarKind::Page => opt(a.page().map(|p| page_str(&p)), b.page().map(|p| page_str(&p)), |x, y| x.cmp(y)), |
| 762 | }, |
| 763 | SortSrc::Macro(m) => { |
| 764 | let ka = macro_key(style, chain, lang, a, an, m, key); |
| 765 | let kb = macro_key(style, chain, lang, b, bn, m, key); |
| 766 | opt(ka, kb, |x, y| collate(x, y)) |
| 767 | } |
| 768 | }; |
| 769 | match empty || !key.ascending { |
| 770 | true => ord.reverse(), |
| 771 | false => ord, |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | /// Compares two sort strings at primary strength, then by code point. |
| 776 | pub fn collate(a: &str, b: &str) -> Ordering { |
| 777 | fn primary(s: &str) -> Vec<(u8, char)> { |
| 778 | nfd(s).chars().filter(|&c| combining_class(c) == 0).map(|c| match c { |
| 779 | c if c.is_whitespace() => (0, ' '), |
| 780 | c if c.is_alphabetic() => (3, c.to_lowercase().next().unwrap_or(c)), |
| 781 | c if c.is_numeric() => (2, c), |
| 782 | c => (1, c), |
| 783 | }).collect() |
| 784 | } |
| 785 | primary(a).cmp(&primary(b)).then_with(|| a.cmp(b)) |
| 786 | } |
| 787 | |
| 788 | /// hayagriva's `Date::csl_cmp`: year, then month and day, a missing part first. |
| 789 | fn date_cmp(a: &DateVal, b: &DateVal) -> Ordering { |
| 790 | let part = |x: Option<u8>, y: Option<u8>| match (x, y) { |
| 791 | (Some(x), Some(y)) => x.cmp(&y), |
| 792 | (Some(_), None) => Ordering::Greater, |
| 793 | (None, Some(_)) => Ordering::Less, |
| 794 | (None, None) => a.approximate.cmp(&b.approximate), |
| 795 | }; |
| 796 | a.year.cmp(&b.year).then_with(|| part(a.month, b.month)).then_with(|| part(a.day, b.day)) |
| 797 | } |
| 798 | |
| 799 | fn page_str(p: &PageVal) -> String { |
| 800 | match p { |
| 801 | PageVal::Typed(r) => { let mut s = String::new(); r.write(&mut s, None, None); s } |
| 802 | PageVal::Str(s) => s.clone(), |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | /// Numbers compare by their values in turn; anything not numeric as a string. |
| 807 | fn num_cmp(a: &str, b: &str) -> Ordering { |
| 808 | match (Numeric::parse(a), Numeric::parse(b)) { |
| 809 | (Some(x), Some(y)) => x.nums.iter().map(|n| n.0).cmp(y.nums.iter().map(|n| n.0)), |
| 810 | _ => a.cmp(b), |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | /// A macro key renders the macro as plain lower-cased text, with the key's name options laid |
| 815 | /// over the style's. |
| 816 | fn macro_key<'a, I: Item>( |
| 817 | style: &'a Style, |
| 818 | chain: &'a Chain<'a>, |
| 819 | lang: Option<&'a str>, |
| 820 | item: &'a I, |
| 821 | num: usize, |
| 822 | name: &str, |
| 823 | key: &SortKey, |
| 824 | ) |
| 825 | -> Option<String> |
| 826 | { |
| 827 | let elems = match style.macros.get(name) { |
| 828 | Some(e) => e, |
| 829 | None => return None, |
| 830 | }; |
| 831 | let cite = Cite { number: Some(num), first: true, ..Cite::default() }; |
| 832 | let names = NameOpts { |
| 833 | et_al_min: key.names_min, |
| 834 | et_al_subsequent_min: key.names_min, |
| 835 | et_al_use_first: key.names_use_first, |
| 836 | et_al_subsequent_use_first: key.names_use_first, |
| 837 | et_al_use_last: key.names_use_last, |
| 838 | ..NameOpts::default() |
| 839 | }; |
| 840 | let mut ctx = Ctx::new(style, chain, item, &cite, lang, false).sorting(Sorting::Macro, names); |
| 841 | ctx.render_all(elems); |
| 842 | Some(node::plain(&ctx.flush()).to_lowercase()) |
| 843 | } |