citum-engine 0.60.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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
/*
SPDX-License-Identifier: MIT OR Apache-2.0
SPDX-FileCopyrightText: © 2023-2026 Bruce D'Arcus and Citum contributors
*/

//! Author-substitution logic for contributor rendering.
//!
//! When a reference has no author, this module handles the fallback chain:
//! editor → title → translator, as configured by the style's `substitute` block.

use crate::processor::rendering::get_variable_key;
use crate::reference::Reference;
use crate::render::format::OutputFormat;
use crate::values::{ProcHints, ProcValues, RenderContext, RenderOptions};
use citum_schema::options::{RoleLabelPreset, SubstituteKey};
use citum_schema::reference::Title;
use citum_schema::template::{ContributorRole, Rendering, TemplateComponent, TemplateContributor};

enum ResolvedRole {
    BuiltIn(ContributorRole),
    Custom(String),
}

impl ResolvedRole {
    fn key(&self) -> &str {
        match self {
            Self::BuiltIn(role) => role.as_str(),
            Self::Custom(role) => role.as_str(),
        }
    }

    fn built_in(&self) -> Option<&ContributorRole> {
        match self {
            Self::BuiltIn(role) => Some(role),
            Self::Custom(_) => None,
        }
    }
}

fn normalize_role_key(value: &str) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return None;
    }

    let canonical = trimmed
        .chars()
        .map(|ch| match ch {
            '_' => '-',
            other => other.to_ascii_lowercase(),
        })
        .collect::<String>();

    canonical
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || ch == '-')
        .then_some(canonical)
}

fn parse_known_role(value: &str) -> Option<ContributorRole> {
    Some(match value {
        "author" => ContributorRole::Author,
        "chair" => ContributorRole::Chair,
        "editor" => ContributorRole::Editor,
        "translator" => ContributorRole::Translator,
        "director" => ContributorRole::Director,
        "composer" => ContributorRole::Composer,
        "illustrator" => ContributorRole::Illustrator,
        "collection-editor" => ContributorRole::CollectionEditor,
        "container-author" => ContributorRole::ContainerAuthor,
        "editorial-director" => ContributorRole::EditorialDirector,
        "textual-editor" => ContributorRole::TextualEditor,
        "original-author" => ContributorRole::OriginalAuthor,
        "reviewed-author" => ContributorRole::ReviewedAuthor,
        "recipient" => ContributorRole::Recipient,
        "interviewer" => ContributorRole::Interviewer,
        "guest" => ContributorRole::Guest,
        "inventor" => ContributorRole::Inventor,
        "counsel" => ContributorRole::Counsel,
        _ => return None,
    })
}

fn resolve_role_key(value: &str) -> Option<ResolvedRole> {
    let canonical = normalize_role_key(value)?;
    Some(
        parse_known_role(&canonical)
            .map(ResolvedRole::BuiltIn)
            .unwrap_or(ResolvedRole::Custom(canonical)),
    )
}

