hayagriva 0.2.1

Work with references: Literature database management, storage, and citation formatting
Documentation
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
use std::collections::HashSet;

use super::{
    and_list_opt, bibliography::Bibliography, get_chunk_title, get_creators, web_creator,
    ChicagoConfig, Mode,
};
use crate::style::{
    alph_designator, delegate_titled_entry, sorted_bibliography, BibliographyOrdering,
    BibliographyStyle, Brackets, Citation, CitationStyle, Database, DisplayCitation,
    DisplayReference, DisplayString, Record,
};
use crate::types::EntryType::*;
use crate::types::Person;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Uniqueness {
    None,
    Initials,
    Full,
}

/// Citations and bibliographies following the Chicago _Author Date_ style.
///
/// # Examples
/// Citations:
/// - Angell 1997
/// - Davidson and McKenna 2010
///
/// Bibliography:
/// - Angell, I. O., and H. J. Godwin. 1977. “On Truncatable Primes.” _Math.
///   Comp._ 31, 265–267. <https://doi.org/10.1090/S0025-5718-1977-0427213-2>.
/// - Donne, John. 1995. _The Variorum Edition of the Poetry of John Donne._
///   Edited by Gary A. Stringer. vol. 6. _The "Anniversaries" and the "Epicedes
///   and Obsequies",_ edited by Gary A. Stringer and Ted-Larry Pebworth.
///   Bloomington: Indiana University Press.
///
/// # Reference
/// See the 17th edition of the Chicago Manual of Style, Chapter 15, for details
/// on how Chicago advises you to format citations and bibliographies.
///
/// If you're unsure on which Chicago style to use, the manual generally
/// recommends [_Notes and Bibliography_](super::notes::ChicagoNotes) for the
/// humanities and social sciences whereas [_Author Date_](ChicagoAuthorDate) is
/// recommended for natural sciences, mathematics, and engineering.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChicagoAuthorDate {
    /// Common config options for all chicago styles.
    /// Primarily important for works without titles.
    pub config: ChicagoConfig,
    /// Number of authors (equal or greater) for which the author
    /// list is truncated.
    pub et_al_limit: u8,
}

impl Default for ChicagoAuthorDate {
    fn default() -> Self {
        Self::new()
    }
}

impl ChicagoAuthorDate {
    /// Create a new author year citation formatter.
    pub fn new() -> Self {
        Self { config: ChicagoConfig::new(), et_al_limit: 4 }
    }

    fn uniqueness<'a>(author: &Person, db: &Database<'a>) -> Uniqueness {
        let total_authors: HashSet<_> = db
            .records()
            .flat_map(|e| get_creators(e.entry).0)
            .filter(|a| a != author)
            .collect();

        let mut unique = Uniqueness::Full;
        for other in total_authors {
            if other.name == author.name {
                if other.initials(None) == author.initials(None) {
                    return Uniqueness::None;
                } else {
                    unique = Uniqueness::Initials;
                }
            }
        }

        unique
    }
}

