-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathmod.rs
2992 lines (2673 loc) · 99.6 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::hash_map::Entry as HmEntry;
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Write};
use std::hash::Hash;
use std::num::{NonZeroI16, NonZeroUsize};
use std::{mem, vec};
use citationberg::taxonomy::{
DateVariable, Locator, NameVariable, NumberVariable, OtherTerm, PageVariable,
StandardVariable, Term, Variable,
};
use citationberg::{
taxonomy as csl_taxonomy, Affixes, BaseLanguage, Citation, CitationFormat, Collapse,
CslMacro, Display, GrammarGender, IndependentStyle, InheritableNameOptions, Layout,
LayoutRenderingElement, Locale, LocaleCode, Names, SecondFieldAlign, StyleCategory,
StyleClass, TermForm, ToFormatting,
};
use citationberg::{DateForm, LongShortForm, OrdinalLookup, TextCase};
use indexmap::IndexSet;
use crate::csl::elem::{simplify_children, NonEmptyStack};
use crate::csl::rendering::names::NameDisambiguationProperties;
use crate::csl::rendering::RenderCsl;
use crate::lang::CaseFolder;
use crate::types::{ChunkKind, ChunkedString, Date, MaybeTyped, Person};
use self::elem::last_text_mut_child;
pub use self::elem::{
BufWriteFormat, Elem, ElemChild, ElemChildren, ElemMeta, Formatted, Formatting,
};
use self::taxonomy::{EntryLike, NumberVariableResult, PageVariableResult};
#[cfg(feature = "archive")]
pub mod archive;
mod citation_label;
mod elem;
mod rendering;
mod sort;
mod taxonomy;
/// This struct formats a set of citations according to a style.
#[derive(Debug)]
pub struct BibliographyDriver<'a, T: EntryLike> {
/// The citations we have seen so far.
citations: Vec<CitationRequest<'a, T>>,
}
impl<T: EntryLike> Default for BibliographyDriver<'_, T> {
fn default() -> Self {
Self { citations: Vec::new() }
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct SpeculativeItemRender<'a, T: EntryLike> {
rendered: ElemChildren,
entry: &'a T,
cite_props: CiteProperties<'a>,
checked_disambiguate: bool,
first_name: Option<NameDisambiguationProperties>,
delim_override: Option<&'a str>,
group_idx: Option<usize>,
locator: Option<SpecificLocator<'a>>,
hidden: bool,
locale: Option<LocaleCode>,
purpose: Option<CitePurpose>,
collapse_verdict: Option<CollapseVerdict>,
}
#[derive(Debug, Hash, PartialEq, Eq)]
struct SpeculativeCiteRender<'a, 'b, T: EntryLike> {
items: Vec<SpeculativeItemRender<'a, T>>,
request: &'b CitationRequest<'a, T>,
}
impl<'a, T: EntryLike> BibliographyDriver<'a, T> {
/// Create a new bibliography driver.
pub fn new() -> Self {
Self::default()
}
/// Create a new citation with the given items.
pub fn citation(&mut self, mut req: CitationRequest<'a, T>) {
for (i, item) in req.items.iter_mut().enumerate() {
item.initial_idx = i;
}
self.citations.push(req);
}
}
/// Implementations for finishing the bibliography.
impl<'a, T: EntryLike + Hash + PartialEq + Eq + Debug> BibliographyDriver<'a, T> {
/// Render the bibliography.
pub fn finish(mut self, request: BibliographyRequest<'_>) -> Rendered {
// 1. Assign citation numbers by bibliography ordering or by citation
// order and render them a first time without their locators.
let bib_style = request.style();
// Only remember each entry once, even if it is cited multiple times.
let mut entry_set = IndexSet::new();
for req in self.citations.iter() {
for item in req.items.iter() {
entry_set.insert(item.entry);
}
}
let mut entries: Vec<_> =
entry_set.into_iter().map(CitationItem::with_entry).collect();
bib_style.sort(
&mut entries,
bib_style.csl.bibliography.as_ref().and_then(|b| b.sort.as_ref()),
request.locale.as_ref(),
|_| 0,
);
let citation_number = |item: &T| {
entries.iter().position(|e| e.entry == item).expect("entry not found")
};
let mut seen: HashSet<*const T> = HashSet::new();
let mut res: Vec<SpeculativeCiteRender<T>> = Vec::new();
let mut last_cite: Option<&CitationItem<T>> = None;
for citation in &mut self.citations {
let style = citation.style();
style.sort(
&mut citation.items,
style.csl.citation.sort.as_ref(),
citation.locale.as_ref(),
citation_number,
);
let items = &citation.items;
let mut renders: Vec<SpeculativeItemRender<'_, T>> = Vec::new();
for item in items.iter() {
let entry = &item.entry;
let is_near_note = citation.note_number.map_or(false, |_| {
res.iter()
.rev()
.take(style.csl.citation.near_note_distance as usize)
.any(|cite| {
cite.request.note_number.is_some()
&& cite.items.iter().any(|item| &item.entry == entry)
})
});
let first_note_number = citation.note_number.map(|n| {
res.iter()
.find_map(|cite| {
cite.request.note_number.filter(|_| {
cite.items.iter().any(|item| &item.entry == entry)
})
})
.unwrap_or(n)
});
let mut cite_props = CiteProperties {
certain: CertainCiteProperties {
note_number: citation.note_number,
first_note_number,
is_near_note,
is_first: seen.insert(*entry),
initial_idx: item.initial_idx,
},
speculative: SpeculativeCiteProperties::speculate(
None,
citation_number(entry),
IbidState::with_last(item, last_cite),
),
};
let ctx = style.do_citation(
*entry,
cite_props.clone(),
item.locale.as_ref(),
citation.locale.as_ref(),
item.purpose,
None,
);
// Copy the identifier usage from the context. Assume it does
// not change throughout disambiguation.
cite_props.speculative.identifier_usage =
ctx.instance.identifier_usage.take();
renders.push(SpeculativeItemRender {
entry,
cite_props,
checked_disambiguate: ctx.writing.checked_disambiguate,
first_name: ctx.writing.first_name.clone(),
delim_override: None,
group_idx: None,
locator: item.locator,
rendered: ctx.flush(),
hidden: item.hidden,
locale: item.locale.clone(),
purpose: item.purpose,
collapse_verdict: None,
});
last_cite = Some(item);
}
res.push(SpeculativeCiteRender { items: renders, request: citation });
}
// 2. Disambiguate the citations.
//
// If we have set the disambiguation state for an item, we need to set
// the same state for all entries referencing that item.
for _ in 0..16 {
let ambiguous = find_ambiguous_sets(&res);
if ambiguous.is_empty() {
break;
}
let mut rerender: HashMap<*const T, DisambiguateState> = HashMap::new();
let mark = |map: &mut HashMap<*const T, DisambiguateState>,
entry: &T,
state: DisambiguateState| {
map.entry(entry)
.and_modify(|e| *e = e.clone().max(state.clone()))
.or_insert(state);
};
for group in ambiguous.iter() {
// 2a. Name Disambiguation loop
disambiguate_names(&res, group, |entry, state| {
mark(&mut rerender, entry, state)
});
// Do not try other methods if the previous method succeeded.
if !rerender.is_empty() {
continue;
}
// 2b. Disambiguate by allowing `cs:choose` disambiguation.
disambiguate_with_choose(&res, group, |entry, state| {
mark(&mut rerender, entry, state)
});
if !rerender.is_empty() {
continue;
}
// 2c. Disambiguate by year-suffix.
disambiguate_year_suffix(&res, group, |entry, state| {
mark(&mut rerender, entry, state)
});
}
if rerender.is_empty() {
break;
}
for cite in res.iter_mut() {
let style_ctx = cite.request.style();
for item in cite.items.iter_mut() {
if let Some(state) = rerender.get(&(item.entry as _)) {
item.cite_props.speculative.disambiguation = state.clone();
item.rendered = do_rerender(&style_ctx, item, cite.request);
}
}
}
}
// 3. Group adjacent citations.
for cite in res.iter_mut() {
// This map contains the last index of each entry with this names
// elem.
let mut map: HashMap<String, usize> = HashMap::new();
let mut group_idx = 0;
for i in 0..cite.items.len() {
let Some(delim) =
cite.request.style.citation.cite_group_delimiter.as_deref().or_else(
|| {
cite.request
.style
.citation
.layout
.delimiter
.as_deref()
.filter(|_| {
cite.request.style.citation.collapse.is_some()
})
},
)
else {
continue;
};
let Some(name_elem) = cite.items[i]
.rendered
.find_meta(ElemMeta::Names)
.map(|e| format!("{:?}", e))
else {
continue;
};
let mut prev = None;
let target = *map
.entry(name_elem)
.and_modify(|i| {
prev = Some(*i);
*i += 1
})
.or_insert_with(|| {
group_idx += 1;
i
});
let mut pos = i;
while target < pos {
cite.items.swap(pos, pos - 1);
pos -= 1;
}
cite.items[target].delim_override = Some(delim);
cite.items[target].group_idx = Some(group_idx);
if let Some(prev) = prev {
cite.items[prev].delim_override = None;
}
}
}
// 4. Render citations with locator.
// 4a. Make final calls on all [`SpeculativeCiteProperties`].
// - Re-check for ibid.
for i in 0..res.len() {
for j in 0..res[i].items.len() {
// TODO filter is not hidden
let last = if j == 0 && i == 0 {
None
} else if j == 0 {
res[i - 1].items.last()
} else {
Some(&res[i].items[j - 1])
}
.map(|l| CitationItem::with_locator(l.entry, l.locator));
res[i].items[j].cite_props.speculative.ibid = IbidState::with_last(
&CitationItem::with_locator(
res[i].items[j].entry,
res[i].items[j].locator,
),
last.as_ref(),
);
// - Add final locator
res[i].items[j].cite_props.speculative.locator = res[i].items[j].locator;
}
}
// - Determine final citation number if bibliography does not sort.
if bib_style
.csl
.bibliography
.as_ref()
.and_then(|b| b.sort.as_ref())
.is_none()
{
let mut seen: HashMap<*const T, usize> = HashMap::new();
let mut start = 0;
for cite in res.iter_mut() {
for item in cite.items.iter_mut() {
item.cite_props.speculative.citation_number =
*seen.entry(item.entry as _).or_insert_with(|| {
let num = start;
start += 1;
num
});
}
}
}
// Rerender.
let mut final_citations: Vec<RenderedCitation> = Vec::new();
for cite in res.iter_mut() {
let style_ctx = cite.request.style();
// 5. Collapse grouped citations.
if cite.request.items.iter().all(|c| c.purpose.is_none()) {
collapse_items(cite);
}
for item in cite.items.iter_mut() {
item.rendered = last_purpose_render(&style_ctx, item, cite.request);
}
// 6. Add affixes.
let formatting = Formatting::default()
.apply(cite.request.style.citation.layout.to_formatting());
final_citations.push(RenderedCitation {
note_number: cite.request.note_number,
citation: if cite.items.iter().all(|i| i.hidden) {
ElemChildren::new()
} else {
let mut elem_children: Vec<ElemChild> = Vec::new();
if let Some(prefix) = cite.request.prefix() {
elem_children.push(ElemChild::Text(Formatted {
text: prefix.to_string(),
formatting,
}));
}
for (i, item) in cite.items.iter().enumerate() {
if item.hidden {
continue;
}
if i != 0 {
if let Some(delim) = cite
.items
.get(i)
.and_then(|i: &SpeculativeItemRender<T>| i.delim_override)
.or(cite
.request
.style
.citation
.layout
.delimiter
.as_deref())
{
elem_children.push(ElemChild::Text(Formatted {
text: delim.to_string(),
formatting,
}));
}
}
elem_children.push(ElemChild::Elem(Elem {
children: item.rendered.clone(),
display: None,
meta: Some(ElemMeta::Entry(
item.cite_props.certain.initial_idx,
)),
}));
}
if let Some(suffix) = cite.request.suffix() {
let print = last_text_mut_child(&mut elem_children)
.map_or(true, |t| !t.text.ends_with(suffix));
if print {
elem_children.push(
Formatted { text: suffix.to_string(), formatting }.into(),
);
}
}
simplify_children(ElemChildren(elem_children))
},
})
}
let bib_render = if let Some(bibliography) = &request.style.bibliography {
let mut items = Vec::new();
for entry in entries.into_iter() {
let cited_item = res
.iter()
.flat_map(|cite| cite.items.iter())
.find(|item| item.entry == entry.entry)
.unwrap();
items.push((
simplify_children(
bib_style
.bibliography(
entry.entry,
CiteProperties {
certain: cited_item.cite_props.certain,
speculative: cited_item
.cite_props
.speculative
.for_bibliography(),
},
cited_item.locale.as_ref(),
request.locale.as_ref(),
)
.unwrap(),
),
entry.entry.key().to_string(),
))
}
Some(RenderedBibliography {
hanging_indent: bibliography.hanging_indent,
second_field_align: bibliography.second_field_align,
line_spacing: bibliography.line_spacing,
entry_spacing: bibliography.entry_spacing,
items: items
.into_iter()
.map(|(mut i, key)| {
if bibliography.second_field_align.is_some() {
BibliographyItem::new(key, i.remove_any_meta(), i)
} else {
BibliographyItem::new(key, None, i)
}
})
.collect(),
})
} else {
None
};
Rendered {
bibliography: bib_render,
citations: final_citations,
}
}
}
/// Create a new citation with the given items. Bibliography-wide disambiguation
/// and some other features will not be applied.
pub fn standalone_citation<T: EntryLike>(
mut req: CitationRequest<'_, T>,
) -> ElemChildren {
let style = req.style();
style.sort(
&mut req.items,
style.csl.citation.sort.as_ref(),
req.locale.as_ref(),
|_| 0,
);
let mut res = vec![];
let mut all_hidden = true;
for item in req.items {
if item.hidden {
continue;
} else {
all_hidden = false;
}
res.push(if let Some(CitePurpose::Year) = item.purpose {
date_replacement(
&style,
item.entry,
&CiteProperties::for_sorting(item.locator, 0),
req.locale.as_ref(),
item.locale.as_ref(),
)
} else {
style.citation(
item.entry,
CiteProperties::for_sorting(item.locator, 0),
item.locale.as_ref(),
req.locale.as_ref(),
item.purpose,
None,
)
});
}
let non_empty: Vec<_> = res.into_iter().filter(|c| c.has_content()).collect();
let formatting =
Formatting::default().apply(style.csl.citation.layout.to_formatting());
if !non_empty.is_empty() && !all_hidden {
let mut res = if let Some(prefix) = style.csl.citation.layout.prefix.as_ref() {
ElemChildren(vec![Formatted { text: prefix.clone(), formatting }.into()])
} else {
ElemChildren::new()
};
for (i, elem_children) in non_empty.into_iter().enumerate() {
let first = i == 0;
if !first {
res.0.push(
Formatted {
text: style
.csl
.citation
.layout
.delimiter
.as_deref()
.unwrap_or(Citation::DEFAULT_CITE_GROUP_DELIMITER)
.to_string(),
formatting,
}
.into(),
);
}
res.0.extend(elem_children.0)
}
if let Some(suffix) = style.csl.citation.layout.suffix.as_ref() {
let print = res.last_text().map_or(true, |t| !t.text.ends_with(suffix));
if print {
res.0.push(Formatted { text: suffix.clone(), formatting }.into());
}
}
simplify_children(res)
} else {
ElemChildren::new()
}
}
fn do_rerender<T: EntryLike>(
ctx: &StyleContext<'_>,
item: &SpeculativeItemRender<T>,
request: &CitationRequest<'_, T>,
) -> ElemChildren {
ctx.citation(
item.entry,
item.cite_props.clone(),
item.locale.as_ref(),
request.locale.as_ref(),
item.purpose,
item.collapse_verdict,
)
}
fn date_replacement<T: EntryLike>(
ctx: &StyleContext<'_>,
entry: &T,
cite_props: &CiteProperties,
term_locale: Option<&LocaleCode>,
locale: Option<&LocaleCode>,
) -> ElemChildren {
let date = entry
.resolve_date_variable(DateVariable::Issued)
.or_else(|| entry.resolve_date_variable(DateVariable::EventDate))
.or_else(|| entry.resolve_date_variable(DateVariable::Submitted))
.or_else(|| entry.resolve_date_variable(DateVariable::OriginalDate));
ElemChildren(vec![ElemChild::Text(Formatted {
text: if let Some(date) = date {
let mut s = String::with_capacity(4);
write_year(date.year, false, &mut s).unwrap();
s
} else if let Some(no_date) = ctx
.ctx(entry, cite_props.clone(), locale, term_locale, false)
.term(Term::Other(OtherTerm::NoDate), TermForm::default(), false)
{
no_date.to_string()
} else {
"n.d.".to_string()
},
formatting: Formatting::default(),
})])
}
pub fn write_year<W: std::fmt::Write>(
year: i32,
short: bool,
w: &mut W,
) -> std::fmt::Result {
if short && year >= 1000 {
return write!(w, "{:02}", year % 100);
}
write!(
w,
"{}{}",
if year > 0 { year } else { year.abs() + 1 },
if year < 1000 {
if year <= 0 {
"BC"
} else {
// AD is used as a postfix, see
// https://docs.citationstyles.org/en/stable/specification.html?#ad-and-bc
"AD"
}
} else {
""
}
)
}
fn last_purpose_render<T: EntryLike + Debug>(
ctx: &StyleContext<'_>,
item: &SpeculativeItemRender<T>,
request: &CitationRequest<'_, T>,
) -> ElemChildren {
if let Some(CitePurpose::Year) = item.purpose {
date_replacement(
ctx,
item.entry,
&item.cite_props,
request.locale.as_ref(),
item.locale.as_ref(),
)
} else {
do_rerender(ctx, item, request)
}
}
type AmbiguousGroup = Vec<(usize, usize)>;
/// Progressively transform names to disambiguate them.
fn disambiguate_names<F, T>(
renders: &[SpeculativeCiteRender<'_, '_, T>],
group: &AmbiguousGroup,
mut mark: F,
) where
T: EntryLike,
F: FnMut(&T, DisambiguateState),
{
for &(cite_idx, item_idx) in group.iter() {
let style = renders[cite_idx].request.style;
let item = &renders[cite_idx].items[item_idx];
if !item.cite_props.speculative.disambiguation.may_disambiguate_names() {
continue;
}
let name_props_slot = if let DisambiguateState::NameDisambiguation(n) =
&item.cite_props.speculative.disambiguation
{
Some(n)
} else {
item.first_name.as_ref()
};
if let Some(name_props) = name_props_slot {
let mut name_props = name_props.clone();
if name_props.disambiguate(
style.citation.disambiguate_add_givenname,
style.citation.givenname_disambiguation_rule,
style.citation.disambiguate_add_names,
) {
mark(item.entry, DisambiguateState::NameDisambiguation(name_props))
}
}
}
}
/// Mark qualifying entries for disambiguation with `cs:choose`.
fn disambiguate_with_choose<F, T>(
renders: &[SpeculativeCiteRender<'_, '_, T>],
group: &AmbiguousGroup,
mut mark: F,
) where
T: EntryLike,
F: FnMut(&T, DisambiguateState),
{
if group.iter().any(|&(cite_idx, item_idx)| {
renders[cite_idx].items[item_idx].checked_disambiguate
&& renders[cite_idx].items[item_idx]
.cite_props
.speculative
.disambiguation
.may_disambiguate_with_choose()
}) {
// Do not set this for the first qualifying entry.
let mut armed = false;
for &(cite_idx, item_idx) in group.iter() {
let item = &renders[cite_idx].items[item_idx];
if item.checked_disambiguate {
if armed {
mark(item.entry, DisambiguateState::Choose);
} else {
armed = true;
}
}
}
}
}
/// Mark qualifying entries for disambiguation with year suffixes.
fn disambiguate_year_suffix<F, T>(
renders: &[SpeculativeCiteRender<'_, '_, T>],
group: &AmbiguousGroup,
mut mark: F,
) where
T: EntryLike + PartialEq,
F: FnMut(&T, DisambiguateState),
{
if renders.iter().flat_map(|r| r.items.iter()).any(|i| {
let entry_has_date = i
.entry
.resolve_date_variable(DateVariable::Issued)
.or_else(|| i.entry.resolve_date_variable(DateVariable::Accessed))
.or_else(|| i.entry.resolve_date_variable(DateVariable::AvailableDate))
.or_else(|| i.entry.resolve_date_variable(DateVariable::EventDate))
.or_else(|| i.entry.resolve_date_variable(DateVariable::Submitted))
.or_else(|| i.entry.resolve_date_variable(DateVariable::OriginalDate))
.is_some();
i.rendered
.find_elem_by(&|e| {
// The citation label will contain the date if there is one.
e.meta == Some(ElemMeta::Date)
|| (entry_has_date && e.meta == Some(ElemMeta::CitationLabel))
})
.is_some()
}) && group.iter().any(|&(cite_idx, item_idx)| {
renders[cite_idx].request.style.citation.disambiguate_add_year_suffix
&& renders[cite_idx].items[item_idx]
.cite_props
.speculative
.disambiguation
.may_disambiguate_with_year_suffix()
}) {
let mut entries = Vec::new();
for &(cite_idx, item_idx) in group.iter() {
let item = &renders[cite_idx].items[item_idx];
if item
.cite_props
.speculative
.disambiguation
.may_disambiguate_with_year_suffix()
&& !entries.contains(&item.entry)
{
entries.push(item.entry);
}
}
// Assign year suffixes.
for (i, entry) in entries.into_iter().enumerate() {
mark(entry, DisambiguateState::YearSuffix(i as u8));
}
}
}
/// Return a vector of that contains every group of mutually ambiguous items
/// with cite and item index.
fn find_ambiguous_sets<T: EntryLike + PartialEq>(
cites: &[SpeculativeCiteRender<'_, '_, T>],
) -> Vec<AmbiguousGroup> {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PotentialDisambiguation {
/// Two usizes for an item that produced this string.
Single((usize, usize)),
/// There were multiple matches. This is the index in the result vector.
Match(usize),
}
let mut map: HashMap<String, PotentialDisambiguation> = HashMap::new();
let mut res: Vec<Vec<(usize, usize)>> = Vec::new();
for (i, cite) in cites.iter().enumerate() {
for (j, item) in cite.items.iter().enumerate() {
if !item
.cite_props
.speculative
.disambiguation
.may_disambiguate_with_year_suffix()
{
// There is nothing we can do.
continue;
}
let buf = format!("{:?}", item.rendered);
match map.entry(buf) {
HmEntry::Occupied(entry) => match *entry.get() {
PotentialDisambiguation::Single(pos) => {
*entry.into_mut() = PotentialDisambiguation::Match(res.len());
res.push(vec![pos, (i, j)]);
}
PotentialDisambiguation::Match(idx) => {
res[idx].push((i, j));
}
},
HmEntry::Vacant(vacant) => {
vacant.insert(PotentialDisambiguation::Single((i, j)));
}
}
}
}
// Only return items if not every item points to the same entry.
res.into_iter()
.filter(|e| {
let Some(first_entry) =
e.first().map(|(cite, item)| cites[*cite].items[*item].entry)
else {
return false;
};
e.iter()
.any(|(cite, item)| cites[*cite].items[*item].entry != first_entry)
})
.collect()
}
fn collapse_items<'a, T: EntryLike>(cite: &mut SpeculativeCiteRender<'a, '_, T>) {
let style = &cite.request.style;
let after_collapse_delim = style
.citation
.after_collapse_delimiter
.as_deref()
.or(style.citation.layout.delimiter.as_deref());
let group_delimiter = style.citation.cite_group_delimiter.as_deref();
match style.citation.collapse {
Some(Collapse::CitationNumber) => {
// Option with the start and end of the range.
let mut range_start: Option<(usize, usize)> = None;
let mut just_collapsed = false;
let end_range = |items: &mut [SpeculativeItemRender<'a, T>],
range_start: &mut Option<(usize, usize)>,
just_collapsed: &mut bool| {
let use_after_collapse_delim = *just_collapsed;
*just_collapsed = false;
if let &mut Some((start, end)) = range_start {
// If the previous citation range was collapsed, use the
// after-collapse delimiter before the next item.
if use_after_collapse_delim {
items[start].delim_override = after_collapse_delim;
}
// There should be at least three items in the range to
// collapse.
if start + 1 < end {
items[end].delim_override = Some("–");
for item in &mut items[start + 1..end] {
item.hidden = true;
}
*just_collapsed = true;
}
}
*range_start = None;
};
for i in 0..cite.items.len() {
let citation_number = {
// Item must be borrowed in this block only because it
// cannot be mutably borrowed below otherwise.
let item = &cite.items[i];
if item.hidden
|| item.rendered.find_meta(ElemMeta::CitationNumber).is_none()
{
end_range(&mut cite.items, &mut range_start, &mut just_collapsed);
continue;
}
item.cite_props.speculative.citation_number
};
let prev_citation_number = match range_start {
Some((_, end)) => {
Some(cite.items[end].cite_props.speculative.citation_number)
}
None => None,
};
match (range_start, prev_citation_number) {
(Some((start, end)), Some(prev_citation_number))
if end + 1 == i
&& prev_citation_number + 1 == citation_number =>
{
// Extend the range.
range_start = Some((start, i));
}
_ => {
end_range(&mut cite.items, &mut range_start, &mut just_collapsed);
range_start = Some((i, i));
}
}
}
end_range(&mut cite.items, &mut range_start, &mut just_collapsed);
}
Some(Collapse::Year | Collapse::YearSuffix | Collapse::YearSuffixRanged) => {
// Index of where the current group started and the group we are
// currently in.
let mut group_idx: Option<(usize, usize)> = None;
for i in 0..cite.items.len() {
match group_idx {
// This is our group.
Some((_, idx)) if Some(idx) == cite.items[i].group_idx => {
// FIXME: Retains delimiter in names.
cite.items[i].delim_override = group_delimiter;
cite.items[i].collapse_verdict = Some(CollapseVerdict::First);
}
// This is a different group.
Some((start, _)) if start + 1 < i => {
cite.items[i].delim_override = after_collapse_delim;
group_idx = cite.items[i].group_idx.map(|idx| (i, idx));
}
// We are at the beginning.
_ => {
group_idx = cite.items[i].group_idx.map(|idx| (i, idx));
}
}
}
// TODO: Year Suffix and Year Suffix ranged.
}
None => {}
}
}