1use 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
37fn 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 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 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 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 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 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 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 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 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 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 {
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 let all_members: Vec<String> = std::iter::once(head_id.clone())
257 .chain(tail_ids.iter().cloned())
258 .collect();
259
260 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 {
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 run.dynamic_compound_sets
283 .insert(head_id.clone(), all_members);
284 }
285
286 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 bibliography_config = self.get_bibliography_config();
320 let local_hints = Disambiguator::new(
321 &scoped_bibliography,
322 config,
323 &bibliography_config,
324 &self.locale,
325 )
326 .calculate_hints();
327
328 for item in items {
329 let Some(local) = local_hints.get(&item.id) else {
330 continue;
331 };
332 let target = scoped_hints.entry(item.id.clone()).or_default();
333 target.expand_given_names = local.expand_given_names;
334 target.expand_given_names_primary_only = local.expand_given_names_primary_only;
335 target.min_names_to_show = local.min_names_to_show;
336 }
337
338 Some(scoped_hints)
339 }
340
341 fn uses_by_cite_givenname(config: &Config) -> bool {
343 let disambiguate = config.effective_processing().config().disambiguate;
344
345 disambiguate
346 .as_ref()
347 .is_some_and(|d| d.add_givenname && matches!(d.givenname_rule, GivennameRule::ByCite))
348 }
349
350 fn merged_compound_data(
356 &self,
357 run: &RunState,
358 ) -> (
359 Option<HashMap<String, String>>,
360 Option<HashMap<String, usize>>,
361 Option<IndexMap<String, Vec<String>>>,
362 ) {
363 if run.dynamic_compound_set_by_ref.is_empty() {
364 return (None, None, None);
365 }
366 let merged_set: HashMap<String, String> = self
367 .compound_set_by_ref
368 .iter()
369 .chain(run.dynamic_compound_set_by_ref.iter())
370 .map(|(k, v)| (k.clone(), v.clone()))
371 .collect();
372 let merged_idx: HashMap<String, usize> = self
373 .compound_member_index
374 .iter()
375 .chain(run.dynamic_compound_member_index.iter())
376 .map(|(k, v)| (k.clone(), *v))
377 .collect();
378 let merged_sets: IndexMap<String, Vec<String>> = self
379 .compound_sets
380 .iter()
381 .chain(run.dynamic_compound_sets.iter())
382 .map(|(k, v)| (k.clone(), v.clone()))
383 .collect();
384 (Some(merged_set), Some(merged_idx), Some(merged_sets))
385 }
386
387 fn render_citation_content<F>(
392 &self,
393 citation: &Citation,
394 effective_spec: &citum_schema::CitationSpec,
395 renderer_delimiter: &str,
396 renderer_inter_delimiter: &str,
397 note_start_text_case: Option<NoteStartTextCase>,
398 run: &RunState,
399 ) -> Result<String, ProcessorError>
400 where
401 F: crate::render::format::OutputFormat<Output = String>,
402 {
403 let sorted_items = if citation.grouped {
406 citation.items.clone()
407 } else {
408 self.sort_citation_items(citation.items.clone(), effective_spec)
409 };
410
411 let (dyn_set_owned, dyn_idx_owned, dyn_sets_owned) = self.merged_compound_data(run);
414 let effective_set_by_ref = dyn_set_owned.as_ref().unwrap_or(&self.compound_set_by_ref);
415 let effective_member_index = dyn_idx_owned
416 .as_ref()
417 .unwrap_or(&self.compound_member_index);
418 let effective_compound_sets = dyn_sets_owned.as_ref().unwrap_or(&self.compound_sets);
419
420 let citation_config = self.get_citation_config();
421 let citation_config = match effective_spec.options.as_ref() {
422 Some(mode_options) => {
423 let mut config = citation_config.into_owned();
424 config.merge(&mode_options.to_config());
425 std::borrow::Cow::Owned(config)
426 }
427 None => citation_config,
428 };
429 let scoped_hints = self.citation_scoped_by_cite_hints(&sorted_items, &citation_config);
430 let renderer_hints = scoped_hints.as_ref().unwrap_or(&self.hints);
431 let citation_config = Arc::new(citation_config.into_owned());
432 let renderer = Renderer::new(
433 RendererResources {
434 style: &self.style,
435 bibliography: &self.bibliography,
436 locale: &self.locale,
437 config: citation_config.clone(),
438 bibliography_config: Some(Arc::new(self.get_bibliography_options().into_owned())),
439 first_note_by_id: Some(&run.first_note_by_id),
440 },
441 renderer_hints,
442 &run.citation_numbers,
443 CompoundRenderData {
444 set_by_ref: effective_set_by_ref,
445 member_index: effective_member_index,
446 sets: effective_compound_sets,
447 },
448 self.show_semantics,
449 self.inject_ast_indices,
450 self.abbreviation_map.as_ref(),
451 );
452 let processing = citation_config.processing.clone().unwrap_or_default();
453 let has_explicit_integral_multi_cite_delimiter = matches!(
454 citation.mode,
455 citum_schema::citation::CitationMode::Integral
456 ) && self
457 .resolve_positioned_citation_spec(citation)
458 .integral
459 .as_ref()
460 .and_then(|spec| spec.multi_cite_delimiter.as_ref())
461 .is_some();
462 let rendered_groups = if matches!(
463 processing,
464 citum_schema::options::Processing::Numeric
465 | citum_schema::options::Processing::Label(_)
466 ) {
467 renderer.render_ungrouped_citation_with_format::<F>(
468 &sorted_items,
469 effective_spec,
470 &citation.mode,
471 renderer_delimiter,
472 citation.suppress_author,
473 citation.position.as_ref(),
474 note_start_text_case,
475 )?
476 } else {
477 renderer.render_grouped_citation_with_format::<F>(
478 &sorted_items,
479 &GroupRenderParams {
480 spec: effective_spec,
481 mode: &citation.mode,
482 intra_delimiter: renderer_delimiter,
483 suppress_author: citation.suppress_author,
484 position: citation.position.as_ref(),
485 note_start_text_case,
486 },
487 )?
488 };
489
490 Ok(
491 if matches!(
492 citation.mode,
493 citum_schema::citation::CitationMode::Integral
494 ) && !has_explicit_integral_multi_cite_delimiter
495 {
496 join_integral_groups(rendered_groups, &self.locale)
497 } else {
498 F::default().join(rendered_groups, renderer_inter_delimiter)
499 },
500 )
501 }
502
503 fn apply_citation_input_affixes<F>(
508 &self,
509 citation: &Citation,
510 content: String,
511 fmt: &F,
512 ) -> String
513 where
514 F: crate::render::format::OutputFormat<Output = String>,
515 {
516 let citation_prefix = citation.prefix.as_deref().unwrap_or("");
517 let citation_suffix = citation.suffix.as_deref().unwrap_or("");
518
519 if citation_prefix.is_empty() && citation_suffix.is_empty() {
520 return content;
521 }
522
523 let formatted_prefix =
524 if !citation_prefix.is_empty() && !citation_prefix.ends_with(char::is_whitespace) {
525 format!("{citation_prefix} ")
526 } else {
527 citation_prefix.to_string()
528 };
529
530 let formatted_suffix =
531 if !citation_suffix.is_empty() && !citation_suffix.starts_with(char::is_whitespace) {
532 format!(" {citation_suffix}")
533 } else {
534 citation_suffix.to_string()
535 };
536
537 fmt.affix(&formatted_prefix, content, &formatted_suffix)
538 }
539
540 fn apply_spec_wrap_and_affixes<F>(
545 &self,
546 citation: &Citation,
547 effective_spec: &citum_schema::CitationSpec,
548 output: String,
549 fmt: &F,
550 ) -> String
551 where
552 F: crate::render::format::OutputFormat<Output = String>,
553 {
554 let spec_prefix = effective_spec.prefix.as_deref().unwrap_or("");
555 let spec_suffix = effective_spec.suffix.as_deref().unwrap_or("");
556
557 if matches!(
558 citation.mode,
559 citum_schema::citation::CitationMode::Integral
560 ) {
561 if !spec_prefix.is_empty() || !spec_suffix.is_empty() {
562 fmt.affix(spec_prefix, output, spec_suffix)
563 } else {
564 output
565 }
566 } else if let Some(wrap) = effective_spec.wrap.as_ref() {
567 let inner_prefix = wrap.inner_prefix.as_deref().unwrap_or("");
568 let inner_suffix = wrap.inner_suffix.as_deref().unwrap_or("");
569 let inner_wrapped = if !inner_prefix.is_empty() || !inner_suffix.is_empty() {
570 fmt.inner_affix(inner_prefix, output, inner_suffix)
571 } else {
572 output
573 };
574 let marks = crate::render::format::QuoteMarks::from(&self.locale.grammar_options);
575 fmt.wrap_punctuation(&wrap.punctuation, inner_wrapped, &marks)
576 } else if !spec_prefix.is_empty() || !spec_suffix.is_empty() {
577 fmt.affix(spec_prefix, output, spec_suffix)
578 } else {
579 output
580 }
581 }
582
583 pub fn process_citation(&self, citation: &Citation) -> Result<String, ProcessorError> {
596 let mut run = self.begin_run();
597 self.process_citation_with_format::<crate::render::plain::PlainText>(citation, &mut run)
598 }
599
600 pub fn process_citation_with_format<F>(
614 &self,
615 citation: &Citation,
616 run: &mut RunState,
617 ) -> Result<String, ProcessorError>
618 where
619 F: crate::render::format::OutputFormat<Output = String>,
620 {
621 let fmt = F::default();
622
623 if citation.grouped {
627 self.initialize_numeric_citation_numbers(run);
628 self.resolve_dynamic_group(citation, run);
629 }
630
631 self.track_cited_ids_and_init_numbers(citation, run);
632
633 let effective_spec = self.resolve_effective_citation_spec(citation);
634 let note_start_text_case =
635 self.sentence_initial_note_start_text_case(citation, &effective_spec);
636 let (renderer_delimiter, renderer_inter_delimiter) =
637 self.resolve_citation_delimiters(&effective_spec);
638 let content = self.render_citation_content::<F>(
639 citation,
640 &effective_spec,
641 renderer_delimiter,
642 renderer_inter_delimiter,
643 note_start_text_case,
644 run,
645 )?;
646 let output = self.apply_citation_input_affixes(citation, content, &fmt);
647 let wrapped = self.apply_spec_wrap_and_affixes(citation, &effective_spec, output, &fmt);
648
649 let finalized = if citation.sentence_start {
654 let case = crate::values::text_case::resolve_text_case(
655 citum_schema::options::titles::TextCase::CapitalizeFirst,
656 Some(self.locale.locale.as_str()),
657 );
658 crate::values::text_case::apply_text_case_markup_aware(&wrapped, case)
659 } else {
660 wrapped
661 };
662
663 Ok(fmt.finish(finalized))
664 }
665
666 pub fn process_citations(&self, citations: &[Citation]) -> Result<Vec<String>, ProcessorError> {
678 let mut run = self.begin_run();
679 self.process_citations_with_format::<crate::render::plain::PlainText>(citations, &mut run)
680 }
681
682 pub fn process_citations_with_format<F>(
694 &self,
695 citations: &[Citation],
696 run: &mut RunState,
697 ) -> Result<Vec<String>, ProcessorError>
698 where
699 F: crate::render::format::OutputFormat<Output = String>,
700 {
701 let mut normalized = self.normalize_note_context(citations, run);
702 self.annotate_positions(&mut normalized);
703 normalized
704 .iter()
705 .map(|citation| self.process_citation_with_format::<F>(citation, run))
706 .collect()
707 }
708}