impl<'a> CitationStyle<'a> for ChicagoAuthorDate {
    fn citation(
        &mut self,
        db: &mut Database<'a>,
        parts: &[Citation<'a>],
    ) -> DisplayCitation {
        let mut items: Vec<DisplayString> = vec![];
        for atomic in parts {
            let entry = delegate_titled_entry(atomic.entry);

            let authors = get_creators(entry).0;

            let date = entry.date_any();
            let similars = db
                .records()
                .filter(|&r| {
                    r.entry.date_any().map(|d| d.year) == date.map(|d| d.year)
                        && get_creators(r.entry).0 == authors
                        && !authors.is_empty()
                })
                .collect::<Vec<_>>();

            let mut s = if !authors.is_empty() {
                let mut last_full = false;
                let names = authors
                    .iter()
                    .map(|author| {
                        let uniqueness = ChicagoAuthorDate::uniqueness(author, db);
                        last_full = uniqueness == Uniqueness::None;
                        match uniqueness {
                            Uniqueness::Full => author.name.clone(),
                            Uniqueness::Initials => author.given_first(true),
                            Uniqueness::None => author.name_first(false, true),
                        }
                    })
                    .collect::<Vec<_>>();

                let et_al_auth = if names.len() >= self.et_al_limit as usize {
                    // 0: First author is different
                    let mut distinction_authors = 0;
                    for entry in db.records().map(|r| r.entry) {
                        if entry == atomic.entry {
                            continue;
                        }
                        let other_authors = get_creators(entry).0;
                        let mut mismatch = other_authors.len();

                        for (i, author) in other_authors.iter().enumerate() {
                            if author != &authors[i] {
                                mismatch = i;
                                break;
                            }
                        }

                        if mismatch == other_authors.len() {
                            continue;
                        }

                        if mismatch > distinction_authors {
                            distinction_authors = mismatch;
                        }
                    }

                    distinction_authors
                } else {
                    0
                };

                let mut list =
                    and_list_opt(names, false, Some(self.et_al_limit.into()), et_al_auth);

                if last_full && !list.ends_with('.') {
                    list.push('.');
                }

                list.into()
            } else if entry.title().is_some() {
                get_chunk_title(entry, true, true, &self.config)
            } else if let Some(creator) =
                web_creator(entry, false, self.config.et_al_limit)
            {
                creator.into()
            } else if matches!(
                entry.entry_type,
                Report | Patent | Legislation | Conference | Exhibition
            ) {
                if let Some(org) = entry.organization() {
                    org.into()
                } else {
                    DisplayString::new()
                }
            } else if let Some(np) = select!(* > ("p":Newspaper)).bound(entry, "p") {
                get_chunk_title(np, true, true, &self.config)
            } else {
                DisplayString::new()
            };

            let space = if let Some(date) = date {
                if !s.is_empty() {
                    s.push(' ');
                }
                s += &date.display_year();
                false
            } else {
                if !s.is_empty() {
                    if s.last() != Some(',') {
                        s.push(',')
                    }
                    s.push(' ');
                }
                s += "n.d.";
                true
            };

            if similars.len() > 1 {
                let pos = similars.iter().position(|&x| x.entry == entry).unwrap();
                let num = if let Some(disambiguation) = similars[pos].disambiguation {
                    disambiguation
                } else {
                    db.records
                        .iter_mut()
                        .find(|(_, r)| r.entry == entry)
                        .unwrap()
                        .1
                        .disambiguation = Some(pos);
                    pos
                };

                let designator = alph_designator(num);

                if space {
                    s.push(' ');
                }

                s.push(designator);
            }

            if let Some(supplement) = atomic.supplement {
                if !supplement.ends_with(';') {
                    s += ", ";
                }

                s += supplement;
            }

            items.push(s);
        }

        DisplayCitation::new(DisplayString::join(&items, "; "), false)
    }

    fn brackets(&self) -> Brackets {
        Brackets::Round
    }

    fn wrapped(&self) -> bool {
        true
    }
}

impl<'a> BibliographyStyle<'a> for ChicagoAuthorDate {
    fn bibliography(
        &self,
        db: &Database<'a>,
        ordering: BibliographyOrdering,
    ) -> Vec<DisplayReference<'a>> {
        let bib_format = Bibliography::new(Mode::AuthorDate, self.config);
        let mut items = vec![];

        for record in db.records() {
            let (bib, al) = bib_format.format(record.entry, record.disambiguation);
            items.push((
                DisplayReference {
                    display: bib,
                    entry: record.entry,
                    prefix: record.prefix.clone().map(Into::into),
                },
                al,
            ))
        }

        sorted_bibliography(items, ordering)
    }

    fn reference(&self, record: &Record<'a>) -> DisplayReference<'a> {
        let bib_format = Bibliography::new(Mode::AuthorDate, self.config);
        let (bib, _) = bib_format.format(record.entry, record.disambiguation);
        DisplayReference {
            display: bib,
            entry: record.entry,
            prefix: record.prefix.clone().map(Into::into),
        }
    }

    fn ordering(&self) -> BibliographyOrdering {
        BibliographyOrdering::ByAuthor
    }
}

#[cfg(test)]
mod tests {
    use crate::style::Database;
    use crate::types::{Date, EntryType, Person, Title};
    use crate::{style::Citation, Entry};

    use super::ChicagoAuthorDate;

    fn date_author_entry(key: &str, authors: Vec<Person>, year: i32) -> Entry {
        let mut e = Entry::new(key, EntryType::Article);
        e.set_authors(authors);
        e.set_date(Date::from_year(year));
        e
    }

    #[allow(non_snake_case)]
    fn A(given: &str, family: &str) -> Person {
        Person::from_strings(&[family, given]).unwrap()
    }

    #[allow(non_snake_case)]
    fn C(entry: &Entry) -> Citation {
        Citation::new(entry, None)
    }

    #[allow(non_snake_case)]
    fn Cs(entries: &[Entry]) -> (Vec<Citation>, Database) {
        let cv = entries.iter().map(|e| C(e)).collect();

        let mut db = Database::new();

        for entry in entries {
            db.push(entry);
        }

        (cv, db)
    }