fn lookup_role_contributor(
    reference: &Reference,
    role: &ResolvedRole,
) -> Option<citum_schema::reference::contributor::Contributor> {
    use citum_schema::reference::ContributorRole as DataRole;

    match role {
        ResolvedRole::BuiltIn(ContributorRole::Editor) => reference.editor(),
        ResolvedRole::BuiltIn(ContributorRole::Translator) => reference.translator(),
        ResolvedRole::BuiltIn(ContributorRole::Director) => {
            reference.contributor(DataRole::Director)
        }
        ResolvedRole::BuiltIn(ContributorRole::Composer) => {
            reference.contributor(DataRole::Composer)
        }
        ResolvedRole::BuiltIn(ContributorRole::Illustrator) => {
            reference.contributor(DataRole::Illustrator)
        }
        ResolvedRole::BuiltIn(ContributorRole::ContainerAuthor) => {
            reference.contributor(DataRole::Unknown("container-author".to_string()))
        }
        ResolvedRole::BuiltIn(ContributorRole::CollectionEditor) => {
            reference.contributor(DataRole::Unknown("collection-editor".to_string()))
        }
        ResolvedRole::BuiltIn(ContributorRole::EditorialDirector) => {
            reference.contributor(DataRole::Unknown("editorial-director".to_string()))
        }
        ResolvedRole::BuiltIn(ContributorRole::TextualEditor) => {
            reference.contributor(DataRole::Unknown("textual-editor".to_string()))
        }
        ResolvedRole::BuiltIn(ContributorRole::OriginalAuthor) => {
            reference.contributor(DataRole::Unknown("original-author".to_string()))
        }
        ResolvedRole::BuiltIn(ContributorRole::ReviewedAuthor) => {
            reference.contributor(DataRole::Unknown("reviewed-author".to_string()))
        }
        ResolvedRole::BuiltIn(ContributorRole::Recipient) => {
            reference.contributor(DataRole::Recipient)
        }
        ResolvedRole::BuiltIn(ContributorRole::Interviewer) => {
            reference.contributor(DataRole::Interviewer)
        }
        ResolvedRole::BuiltIn(ContributorRole::Guest) => reference.contributor(DataRole::Guest),
        ResolvedRole::BuiltIn(ContributorRole::Chair) => {
            reference.contributor(DataRole::Unknown("chair".to_string()))
        }
        ResolvedRole::BuiltIn(ContributorRole::Inventor) => {
            reference.contributor(DataRole::Unknown("inventor".to_string()))
        }
        ResolvedRole::BuiltIn(ContributorRole::Counsel) => {
            reference.contributor(DataRole::Unknown("counsel".to_string()))
        }
        ResolvedRole::Custom(role) => match role.as_str() {
            "compiler" => reference.contributor(DataRole::Compiler),
            "performer" => reference.contributor(DataRole::Performer),
            "narrator" => reference.contributor(DataRole::Narrator),
            "host" => reference.contributor(DataRole::Host),
            "producer" | "executive-producer" => reference.contributor(DataRole::Producer),
            "writer" => reference.contributor(DataRole::Writer),
            _ => reference.contributor(DataRole::Unknown(role.clone())),
        },
        _ => None,
    }
}

/// Resolve all multilingual names for a contributor using the current options.
///
/// Eliminates the copy-paste resolution pattern across Editor, Translator, and
/// primary-contributor paths.
pub(super) fn resolve_multilingual_for_contrib(
    contrib: &citum_schema::reference::contributor::Contributor,
    options: &RenderOptions<'_>,
) -> Vec<crate::reference::FlatName> {
    let mode = options
        .config
        .multilingual
        .as_ref()
        .and_then(|m| m.name_mode.as_ref());
    let preferred_transliteration = options
        .config
        .multilingual
        .as_ref()
        .and_then(|m| m.preferred_transliteration.as_deref());
    let preferred_script = options
        .config
        .multilingual
        .as_ref()
        .and_then(|m| m.preferred_script.as_ref());
    crate::values::resolve_multilingual_name(
        contrib,
        mode,
        preferred_transliteration,
        preferred_script,
        &options.locale.locale,
    )
}

/// Resolve substitute-path role labels for a rendered fallback contributor.
fn resolve_substitute_role_labels<F: OutputFormat<Output = String>>(
    component: &TemplateContributor,
    role: &ResolvedRole,
    names_count: usize,
    options: &RenderOptions<'_>,
    effective_rendering: &Rendering,
    fmt: &F,
    substitute: &citum_schema::options::Substitute,
) -> (Option<String>, Option<String>) {
    if options.context != RenderContext::Bibliography
        || role
            .built_in()
            .is_some_and(|known| super::is_role_label_omitted(options, known))
    {
        return (None, None);
    }

    let preset = substitute
        .contributor_role_form
        .as_deref()
        .and_then(|form| match form {
            "short" => Some(RoleLabelPreset::ShortSuffix),
            "long" => Some(RoleLabelPreset::LongSuffix),
            _ => None,
        })
        .or_else(|| {
            options
                .config
                .contributors
                .as_ref()
                .and_then(|contributors| {
                    role.built_in()
                        .and_then(|known| contributors.effective_role_label_preset(known))
                })
        });

    preset
        .and_then(|selected| {
            if component.contributor == ContributorRole::Author
                && matches!(
                    selected,
                    RoleLabelPreset::VerbPrefix | RoleLabelPreset::VerbShortPrefix
                )
            {
                return None;
            }

            role.built_in().map(|known| {
                super::labels::resolve_role_label_preset::<F>(
                    known,
                    selected,
                    names_count,
                    None,
                    effective_rendering,
                    options,
                    fmt,
                )
            })
        })
        .unwrap_or((None, None))
}

