citum-engine 0.64.0

Citum citation and bibliography processor
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
/*
SPDX-License-Identifier: MIT OR Apache-2.0
SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus and Citum contributors
*/

//! Integral-name state handling for document processing.

#[rustfmt::skip]
use super::note_support::{NoteOccurrence, build_note_order_indices};
use super::{
    CitationPlacement, CitationStructure, DocumentIntegralNameOverride, DocumentOptionsOverride,
    DocumentOrgAbbreviationOverride, ParsedDocument,
};
use crate::reference::Contributor;
use crate::{Citation, Processor};
use citum_schema::options::{IntegralNameContexts, IntegralNameScope};
use std::collections::HashMap;

#[derive(Debug, Clone)]
pub(super) struct IntegralNameContext {
    pub(super) placement: CitationPlacement,
    pub(super) structure: CitationStructure,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SeenIntegralNameState {
    Unseen,
    NoteOnlySeen,
    BodySeen,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum AnnotateKind {
    Personal,
    OrgAbbreviation,
}

impl Processor {
    #[allow(
        clippy::indexing_slicing,
        reason = "indices are verified within bounds"
    )]
    pub(super) fn normalize_integral_name_citations(
        &self,
        parsed: &ParsedDocument,
    ) -> Vec<Citation> {
        let mut normalized: Vec<Citation> = parsed
            .citations
            .iter()
            .map(|parsed| parsed.citation.clone())
            .collect();
        let ordered_indices = build_integral_name_order_indices(parsed);
        #[allow(
            clippy::indexing_slicing,
            reason = "index derived from citations collection"
        )]
        let mut ordered_citations: Vec<Citation> = ordered_indices
            .iter()
            .map(|index| normalized[*index].clone())
            .collect();
        #[allow(
            clippy::indexing_slicing,
            reason = "index derived from citations collection"
        )]
        let ordered_contexts: Vec<_> = ordered_indices
            .iter()
            .map(|index| IntegralNameContext {
                placement: parsed.citations[*index].placement.clone(),
                structure: parsed.citations[*index].structure.clone(),
            })
            .collect();
        self.annotate_integral_name_states(&mut ordered_citations, &ordered_contexts);
        #[allow(
            clippy::indexing_slicing,
            reason = "index derived from citations collection"
        )]
        for (citation, index) in ordered_citations.into_iter().zip(ordered_indices) {
            normalized[index] = citation;
        }
        self.normalize_note_context(&normalized)
    }

    /// Annotate integral-name First/Subsequent state across a flat, ordered
    /// citation list (API paths with no parsed document).
    ///
    /// Citations are processed in list order. A citation with a `note_number`
    /// is treated as a note context; otherwise as body prose. There is no
    /// chapter/section structure, so all citations share the document scope
    /// regardless of the configured [`IntegralNameScope`].
    pub(crate) fn annotate_flat_integral_name_states(&self, citations: &mut [Citation]) {
        let contexts: Vec<IntegralNameContext> = citations
            .iter()
            .map(|citation| IntegralNameContext {
                placement: if citation.note_number.is_some() {
                    CitationPlacement::ManualFootnote {
                        label: String::new(),
                    }
                } else {
                    CitationPlacement::InlineProse
                },
                structure: CitationStructure::default(),
            })
            .collect();
        self.annotate_integral_name_states(citations, &contexts);
    }

    pub(crate) fn processor_with_document_integral_name_override(
        &self,
        override_config: Option<&DocumentIntegralNameOverride>,
    ) -> Option<Self> {
        let override_config = override_config?;
        let mut style = self.style.clone();
        let base = style
            .options
            .as_ref()
            .and_then(|options| options.integral_name_memory.as_ref());
        let applied = override_config.apply_to(base);
        style
            .options
            .get_or_insert_with(Default::default)
            .integral_name_memory = applied;
        // The style cloned from self.style is already resolved — bypass
        // into_resolved() to prevent a second preset application that would
        // restore null-cleared fields (e.g. type-variants: ~).
        Some(Self::build_processor_pre_resolved(
            style,
            self.bibliography.clone(),
            self.locale.clone(),
            self.compound_sets.clone(),
        ))
    }

    pub(super) fn processor_with_document_org_abbreviation_override(
        &self,
        override_config: Option<&DocumentOrgAbbreviationOverride>,
    ) -> Option<Self> {
        let override_config = override_config?;
        let mut style = self.style.clone();
        let base = style
            .options
            .as_ref()
            .and_then(|options| options.org_abbreviation_memory.as_ref());
        let applied = override_config.apply_to(base);
        style
            .options
            .get_or_insert_with(Default::default)
            .org_abbreviation_memory = applied;
        Some(Self::build_processor_pre_resolved(
            style,
            self.bibliography.clone(),
            self.locale.clone(),
            self.compound_sets.clone(),
        ))
    }

    /// Build a new processor with bibliography overrides from a `DocumentOptionsOverride` applied.
    ///
    /// Writes non-`None` bibliography option fields into a cloned style and
    /// calls `apply_scoped_options` so that template mutations stay consistent.
    pub(super) fn processor_with_bibliography_override(
        &self,
        options: &DocumentOptionsOverride,
    ) -> Self {
        let mut style = self.style.clone();
        options.apply_bibliography_to(&mut style);
        Self::build_processor_pre_resolved(
            style,
            self.bibliography.clone(),
            self.locale.clone(),
            self.compound_sets.clone(),
        )
    }

    fn annotate_name_states_for_kind(
        &self,
        citations: &mut [Citation],
        contexts: &[IntegralNameContext],
        kind: AnnotateKind,
        scope: IntegralNameScope,
        name_contexts: IntegralNameContexts,
    ) {
        let mut seen: HashMap<(String, String), SeenIntegralNameState> = HashMap::new();
        for (citation, context) in citations.iter_mut().zip(contexts.iter()) {
            let counts_as_integral = matches!(
                citation.mode,
                citum_schema::citation::CitationMode::Integral
            ) || citation.suppress_author;
            if !counts_as_integral {
                continue;
            }

            let is_body = matches!(context.placement, CitationPlacement::InlineProse);
            if matches!(name_contexts, IntegralNameContexts::BodyOnly) && !is_body {
                continue;
            }

            let scope_key = match scope {
                IntegralNameScope::Document => "document".to_string(),
                IntegralNameScope::Chapter => context.structure.chapter_scope.clone(),
                IntegralNameScope::Section => context.structure.section_scope.clone(),
            };

            for item in &mut citation.items {
                let is_org = first_author_is_org(&self.bibliography, &item.id);
                match kind {
                    AnnotateKind::Personal if is_org => continue,
                    AnnotateKind::OrgAbbreviation if !is_org => continue,
                    _ => {}
                }

                let state_already_set = match kind {
                    AnnotateKind::Personal => item.integral_name_state.is_some(),
                    AnnotateKind::OrgAbbreviation => item.org_abbreviation_state.is_some(),
                };
                if state_already_set {
                    continue;
                }

                let author_key = match kind {
                    AnnotateKind::Personal => {
                        personal_author_key_for_item(&self.bibliography, &item.id)
                    }
                    AnnotateKind::OrgAbbreviation => {
                        first_author_key_for_item(&self.bibliography, &item.id)
                    }
                };
                let key = (scope_key.clone(), author_key);
                let state = seen
                    .get(&key)
                    .copied()
                    .unwrap_or(SeenIntegralNameState::Unseen);
                let derived = match name_contexts {
                    IntegralNameContexts::BodyOnly => {
                        if matches!(state, SeenIntegralNameState::BodySeen) {
                            citum_schema::citation::IntegralNameState::Subsequent
                        } else {
                            seen.insert(key, SeenIntegralNameState::BodySeen);
                            citum_schema::citation::IntegralNameState::First
                        }
                    }
                    IntegralNameContexts::BodyAndNotes => {
                        if is_body {
                            match state {
                                SeenIntegralNameState::BodySeen => {
                                    citum_schema::citation::IntegralNameState::Subsequent
                                }
                                SeenIntegralNameState::Unseen
                                | SeenIntegralNameState::NoteOnlySeen => {
                                    seen.insert(key, SeenIntegralNameState::BodySeen);
                                    citum_schema::citation::IntegralNameState::First
                                }
                            }
                        } else {
                            match state {
                                SeenIntegralNameState::Unseen => {
                                    seen.insert(key, SeenIntegralNameState::NoteOnlySeen);
                                    citum_schema::citation::IntegralNameState::First
                                }
                                SeenIntegralNameState::NoteOnlySeen
                                | SeenIntegralNameState::BodySeen => {
                                    citum_schema::citation::IntegralNameState::Subsequent
                                }
                            }
                        }
                    }
                };
                match kind {
                    AnnotateKind::Personal => item.integral_name_state = Some(derived),
                    AnnotateKind::OrgAbbreviation => item.org_abbreviation_state = Some(derived),
                }
            }
        }
    }

    pub(super) fn annotate_integral_name_states(
        &self,
        citations: &mut [Citation],
        contexts: &[IntegralNameContext],
    ) {
        let citation_config = self.get_citation_config();

        if let Some(config) = citation_config
            .integral_name_memory
            .as_ref()
            .map(citum_schema::options::IntegralNameMemoryConfig::resolve)
        {
            self.annotate_name_states_for_kind(
                citations,
                contexts,
                AnnotateKind::Personal,
                config.scope,
                config.contexts,
            );
        }

        if let Some(config) = citation_config
            .org_abbreviation_memory
            .as_ref()
            .map(citum_schema::options::OrgAbbreviationMemoryConfig::resolve)
        {
            self.annotate_name_states_for_kind(
                citations,
                contexts,
                AnnotateKind::OrgAbbreviation,
                config.scope,
                config.contexts,
            );
        }
    }
}