    #[test]
    fn simple() {
        let es = vec![date_author_entry("key", vec![A("Martin", "Haug")], 2018)];
        let mut formatter = ChicagoAuthorDate::default();
        let (citations, mut database) = Cs(&es);
        assert_eq!(
            database.citation(&mut formatter, &citations).display.value,
            "Haug 2018"
        );
    }

    #[test]
    fn same_author_year() {
        let es = vec![
            date_author_entry("klaus1", vec![A("Klaus", "Kinsky")], 2018),
            date_author_entry("klaus2", vec![A("Klaus", "Kinsky")], 2018),
            date_author_entry("unklaus", vec![A("Haus", "Hinsky")], 2018),
            date_author_entry("klaus3", vec![A("Klaus", "Kinsky")], 2018),
            date_author_entry("klaus4", vec![A("Klaus", "Kinsky")], 2019),
            date_author_entry("klaus5", vec![A("Klaus", "Kinsky")], 2019),
        ];
        let mut formatter = ChicagoAuthorDate::default();
        let (citations, mut database) = Cs(&es);
        assert_eq!(
            database.citation(&mut formatter, &citations).display.value,
            "Kinsky 2018a; Kinsky 2018b; Hinsky 2018; Kinsky 2018c; Kinsky 2019a; Kinsky 2019b"
        );
    }

    #[test]
    fn author_initials() {
        let es = vec![
            date_author_entry("1", vec![A("John", "Doe")], 1967),
            date_author_entry("2", vec![A("Rich", "Doe")], 2011),
        ];
        let mut formatter = ChicagoAuthorDate::default();
        let (citations, mut database) = Cs(&es);
        assert_eq!(
            database.citation(&mut formatter, &citations).display.value,
            "J. Doe 1967; R. Doe 2011"
        );
    }

    #[test]
    fn author_gn() {
        let es = vec![
            date_author_entry("1", vec![A("John", "Doe")], 1967),
            date_author_entry("2", vec![A("Janet", "Doe")], 2011),
        ];
        let mut formatter = ChicagoAuthorDate::default();
        let (citations, mut database) = Cs(&es);
        assert_eq!(
            database.citation(&mut formatter, &citations).display.value,
            "Doe, John. 1967; Doe, Janet. 2011"
        );
    }

    #[test]
    fn multi_author() {
        let es = vec![
            date_author_entry(
                "key",
                vec![A("Laurenz", "Mädje"), A("Martin", "Haug")],
                2020,
            ),
            date_author_entry(
                "key2",
                vec![
                    A("Jean-Baptiste", "Poquelin"),
                    A("Madeleine", "Béjart"),
                    A("Charles", "du Fresne"),
                ],
                1648,
            ),
        ];
        let mut formatter = ChicagoAuthorDate::default();
        formatter.et_al_limit = 3;
        let (citations, mut database) = Cs(&es);
        assert_eq!(
            database.citation(&mut formatter, &citations).display.value,
            "Mädje and Haug 2020; Poquelin et al. 1648"
        );
    }

    #[test]
    fn differentiate_et_al() {
        let es = vec![
            date_author_entry(
                "key",
                vec![
                    A("Jean-Baptiste", "Poquelin"),
                    A("Madeleine", "Béjart"),
                    A("Charles", "du Fresne"),
                ],
                1648,
            ),
            date_author_entry(
                "2",
                vec![
                    A("Jean-Baptiste", "Poquelin"),
                    A("Armande", "Béjart"),
                    A("Charles", "du Fresne"),
                ],
                1662,
            ),
        ];
        let mut formatter = ChicagoAuthorDate::default();
        formatter.et_al_limit = 3;
        let (citations, mut database) = Cs(&es);
        assert_eq!(
            database.citation(&mut formatter, &citations).display.value,
            "Poquelin, M. Béjart, et al. 1648; Poquelin, A. Béjart, et al. 1662"
        );
    }

    #[test]
    fn no_author() {
        let mut e = Entry::new("report", EntryType::Report);
        e.set_date(Date::from_year(1999));
        e.set_title(Title::new("Third International Report on Reporting"));
        let es = vec![e];
        let mut formatter = ChicagoAuthorDate::default();
        let (citations, mut database) = Cs(&es);
        assert_eq!(
            database.citation(&mut formatter, &citations).display.value,
            "Third International Report on Reporting 1999"
        );
    }

    #[test]
    fn no_date() {
        let mut e = Entry::new("report", EntryType::Report);
        e.set_authors(vec![A("John", "Doe")]);
        let es = vec![e];
        let mut formatter = ChicagoAuthorDate::default();
        let (citations, mut database) = Cs(&es);
        assert_eq!(
            database.citation(&mut formatter, &citations).display.value,
            "Doe, n.d."
        );
    }
}