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 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 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 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 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 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 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 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 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 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 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 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 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 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 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}