/// Format a substitute contributor using the current role-aware config path.
#[allow(
    clippy::too_many_arguments,
    reason = "Role-aware substitute formatting needs shared engine state until this module is refactored."
)]
fn resolve_named_substitute<F: OutputFormat<Output = String>>(
    role: &ResolvedRole,
    contributor: &citum_schema::reference::contributor::Contributor,
    component: &TemplateContributor,
    hints: &ProcHints,
    options: &RenderOptions<'_>,
    reference: &Reference,
    effective_rendering: &Rendering,
    fmt: &F,
    substitute: &citum_schema::options::Substitute,
) -> Option<ProcValues<F::Output>> {
    let names_vec = resolve_multilingual_for_contrib(contributor, options);
    if names_vec.is_empty() {
        return None;
    }

    let effective_name_order = component.name_order.as_ref().or_else(|| {
        role.built_in().and_then(|known| {
            options
                .config
                .contributors
                .as_ref()
                .and_then(|contributors| contributors.effective_role_name_order(known))
        })
    });

    // Priority chain for name_form:
    // 1. component.name_form (TemplateContributor-level override - highest priority)
    // 2. effective_rendering.name_form (from overrides, second priority)
    // 3. config (options-level fallback)
    let effective_name_form = component.name_form.or(effective_rendering.name_form);

    let name_overrides = super::names::NamesOverrides {
        name_order: effective_name_order,
        sort_separator: component.sort_separator.as_ref(),
        shorten: component.shorten.as_ref(),
        and: component.and.as_ref(),
        initialize_with: effective_rendering.initialize_with.as_ref(),
        name_form: effective_name_form,
    };
    let formatted =
        super::names::format_names(&names_vec, &component.form, options, &name_overrides, hints);
    let (prefix, suffix) = resolve_substitute_role_labels::<F>(
        component,
        role,
        names_vec.len(),
        options,
        effective_rendering,
        fmt,
        substitute,
    );

    let url = crate::values::resolve_effective_url(
        component.links.as_ref(),
        options.config.links.as_ref(),
        reference,
        citum_schema::options::LinkAnchor::Component,
    );

    let substituted_key = role.built_in().map_or_else(
        || Some(format!("contributor:{}", role.key())),
        |known| {
            get_variable_key(&TemplateComponent::Contributor(TemplateContributor {
                contributor: known.clone(),
                rendering: component.rendering.clone(),
                ..Default::default()
            }))
        },
    );

    Some(ProcValues {
        value: fmt.text(&formatted),
        prefix,
        suffix,
        url,
        substituted_key,
        pre_formatted: true,
    })
}

/// Check if a role should be suppressed by role-substitute configuration.
///
/// Returns true if this role appears as a fallback in some other role's chain
/// AND that primary role has data on the reference.
pub(super) fn is_role_suppressed_by_substitute(
    role: &ContributorRole,
    substitute: &citum_schema::options::Substitute,
    reference: &Reference,
) -> bool {
    let role_str = role.as_str();

    for (primary_role_str, fallback_chain) in &substitute.role_substitute {
        // Check if this role is in the fallback chain
        if !fallback_chain
            .iter()
            .filter_map(|entry| resolve_role_key(entry))
            .any(|entry| entry.key() == role_str)
        {
            continue;
        }

        if let Some(primary_role) = resolve_role_key(primary_role_str)
            && lookup_role_contributor(reference, &primary_role).is_some()
        {
            return true;
        }
    }

    false
}

fn find_role_substitute_chain<'a>(
    substitute: &'a citum_schema::options::Substitute,
    primary_role: &ContributorRole,
) -> Option<&'a Vec<String>> {
    let primary_role_str = primary_role.as_str();

    substitute
        .role_substitute
        .get(primary_role_str)
        .or_else(|| {
            substitute
                .role_substitute
                .iter()
                .find_map(|(configured_role, fallback_chain)| {
                    resolve_role_key(configured_role)
                        .filter(|resolved| resolved.key() == primary_role_str)
                        .map(|_| fallback_chain)
                })
        })
}