fn personal_author_key_for_item(bibliography: &crate::Bibliography, item_id: &str) -> String {
    bibliography
        .get(item_id)
        .and_then(|r| r.author())
        .and_then(|c| contributor_personal_key(&c))
        .unwrap_or_else(|| item_id.to_string())
}

fn contributor_personal_key(contributor: &Contributor) -> Option<String> {
    match contributor {
        Contributor::StructuredName(n) => {
            let given = n.given.to_string();
            let family = n.family.to_string();
            let suffix = n.suffix.as_deref().unwrap_or("");
            Some(format!("{given}|{family}|{suffix}"))
        }
        Contributor::Multilingual(m) => {
            let given = m.original.given.to_string();
            let family = m.original.family.to_string();
            let suffix = m.original.suffix.as_deref().unwrap_or("");
            Some(format!("{given}|{family}|{suffix}"))
        }
        Contributor::SimpleName(n) => Some(n.name.to_string()),
        Contributor::ContributorList(l) => l.0.first().and_then(contributor_personal_key),
    }
}

/// Returns a name-based tracking key for integral name-memory state.
///
/// Uses the first author's family name so that two works by the same author
/// share a single First/Subsequent slot, regardless of citation key.
/// Falls back to `item_id` when no author or family name is available.
fn first_author_key_for_item(bibliography: &crate::Bibliography, item_id: &str) -> String {
    bibliography
        .get(item_id)
        .and_then(|r| r.author())
        .and_then(|c| contributor_first_family(&c))
        .unwrap_or_else(|| item_id.to_string())
}

