Skip to main content

citum_engine/processor/
citation.rs

1/*
2SPDX-License-Identifier: MIT OR Apache-2.0
3SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus and Citum contributors
4*/
5
6//! Citation rendering orchestration.
7//!
8//! This module resolves the effective citation spec for each citation, prepares
9//! renderer delimiters and affixes. Template-level rendering, including
10//! sentence-initial note-start handling, lives in `rendering`.
11//!
12//! Registration (`&mut RunState`) and rendering (`&RunState`) are interleaved
13//! per citation, in document order: each citation's disambiguation,
14//! position, and dynamic grouping depend on the cumulative state left by
15//! every citation processed before it, and citation numbers may be assigned
16//! lazily during one citation's render that a later citation's registration
17//! then reads. This is why citation processing takes `&mut RunState`
18//! end-to-end rather than the `&FinalizedRun` used by bibliography
19//! rendering, which requires the complete, final state from all citations.
20//! See `docs/specs/EXPLICIT_RENDER_RUN_STATE.md`.
21
22use super::Processor;
23use super::disambiguation::Disambiguator;
24use super::rendering::{CompoundRenderData, GroupRenderParams, Renderer, RendererResources};
25use super::run_state::RunState;
26use crate::error::ProcessorError;
27use crate::reference::Citation;
28use crate::values::ProcHints;
29use citum_schema::NoteStartTextCase;
30use citum_schema::locale::{GeneralTerm, Locale, TermForm};
31use citum_schema::options::{Config, GivennameRule};
32use citum_schema::template::DelimiterPunctuation;
33use indexmap::IndexMap;
34use std::collections::HashMap;
35use std::sync::Arc;
36
37/// Join rendered integral (narrative) groups with localized conjunctions.
38///
39/// Uses the locale's "and" term to join groups according to document grammar
40/// rules (e.g., "A and B" or "A, B, and C" with optional serial comma).
41fn join_integral_groups(rendered_groups: Vec<String>, locale: &Locale) -> String {
42    match rendered_groups.len() {
43        0 => String::new(),
44        1 => rendered_groups.into_iter().next().unwrap_or_default(),
45        2 => {
46            let conjunction = locale
47                .resolved_general_term(&GeneralTerm::And, &TermForm::Long, None)
48                .unwrap_or_else(|| locale.and_term(false).to_string());
49            rendered_groups.join(&format!(" {} ", conjunction.trim()))
50        }
51        _ => {
52            let conjunction = locale
53                .resolved_general_term(&GeneralTerm::And, &TermForm::Long, None)
54                .unwrap_or_else(|| locale.and_term(false).to_string());
55            let final_delimiter = if locale.grammar_options.serial_comma {
56                format!(", {} ", conjunction.trim())
57            } else {
58                format!(" {} ", conjunction.trim())
59            };
60
61            let mut rendered_groups = rendered_groups;
62            let last = rendered_groups.pop().unwrap_or_default();
63            format!("{}{}{}", rendered_groups.join(", "), final_delimiter, last)
64        }
65    }
66}
67
68impl Processor {
69    /// Determine the text-case policy for a citation at the start of a note.
70    ///
71    /// Only applies for note-based styles when a repeated-citation position (Ibid)
72    /// is at the start of the note and has no user-supplied or spec-defined prefix.
73    fn sentence_initial_note_start_text_case(
74        &self,
75        citation: &Citation,
76        effective_spec: &citum_schema::CitationSpec,
77    ) -> Option<NoteStartTextCase> {
78        let spec_prefix = effective_spec.prefix.as_deref().unwrap_or("");
79        if self.is_note_style()
80            && matches!(
81                citation.position,
82                Some(
83                    citum_schema::citation::Position::Ibid
84                        | citum_schema::citation::Position::IbidWithLocator
85                )
86            )
87            && matches!(
88                citation.mode,
89                citum_schema::citation::CitationMode::NonIntegral
90            )
91            && citation.prefix.as_deref().unwrap_or("").is_empty()
92            && spec_prefix.is_empty()
93        {
94            effective_spec.note_start_text_case
95        } else {
96            None
97        }
98    }
99
100    /// Resolve the citation specification based on the citation's document position.
101    ///
102    /// Delegates to the style's citation spec to handle ibid, subsequent, or first
103    /// position overrides.
104    fn resolve_positioned_citation_spec(
105        &self,
106        citation: &Citation,
107    ) -> std::borrow::Cow<'_, citum_schema::CitationSpec> {
108        self.style.citation.as_ref().map_or_else(
109            || std::borrow::Cow::Owned(citum_schema::CitationSpec::default()),
110            |spec| spec.resolve_for_position(citation.position.as_ref()),
111        )
112    }
113
114    /// Register nocite reference IDs into the cited set.
115    ///
116    /// Nocite IDs are treated as cited for bibliography-selection purposes (they
117    /// appear in `bibliography.entries` alongside normally cited refs and are
118    /// matched by `CitedStatus::Visible` selectors), but no `formatted_citations`
119    /// entry is produced for them. This matches standard citeproc / Pandoc `nocite`
120    /// semantics.
121    ///
122    /// IDs that are absent from `self.bibliography` are silently ignored here;
123    /// callers are responsible for emitting `nocite_missing_ref` warnings first.
124    pub fn register_nocite_ids(&self, ids: impl IntoIterator<Item = String>, run: &mut RunState) {
125        for id in ids {
126            run.cited_ids.insert(id);
127        }
128    }
129
130    /// Register cited reference IDs and ensure numeric labels are initialized.
131    ///
132    /// This maintains the set of all references cited in the document and ensures
133    /// that numeric styles have a stable numbering map.
134    fn track_cited_ids_and_init_numbers(&self, citation: &Citation, run: &mut RunState) {
135        self.initialize_numeric_citation_numbers(run);
136        for item in &citation.items {
137            run.cited_ids.insert(item.id.clone());
138        }
139    }
140
141    /// Resolve the final effective citation spec for a given mode and position.
142    fn resolve_effective_citation_spec(&self, citation: &Citation) -> citum_schema::CitationSpec {
143        self.resolve_positioned_citation_spec(citation)
144            .into_owned()
145            .resolve_for_mode(&citation.mode)
146            .into_owned()
147    }
148
149    /// Resolve intra-item and inter-citation delimiters for a citation spec.
150    fn resolve_citation_delimiters<'a>(
151        &self,
152        effective_spec: &'a citum_schema::CitationSpec,
153    ) -> (&'a str, &'a str) {
154        let intra_delimiter = effective_spec.delimiter.as_deref().unwrap_or(", ");
155        let inter_delimiter = effective_spec
156            .multi_cite_delimiter
157            .as_deref()
158            .unwrap_or("; ");
159
160        (
161            if matches!(
162                DelimiterPunctuation::from_csl_string(intra_delimiter),
163                DelimiterPunctuation::None
164            ) {
165                ""
166            } else {
167                intra_delimiter
168            },
169            if matches!(
170                DelimiterPunctuation::from_csl_string(inter_delimiter),
171                DelimiterPunctuation::None
172            ) {
173                ""
174            } else {
175                inter_delimiter
176            },
177        )
178    }
179
180    /// Register a dynamic compound group for a `grouped` citation.
181    ///
182    /// The first item in `citation.items` is the head; subsequent items are tails.
183    /// Skips silently when:
184    /// - The style has no `compound-numeric` bibliography configuration (non-numeric style).
185    /// - A static compound set already covers the head or any tail (static sets take precedence).
186    /// - The head or any tail was previously cited in any context (first occurrence wins).
187    ///
188    /// This method must be called before `track_cited_ids_and_init_numbers` so that
189    /// `cited_ids` reflects only references from prior citations, not the current one.
190    fn resolve_dynamic_group(&self, citation: &Citation, run: &mut RunState) {
191        if self.get_bibliography_options().compound_numeric.is_none() {
192            return;
193        }
194
195        if citation.items.len() < 2 {
196            return;
197        }
198
199        #[allow(clippy::indexing_slicing, reason = "citation.items.len() >= 2")]
200        let head_id = &citation.items[0].id;
201        #[allow(clippy::indexing_slicing, reason = "citation.items.len() >= 2")]
202        let tail_ids: Vec<String> = citation.items[1..].iter().map(|i| i.id.clone()).collect();
203
204        // Static sets take precedence — skip if head or any tail is in a static set.
205        if self.compound_set_by_ref.contains_key(head_id) {
206            return;
207        }
208        for tail in &tail_ids {
209            if self.compound_set_by_ref.contains_key(tail.as_str()) {
210                return;
211            }
212        }
213
214        // First-occurrence wins: reject if the head or any tail was already cited in any
215        // context — whether via a prior dynamic group or a previous ungrouped citation.
216        // Because this method is called before cited_ids is updated for the current
217        // citation, `cited_ids` contains only references from earlier citations.
218        if run
219            .dynamic_compound_set_by_ref
220            .contains_key(head_id.as_str())
221            || run.cited_ids.contains(head_id.as_str())
222        {
223            return;
224        }
225        for tail in &tail_ids {
226            if run.dynamic_compound_set_by_ref.contains_key(tail.as_str())
227                || run.cited_ids.contains(tail.as_str())
228            {
229                return;
230            }
231        }
232
233        let head_number = {
234            let numbers = run
235                .citation_numbers
236                .read()
237                .unwrap_or_else(std::sync::PoisonError::into_inner);
238            let Some(&n) = numbers.get(head_id.as_str()) else {
239                return;
240            };
241            n
242        };
243
244        // Assign all tails the same citation number as the head.
245        {
246            let mut numbers = run
247                .citation_numbers
248                .write()
249                .unwrap_or_else(std::sync::PoisonError::into_inner);
250            for tail in &tail_ids {
251                numbers.insert(tail.clone(), head_number);
252            }
253        }
254
255        // Build the ordered member list for this group.
256        let all_members: Vec<String> = std::iter::once(head_id.clone())
257            .chain(tail_ids.iter().cloned())
258            .collect();
259
260        // Populate dynamic index maps so the renderer can assign sub-labels.
261        for (idx, member) in all_members.iter().enumerate() {
262            run.dynamic_compound_set_by_ref
263                .insert(member.clone(), head_id.clone());
264            run.dynamic_compound_member_index
265                .insert(member.clone(), idx);
266        }
267
268        // Inject into compound_groups for bibliography rendering.
269        {
270            let members = run
271                .compound_groups
272                .entry(head_number)
273                .or_insert_with(|| vec![head_id.clone()]);
274            for tail in &tail_ids {
275                if !members.contains(tail) {
276                    members.push(tail.clone());
277                }
278            }
279        }
280
281        // Register dynamic set so citation_sub_label_for_ref can find members.
282        run.dynamic_compound_sets
283            .insert(head_id.clone(), all_members);
284    }
285
286    /// Build a citation-local hint overlay for CSL `givenname-disambiguation-rule: by-cite`.
287    ///
288    /// Global hints remain authoritative for bibliography rendering, year-suffix ordering,
289    /// numeric state, and note-position state. This overlay only recalculates name expansion
290    /// fields for the references rendered by the current citation.
291    fn citation_scoped_by_cite_hints(
292        &self,
293        items: &[crate::reference::CitationItem],
294        config: &Config,
295    ) -> Option<HashMap<String, ProcHints>> {
296        if !Self::uses_by_cite_givenname(config) {
297            return None;
298        }
299
300        let mut scoped_hints = HashMap::new();
301        let mut scoped_bibliography = IndexMap::new();
302
303        for item in items {
304            let mut hint = self.hints.get(&item.id).cloned().unwrap_or_default();
305            hint.expand_given_names = false;
306            hint.expand_given_names_primary_only = false;
307            hint.min_names_to_show = None;
308            scoped_hints.insert(item.id.clone(), hint);
309
310            if let Some(reference) = self.bibliography.get(&item.id) {
311                scoped_bibliography.insert(item.id.clone(), reference.clone());
312            }
313        }
314
315        if scoped_bibliography.len() < 2 {
316            return Some(scoped_hints);
317        }
318
319        let local_hints =
320            Disambiguator::new(&scoped_bibliography, config, &self.locale).calculate_hints();
321
322        for item in items {
323            let Some(local) = local_hints.get(&item.id) else {
324                continue;
325            };
326            let target = scoped_hints.entry(item.id.clone()).or_default();
327            target.expand_given_names = local.expand_given_names;
328            target.expand_given_names_primary_only = local.expand_given_names_primary_only;
329            target.min_names_to_show = local.min_names_to_show;
330        }
331
332        Some(scoped_hints)
333    }
334
335    /// Return true when the active citation config requests CSL by-cite given-name expansion.
336    fn uses_by_cite_givenname(config: &Config) -> bool {
337        let disambiguate = config.effective_processing().config().disambiguate;
338
339        disambiguate
340            .as_ref()
341            .is_some_and(|d| d.add_givenname && matches!(d.givenname_rule, GivennameRule::ByCite))
342    }
343
344    /// Build the merged static + dynamic compound lookup maps for the renderer.
345    ///
346    /// When no dynamic groups exist (the common case) the static maps are returned
347    /// via references with no allocation. Owned merged maps are only constructed when
348    /// at least one dynamic group is registered.
349    fn merged_compound_data(
350        &self,
351        run: &RunState,
352    ) -> (
353        Option<HashMap<String, String>>,
354        Option<HashMap<String, usize>>,
355        Option<IndexMap<String, Vec<String>>>,
356    ) {
357        if run.dynamic_compound_set_by_ref.is_empty() {
358            return (None, None, None);
359        }
360        let merged_set: HashMap<String, String> = self
361            .compound_set_by_ref
362            .iter()
363            .chain(run.dynamic_compound_set_by_ref.iter())
364            .map(|(k, v)| (k.clone(), v.clone()))
365            .collect();
366        let merged_idx: HashMap<String, usize> = self
367            .compound_member_index
368            .iter()
369            .chain(run.dynamic_compound_member_index.iter())
370            .map(|(k, v)| (k.clone(), *v))
371            .collect();
372        let merged_sets: IndexMap<String, Vec<String>> = self
373            .compound_sets
374            .iter()
375            .chain(run.dynamic_compound_sets.iter())
376            .map(|(k, v)| (k.clone(), v.clone()))
377            .collect();
378        (Some(merged_set), Some(merged_idx), Some(merged_sets))
379    }
380
381    /// Render the core content of a citation, handling sorting and grouping.
382    ///
383    /// This is the main orchestration point for template rendering, compound data
384    /// resolution, and mode-specific (integral vs non-integral) formatting.
385    fn render_citation_content<F>(
386        &self,
387        citation: &Citation,
388        effective_spec: &citum_schema::CitationSpec,
389        renderer_delimiter: &str,
390        renderer_inter_delimiter: &str,
391        note_start_text_case: Option<NoteStartTextCase>,
392        run: &RunState,
393    ) -> Result<String, ProcessorError>
394    where
395        F: crate::render::format::OutputFormat<Output = String>,
396    {
397        // Grouped citations preserve item order (dynamic grouping was already resolved
398        // in process_citation_with_format before cited_ids was updated).
399        let sorted_items = if citation.grouped {
400            citation.items.clone()
401        } else {
402            self.sort_citation_items(citation.items.clone(), effective_spec)
403        };
404
405        // Build merged compound lookup maps (static + dynamic).
406        // Return owned maps only when dynamic groups exist; otherwise use static maps directly.
407        let (dyn_set_owned, dyn_idx_owned, dyn_sets_owned) = self.merged_compound_data(run);
408        let effective_set_by_ref = dyn_set_owned.as_ref().unwrap_or(&self.compound_set_by_ref);
409        let effective_member_index = dyn_idx_owned
410            .as_ref()
411            .unwrap_or(&self.compound_member_index);
412        let effective_compound_sets = dyn_sets_owned.as_ref().unwrap_or(&self.compound_sets);
413
414        let citation_config = self.get_citation_config();
415        let citation_config = match effective_spec.options.as_ref() {
416            Some(mode_options) => {
417                let mut config = citation_config.into_owned();
418                config.merge(&mode_options.to_config());
419                std::borrow::Cow::Owned(config)
420            }
421            None => citation_config,
422        };
423        let scoped_hints = self.citation_scoped_by_cite_hints(&sorted_items, &citation_config);
424        let renderer_hints = scoped_hints.as_ref().unwrap_or(&self.hints);
425        let citation_config = Arc::new(citation_config.into_owned());
426        let renderer = Renderer::new(
427            RendererResources {
428                style: &self.style,
429                bibliography: &self.bibliography,
430                locale: &self.locale,
431                config: citation_config.clone(),
432                bibliography_config: Some(Arc::new(self.get_bibliography_options().into_owned())),
433                first_note_by_id: Some(&run.first_note_by_id),
434            },
435            renderer_hints,
436            &run.citation_numbers,
437            CompoundRenderData {
438                set_by_ref: effective_set_by_ref,
439                member_index: effective_member_index,
440                sets: effective_compound_sets,
441            },
442            self.show_semantics,
443            self.inject_ast_indices,
444            self.abbreviation_map.as_ref(),
445        );
446        let processing = citation_config.processing.clone().unwrap_or_default();
447        let has_explicit_integral_multi_cite_delimiter = matches!(
448            citation.mode,
449            citum_schema::citation::CitationMode::Integral
450        ) && self
451            .resolve_positioned_citation_spec(citation)
452            .integral
453            .as_ref()
454            .and_then(|spec| spec.multi_cite_delimiter.as_ref())
455            .is_some();
456        let rendered_groups = if matches!(
457            processing,
458            citum_schema::options::Processing::Numeric
459                | citum_schema::options::Processing::Label(_)
460        ) {
461            renderer.render_ungrouped_citation_with_format::<F>(
462                &sorted_items,
463                effective_spec,
464                &citation.mode,
465                renderer_delimiter,
466                citation.suppress_author,
467                citation.position.as_ref(),
468                note_start_text_case,
469            )?
470        } else {
471            renderer.render_grouped_citation_with_format::<F>(
472                &sorted_items,
473                &GroupRenderParams {
474                    spec: effective_spec,
475                    mode: &citation.mode,
476                    intra_delimiter: renderer_delimiter,
477                    suppress_author: citation.suppress_author,
478                    position: citation.position.as_ref(),
479                    note_start_text_case,
480                },
481            )?
482        };
483
484        Ok(
485            if matches!(
486                citation.mode,
487                citum_schema::citation::CitationMode::Integral
488            ) && !has_explicit_integral_multi_cite_delimiter
489            {
490                join_integral_groups(rendered_groups, &self.locale)
491            } else {
492                F::default().join(rendered_groups, renderer_inter_delimiter)
493            },
494        )
495    }
496
497    /// Apply user-supplied prefix and suffix from the citation input.
498    ///
499    /// Automatically adds a trailing space to the prefix and a leading space to
500    /// the suffix if they are not already present and not empty.
501    fn apply_citation_input_affixes<F>(
502        &self,
503        citation: &Citation,
504        content: String,
505        fmt: &F,
506    ) -> String
507    where
508        F: crate::render::format::OutputFormat<Output = String>,
509    {
510        let citation_prefix = citation.prefix.as_deref().unwrap_or("");
511        let citation_suffix = citation.suffix.as_deref().unwrap_or("");
512
513        if citation_prefix.is_empty() && citation_suffix.is_empty() {
514            return content;
515        }
516
517        let formatted_prefix =
518            if !citation_prefix.is_empty() && !citation_prefix.ends_with(char::is_whitespace) {
519                format!("{citation_prefix} ")
520            } else {
521                citation_prefix.to_string()
522            };
523
524        let formatted_suffix =
525            if !citation_suffix.is_empty() && !citation_suffix.starts_with(char::is_whitespace) {
526                format!(" {citation_suffix}")
527            } else {
528                citation_suffix.to_string()
529            };
530
531        fmt.affix(&formatted_prefix, content, &formatted_suffix)
532    }
533
534    /// Apply style-defined wrapping and affixes to the rendered citation output.
535    ///
536    /// Handles `wrap` logic (inner prefixes/suffixes and punctuation) based on
537    /// the citation mode and position.
538    fn apply_spec_wrap_and_affixes<F>(
539        &self,
540        citation: &Citation,
541        effective_spec: &citum_schema::CitationSpec,
542        output: String,
543        fmt: &F,
544    ) -> String
545    where
546        F: crate::render::format::OutputFormat<Output = String>,
547    {
548        let spec_prefix = effective_spec.prefix.as_deref().unwrap_or("");
549        let spec_suffix = effective_spec.suffix.as_deref().unwrap_or("");
550
551        if matches!(
552            citation.mode,
553            citum_schema::citation::CitationMode::Integral
554        ) {
555            if !spec_prefix.is_empty() || !spec_suffix.is_empty() {
556                fmt.affix(spec_prefix, output, spec_suffix)
557            } else {
558                output
559            }
560        } else if let Some(wrap) = effective_spec.wrap.as_ref() {
561            let inner_prefix = wrap.inner_prefix.as_deref().unwrap_or("");
562            let inner_suffix = wrap.inner_suffix.as_deref().unwrap_or("");
563            let inner_wrapped = if !inner_prefix.is_empty() || !inner_suffix.is_empty() {
564                fmt.inner_affix(inner_prefix, output, inner_suffix)
565            } else {
566                output
567            };
568            let marks = crate::render::format::QuoteMarks::from(&self.locale.grammar_options);
569            fmt.wrap_punctuation(&wrap.punctuation, inner_wrapped, &marks)
570        } else if !spec_prefix.is_empty() || !spec_suffix.is_empty() {
571            fmt.affix(spec_prefix, output, spec_suffix)
572        } else {
573            output
574        }
575    }
576
577    /// Render a single citation to plain text.
578    ///
579    /// This is a one-shot convenience wrapper: it begins a throwaway
580    /// [`RunState`] internally, so it has no continuity with any other call.
581    /// Use [`Processor::process_citations`] (or the run-threaded
582    /// `_with_format` variants with an explicit, shared `RunState`) to render
583    /// multiple citations from one document with correct cumulative
584    /// numbering, cite-order tracking, and dynamic compound grouping.
585    ///
586    /// # Errors
587    ///
588    /// Returns an error when referenced items are missing or rendering fails.
589    pub fn process_citation(&self, citation: &Citation) -> Result<String, ProcessorError> {
590        let mut run = self.begin_run();
591        self.process_citation_with_format::<crate::render::plain::PlainText>(citation, &mut run)
592    }
593
594    /// Render a citation to a string using a specific output format.
595    ///
596    /// This resolves the effective citation spec for the citation's mode and
597    /// position, renders the citation body, and applies input and style
598    /// affixes. `run` accumulates cite-order state (citation numbers, cited
599    /// IDs, dynamic compound groups) across calls; pass the same `RunState`
600    /// for every citation in one document to get correct cumulative
601    /// behavior, or a fresh one (via [`Processor::begin_run`]) for an
602    /// isolated, one-off render.
603    ///
604    /// # Errors
605    ///
606    /// Returns an error when referenced items are missing or rendering fails.
607    pub fn process_citation_with_format<F>(
608        &self,
609        citation: &Citation,
610        run: &mut RunState,
611    ) -> Result<String, ProcessorError>
612    where
613        F: crate::render::format::OutputFormat<Output = String>,
614    {
615        let fmt = F::default();
616
617        // For grouped citations, resolve the dynamic compound group BEFORE updating
618        // cited_ids with the current citation's items. This ensures the first-occurrence
619        // check in resolve_dynamic_group sees only references from prior citations.
620        if citation.grouped {
621            self.initialize_numeric_citation_numbers(run);
622            self.resolve_dynamic_group(citation, run);
623        }
624
625        self.track_cited_ids_and_init_numbers(citation, run);
626
627        let effective_spec = self.resolve_effective_citation_spec(citation);
628        let note_start_text_case =
629            self.sentence_initial_note_start_text_case(citation, &effective_spec);
630        let (renderer_delimiter, renderer_inter_delimiter) =
631            self.resolve_citation_delimiters(&effective_spec);
632        let content = self.render_citation_content::<F>(
633            citation,
634            &effective_spec,
635            renderer_delimiter,
636            renderer_inter_delimiter,
637            note_start_text_case,
638            run,
639        )?;
640        let output = self.apply_citation_input_affixes(citation, content, &fmt);
641        let wrapped = self.apply_spec_wrap_and_affixes(citation, &effective_spec, output, &fmt);
642
643        // If the host signals that this cluster opens a sentence, capitalize
644        // the leading character of the composed output.  The markup-aware
645        // variant skips leading punctuation (e.g. an opening parenthesis) so
646        // only the first alphabetic character is affected.
647        let finalized = if citation.sentence_start {
648            let case = crate::values::text_case::resolve_text_case(
649                citum_schema::options::titles::TextCase::CapitalizeFirst,
650                Some(self.locale.locale.as_str()),
651            );
652            crate::values::text_case::apply_text_case_markup_aware(&wrapped, case)
653        } else {
654            wrapped
655        };
656
657        Ok(fmt.finish(finalized))
658    }
659
660    /// Render multiple citations in document order.
661    ///
662    /// For note-based styles, normalizes context and assigns citation
663    /// positions. This is a one-shot convenience wrapper: it begins a
664    /// throwaway [`RunState`] internally, shared across all citations in
665    /// `citations` (so cumulative numbering/grouping within this call is
666    /// correct) but not shared with any other call.
667    ///
668    /// # Errors
669    ///
670    /// Returns an error when any citation in the sequence fails to render.
671    pub fn process_citations(&self, citations: &[Citation]) -> Result<Vec<String>, ProcessorError> {
672        let mut run = self.begin_run();
673        self.process_citations_with_format::<crate::render::plain::PlainText>(citations, &mut run)
674    }
675
676    /// Render multiple citations with a custom output format.
677    ///
678    /// `run` is threaded through every citation in `citations`, in order, so
679    /// numbering/cite-order/dynamic-grouping state accumulates correctly
680    /// across the whole batch. Pass the same `run` on to bibliography
681    /// rendering (after [`RunState::finalize`]) to render a consistent
682    /// document.
683    ///
684    /// # Errors
685    ///
686    /// Returns an error when any citation in the sequence fails to render.
687    pub fn process_citations_with_format<F>(
688        &self,
689        citations: &[Citation],
690        run: &mut RunState,
691    ) -> Result<Vec<String>, ProcessorError>
692    where
693        F: crate::render::format::OutputFormat<Output = String>,
694    {
695        let mut normalized = self.normalize_note_context(citations, run);
696        self.annotate_positions(&mut normalized);
697        normalized
698            .iter()
699            .map(|citation| self.process_citation_with_format::<F>(citation, run))
700            .collect()
701    }
702}