/// Attempt to substitute a non-author contributor field via role-substitute fallback chain.
///
/// Returns `Some(ProcValues)` if a substitute from the chain was found, `None` if the chain
/// is exhausted with no result.
#[allow(
    clippy::too_many_arguments,
    reason = "Role-aware role-substitute needs shared engine state."
)]
pub(super) fn resolve_role_substitute<F: OutputFormat<Output = String>>(
    primary_role: &ContributorRole,
    component: &TemplateContributor,
    hints: &ProcHints,
    options: &RenderOptions<'_>,
    reference: &Reference,
    effective_rendering: &Rendering,
    fmt: &F,
    substitute: &citum_schema::options::Substitute,
) -> Option<ProcValues<F::Output>> {
    let fallback_chain = find_role_substitute_chain(substitute, primary_role)?;

    for fallback_role_str in fallback_chain {
        let Some(fallback_role) = resolve_role_key(fallback_role_str) else {
            continue;
        };

        if let Some(contrib) = lookup_role_contributor(reference, &fallback_role) {
            return resolve_named_substitute(
                &fallback_role,
                &contrib,
                component,
                hints,
                options,
                reference,
                effective_rendering,
                fmt,
                substitute,
            );
        }
    }

    None
}

/// Attempt to substitute an empty author field with editor, title, or translator.
///
/// Returns `Some(ProcValues)` if a substitute was found, `None` if the chain
/// is exhausted with no result (caller should then return `None` from `values()`).
pub(super) fn resolve_author_substitute<F: OutputFormat<Output = String>>(
    component: &TemplateContributor,
    hints: &ProcHints,
    options: &RenderOptions<'_>,
    reference: &Reference,
    effective_rendering: &Rendering,
    fmt: &F,
    substitute: &citum_schema::options::Substitute,
) -> Option<ProcValues<F::Output>> {
    for key in &substitute.template {
        match key {
            SubstituteKey::Editor => {
                if let Some(editors) = reference.editor()
                    && let Some(result) = resolve_named_substitute(
                        &ResolvedRole::BuiltIn(ContributorRole::Editor),
                        &editors,
                        component,
                        hints,
                        options,
                        reference,
                        effective_rendering,
                        fmt,
                        substitute,
                    )
                {
                    return Some(result);
                }
            }
            SubstituteKey::Title => {
                if let Some(title) = reference.title() {
                    // In citation context use a short-form title (main title only,
                    // no subtitle) so the substitute doesn't bloat the in-text cite.
                    // In bibliography use the full display form.
                    let title_str = match options.context {
                        RenderContext::Citation => match title {
                            Title::Structured(s) => s.main.clone(),
                            Title::MultiStructured(v) => {
                                v.first().map(|(_, s)| s.main.clone()).unwrap_or_default()
                            }
                            Title::Shorthand(abbr, _) => abbr.clone(),
                            _ => title.to_string(),
                        },
                        _ => title.to_string(),
                    };
                    // In citations: quote the title per CSL conventions.
                    // In bibliography: use title as-is (will be styled normally).
                    let value = if options.context == RenderContext::Citation {
                        fmt.quote(fmt.text(&title_str))
                    } else {
                        fmt.text(&title_str)
                    };

                    let url = crate::values::resolve_effective_url(
                        component.links.as_ref(),
                        options.config.links.as_ref(),
                        reference,
                        citum_schema::options::LinkAnchor::Title,
                    );

                    return Some(ProcValues {
                        value,
                        prefix: None,
                        suffix: None,
                        url,
                        substituted_key: Some("title:Primary".to_string()),
                        pre_formatted: true,
                    });
                }
            }
            SubstituteKey::Translator => {
                if let Some(translators) = reference.translator()
                    && let Some(result) = resolve_named_substitute(
                        &ResolvedRole::BuiltIn(ContributorRole::Translator),
                        &translators,
                        component,
                        hints,
                        options,
                        reference,
                        effective_rendering,
                        fmt,
                        substitute,
                    )
                {
                    return Some(result);
                }
            }
        }
    }

    None
}