fn contributor_first_family(contributor: &Contributor) -> Option<String> {
    match contributor {
        Contributor::StructuredName(n) => Some(n.family.to_string()),
        Contributor::Multilingual(m) => Some(m.original.family.to_string()),
        Contributor::SimpleName(n) => Some(n.name.to_string()),
        Contributor::ContributorList(l) => l.0.first().and_then(contributor_first_family),
    }
}

fn first_author_is_org(bibliography: &crate::Bibliography, item_id: &str) -> bool {
    bibliography
        .get(item_id)
        .and_then(|r| r.author())
        .is_some_and(|c| first_contributor_is_org(&c))
}

fn first_contributor_is_org(contributor: &Contributor) -> bool {
    match contributor {
        Contributor::SimpleName(_) => true,
        Contributor::StructuredName(_) | Contributor::Multilingual(_) => false,
        Contributor::ContributorList(l) => l.0.first().is_some_and(first_contributor_is_org),
    }
}

pub(super) fn build_integral_name_order_indices(parsed: &ParsedDocument) -> Vec<usize> {
    let mut manual_citations: HashMap<String, Vec<usize>> = HashMap::new();
    let mut note_occurrences: Vec<NoteOccurrence> = parsed
        .manual_note_references
        .iter()
        .map(|note| NoteOccurrence::Manual {
            label: note.label.clone(),
            start: note.start,
        })
        .collect();

    for (index, parsed_citation) in parsed.citations.iter().enumerate() {
        match &parsed_citation.placement {
            CitationPlacement::InlineProse => note_occurrences.push(NoteOccurrence::Generated {
                citation_index: index,
                start: parsed_citation.start,
            }),
            CitationPlacement::ManualFootnote { label } => {
                manual_citations
                    .entry(label.clone())
                    .or_default()
                    .push(index);
            }
        }
    }

    for indices in manual_citations.values_mut() {
        #[allow(
            clippy::indexing_slicing,
            reason = "index derived from citations collection"
        )]
        indices.sort_by_key(|index| parsed.citations[*index].start);
    }

    note_occurrences.sort_by_key(NoteOccurrence::start);
    build_note_order_indices(&note_occurrences, &manual_citations)
}