Oregami
Repositories/oxedyne/fe2o3

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

69.2 KiB, 201 runs

created by r1870400018:73624, 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`, the writing context; `src/csl/rendering/mod.rs` and
3//! `rendering/names.rs`, the element renderers; citationberg 0.7.0 `OrdinalLookup`, same
4//! licence).
5//!
6//! Dates are hayagriva's `rendering/mod.rs` 624-905 and names `rendering/names.rs` 190-868. B3
7//! adds the special forms, sorting (which reverses names and strips institutional articles), name
8//! disambiguation, the implicit year-suffix, the citation layout and second-field-align.
9use crate::csl::{
10 case::{
11 is_language_dependent,
12 Case,
13 CaseFolder,
14 },
15 item::{
16 is_number_of,
17 var_kind,
18 Chunked,
19 DateVal,
20 Item,
21 NumDelim,
22 NumVal,
23 Numeric,
24 VarKind,
25 },
26 locale::{
27 Chain,
28 Gender,
29 OrdMatch,
30 Term,
31 },
32 node::{
33 self,
34 Elem as NodeElem,
35 Formatting,
36 Meta,
37 Node,
38 },
39 page::PageVal,
40 person::Person,
41 style::{
42 And,
43 Choose,
44 Cond,
45 Date,
46 DatePart,
47 DatePartForm,
48 DatePartName,
49 DateParts,
50 DelimRule,
51 Demote,
52 Display,
53 Elem,
54 EtAl,
55 Fmt,
56 Group,
57 Label,
58 Look,
59 Match,
60 Name,
61 NameForm,
62 NameOpts,
63 NamePart,
64 Names,
65 NumForm,
66 Number,
67 Plural,
68 PartName,
69 Position,
70 SortOrder,
71 Style,
72 Test,
73 Text,
74 TextCase,
75 TextSrc,
76 TermForm,
77 VarForm,
78 },
79};
80
81use std::fmt::Write;
82
83
84#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
85pub enum Ibid { #[default] No, Ibid, WithLocator }
86
87/// Rendering a sort key: by a variable, or through a macro. Names reverse, institutional names
88/// lose a leading article, and dates and numbers render as sortable values.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum Sorting { Variable, Macro }
91
92/// What a cite's disambiguation has reached: hayagriva's `DisambiguateState`.
93#[derive(Clone, Debug, Default, PartialEq, Eq)]
94pub enum Disamb { #[default] None, Names(NameDisamb), Choose, YearSuffix(u8) }
95
96impl Disamb {
97
98 pub fn may_names(&self) -> bool {
99 matches!(self, Self::None | Self::Names(_))
100 }
101
102 pub fn may_choose(&self) -> bool {
103 matches!(self, Self::None | Self::Names(_))
104 }
105
106 pub fn may_year_suffix(&self) -> bool {
107 matches!(self, Self::None | Self::Names(_) | Self::Choose)
108 }
109
110 /// The further of two states: names, then choose, then a year-suffix.
111 pub fn max(self, other: Self) -> Self {
112 match (self, other) {
113 (Self::None, o) => o,
114 (s, Self::None) => s,
115 (Self::Names(a), Self::Names(b)) => Self::Names(a.max(b)),
116 (Self::Names(_), o) => o,
117 (s, Self::Names(_)) => s,
118 (Self::Choose, o) => o,
119 (s, Self::Choose) => s,
120 (Self::YearSuffix(a), Self::YearSuffix(b)) => Self::YearSuffix(a.max(b)),
121 }
122 }
123}
124
125/// hayagriva's `NameDisambiguationProperties`: for each variable of a `names` element, each
126/// person's form, `None` while et al. cuts it.
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct NameDisamb {
129 forms: Vec<Vec<Option<NForm>>>,
130 default: NForm,
131 vars: Vec<String>,
132}
133
134impl NameDisamb {
135
136 /// Shows the first `num` names of the first variable that has as many.
137 pub fn add_name(&mut self, num: usize) -> bool {
138 let def = self.default;
139 match self.forms.iter_mut().find(|l| l.len() >= num) {
140 Some(l) => {
141 for n in l.iter_mut().take(num) {
142 if n.is_none() {
143 *n = Some(def);
144 }
145 }
146 true
147 }
148 None => false,
149 }
150 }
151
152 /// The more disambiguated: more names shown, then the larger forms.
153 pub fn max(self, other: Self) -> Self {
154 let shown = |x: &Self| x.forms.iter().flatten().filter(|f| f.is_some()).count();
155 let ord = shown(&self).cmp(&shown(&other))
156 .then_with(|| self.forms.iter().flatten().cmp(other.forms.iter().flatten()));
157 match ord {
158 std::cmp::Ordering::Greater => self,
159 _ => other,
160 }
161 }
162
163 /// The `idx`th name's form across the variables, or the default form when it is cut or
164 /// absent.
165 pub fn form_mut(&mut self, idx: usize) -> &mut NForm {
166 match self.forms.iter_mut().flat_map(|l| l.iter_mut()).nth(idx) {
167 Some(Some(f)) => f,
168 _ => &mut self.default,
169 }
170 }
171}
172
173/// hayagriva's special forms: render one variable only, the first date alone (a collapsed
174/// year), the year-suffix alone, or everything but the author.
175#[derive(Clone, Debug, PartialEq, Eq)]
176pub enum Special { VarOnly(String), OnlyFirstDate, OnlyYearSuffix, SuppressAuthor }
177
178/// What the citation, rather than the entry, supplies: its number, label and locator, and the
179/// position tests' answers.
180#[derive(Clone, Debug, Default)]
181pub struct Cite {
182 pub number: Option<usize>,
183 pub label: Option<String>,
184 pub locator: Option<(String, NumVal)>, // kind (`page`, `custom`) and value
185 pub first_note: Option<usize>, // first-reference-note-number
186 pub disamb: Disamb,
187 pub first: bool,
188 pub ibid: Ibid,
189 pub near_note: bool,
190}
191
192// Usage
193#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
194struct Usage {
195 vars: bool,
196 non_empty: bool,
197 macros: bool,
198 group: bool,
199}
200
201impl Usage {
202 fn merge(self, c: Self) -> Self {
203 Self {
204 vars: self.vars || c.vars,
205 non_empty: self.non_empty || c.non_empty,
206 macros: self.macros || c.macros,
207 group: self.group || c.group,
208 }
209 }
210
211 /// Does a group with this usage print? Only when it queried no variable, or one of them was
212 /// non-empty (directly, through a macro, or through a nested group).
213 fn should_render_group(&self) -> bool {
214 !self.vars || self.non_empty || self.macros || self.group
215 }
216}
217
218// Writer
219#[derive(Clone, Copy, Debug)]
220struct Loc {
221 elem: usize,
222 fmt: usize,
223}
224
225#[derive(Clone, Copy, Debug)]
226struct Affix {
227 loc: Loc,
228 plen: usize, // prefix length in bytes
229}
230
231/// hayagriva's `WritingContext`: stacks of formatting, case and delimiter over a case-folding
232/// buffer, and a stack of element levels. Each stack's base is held apart so it is never popped.
233#[derive(Debug, Default)]
234struct Writer {
235 pull: bool,
236 inner_quotes: bool,
237 strip_periods: bool,
238 suppressing: bool,
239 suppressed: Vec<String>,
240 checked_disamb: bool,
241 first_name: Option<NameDisamb>, // the first `names` element's forms
242 dates_seen: bool, // the first date has rendered
243 fmts: Vec<Formatting>,
244 cases: Vec<Option<TextCase>>,
245 delims: Vec<Option<String>>,
246 buf: CaseFolder,
247 base: Vec<Node>,
248 stack: Vec<Vec<Node>>,
249}
250
251impl Writer {
252
253 fn fmt(&self) -> Formatting {
254 self.fmts.last().copied().unwrap_or_default()
255 }
256
257 fn top(&self) -> &Vec<Node> {
258 match self.stack.last() {
259 Some(l) => l,
260 None => &self.base,
261 }
262 }
263
264 fn top_mut(&mut self) -> &mut Vec<Node> {
265 match self.stack.last_mut() {
266 Some(l) => l,
267 None => &mut self.base,
268 }
269 }
270
271 /// The topmost level that is not empty, as hayagriva's `last_mut_predicate`.
272 fn top_non_empty_mut(&mut self) -> Option<&mut Vec<Node>> {
273 match self.stack.iter().rposition(|l| !node::is_empty(l)) {
274 Some(i) => self.stack.get_mut(i),
275 None if !node::is_empty(&self.base) => Some(&mut self.base),
276 None => None,
277 }
278 }
279
280 fn push_format(&mut self, f: &Fmt) -> usize {
281 if f.is_plain() {
282 return self.fmts.len();
283 }
284 self.save();
285 let pos = self.fmts.len();
286 let top = self.fmt().apply(f);
287 self.fmts.push(top);
288 pos
289 }
290
291 fn pop_format(&mut self, pos: usize) {
292 if pos == self.fmts.len() {
293 return;
294 }
295 self.save();
296 self.fmts.truncate(pos);
297 }
298
299 /// Moves the buffer into the top level, merging with a last text run of equal formatting. The
300 /// buffer is replaced by a fresh folder with no case, which `reconfigure` later corrects.
301 fn save(&mut self) {
302 if self.buf.is_empty() {
303 return;
304 }
305 let fmt = self.fmt();
306 let text = std::mem::take(&mut self.buf).finish();
307 let top = self.top_mut();
308 if let Some(Node::Text(t, f)) = top.last_mut() {
309 if *f == fmt {
310 t.push_str(&text);
311 return;
312 }
313 }
314 top.push(Node::Text(text, fmt));
315 }
316
317 fn push_elem(&mut self, f: &Fmt) -> Loc {
318 self.save();
319 let elem = self.stack.len();
320 self.stack.push(Vec::new());
321 Loc { elem, fmt: self.push_format(f) }
322 }
323
324 fn discard_elem(&mut self, loc: Loc) {
325 self.pop_format(loc.fmt);
326 self.save();
327 self.stack.truncate(loc.elem);
328 }
329
330 /// Closes a level, wrapping it in an element only when it carries display or meta, and
331 /// otherwise splicing its children into the level below.
332 fn commit_elem(&mut self, loc: Loc, display: Option<Display>, meta: Option<Meta>) {
333 self.pop_format(loc.fmt);
334 self.save();
335 let children: Vec<Node> = self.stack.split_off(loc.elem).into_iter().flatten().collect();
336 if display.is_some() || meta.is_some() {
337 self.top_mut().push(Node::Elem(NodeElem { children, display, meta }));
338 } else {
339 self.top_mut().extend(children);
340 }
341 }
342
343 /// Pushes a plain level and writes the prefix straight into the buffer, uncased and
344 /// unchecked.
345 fn apply_prefix(&mut self, prefix: Option<&str>) -> Affix {
346 let loc = self.push_elem(&Fmt::default());
347 if let Some(p) = prefix {
348 self.buf.push_str(p);
349 }
350 Affix { loc, plen: prefix.map_or(0, str::len) }
351 }
352
353 fn has_content_since(&mut self, a: &Affix) -> bool {
354 self.save();
355 let top = self.top();
356 let first = match top.first() {
357 Some(Node::Text(t, _)) => t.get(a.plen..).map_or(false, |r| r.chars().any(|c| !c.is_whitespace())),
358 Some(Node::Elem(e)) => node::has_content(&e.children),
359 Some(_) => true,
360 None => false,
361 };
362 first || top.iter().skip(1).any(Node::has_content)
363 }
364
365 fn reconfigure(&mut self) {
366 let case = self.cases.last().copied().flatten().map(Case::from).unwrap_or_default();
367 self.buf.reconfigure(case);
368 }
369
370 fn push_delim(&mut self, d: Option<String>) -> usize {
371 let idx = self.delims.len();
372 self.delims.push(d);
373 idx
374 }
375
376 fn pop_delim(&mut self, idx: usize) {
377 self.delims.truncate(idx);
378 }
379
380 fn delim(&self) -> Option<String> {
381 self.delims.last().cloned().flatten()
382 }
383
384 fn pop_case(&mut self, idx: usize) {
385 self.cases.truncate(idx);
386 }
387
388 /// The buffer if it holds text, else the last text of the topmost non-empty level.
389 fn last_buffer(&mut self) -> Option<&mut String> {
390 if !self.buf.is_empty() {
391 return Some(self.buf.as_string_mut());
392 }
393 self.top_non_empty_mut().and_then(|l| node::last_text_mut(l))
394 }
395
396 /// A space after what is written, unless it already ends in a space or NBSP. With the buffer
397 /// empty it goes on the top level's last text.
398 fn ensure_space(&mut self) {
399 if !self.buf.is_empty() {
400 let s = self.buf.as_str();
401 if !s.ends_with(' ') && !s.ends_with('\u{a0}') {
402 self.buf.push(' ');
403 }
404 } else if let Some(l) = node::last_text_mut(self.top_mut()) {
405 if !l.ends_with(' ') && !l.ends_with('\u{a0}') {
406 l.push(' ');
407 }
408 }
409 }
410
411 fn len(&self) -> usize {
412 self.buf.len()
413 + self.base.iter().map(Node::str_len).sum::<usize>()
414 + self.stack.iter().flat_map(|l| l.iter().map(Node::str_len)).sum::<usize>()
415 }
416
417 fn flush(mut self) -> Vec<Node> {
418 self.save();
419 let mut base = self.base;
420 for l in self.stack {
421 base.extend(l);
422 }
423 base
424 }
425}
426
427/// The last text of a node, descending only through elements with a single child. Pulling
428/// punctuation into a quote uses this rather than `last_text_mut`, so that `“On $x^2$ and other
429/// things”,` keeps its comma outside: the quote sits in an element with several children.
430fn get_last_text(n: &mut Node) -> Option<&mut String> {
431 match n {
432 Node::Text(t, _) => Some(t),
433 Node::Elem(e) if e.children.len() == 1 => e.children.first_mut().and_then(get_last_text),
434 _ => None,
435 }
436}
437
438fn is_english_code(code: &str) -> bool {
439 code.starts_with("en") && (code.len() == 2 || code.get(2..3) == Some("-"))
440}
441
442fn url_prefix(var: &str) -> Option<&'static str> {
443 match var {
444 "DOI" => Some("https://doi.org/"),
445 "PMID" => Some("https://www.ncbi.nlm.nih.gov/pubmed/"),
446 "PMCID" => Some("https://www.ncbi.nlm.nih.gov/pmc/articles/"),
447 _ => None,
448 }
449}
450
451/// Formatting laid over a base: each attribute `top` sets wins.
452fn fmt_over(top: &Fmt, base: &Fmt) -> Fmt {
453 Fmt {
454 style: top.style.or(base.style),
455 variant: top.variant.or(base.variant),
456 weight: top.weight.or(base.weight),
457 deco: top.deco.or(base.deco),
458 valign: top.valign.or(base.valign),
459 }
460}
461
462/// A date part's form, defaulting to numeric days, long months and long years.
463fn part_form(p: &DatePart) -> DatePartForm {
464 match (p.form, p.name) {
465 (Some(f), _) => f,
466 (None, DatePartName::Day) => DatePartForm::Numeric,
467 (None, _) => DatePartForm::Long,
468 }
469}
470
471// Names
472/// hayagriva's `DisambiguatedNameForm`, ordered as it is.
473#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
474pub enum NForm { Count, ShortInit, ShortFull, LongInit, LongFull }
475
476/// citationberg's `NameOptions`: a `name`'s options over those it inherits, with CSL's defaults.
477#[derive(Clone, Debug)]
478struct NOpts {
479 and: Option<And>,
480 delim: String,
481 prec_et_al: DelimRule,
482 prec_last: DelimRule,
483 min: Option<u32>,
484 use_first: Option<u32>,
485 sub_min: Option<u32>,
486 sub_first: Option<u32>,
487 use_last: bool,
488 form: NameForm,
489 initialize: bool,
490 init_with: Option<String>,
491 sort_order: Option<SortOrder>,
492 sort_sep: String,
493}
494
495impl NOpts {
496
497 fn new(o: NameOpts) -> Self {
498 Self {
499 and: o.and,
500 delim: o.delimiter.unwrap_or_else(|| ", ".to_string()),
501 prec_et_al: o.delim_precedes_et_al.unwrap_or(DelimRule::Contextual),
502 prec_last: o.delim_precedes_last.unwrap_or(DelimRule::Contextual),
503 min: o.et_al_min,
504 use_first: o.et_al_use_first,
505 sub_min: o.et_al_subsequent_min,
506 sub_first: o.et_al_subsequent_use_first,
507 use_last: o.et_al_use_last.unwrap_or(false),
508 form: o.form.unwrap_or(NameForm::Long),
509 initialize: o.initialize.unwrap_or(true),
510 init_with: o.initialize_with,
511 sort_order: o.name_as_sort_order,
512 sort_sep: o.sort_separator.unwrap_or_else(|| ", ".to_string()),
513 }
514 }
515
516 fn form(&self) -> NForm {
517 match (self.init_with.is_some() && self.initialize, self.form) {
518 (true, NameForm::Short) => NForm::ShortInit,
519 (true, _) => NForm::LongInit,
520 (false, NameForm::Short) => NForm::ShortFull,
521 (false, NameForm::Count) => NForm::Count,
522 (false, NameForm::Long) => NForm::LongFull,
523 }
524 }
525
526 /// Is the name at `i` of `len` cut by et al.? The last name never is under et-al-use-last.
527 fn is_suppressed(&self, i: usize, len: usize, subsequent: bool) -> bool {
528 let (min, first) = match subsequent {
529 true => (self.sub_min.or(self.min), self.sub_first.or(self.use_first)),
530 false => (self.min, self.use_first),
531 };
532 if self.use_last && i + 1 == len {
533 return false;
534 }
535 match (min, first) {
536 (Some(m), Some(f)) => len >= m as usize && i + 1 > f as usize,
537 _ => false,
538 }
539 }
540}
541
542/// A `names` element as rendered. Inside a `substitute`, a `names` with no `name`, `et-al` or
543/// `substitute` of its own takes its parent's name, et-al, label, delimiter, affixes, display and
544/// formatting, and its variables when it names none.
545#[derive(Clone, Copy)]
546struct NamesView<'a> {
547 vars: &'a [String],
548 delimiter: Option<&'a str>,
549 opts: &'a NameOpts,
550 name: Option<&'a Name>,
551 et_al: Option<&'a EtAl>,
552 label: Option<&'a Label>,
553 label_first: bool,
554 look: &'a Look,
555 substitute: Option<&'a [Elem]>,
556}
557
558impl<'a> NamesView<'a> {
559
560 fn of(n: &'a Names) -> Self {
561 Self {
562 vars: &n.vars,
563 delimiter: n.delimiter.as_deref(),
564 opts: &n.opts,
565 name: n.name.as_ref(),
566 et_al: n.et_al.as_ref(),
567 label: n.label.as_ref(),
568 label_first: n.label_first,
569 look: &n.look,
570 substitute: n.substitute.as_deref(),
571 }
572 }
573
574 fn substitute_child(self, c: &'a Names) -> Self {
575 if c.name.is_some() || c.et_al.is_some() || c.substitute.is_some() {
576 return Self::of(c);
577 }
578 let (label, label_first) = match &c.label {
579 Some(l) => (Some(l), c.label_first),
580 None => (self.label, self.label_first),
581 };
582 Self {
583 vars: if c.vars.is_empty() { self.vars } else { &c.vars },
584 label,
585 label_first,
586 substitute: None,
587 ..self
588 }
589 }
590}
591
592/// A year-suffix as letters: a to z, then aa.
593fn letters(n: u8) -> String {
594 let mut out = Vec::new();
595 let mut c = n as u32;
596 loop {
597 out.insert(0, (b'a' + (c % 26) as u8) as char);
598 if c < 26 {
599 break;
600 }
601 c = (c - 26) / 26;
602 }
603 out.into_iter().collect()
604}
605
606fn roman(n: i32) -> Option<String> {
607 if !(1..=3999).contains(&n) {
608 return None;
609 }
610 const R: [(i32, &str); 13] = [
611 (1000, "m"), (900, "cm"), (500, "d"), (400, "cd"), (100, "c"), (90, "xc"),
612 (50, "l"), (40, "xl"), (10, "x"), (9, "ix"), (5, "v"), (4, "iv"), (1, "i"),
613 ];
614 let mut n = n;
615 let mut s = String::new();
616 for (v, r) in R {
617 while n >= v {
618 s.push_str(r);
619 n -= v;
620 }
621 }
622 Some(s)
623}
624
625// Ordinals
626enum OrdName { Ordinal, N(u8), Long(u8), Other }
627
628fn ord_name(name: &str) -> OrdName {
629 if name == "ordinal" {
630 OrdName::Ordinal
631 } else if let Some(n) = name.strip_prefix("long-ordinal-").and_then(|n| n.parse().ok()) {
632 OrdName::Long(n)
633 } else if let Some(n) = name.strip_prefix("ordinal-").and_then(|n| n.parse().ok()) {
634 OrdName::N(n)
635 } else {
636 OrdName::Other
637 }
638}
639
640/// citationberg's `OrdinalLookup`: the ordinal terms of the first locale in the chain that has
641/// any.
642struct Ords<'a> {
643 terms: Vec<&'a Term>,
644 legacy: bool, // no `ordinal` term but `ordinal-01` to `-04`: CSL 1.0's scheme
645}
646
647impl<'a> Ords<'a> {
648
649 fn new(chain: &Chain<'a>) -> Self {
650 let terms = chain.first(|l| {
651 let ts: Vec<&'a Term> = l.terms.iter()
652 .filter(|t| !matches!(ord_name(&t.name), OrdName::Other))
653 .collect();
654 if ts.is_empty() { None } else { Some(ts) }
655 }).unwrap_or_default();
656 let defines = terms.iter().any(|t| matches!(ord_name(&t.name), OrdName::Ordinal));
657 let legacy = !defines && (1..=4u8).all(|n| terms.iter().any(|t| matches!(ord_name(&t.name), OrdName::N(o) if o == n)));
658 Self { terms, legacy }
659 }
660
661 /// The best ordinal suffix: a two-digit term over a one-digit one, then one of the asked
662 /// gender, then the nearest number. citationberg compares the term's `gender`, not its
663 /// `gender-form`, so `gender-form` never steers the choice.
664 fn lookup(&self, n: i32, gender: Option<Gender>) -> Option<&'a str> {
665 let mut best: Option<&'a Term> = None;
666 for &t in &self.terms {
667 let hit = match ord_name(&t.name) {
668 OrdName::Ordinal => true,
669 OrdName::N(o) if self.legacy => {
670 let class = match (n, n % 10) {
671 (11..=13, _) => 4,
672 (_, v @ 1..=3) => v as u8,
673 _ => 4,
674 };
675 o == class
676 }
677 OrdName::N(o) if o <= 9 => match t.matching {
678 Some(OrdMatch::LastDigit) | None => n % 10 == o as i32,
679 Some(OrdMatch::LastTwoDigits) => n % 100 == o as i32,
680 Some(OrdMatch::WholeNumber) => n == o as i32,
681 },
682 OrdName::N(o) if o <= 99 => match t.matching {
683 Some(OrdMatch::LastTwoDigits) | None => n % 100 == o as i32,
684 Some(OrdMatch::WholeNumber) => n == o as i32,
685 Some(OrdMatch::LastDigit) => false,
686 },
687 _ => false,
688 };
689 if !hit {
690 continue;
691 }
692 let cur = match best {
693 None => { best = Some(t); continue; }
694 Some(c) => c,
695 };
696 let OrdName::N(other_n) = ord_name(&t.name) else { continue };
697 let OrdName::N(cur_n) = ord_name(&cur.name) else { best = Some(t); continue };
698 best = Some(if other_n >= 10 && cur_n < 10 {
699 t
700 } else if other_n < 10 && cur_n >= 10 {
701 cur
702 } else if gender == cur.gender && gender != t.gender {
703 cur
704 } else if gender != cur.gender && gender == t.gender {
705 t
706 } else if (n - other_n as i32).abs() <= (n - cur_n as i32).abs() {
707 t
708 } else {
709 cur
710 });
711 }
712 best.map(|t| t.single.as_str())
713 }
714
715 /// A long ordinal; 1 to 10 need an exact match.
716 fn lookup_long(&self, n: i32) -> Option<&'a str> {
717 self.terms.iter().find(|t| {
718 let OrdName::Long(o) = ord_name(&t.name) else { return false };
719 if n > 0 && n <= 10 {
720 n == o as i32
721 } else {
722 match t.matching {
723 Some(OrdMatch::LastTwoDigits) | None => n % 100 == o as i32,
724 Some(OrdMatch::WholeNumber) => n == o as i32,
725 Some(OrdMatch::LastDigit) => false,
726 }
727 }
728 }).map(|t| t.single.as_str())
729 }
730}
731
732// Context
733enum Target<'a> {
734 Std(&'a str, Chunked),
735 Num(&'a str, NumVal),
736 Page(PageVal),
737 Macro(&'a [Elem]),
738 Term(&'a str),
739 Value(&'a str),
740}
741
742enum NumOrPage {
743 Num(NumVal),
744 Page(PageVal),
745}
746
747/// A `names` element's metadata: each variable's people, so that grouping and disambiguation can
748/// compare them.
749fn meta_people(people: &[(&[Person], &str)]) -> Meta {
750 Meta::Names(people.iter().map(|(p, v)| (p.to_vec(), v.to_string())).collect())
751}
752
753/// One rendering of one entry: the style, the locale chain, the item and the citation, over a
754/// writer.
755pub struct Ctx<'a, I: Item> {
756 style: &'a Style,
757 chain: &'a Chain<'a>,
758 item: &'a I,
759 cite: &'a Cite,
760 lang: Option<&'a str>, // the locale the document asked for, if any
761 bib: bool,
762 sorting: Option<Sorting>,
763 sort_names: NameOpts, // a macro sort key's names-min, -use-first and -use-last
764 special: Option<Special>,
765 w: Writer,
766}
767
768impl<'a, I: Item> Write for Ctx<'a, I> {
769 fn write_str(&mut self, s: &str) -> std::fmt::Result {
770 self.push_str(s);
771 Ok(())
772 }
773}
774
775/// Renders one bibliography entry through the style's bibliography layout, wrapped in the
776/// layout's prefix and suffix. `None` when the style has no bibliography.
777pub fn bibliography_entry<'a, I: Item>(
778 style: &'a Style,
779 chain: &'a Chain<'a>,
780 item: &'a I,
781 cite: &'a Cite,
782 lang: Option<&'a str>,
783)
784 -> Option<Vec<Node>>
785{
786 let bib = match style.bibliography.as_ref() {
787 Some(b) => b,
788 None => return None,
789 };
790 let mut ctx = Ctx::new(style, chain, item, cite, lang, true);
791 let layout = &bib.layout;
792 let a = ctx.w.apply_prefix(layout.look.prefix.as_deref());
793 let fi = ctx.w.push_format(&layout.look.fmt);
794 let di = ctx.w.push_delim(layout.delimiter.clone());
795 for e in &layout.elems {
796 ctx.render(e);
797 }
798 ctx.w.pop_delim(di);
799 ctx.w.pop_format(fi);
800 ctx.apply_suffix(layout.look.suffix.as_deref(), a);
801 Some(ctx.flush())
802}
803
804/// One cite rendered through the citation layout, which, as in hayagriva, applies its formatting
805/// and delimiter but leaves its affixes to the whole citation.
806#[derive(Clone, Debug, Default)]
807pub struct CiteOut {
808 pub nodes: Vec<Node>,
809 pub checked_disamb: bool, // a `choose` asked `disambiguate`
810 pub first_name: Option<NameDisamb>,
811}
812
813pub fn citation_entry<'a, I: Item>(
814 style: &'a Style,
815 chain: &'a Chain<'a>,
816 item: &'a I,
817 cite: &'a Cite,
818 lang: Option<&'a str>,
819 special: Option<Special>,
820)
821 -> CiteOut
822{
823 let mut ctx = Ctx::new(style, chain, item, cite, lang, false).special(special);
824 let layout = &style.citation.layout;
825 let fi = ctx.w.push_format(&layout.look.fmt);
826 let di = ctx.w.push_delim(layout.delimiter.clone());
827 ctx.render_all(&layout.elems);
828 ctx.w.pop_delim(di);
829 ctx.w.pop_format(fi);
830 let checked_disamb = ctx.checked_disambiguate();
831 let first_name = ctx.w.first_name.take();
832 CiteOut { nodes: ctx.flush(), checked_disamb, first_name }
833}
834
835impl<'a, I: Item> Ctx<'a, I> {
836
837 pub fn new(
838 style: &'a Style,
839 chain: &'a Chain<'a>,
840 item: &'a I,
841 cite: &'a Cite,
842 lang: Option<&'a str>,
843 bib: bool,
844 )
845 -> Self
846 {
847 Self { style, chain, item, cite, lang, bib, sorting: None, sort_names: NameOpts::default(), special: None, w: Writer::default() }
848 }
849
850 /// This context renders a sort key.
851 pub fn sorting(mut self, s: Sorting, names: NameOpts) -> Self {
852 self.sorting = Some(s);
853 self.sort_names = names;
854 self
855 }
856
857 /// The special form to render in, or none.
858 pub fn special(mut self, s: Option<Special>) -> Self {
859 self.special = s;
860 self
861 }
862
863 pub fn render_all(&mut self, elems: &'a [Elem]) {
864 for e in elems {
865 self.render(e);
866 }
867 }
868
869 pub fn flush(self) -> Vec<Node> {
870 self.w.flush()
871 }
872
873 /// Did a `choose` ask the `disambiguate` condition? B3 reads this to know whether
874 /// disambiguation could change the output.
875 pub fn checked_disambiguate(&self) -> bool {
876 self.w.checked_disamb
877 }
878
879 // Writing
880
881 /// Pushes text through the quirks hayagriva applies, in its order: pull punctuation into a
882 /// closing quote, reconfigure the case, let punctuation eat a trailing space, drop an affix
883 /// that duplicates the end of what is written, and strip periods.
884 fn push_str(&mut self, s: &str) {
885 let pulled = self.pull_punctuation(s);
886 let s = pulled.as_str();
887 self.w.reconfigure();
888
889 let ends_ws = self.w.last_buffer()
890 .map_or(false, |b| b.chars().next_back().map_or(false, char::is_whitespace));
891 // Punctuation eats spaces.
892 if ends_ws && s.chars().next().map_or(false, |c| c.is_whitespace() || matches!(c, '.' | ',' | ']' | ')')) {
893 if let Some(b) = self.w.last_buffer() {
894 let n = b.trim_end().len();
895 b.truncate(n);
896 }
897 }
898
899 // A string with no letters is not written twice in a row, so `.` after `.` is one.
900 if s.chars().all(|c| !c.is_alphabetic()) {
901 let tr = s.trim_end();
902 if let Some(last) = self.w.last_buffer() {
903 if last.ends_with(tr) {
904 let n = last.len() - tr.len();
905 last.truncate(n);
906 }
907 }
908 }
909
910 if self.w.strip_periods {
911 // citeproc.js's rule: a period goes unless the character before it was a period.
912 let mut last_period = false;
913 for c in s.chars() {
914 let is_period = c == '.';
915 if !is_period || last_period {
916 self.w.buf.push(c);
917 }
918 last_period = is_period;
919 }
920 } else {
921 self.w.buf.push_str(s);
922 }
923 self.w.pull = false;
924 }
925
926 /// Moves a leading `.`, `,`, `;`, `!` or `?` inside a closing quote just written, when the
927 /// locale puts punctuation in quotes.
928 fn pull_punctuation(&mut self, s: &str) -> String {
929 let first = match s.chars().next() {
930 Some(c) if self.w.pull && matches!(c, '.' | ',' | ';' | '!' | '?') => c,
931 _ => return s.to_string(),
932 };
933 let cq = self.term("close-quote", TermForm::Long, false);
934 let ciq = self.term("close-inner-quote", TermForm::Long, false);
935 let in_tree = self.w.buf.is_empty() && self.w.top_non_empty_mut()
936 .and_then(|l| l.last_mut())
937 .and_then(get_last_text)
938 .is_some();
939 let used_buf = !in_tree;
940 let buf: &mut String = if in_tree {
941 match self.w.top_non_empty_mut().and_then(|l| l.last_mut()).and_then(get_last_text) {
942 Some(b) => b,
943 None => return s.to_string(),
944 }
945 } else {
946 self.w.buf.as_string_mut()
947 };
948 let mut rest = s;
949 for q in [cq, ciq].into_iter().flatten() {
950 if buf.ends_with(q) {
951 let n = buf.len() - q.len();
952 buf.truncate(n);
953 rest = &s[first.len_utf8()..];
954 buf.push(first);
955 buf.push_str(q);
956 if used_buf {
957 self.w.buf.mark_changed();
958 }
959 break;
960 }
961 }
962 rest.to_string()
963 }
964
965 /// Pushes a chunked variable: protected chunks bypass the case, and mathematical chunks
966 /// become `Math` nodes the case folder never trims across.
967 fn push_chunked(&mut self, c: &Chunked) {
968 use crate::csl::item::ChunkKind;
969 for chunk in &c.0 {
970 match chunk.kind {
971 ChunkKind::Normal => self.push_str(&chunk.value),
972 ChunkKind::Verbatim => {
973 self.w.buf.push_verbatim(&chunk.value);
974 self.w.pull = false;
975 }
976 ChunkKind::Math => {
977 self.w.buf.prevent_trimming();
978 self.w.save();
979 self.w.top_mut().push(Node::Math(chunk.value.clone()));
980 self.w.reconfigure();
981 self.w.buf.prevent_trimming();
982 }
983 }
984 }
985 }
986
987 fn push_link(&mut self, text: String, url: String) {
988 let fmt = self.w.fmt();
989 self.w.save();
990 self.w.top_mut().push(Node::Link { text, fmt, url });
991 }
992
993 fn push_transparent(&mut self, idx: usize) {
994 let fmt = self.w.fmt();
995 self.w.save();
996 self.w.top_mut().push(Node::Cite { idx, fmt });
997 }
998
999 fn push_quotes(&mut self) {
1000 let name = if self.w.inner_quotes { "open-inner-quote" } else { "open-quote" };
1001 if let Some(m) = self.term(name, TermForm::Long, false) {
1002 self.push_str(m);
1003 }
1004 self.w.inner_quotes = !self.w.inner_quotes;
1005 }
1006
1007 fn pop_quotes(&mut self) {
1008 self.w.inner_quotes = !self.w.inner_quotes;
1009 let name = if self.w.inner_quotes { "close-inner-quote" } else { "close-quote" };
1010 if let Some(m) = self.term(name, TermForm::Long, false) {
1011 self.push_str(m);
1012 }
1013 }
1014
1015 fn may_pull_punctuation(&mut self) {
1016 self.w.pull |= self.chain.punctuation_in_quote();
1017 }
1018
1019 /// Pushes a text case. hayagriva applies title and sentence case only to English: the
1020 /// entry's language decides, then the requested locale, then the style's default, and an
1021 /// unknown language counts as English. This departs from CSL, which leaves sentence case
1022 /// to the style.
1023 fn push_case(&mut self, case: Option<TextCase>) -> usize {
1024 let idx = self.w.cases.len();
1025 let english = self.item.is_english()
1026 .or_else(|| self.lang.map(is_english_code))
1027 .or_else(|| self.style.default_locale.as_deref().map(is_english_code))
1028 .unwrap_or(true);
1029 let apply = case.map_or(true, |c| !is_language_dependent(c)) || english;
1030 self.w.cases.push(if apply { case } else { None });
1031 idx
1032 }
1033
1034 /// A term, the `locator` term being replaced by the cited locator's kind.
1035 fn term(&self, name: &str, form: TermForm, plural: bool) -> Option<&'a str> {
1036 let name = match (&self.cite.locator, name) {
1037 (Some((kind, _)), "locator") => kind.as_str(),
1038 _ => name,
1039 };
1040 self.chain.term_text(name, form, plural)
1041 }
1042
1043 fn apply_suffix(&mut self, suffix: Option<&str>, a: Affix) {
1044 if !self.w.has_content_since(&a) {
1045 self.w.discard_elem(a.loc);
1046 return;
1047 }
1048 if let Some(sfx) = suffix {
1049 // A suffix the text already ends with is not repeated.
1050 let present = if !self.w.buf.is_empty() {
1051 self.w.buf.as_str().ends_with(sfx)
1052 } else {
1053 node::last_text(self.w.top()).map_or(false, |l| l.ends_with(sfx))
1054 };
1055 if !present {
1056 self.push_str(sfx);
1057 }
1058 }
1059 self.w.commit_elem(a.loc, None, None);
1060 }
1061
1062 // Variables
1063
1064 /// Is the variable still available? Once a substituted variable has rendered it is
1065 /// suppressed for the rest of the entry; while suppression is on, each variable asked for
1066 /// is recorded.
1067 fn prepare(&mut self, var: &str) -> bool {
1068 if self.w.suppressed.iter().any(|v| v == var) {
1069 return false;
1070 }
1071 if self.w.suppressing {
1072 self.w.suppressed.push(var.to_string());
1073 }
1074 true
1075 }
1076
1077 fn resolve_std(&mut self, var: &str, form: VarForm) -> Option<Chunked> {
1078 if !self.prepare(var) {
1079 return None;
1080 }
1081 match var {
1082 "citation-label" => self.cite.label.as_deref().map(Chunked::normal),
1083 "year-suffix" => match self.cite.disamb {
1084 Disamb::YearSuffix(n) => Some(Chunked::normal(&letters(n))),
1085 _ => None,
1086 },
1087 _ => self.item.text(var, form),
1088 }
1089 }
1090
1091 fn resolve_num(&mut self, var: &str) -> Option<NumVal> {
1092 if !self.prepare(var) {
1093 return None;
1094 }
1095 match var {
1096 "citation-number" => self.cite.number.map(|n| NumVal::Typed(Numeric::new(n as i32))),
1097 "locator" => self.cite.locator.as_ref().map(|(_, v)| v.clone()),
1098 "first-reference-note-number" => self.cite.first_note.map(|n| NumVal::Typed(Numeric::new(n as i32))),
1099 _ => self.item.number(var).map(|s| NumVal::from_str(&s)),
1100 }
1101 }
1102
1103 fn resolve_page(&mut self) -> Option<PageVal> {
1104 if !self.prepare("page") {
1105 return None;
1106 }
1107 self.item.page()
1108 }
1109
1110 fn resolve_num_or_page(&mut self, var: &str) -> Option<NumOrPage> {
1111 match var_kind(var) {
1112 VarKind::Page => self.resolve_page().map(NumOrPage::Page),
1113 _ => self.resolve_num(var).map(NumOrPage::Num),
1114 }
1115 }
1116
1117 fn resolve_date(&mut self, var: &str) -> Option<DateVal> {
1118 if !self.prepare(var) {
1119 return None;
1120 }
1121 self.item.date(var)
1122 }
1123
1124 fn resolve_names(&mut self, var: &str) -> &'a [Person] {
1125 if !self.prepare(var) {
1126 return &[];
1127 }
1128 let item: &'a I = self.item;
1129 item.names(var)
1130 }
1131
1132 // Rendering
1133
1134 pub fn render(&mut self, e: &'a Elem) {
1135 match e {
1136 Elem::Text(t) => self.render_text(t),
1137 Elem::Number(n) => self.render_number(n),
1138 Elem::Label(l) => self.render_label(l),
1139 Elem::Names(n) => self.render_names(n),
1140 Elem::Date(d) => self.render_date(d),
1141 Elem::Group(g) => self.render_group(g),
1142 Elem::Choose(c) => self.render_choose(c),
1143 }
1144 }
1145
1146 /// Will the element print, and what did it query? hayagriva's `will_have_info`.
1147 fn info(&mut self, e: &'a Elem) -> (bool, Usage) {
1148 match e {
1149 Elem::Text(t) => self.text_info(t),
1150 Elem::Number(n) => self.number_info(n),
1151 Elem::Label(l) => self.label_info(l),
1152 Elem::Names(n) => self.names_info(n),
1153 Elem::Date(d) => self.date_info(d),
1154 Elem::Group(g) => self.group_info(g),
1155 Elem::Choose(c) => self.choose_info(c),
1156 }
1157 }
1158
1159 /// Runs `f` with variable suppression off, restoring it after.
1160 fn unsuppressed<R, F: FnOnce(&mut Self) -> R>(&mut self, f: F) -> R {
1161 let s = self.w.suppressing;
1162 self.w.suppressing = false;
1163 let r = f(self);
1164 self.w.suppressing = s;
1165 r
1166 }
1167
1168 fn target(&mut self, t: &'a Text) -> Option<Target<'a>> {
1169 // A special form passes macros and only its own variables.
1170 if let (Some(sp), TextSrc::Var { name, .. }) = (&self.special, &t.src) {
1171 let pass = match sp {
1172 Special::VarOnly(v) => v == name,
1173 Special::OnlyFirstDate | Special::OnlyYearSuffix => name == "year-suffix" || name == "locator",
1174 Special::SuppressAuthor => true,
1175 };
1176 if !pass {
1177 return None;
1178 }
1179 }
1180 if let (Some(Special::VarOnly(_) | Special::OnlyFirstDate | Special::OnlyYearSuffix), TextSrc::Term { .. } | TextSrc::Value(_)) = (&self.special, &t.src) {
1181 return None;
1182 }
1183 match &t.src {
1184 TextSrc::Var { name, form } => match var_kind(name) {
1185 VarKind::Standard => self.resolve_std(name, *form).map(|v| Target::Std(name, v)),
1186 VarKind::Number => self.resolve_num(name).map(|n| Target::Num(name, n)),
1187 VarKind::Page => self.resolve_page().map(Target::Page),
1188 _ => None,
1189 },
1190 TextSrc::Macro(m) => self.style.get_macro(m).map(Target::Macro),
1191 TextSrc::Term { name, form, plural } => self.term(name, *form, *plural).map(Target::Term),
1192 TextSrc::Value(v) => Some(Target::Value(v)),
1193 }
1194 }
1195
1196 /// `text`. The prefix goes inside the element's formatting, so an italic title's prefix is
1197 /// italic too (hayagriva departs from CSL here). DOI, PMID and PMCID become links, and a
1198 /// prefix equal to the resolver URL is dropped in favour of showing the full URL.
1199 fn render_text(&mut self, t: &'a Text) {
1200 let target = match self.target(t) {
1201 Some(x) => x,
1202 None => return,
1203 };
1204 let depth = self.w.push_elem(&t.look.fmt);
1205 let url = match &target {
1206 Target::Std(v, _) => url_prefix(v),
1207 _ => None,
1208 };
1209 let affix_is_url = url.map_or(false, |p| t.look.prefix.as_deref() == Some(p));
1210 // A macro used out of its context, under VarOnly, prints no affixes.
1211 let out_of_context = matches!(self.special, Some(Special::VarOnly(_))) && matches!(t.src, TextSrc::Macro(_));
1212 let a = match affix_is_url || out_of_context {
1213 true => None,
1214 false => Some(self.w.apply_prefix(t.look.prefix.as_deref())),
1215 };
1216 if t.look.quotes {
1217 self.push_quotes();
1218 }
1219 self.w.strip_periods = t.look.strip_periods;
1220 let cidx = self.push_case(t.look.text_case);
1221 let mut should_render = true;
1222 match target {
1223 Target::Std(var, val) => match url {
1224 Some(p) => {
1225 let full = format!("{}{}", p, val);
1226 let shown = if affix_is_url { full.clone() } else { val.to_string() };
1227 self.push_link(shown, full);
1228 }
1229 None if var == "URL" => self.push_link(val.to_string(), val.to_string()),
1230 None => self.push_chunked(&val),
1231 },
1232 Target::Num(_, n) => match n {
1233 NumVal::Typed(num) if num.will_transform() => self.push_num(&num, NumForm::Numeric, None),
1234 NumVal::Typed(num) => self.push_str(&num.to_string()),
1235 NumVal::Str(s) => self.push_str(&s),
1236 NumVal::Transparent(i) => self.push_transparent(i),
1237 },
1238 Target::Page(p) => self.push_page(p, true),
1239 Target::Macro(m) => {
1240 should_render = self.text_info(t).1.should_render_group();
1241 if should_render {
1242 let di = self.w.push_delim(None);
1243 for c in m {
1244 self.render(c);
1245 }
1246 self.w.pop_delim(di);
1247 }
1248 }
1249 Target::Term(s) => self.push_str(s),
1250 Target::Value(v) => self.push_str(v),
1251 }
1252 self.w.pop_case(cidx);
1253 self.w.strip_periods = false;
1254 if t.look.quotes {
1255 self.pop_quotes();
1256 self.may_pull_punctuation();
1257 }
1258 if let Some(a) = a {
1259 self.apply_suffix(t.look.suffix.as_deref(), a);
1260 }
1261 if should_render {
1262 let meta = match &t.src {
1263 TextSrc::Var { name, .. } if name == "citation-number" => Some(Meta::CitationNumber),
1264 TextSrc::Var { name, .. } if name == "citation-label" => Some(Meta::CitationLabel),
1265 TextSrc::Var { .. } => Some(Meta::Text),
1266 _ => None,
1267 };
1268 self.w.commit_elem(depth, t.look.display, meta);
1269 } else {
1270 self.w.discard_elem(depth);
1271 }
1272 }
1273
1274 fn text_info(&mut self, t: &'a Text) -> (bool, Usage) {
1275 let found = self.unsuppressed(|c| c.target(t));
1276 let targets_var = matches!(&t.src, TextSrc::Var { name, .. } if name != "year-suffix");
1277 let vars = Usage { vars: true, ..Usage::default() };
1278 match found {
1279 None => (false, Usage { vars: targets_var, ..Usage::default() }),
1280 Some(Target::Std(_, s)) if s.is_empty() => (false, vars),
1281 Some(Target::Std(..) | Target::Num(..) | Target::Page(_)) => (true, Usage { non_empty: true, ..vars }),
1282 Some(Target::Macro(m)) => {
1283 let (print, info) = self.children_info(m);
1284 let print = print && info.should_render_group();
1285 (print, Usage { macros: print, ..info })
1286 }
1287 Some(Target::Term(_)) => (true, Usage::default()),
1288 Some(Target::Value(v)) => (!v.is_empty(), Usage::default()),
1289 }
1290 }
1291
1292 fn children_info(&mut self, elems: &'a [Elem]) -> (bool, Usage) {
1293 let mut print = false;
1294 let mut info = Usage::default();
1295 for c in elems {
1296 let (p, i) = self.info(c);
1297 print |= p;
1298 info = info.merge(i);
1299 }
1300 (print, info)
1301 }
1302
1303 /// Writes a number in a form, each through `push_str` as hayagriva's `write!` does.
1304 fn push_num(&mut self, num: &Numeric, form: NumForm, gender: Option<Gender>) {
1305 let ords = Ords::new(self.chain);
1306 for (n, d) in &num.nums {
1307 let n = *n;
1308 match form {
1309 NumForm::Numeric => self.push_str(&n.to_string()),
1310 NumForm::Ordinal => {
1311 self.push_str(&n.to_string());
1312 self.push_str(ords.lookup(n, gender).unwrap_or(""));
1313 }
1314 NumForm::LongOrdinal => match ords.lookup_long(n) {
1315 Some(s) => self.push_str(s),
1316 None => {
1317 self.push_str(&n.to_string());
1318 self.push_str(ords.lookup(n, gender).unwrap_or(""));
1319 }
1320 },
1321 NumForm::Roman => match roman(n) {
1322 Some(r) => self.push_str(&r),
1323 None => self.push_str(&n.to_string()),
1324 },
1325 }
1326 if let Some(d) = d {
1327 self.push_str(NumDelim::as_str(*d));
1328 }
1329 }
1330 }
1331
1332 /// A page value: typed ranges through `page-range-format` and the locale's range delimiter. An
1333 /// untyped value has its hyphens made en dashes in `text` but is written as given by `number`
1334 /// (hayagriva).
1335 fn push_page(&mut self, p: PageVal, in_text: bool) {
1336 match p {
1337 PageVal::Typed(r) => {
1338 let fmt = self.style.page_range_format;
1339 let delim = self.term("page-range-delimiter", TermForm::Long, false);
1340 r.write(self, fmt, delim);
1341 }
1342 PageVal::Str(s) if in_text => self.push_str(&s.replace('-', "–")),
1343 PageVal::Str(s) => self.push_str(&s),
1344 }
1345 }
1346
1347 /// `number`. The gender for ordinals is that of the variable's own long term.
1348 fn render_number(&mut self, n: &'a Number) {
1349 if !self.number_passes(&n.var) {
1350 return;
1351 }
1352 let value = self.resolve_num_or_page(&n.var);
1353 let depth = self.w.push_elem(&n.look.fmt);
1354 let a = self.w.apply_prefix(n.look.prefix.as_deref());
1355 let cidx = self.push_case(n.look.text_case);
1356 let gender = self.chain.term(&n.var, TermForm::Long).and_then(|t| t.gender);
1357 match value {
1358 Some(NumOrPage::Num(NumVal::Typed(num))) if num.will_transform() => self.push_num(&num, n.form, gender),
1359 Some(NumOrPage::Num(NumVal::Typed(num))) => { let _ = write!(self, "{}", num); }
1360 Some(NumOrPage::Num(NumVal::Str(s))) => self.push_str(&s),
1361 Some(NumOrPage::Num(NumVal::Transparent(i))) => self.push_transparent(i),
1362 Some(NumOrPage::Page(p)) => self.push_page(p, false),
1363 None => {}
1364 }
1365 self.w.pop_case(cidx);
1366 self.apply_suffix(n.look.suffix.as_deref(), a);
1367 let meta = if n.var == "citation-number" { Meta::CitationNumber } else { Meta::Number };
1368 self.w.commit_elem(depth, n.look.display, Some(meta));
1369 }
1370
1371 /// Does a special form let a number or label of this variable through? hayagriva's
1372 /// `Number::will_render`: only the locator, under a date form, and nothing under VarOnly.
1373 fn number_passes(&self, var: &str) -> bool {
1374 match &self.special {
1375 None | Some(Special::SuppressAuthor) => true,
1376 Some(Special::OnlyFirstDate | Special::OnlyYearSuffix) => var == "locator",
1377 Some(Special::VarOnly(_)) => false,
1378 }
1379 }
1380
1381 /// hayagriva's answer under a special form: a number other than the locator claims to print
1382 /// and queries nothing, so its group still renders.
1383 fn special_info(&self, var: &str) -> Option<(bool, Usage)> {
1384 match &self.special {
1385 Some(Special::VarOnly(v)) if v != var => Some((false, Usage::default())),
1386 Some(Special::VarOnly(_) | Special::OnlyFirstDate | Special::OnlyYearSuffix)
1387 if var != "locator" => Some((true, Usage::default())),
1388 _ => None,
1389 }
1390 }
1391
1392 fn number_info(&mut self, n: &'a Number) -> (bool, Usage) {
1393 if let Some(r) = self.special_info(&n.var) {
1394 return r;
1395 }
1396 let found = self.unsuppressed(|c| c.resolve_num_or_page(&n.var).is_some());
1397 (found, Usage { vars: true, non_empty: found, ..Usage::default() })
1398 }
1399
1400 fn label_plural(l: &Label, v: &NumVal) -> bool {
1401 match l.plural {
1402 Plural::Always => true,
1403 Plural::Never => false,
1404 Plural::Contextual => match v {
1405 NumVal::Typed(n) => n.is_plural(is_number_of(&l.var)),
1406 _ => false,
1407 },
1408 }
1409 }
1410
1411 /// The label's term and plural, or `None` when its variable is absent.
1412 fn label_term(&mut self, l: &'a Label) -> Option<Option<&'a str>> {
1413 let plural = match var_kind(&l.var) {
1414 // hayagriva ignores the label's `plural` attribute for pages.
1415 VarKind::Page => match self.resolve_page() {
1416 Some(p) => p.is_plural(),
1417 None => return None,
1418 },
1419 _ => match self.resolve_num(&l.var) {
1420 Some(v) => Self::label_plural(l, &v),
1421 None => return None,
1422 },
1423 };
1424 Some(self.term(&l.var, l.form, plural))
1425 }
1426
1427 /// `label`. Inside `names` (an empty variable) it is B2b's.
1428 fn render_label(&mut self, l: &'a Label) {
1429 if l.var.is_empty() || !self.label_info(l).0 {
1430 return;
1431 }
1432 let content = match self.label_term(l) {
1433 Some(c) => c.unwrap_or(""),
1434 None => return,
1435 };
1436 let depth = self.w.push_elem(&Fmt::default());
1437 if !content.is_empty() {
1438 let fi = self.w.push_format(&l.look.fmt);
1439 let a = self.w.apply_prefix(l.look.prefix.as_deref());
1440 self.w.strip_periods = l.look.strip_periods;
1441 let cidx = self.push_case(l.look.text_case);
1442 self.push_str(content);
1443 self.w.pop_case(cidx);
1444 self.w.strip_periods = false;
1445 self.apply_suffix(l.look.suffix.as_deref(), a);
1446 self.w.pop_format(fi);
1447 }
1448 self.w.commit_elem(depth, None, Some(Meta::Label));
1449 }
1450
1451 /// A label of a `custom` locator never prints. Unlike most queries this one runs with
1452 /// suppression as it stands (hayagriva).
1453 fn label_info(&mut self, l: &'a Label) -> (bool, Usage) {
1454 if let Some(r) = self.special_info(&l.var) {
1455 return r;
1456 }
1457 if l.var == "locator" && self.cite.locator.as_ref().map_or(false, |(k, _)| k == "custom") {
1458 return (false, Usage::default());
1459 }
1460 (self.label_term(l).map_or(false, |t| t.is_some()), Usage::default())
1461 }
1462
1463 /// `names`. An empty list with a `substitute` renders the first substitute child that writes
1464 /// anything, with suppression on so the variable it used is not repeated later.
1465 fn render_names(&mut self, n: &'a Names) {
1466 self.render_names_view(NamesView::of(n));
1467 }
1468
1469 /// The variables' people. editor and translator merge into editor-translator when both are
1470 /// asked for, the locale has the term, and the lists are equal.
1471 fn people(&mut self, v: NamesView<'a>) -> Vec<(&'a [Person], &'a str)> {
1472 let has = |s: &str| v.vars.iter().any(|x| x == s);
1473 if v.vars.len() == 2 && has("editor") && has("translator")
1474 && self.term("editor-translator", TermForm::Long, false).is_some()
1475 {
1476 let eds = self.resolve_names("editor");
1477 let trs = self.resolve_names("translator");
1478 let mut out = Vec::new();
1479 if !eds.is_empty() && eds == trs {
1480 out.push((eds, "editor-translator"));
1481 } else {
1482 if !eds.is_empty() {
1483 out.push((eds, "editor"));
1484 }
1485 if !trs.is_empty() {
1486 out.push((trs, "translator"));
1487 }
1488 }
1489 return out;
1490 }
1491 v.vars.iter().map(|x| (self.resolve_names(x), x.as_str())).collect()
1492 }
1493
1494 fn render_names_view(&mut self, v: NamesView<'a>) {
1495 let people = self.people(v);
1496 let empty = people.iter().all(|(p, _)| p.is_empty());
1497 if !self.names_pass(v.vars, v.substitute, empty) {
1498 return;
1499 }
1500 if people.iter().any(|(p, _)| !p.is_empty()) {
1501 self.render_name_list(v, &people);
1502 return;
1503 }
1504 if let Some(sub) = v.substitute {
1505 self.w.suppressing = true;
1506 let depth = self.w.push_elem(&v.look.fmt);
1507 for c in sub {
1508 let len = self.w.len();
1509 match c {
1510 Elem::Names(cn) => self.render_names_view(v.substitute_child(cn)),
1511 _ => self.render(c),
1512 }
1513 if len < self.w.len() {
1514 break;
1515 }
1516 }
1517 self.w.commit_elem(depth, v.look.display, Some(meta_people(&people)));
1518 self.w.suppressing = false;
1519 }
1520 }
1521
1522 /// The name options a `name` inherits: the bibliography's or citation's over the style's, and
1523 /// the delimiter between variables likewise.
1524 fn inherited_names(&self) -> (NameOpts, Option<&'a str>) {
1525 let style: &'a Style = self.style;
1526 // hayagriva's macro sort context stacks the key's options on the style's alone.
1527 if self.sorting == Some(Sorting::Macro) {
1528 return (self.sort_names.over(&style.names), style.names_delimiter.as_deref());
1529 }
1530 let (o, d) = match (self.bib, style.bibliography.as_ref()) {
1531 (true, Some(b)) => (&b.names, b.names_delimiter.as_deref()),
1532 _ => (&style.citation.names, style.citation.names_delimiter.as_deref()),
1533 };
1534 (o.over(&style.names), d.or(style.names_delimiter.as_deref()))
1535 }
1536
1537 /// A non-empty name list, each variable's names after the delimiter between variables, with
1538 /// the label before or after them. B3 adds name disambiguation, which changes the forms.
1539 fn render_name_list(&mut self, v: NamesView<'a>, people: &[(&'a [Person], &'a str)]) {
1540 let depth = self.w.push_elem(&v.look.fmt);
1541 let a = self.w.apply_prefix(v.look.prefix.as_deref());
1542 let (base, names_delim) = self.inherited_names();
1543 let plain = Name::default();
1544 let name = v.name.unwrap_or(&plain);
1545 let o = NOpts::new(name.opts.over(&v.opts.over(&base)));
1546 let form = o.form();
1547 // hayagriva asks the cite whether it is the entry's first; a bibliography inherits the
1548 // first citation's answer.
1549 let subsequent = !self.cite.first;
1550 if form == NForm::Count {
1551 // Only the names that would be written are counted.
1552 let n: usize = people.iter()
1553 .map(|(p, _)| (0..p.len()).filter(|&i| !o.is_suppressed(i, p.len(), subsequent)).count())
1554 .sum();
1555 self.push_str(&n.to_string());
1556 self.apply_suffix(v.look.suffix.as_deref(), a);
1557 self.w.commit_elem(depth, v.look.display, Some(meta_people(people)));
1558 return;
1559 }
1560 // A disambiguated cite brings its own forms, when they are for these variables.
1561 let props = match &self.cite.disamb {
1562 Disamb::Names(p) if p.vars.iter().map(String::as_str).eq(people.iter().map(|(_, v)| *v)) => p.clone(),
1563 _ => NameDisamb {
1564 forms: people.iter().map(|(p, _)| (0..p.len())
1565 .map(|j| if o.is_suppressed(j, p.len(), subsequent) { None } else { Some(form) })
1566 .collect()).collect(),
1567 default: form,
1568 vars: v.vars.to_vec(),
1569 },
1570 };
1571 let listed = people.iter().zip(props.forms.iter()).filter(|((p, _), _)| !p.is_empty());
1572 for (i, ((persons, var), forms)) in listed.enumerate() {
1573 let plural = persons.len() != 1;
1574 if i > 0 {
1575 let d = v.delimiter.or(names_delim).unwrap_or("");
1576 if !d.is_empty() {
1577 self.push_str(d);
1578 }
1579 }
1580 if let (Some(l), true, None) = (v.label, v.label_first, self.sorting) {
1581 let t = self.term(var, l.form, plural).unwrap_or("");
1582 self.render_label_with_var(l, t);
1583 }
1584 let fi = self.w.push_format(&name.look.fmt);
1585 self.add_names(v, persons, name, &o, forms, var);
1586 self.w.pop_format(fi);
1587 if let (Some(l), false, None) = (v.label, v.label_first, self.sorting) {
1588 let t = self.term(var, l.form, plural).unwrap_or("");
1589 self.render_label_with_var(l, t);
1590 }
1591 }
1592 self.apply_suffix(v.look.suffix.as_deref(), a);
1593 self.w.commit_elem(depth, v.look.display, Some(meta_people(people)));
1594 if self.w.first_name.is_none() {
1595 self.w.first_name = Some(props);
1596 }
1597 }
1598
1599 /// A label inside `names`, its term chosen by the caller.
1600 fn render_label_with_var(&mut self, l: &Label, content: &str) {
1601 if content.is_empty() {
1602 return;
1603 }
1604 let fi = self.w.push_format(&l.look.fmt);
1605 let a = self.w.apply_prefix(l.look.prefix.as_deref());
1606 self.w.strip_periods = l.look.strip_periods;
1607 let cidx = self.push_case(l.look.text_case);
1608 self.push_str(content);
1609 self.w.pop_case(cidx);
1610 self.w.strip_periods = false;
1611 self.apply_suffix(l.look.suffix.as_deref(), a);
1612 self.w.pop_format(fi);
1613 }
1614
1615 fn and_text(&self, a: And) -> &'a str {
1616 match a {
1617 And::Text => self.term("and", TermForm::Long, false).unwrap_or(""),
1618 And::Symbol => "&",
1619 }
1620 }
1621
1622 /// One variable's names. The "and" goes in only when there is no et al., and an
1623 /// et-al-use-last list ends in the delimiter, an ellipsis and the last name.
1624 fn add_names(
1625 &mut self,
1626 v: NamesView<'a>,
1627 persons: &[Person],
1628 name: &Name,
1629 o: &NOpts,
1630 forms: &[Option<NForm>],
1631 var: &str,
1632 ) {
1633 let has_et_al = forms.iter().any(Option::is_none);
1634 let take = forms.iter().position(Option::is_none).unwrap_or(persons.len());
1635 let use_last = match o.use_last && has_et_al {
1636 true => forms.last().copied().flatten(),
1637 false => None,
1638 };
1639 let demote = match self.style.demote_particle {
1640 Demote::DisplayAndSort => true,
1641 Demote::SortOnly => self.sorting.is_some(),
1642 Demote::Never => false,
1643 };
1644 let mut last_inverted = false;
1645 for (i, (p, f)) in persons.iter().take(take).zip(forms).enumerate() {
1646 let f = match f {
1647 Some(f) => *f,
1648 None => continue,
1649 };
1650 if i > 0 {
1651 let and = match i + 1 == take && !has_et_al {
1652 true => o.and,
1653 false => None,
1654 };
1655 match and {
1656 None => self.push_str(&o.delim),
1657 Some(and) => {
1658 let with_delim = match o.prec_last {
1659 DelimRule::Contextual => i >= 2,
1660 DelimRule::AfterInvertedName => last_inverted,
1661 DelimRule::Always => true,
1662 DelimRule::Never => false,
1663 };
1664 if with_delim {
1665 self.push_str(&o.delim);
1666 } else {
1667 self.push_str(" ");
1668 }
1669 let t = self.and_text(and);
1670 self.push_str(t);
1671 self.w.ensure_space();
1672 }
1673 }
1674 }
1675 let reverse = match o.sort_order {
1676 Some(SortOrder::First) => i == 0,
1677 Some(SortOrder::All) => true,
1678 None => false,
1679 };
1680 self.write_name(p, f, reverse, demote, name, o, var, i);
1681 last_inverted = reverse;
1682 }
1683 if let Some(f) = use_last {
1684 if let Some(p) = persons.last() {
1685 self.push_str(&o.delim);
1686 self.push_str("… ");
1687 let reverse = o.sort_order == Some(SortOrder::All);
1688 self.write_name(p, f, reverse, demote, name, o, var, persons.len() - 1);
1689 }
1690 } else if has_et_al && self.sorting.is_none() {
1691 let (tname, fmt) = match v.et_al {
1692 Some(e) => (e.term.as_str(), e.look.fmt),
1693 None => ("et-al", Fmt::default()),
1694 };
1695 if let Some(t) = self.term(tname, TermForm::Long, false) {
1696 let with_delim = match o.prec_et_al {
1697 DelimRule::Always => true,
1698 DelimRule::Contextual => take >= 2,
1699 DelimRule::AfterInvertedName => last_inverted,
1700 DelimRule::Never => false,
1701 };
1702 if with_delim {
1703 self.push_str(&o.delim);
1704 }
1705 let fi = self.w.push_format(&fmt);
1706 self.w.ensure_space();
1707 self.push_str(t);
1708 self.w.pop_format(fi);
1709 }
1710 }
1711 }
1712
1713 /// The given name: initials with `initialize-with` when initialising, else the given names
1714 /// joined by it.
1715 fn first_name(&mut self, p: &Person, form: NForm, o: &NOpts) {
1716 let given = match &p.given {
1717 Some(g) => g,
1718 None => return,
1719 };
1720 let hyphen = self.style.initialize_with_hyphen;
1721 match &o.init_with {
1722 Some(w) if form == NForm::LongInit => { let _ = p.initials(self, Some(w), hyphen); }
1723 Some(w) => { let _ = p.given_with_delimiter(self, Some(w)); }
1724 None => self.push_str(given),
1725 }
1726 }
1727
1728 /// Opens a name part's formatting and case and writes its prefix; `close_part` ends it.
1729 fn open_part(&mut self, part: Option<&NamePart>, cased: bool) -> (usize, usize) {
1730 let fi = self.w.push_format(&part.map(|x| x.look.fmt).unwrap_or_default());
1731 let ci = self.push_case(if cased { part.and_then(|x| x.look.text_case) } else { None });
1732 if let Some(pre) = part.and_then(|x| x.look.prefix.as_deref()) {
1733 self.push_str(pre);
1734 }
1735 (fi, ci)
1736 }
1737
1738 fn close_part(&mut self, (fi, ci): (usize, usize)) {
1739 self.w.pop_case(ci);
1740 self.w.pop_format(fi);
1741 }
1742
1743 fn part_suffix(&mut self, part: Option<&NamePart>) {
1744 if let Some(suf) = part.and_then(|x| x.look.suffix.as_deref()) {
1745 self.push_str(suf);
1746 }
1747 }
1748
1749 /// One name in its own element. Institutional and short names are the family part alone, a
1750 /// long CJK name is family then given, unspaced, and a reversed name is family first after
1751 /// which the sort separator.
1752 #[allow(clippy::too_many_arguments)]
1753 fn write_name(
1754 &mut self,
1755 p: &Person,
1756 form: NForm,
1757 reverse: bool,
1758 demote: bool,
1759 name: &Name,
1760 o: &NOpts,
1761 var: &str,
1762 idx: usize,
1763 ) {
1764 let giv = name.parts.iter().find(|x| x.part == PartName::Given);
1765 let fam = name.parts.iter().find(|x| x.part == PartName::Family);
1766 let loc = self.w.push_elem(&Fmt::default());
1767 let long = matches!(form, NForm::LongInit | NForm::LongFull);
1768 if p.is_institutional() && self.sorting.is_some() {
1769 let s = self.open_part(fam, true);
1770 self.push_str(p.family_without_article());
1771 self.close_part(s);
1772 } else if p.is_institutional() || !long {
1773 let s = self.open_part(fam, true);
1774 self.push_str(&p.family);
1775 self.close_part(s);
1776 self.part_suffix(fam);
1777 } else if p.is_cjk() {
1778 // hayagriva applies neither part's case here.
1779 let s = self.open_part(fam, false);
1780 self.push_str(&p.family);
1781 self.close_part(s);
1782 self.part_suffix(fam);
1783 if let Some(g) = &p.given {
1784 let s = self.open_part(giv, false);
1785 self.push_str(g);
1786 self.close_part(s);
1787 self.part_suffix(giv);
1788 }
1789 } else if reverse || self.sorting.is_some() {
1790 let s = self.open_part(fam, true);
1791 self.push_str(if demote { p.family_without_particle() } else { p.family.as_str() });
1792 self.close_part(s);
1793 self.part_suffix(fam);
1794 if p.given.is_some() {
1795 self.push_str(&o.sort_sep);
1796 let s = self.open_part(giv, true);
1797 self.first_name(p, form, o);
1798 if let Some(pt) = &p.particle {
1799 self.w.ensure_space();
1800 self.push_str(pt);
1801 }
1802 self.close_part(s);
1803 if demote {
1804 if let Some(pt) = p.particle_in_family() {
1805 self.w.ensure_space();
1806 self.push_str(pt);
1807 }
1808 }
1809 self.part_suffix(giv);
1810 }
1811 if let Some(s) = &p.suffix {
1812 self.push_str(&o.sort_sep);
1813 self.push_str(s);
1814 }
1815 } else {
1816 let s = self.open_part(giv, true);
1817 self.first_name(p, form, o);
1818 if let Some(pt) = &p.particle {
1819 self.w.ensure_space();
1820 self.push_str(pt);
1821 }
1822 self.close_part(s);
1823 self.part_suffix(giv);
1824 self.w.ensure_space();
1825 let s = self.open_part(fam, true);
1826 self.push_str(&p.family);
1827 self.close_part(s);
1828 if let Some(sx) = &p.suffix {
1829 if p.comma_suffix {
1830 self.push_str(&o.sort_sep);
1831 }
1832 self.w.ensure_space();
1833 self.push_str(sx);
1834 }
1835 // The family part's suffix follows the name's suffix (hayagriva).
1836 self.part_suffix(fam);
1837 }
1838 self.w.commit_elem(loc, None, Some(Meta::Name(var.to_string(), idx)));
1839 }
1840
1841 /// hayagriva's `renders_given_special_form`: VarOnly passes a `names` holding its variable,
1842 /// directly or through the substitute of an empty one; SuppressAuthor stops one that would
1843 /// render the author; the date forms stop every `names`.
1844 fn names_pass(&mut self, vars: &'a [String], sub: Option<&'a [Elem]>, empty: bool) -> bool {
1845 match self.special.clone() {
1846 Some(Special::VarOnly(var)) => {
1847 let has = vars.iter().any(|v| *v == var);
1848 let in_sub = empty && sub.map_or(false, |s| s.iter().any(|c| match c {
1849 Elem::Names(n) => n.vars.iter().any(|v| *v == var),
1850 _ => false,
1851 }));
1852 has || in_sub
1853 }
1854 Some(Special::OnlyFirstDate | Special::OnlyYearSuffix) => false,
1855 Some(Special::SuppressAuthor) => !self.names_will_render(vars, sub, "author"),
1856 None => true,
1857 }
1858 }
1859
1860 fn names_info(&mut self, n: &'a Names) -> (bool, Usage) {
1861 let s = self.w.suppressing;
1862 self.w.suppressing = false;
1863 let counts: Vec<usize> = n.vars.iter().map(|v| self.resolve_names(v).len()).collect();
1864 if !self.names_pass(&n.vars, n.substitute.as_deref(), counts.iter().all(|&c| c == 0)) {
1865 self.w.suppressing = s;
1866 return (false, Usage::default());
1867 }
1868 let mut empty = counts.iter().all(|&c| c == 0);
1869 let mut sub = (false, Usage::default());
1870 if let Some(elems) = &n.substitute {
1871 for c in elems {
1872 let (p, i) = self.info(c);
1873 sub = (sub.0 || p, sub.1.merge(i));
1874 }
1875 }
1876 // A name element showing none of an et-al list counts as empty. So, as in hayagriva, does
1877 // a `names` with children but no `name`: AMA's `<names variable="editor"><label/></names>`
1878 // prints nothing, though CSL would print the names with an implicit `name`.
1879 match &n.name {
1880 Some(name) => if let (Some(min), Some(0)) = (name.opts.et_al_min, name.opts.et_al_use_first) {
1881 if counts.iter().all(|&c| c >= min as usize) {
1882 empty = true;
1883 }
1884 },
1885 None => if n.et_al.is_some() || n.label.is_some() || n.substitute.is_some() {
1886 empty = true;
1887 },
1888 }
1889 self.w.suppressing = s;
1890 let visible = !empty || sub.0;
1891 (visible, if empty { sub.1 } else { Usage { vars: true, non_empty: true, ..Usage::default() } })
1892 }
1893
1894 /// `date`. hayagriva renders no date ranges (a BibTeX range reaches it as its end date) and
1895 /// nothing for circa, which only answers `is-uncertain-date`. A localised form takes the
1896 /// locale's parts and delimiter, each part overridden by the style's part of the same name,
1897 /// and the cs:date's own delimiter is ignored, as CSL 1.0.2 says.
1898 fn render_date(&mut self, d: &'a Date) {
1899 if d.var.is_empty() || !self.date_passes(&d.var) {
1900 return;
1901 }
1902 let date = match self.resolve_date(&d.var) {
1903 Some(x) => x,
1904 None => return,
1905 };
1906 if let Some(sorting) = self.sorting {
1907 // citeproc's trick, as hayagriva has it: BC years as N(i32::MAX + y), AD as Py.
1908 let has = |n: DatePartName| d.parts.iter().any(|p| p.name == n);
1909 let (y, m, dd) = match (d.form, sorting) {
1910 (Some(_), _) => match d.parts_sel {
1911 Some(DateParts::Year) => (true, false, false),
1912 Some(DateParts::YearMonth) => (true, true, false),
1913 _ => (true, true, true),
1914 },
1915 (None, Sorting::Variable) => (true, true, true),
1916 (None, Sorting::Macro) => (has(DatePartName::Year), has(DatePartName::Month), has(DatePartName::Day)),
1917 };
1918 let mut k = String::new();
1919 if y {
1920 let _ = match date.year < 0 {
1921 true => write!(k, "N{:09}", i32::MAX + date.year),
1922 false => write!(k, "P{:09}", date.year),
1923 };
1924 }
1925 if m {
1926 let _ = write!(k, "{:02}", date.month.unwrap_or(0));
1927 }
1928 if dd {
1929 let _ = write!(k, "{:02}", date.day.unwrap_or(0));
1930 }
1931 self.push_str(&k);
1932 return;
1933 }
1934 let base: Option<&'a Date> = match d.form {
1935 // A locale without the form prints nothing.
1936 Some(f) => match self.chain.date(f) {
1937 Some(b) => Some(b),
1938 None => return,
1939 },
1940 None => None,
1941 };
1942 let first = !self.w.dates_seen;
1943 self.w.dates_seen = true;
1944 let fmt = match base {
1945 Some(b) => fmt_over(&d.look.fmt, &b.look.fmt),
1946 None => d.look.fmt,
1947 };
1948 let depth = self.w.push_elem(&fmt);
1949 let a = self.w.apply_prefix(d.look.prefix.as_deref());
1950 let cidx = self.push_case(d.look.text_case.or(base.and_then(|b| b.look.text_case)));
1951 let sel = d.parts_sel.or(base.and_then(|b| b.parts_sel)).unwrap_or(DateParts::YearMonthDay);
1952 let delim = match base {
1953 Some(b) => b.delimiter.as_deref(),
1954 None => d.delimiter.as_deref(),
1955 };
1956 let mut last_empty = true;
1957 for part in &base.unwrap_or(d).parts {
1958 match part.name {
1959 DatePartName::Month if sel == DateParts::Year && date.season.is_none() => continue,
1960 DatePartName::Day if sel != DateParts::YearMonthDay => continue,
1961 _ => {}
1962 }
1963 let cursor = self.w.len();
1964 if !last_empty {
1965 if let Some(dl) = delim {
1966 self.push_str(dl);
1967 }
1968 }
1969 let over = match base {
1970 Some(_) => d.parts.iter().find(|p| p.name == part.name),
1971 None => None,
1972 };
1973 self.render_date_part(part, &date, over, first);
1974 last_empty = cursor == self.w.len();
1975 }
1976 self.w.pop_case(cidx);
1977 self.apply_suffix(d.look.suffix.as_deref(), a);
1978 self.w.commit_elem(depth, d.look.display, Some(Meta::Date));
1979 }
1980
1981 /// One date part. A style part overriding a localised one replaces its form whole (an unset
1982 /// form being the default), lays its formatting over it and wins on case; the affixes and
1983 /// strip-periods stay the locale's.
1984 fn render_date_part(&mut self, part: &DatePart, date: &DateVal, over: Option<&DatePart>, first: bool) {
1985 let val = match part.name {
1986 DatePartName::Day => date.day.map(i32::from),
1987 DatePartName::Month => date.month.or(date.season).map(i32::from),
1988 DatePartName::Year => Some(date.year),
1989 };
1990 let val = match val {
1991 Some(v) => v,
1992 None => return,
1993 };
1994 let form = part_form(over.unwrap_or(part));
1995 let fmt = match over {
1996 Some(o) => fmt_over(&o.look.fmt, &part.look.fmt),
1997 None => part.look.fmt,
1998 };
1999 let fi = self.w.push_format(&fmt);
2000 // The year-suffix form writes only the suffix, without the part's affixes.
2001 let only_suffix = self.special == Some(Special::OnlyYearSuffix);
2002 let a = match only_suffix {
2003 true => None,
2004 false => Some(self.w.apply_prefix(part.look.prefix.as_deref())),
2005 };
2006 if part.name == DatePartName::Month {
2007 self.w.strip_periods = part.look.strip_periods;
2008 }
2009 let cidx = self.push_case(over.and_then(|o| o.look.text_case).or(part.look.text_case));
2010 match (part.name, form) {
2011 _ if only_suffix => {}
2012 (DatePartName::Month, _) if date.month.is_none() => {
2013 // A season. hayagriva returns early when the locale lacks the term, leaving its
2014 // stacks pushed; here the part is closed as usual.
2015 if let Some(t) = self.term(&format!("season-{:02}", val), TermForm::Short, false) {
2016 self.push_str(t);
2017 }
2018 }
2019 (DatePartName::Year, DatePartForm::Short) if val >= 1000 => {
2020 self.push_str(&format!("{:02}", val % 100));
2021 }
2022 (DatePartName::Year, _) => {
2023 let mut s = if val > 0 { val.to_string() } else { (val.abs() + 1).to_string() };
2024 if val < 1000 {
2025 let era = match val <= 0 {
2026 true => self.term("bc", TermForm::Long, false).unwrap_or(" BC"),
2027 false => self.term("ad", TermForm::Long, false).unwrap_or(" AD"),
2028 };
2029 s.push_str(era);
2030 }
2031 self.push_str(&s);
2032 }
2033 (_, DatePartForm::NumericLeadingZeros) => self.push_str(&format!("{:02}", val)),
2034 (DatePartName::Day, DatePartForm::Ordinal) if val == 1 || !self.chain.limit_ordinals_to_day_1() => {
2035 let gender = date.month
2036 .and_then(|m| self.chain.term(&format!("month-{:02}", m), TermForm::Long))
2037 .and_then(|t| t.gender);
2038 let ords = Ords::new(self.chain);
2039 self.push_str(&val.to_string());
2040 self.push_str(ords.lookup(val, gender).unwrap_or(""));
2041 }
2042 (DatePartName::Month, DatePartForm::Long | DatePartForm::Short) => {
2043 let tf = if form == DatePartForm::Long { TermForm::Long } else { TermForm::Short };
2044 match self.term(&format!("month-{:02}", val), tf, false) {
2045 Some(t) => self.push_str(t),
2046 None => self.push_str(&val.to_string()),
2047 }
2048 }
2049 _ => self.push_str(&val.to_string()),
2050 }
2051 if part.name == DatePartName::Year && first && self.year_suffix_implicit() {
2052 if let Some(c) = self.resolve_std("year-suffix", VarForm::Long) {
2053 self.push_chunked(&c);
2054 }
2055 }
2056 if let Some(a) = a {
2057 self.apply_suffix(part.look.suffix.as_deref(), a);
2058 }
2059 self.w.strip_periods = false;
2060 self.w.pop_case(cidx);
2061 self.w.pop_format(fi);
2062 }
2063
2064 /// hayagriva's `Date::will_render` for its own variable: VarOnly passes only that date, and
2065 /// the date forms only the first date.
2066 fn date_passes(&self, var: &str) -> bool {
2067 match &self.special {
2068 Some(Special::VarOnly(v)) => v == var,
2069 Some(Special::OnlyFirstDate | Special::OnlyYearSuffix) => !self.w.dates_seen,
2070 _ => true,
2071 }
2072 }
2073
2074 /// Is the year-suffix written after the first date's year, because neither layout writes it?
2075 fn year_suffix_implicit(&mut self) -> bool {
2076 let style: &'a Style = self.style;
2077 if self.will_render_all(&style.citation.layout.elems, "year-suffix") {
2078 return false;
2079 }
2080 !style.bibliography.as_ref().map_or(false, |b| self.will_render_all(&b.layout.elems, "year-suffix"))
2081 }
2082
2083 fn will_render_all(&mut self, elems: &'a [Elem], var: &str) -> bool {
2084 elems.iter().any(|e| self.will_render(e, var))
2085 }
2086
2087 /// Would the element render the variable? hayagriva's `will_render`: a text resolves its
2088 /// target, a group any child, a choose its chosen branch, a label never.
2089 pub fn will_render(&mut self, e: &'a Elem, var: &str) -> bool {
2090 match e {
2091 Elem::Text(t) => match self.target(t) {
2092 Some(Target::Std(v, _) | Target::Num(v, _)) => v == var,
2093 Some(Target::Page(_)) => var == "page",
2094 Some(Target::Macro(m)) => self.will_render_all(m, var),
2095 _ => false,
2096 },
2097 Elem::Number(n) => self.number_passes(&n.var) && n.var == var,
2098 Elem::Label(_) => false,
2099 Elem::Names(n) => self.names_will_render(&n.vars, n.substitute.as_deref(), var),
2100 Elem::Date(d) => match &self.special {
2101 Some(Special::OnlyFirstDate | Special::OnlyYearSuffix) => !self.w.dates_seen,
2102 _ => self.date_passes(&d.var) && d.var == var,
2103 },
2104 Elem::Group(g) => self.will_render_all(&g.elems, var),
2105 Elem::Choose(c) => match self.choose_branch(c) {
2106 Some(b) => self.will_render_all(b, var),
2107 None => false,
2108 },
2109 }
2110 }
2111
2112 fn names_will_render(&mut self, vars: &'a [String], sub: Option<&'a [Elem]>, var: &str) -> bool {
2113 if vars.iter().any(|v| v == var) {
2114 return true;
2115 }
2116 match sub {
2117 Some(s) if vars.iter().all(|v| self.item.names(v).is_empty()) => self.will_render_all(s, var),
2118 _ => false,
2119 }
2120 }
2121
2122 /// The date is queried after suppression is restored, so it is recorded (hayagriva).
2123 fn date_info(&mut self, d: &'a Date) -> (bool, Usage) {
2124 if d.var.is_empty() {
2125 return (false, Usage { vars: true, ..Usage::default() });
2126 }
2127 let found = self.resolve_date(&d.var).is_some();
2128 (found, Usage { vars: true, non_empty: found, ..Usage::default() })
2129 }
2130
2131 /// `group`: rendered and then kept only if it queried no variable or one was non-empty.
2132 fn render_group(&mut self, g: &'a Group) {
2133 let depth = self.w.push_elem(&g.look.fmt);
2134 let a = self.w.apply_prefix(g.look.prefix.as_deref());
2135 let info = self.group_info(g).1;
2136 let di = self.w.push_delim(g.delimiter.clone());
2137 self.render_with_delimiter(&g.elems);
2138 self.w.pop_delim(di);
2139 self.apply_suffix(g.look.suffix.as_deref(), a);
2140 if info.should_render_group() {
2141 self.w.commit_elem(depth, g.look.display, None);
2142 } else {
2143 self.w.discard_elem(depth);
2144 }
2145 }
2146
2147 fn group_info(&mut self, g: &'a Group) -> (bool, Usage) {
2148 let mut print = false;
2149 let mut info = Usage::default();
2150 for c in &g.elems {
2151 let (p, i) = self.info(c);
2152 print |= p;
2153 info = info.merge(i);
2154 if p && matches!(c, Elem::Group(_)) {
2155 info.group = true;
2156 }
2157 }
2158 (print && info.should_render_group(), info)
2159 }
2160
2161 /// Renders children that will print, the current delimiter between them. A delimiter opens a
2162 /// level that also holds the child after it.
2163 fn render_with_delimiter(&mut self, elems: &'a [Elem]) {
2164 let delim = self.w.delim();
2165 let mut first = true;
2166 let mut loc: Option<Loc> = None;
2167 for c in elems {
2168 if !self.info(c).0 {
2169 continue;
2170 }
2171 if !first {
2172 if let Some(d) = &delim {
2173 if let Some(prev) = loc.take() {
2174 self.w.commit_elem(prev, None, None);
2175 }
2176 loc = Some(self.w.push_elem(&Fmt::default()));
2177 self.push_str(d);
2178 }
2179 }
2180 first = false;
2181 let pos = self.w.push_elem(&Fmt::default());
2182 self.render(c);
2183 self.w.commit_elem(pos, None, None);
2184 }
2185 if let Some(l) = loc {
2186 self.w.commit_elem(l, None, None);
2187 }
2188 }
2189
2190 fn render_choose(&mut self, c: &'a Choose) {
2191 if let Some(elems) = self.choose_branch(c) {
2192 self.render_with_delimiter(elems);
2193 }
2194 }
2195
2196 fn choose_info(&mut self, c: &'a Choose) -> (bool, Usage) {
2197 match self.choose_branch(c) {
2198 Some(elems) => self.children_info(elems),
2199 None => (false, Usage::default()),
2200 }
2201 }
2202
2203 fn choose_branch(&mut self, c: &'a Choose) -> Option<&'a [Elem]> {
2204 self.unsuppressed(|ctx| {
2205 for b in &c.branches {
2206 match &b.cond {
2207 Some(cond) if ctx.test(cond) => return Some(b.elems.as_slice()),
2208 Some(_) => {}
2209 None => return Some(b.elems.as_slice()),
2210 }
2211 }
2212 None
2213 })
2214 }
2215
2216 /// Evaluates a condition's tests lazily, in hayagriva's order whatever the attribute order:
2217 /// disambiguate, is-numeric, is-uncertain-date, locator, position, type, variable. Position is
2218 /// skipped in a bibliography.
2219 fn test(&mut self, cond: &'a Cond) -> bool {
2220 fn rank(t: &Test) -> u8 {
2221 match t {
2222 Test::Disambiguate(_) => 0,
2223 Test::IsNumeric(_) => 1,
2224 Test::IsUncertainDate(_) => 2,
2225 Test::Locator(_) => 3,
2226 Test::Position(_) => 4,
2227 Test::Type(_) => 5,
2228 Test::Variable(_) => 6,
2229 }
2230 }
2231 let mut tests: Vec<&'a Test> = cond.tests.iter()
2232 .filter(|t| !(self.bib && matches!(t, Test::Position(_))))
2233 .collect();
2234 tests.sort_by_key(|t| rank(t));
2235 let mut results = tests.into_iter().map(|t| self.eval(t));
2236 match cond.mode {
2237 Match::All => results.all(|b| b),
2238 Match::Any => results.any(|b| b),
2239 Match::None => !results.any(|b| b),
2240 }
2241 }
2242
2243 fn eval(&mut self, t: &'a Test) -> bool {
2244 match t {
2245 Test::Disambiguate(d) => {
2246 self.w.checked_disamb = true;
2247 *d == (self.cite.disamb == Disamb::Choose)
2248 }
2249 Test::IsNumeric(v) => match var_kind(v) {
2250 VarKind::Standard => self.resolve_std(v, VarForm::Long).map_or(false, |c| Numeric::parse(&c.to_string()).is_some()),
2251 VarKind::Number => matches!(self.resolve_num(v), Some(NumVal::Typed(_))),
2252 VarKind::Page => matches!(self.resolve_page(), Some(PageVal::Typed(_))),
2253 _ => false,
2254 },
2255 Test::IsUncertainDate(v) => self.resolve_date(v).map_or(false, |d| d.approximate),
2256 Test::Locator(l) => self.cite.locator.as_ref().map_or(false, |(k, _)| k == l),
2257 Test::Position(p) => match p {
2258 Position::First => self.cite.first,
2259 Position::Subsequent => !self.cite.first,
2260 Position::Ibid => self.cite.ibid != Ibid::No,
2261 Position::IbidWithLocator => self.cite.ibid == Ibid::WithLocator,
2262 Position::NearNote => self.cite.near_note,
2263 },
2264 Test::Type(ty) => self.item.is_type(ty),
2265 Test::Variable(v) => match var_kind(v) {
2266 VarKind::Standard => self.resolve_std(v, VarForm::Long).map_or(false, |c| !c.is_blank()),
2267 VarKind::Number => self.resolve_num(v).is_some(),
2268 VarKind::Date => self.resolve_date(v).is_some(),
2269 VarKind::Name => !self.resolve_names(v).is_empty(),
2270 VarKind::Page => self.resolve_page().is_some(),
2271 },
2272 }
2273 }
2274}