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

//! Djot and org-mode inline markup rendering for free-text fields.

use super::format::OutputFormat;
use jotdown::{Attributes, Container, Event, Parser};

/// Ambient context used while rendering inline rich text.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct InlineRenderContext {
    /// Quote nesting depth inherited from an outer template wrapper.
    pub quote_depth: usize,
}

#[derive(Default)]
struct DjotFrame {
    children: Vec<String>,
    classes: Vec<String>,
    link_url: Option<String>,
    has_explicit_link: bool,
    last_char: Option<char>,
    /// True when this frame (or an ancestor) carries `.nocase` protection.
    case_protected: bool,
}

impl DjotFrame {
    fn push_rendered(&mut self, rendered: String, logical_last_char: Option<char>) {
        self.children.push(rendered);
        if let Some(ch) = logical_last_char {
            self.last_char = Some(ch);
        }
    }

    fn prev_opens_quote(&self) -> bool {
        self.last_char
            .is_none_or(|c| c.is_whitespace() || "([{\u{2018}\u{201C}'\"".contains(c))
    }
}

fn opening_quote_depth(
    context: InlineRenderContext,
    current_depth: usize,
    source_inner: bool,
) -> usize {
    if source_inner && current_depth <= context.quote_depth {
        context.quote_depth + 1
    } else {
        current_depth
    }
}

fn push_open_quote<F: OutputFormat<Output = String>>(frame: &mut DjotFrame, fmt: &F, depth: usize) {
    let (open, _) = fmt.quote_marks(depth);
    let logical_char = open.chars().next();
    frame.push_rendered(fmt.text(open), logical_char);
}

fn push_close_quote<F: OutputFormat<Output = String>>(
    frame: &mut DjotFrame,
    fmt: &F,
    depth: usize,
) {
    let (_, close) = fmt.quote_marks(depth);
    let logical_char = close.chars().last();
    frame.push_rendered(fmt.text(close), logical_char);
}

struct QuoteRenderState {
    depth: usize,
    stack: Vec<usize>,
}

impl QuoteRenderState {
    fn new(context: InlineRenderContext) -> Self {
        Self {
            depth: context.quote_depth,
            stack: Vec::new(),
        }
    }

    fn render_event<F: OutputFormat<Output = String>>(
        &mut self,
        frame: &mut DjotFrame,
        fmt: &F,
        context: InlineRenderContext,
        source_inner: bool,
        opens_quote: bool,
    ) {
        if opens_quote {
            let depth = opening_quote_depth(context, self.depth, source_inner);
            push_open_quote(frame, fmt, depth);
            self.stack.push(depth);
            self.depth = depth + 1;
        } else {
            let fallback_depth = context.quote_depth + usize::from(source_inner);
            let depth = self.stack.pop().unwrap_or(fallback_depth);
            push_close_quote(frame, fmt, depth);
            self.depth = self.stack.last().map_or(context.quote_depth, |d| d + 1);
        }
    }
}

fn span_classes(attrs: Option<&Attributes>) -> Vec<String> {
    attrs
        .into_iter()
        .flat_map(|attrs| attrs.iter())
        .filter_map(|(kind, val)| {
            use jotdown::AttributeKind;
            if matches!(kind, AttributeKind::Class) {
                Some(val.to_string())
            } else {
                None
            }
        })
        .flat_map(|classes| {
            classes
                .split_whitespace()
                .map(std::string::ToString::to_string)
                .collect::<Vec<_>>()
        })
        .collect()
}

/// Process a djot End container event, applying formatting and merging into parent frame.
fn handle_end_event<F: OutputFormat<Output = String>>(
    container: Container,
    frame: DjotFrame,
    parent: &mut DjotFrame,
    fmt: &F,
) {
    let inner_text = frame.children.join("");
    let formatted = match container {
        Container::Emphasis => fmt.emph(inner_text),
        Container::Strong => fmt.strong(inner_text),
        Container::Link(_, _) => {
            if let Some(url) = frame.link_url.as_deref() {
                fmt.link(url, inner_text)
            } else {
                inner_text
            }
        }
        Container::Span => {
            if frame
                .classes
                .iter()
                .any(|class| class == "smallcaps" || class == "small-caps")
            {
                fmt.small_caps(inner_text)
            } else {
                inner_text
            }
        }
        _ => inner_text,
    };
    parent.push_rendered(formatted, frame.last_char);
    parent.has_explicit_link |= frame.has_explicit_link;
}

fn render_djot_inline_internal<F, G>(
    src: &str,
    fmt: &F,
    context: InlineRenderContext,
    mut transform_text: G,
) -> (String, bool)
where
    F: OutputFormat<Output = String>,
    G: FnMut(&str) -> String,
{
    let parser = Parser::new(src);
    let mut stack = vec![DjotFrame::default()];
    let mut quote_state = QuoteRenderState::new(context);

    for event in parser {
        match event {
            Event::Start(container, attrs) => {
                let link_url = if let Container::Link(url, _) = &container {
                    Some(url.to_string())
                } else {
                    None
                };
                let classes = span_classes(Some(&attrs));
                let parent_protected = stack.last().is_some_and(|f| f.case_protected);
                let is_nocase = classes.iter().any(|c| c == "nocase");
                stack.push(DjotFrame {
                    case_protected: parent_protected || is_nocase,
                    has_explicit_link: link_url.is_some(),
                    link_url,
                    classes,
                    ..Default::default()
                });
            }
            Event::End(container) => {
                if let (Some(frame), Some(parent)) = (stack.pop(), stack.last_mut()) {
                    handle_end_event(container, frame, parent, fmt);
                }
            }
            Event::Str(s) => {
                if let Some(frame) = stack.last_mut() {
                    // Always call transform_text so stateful transforms (e.g., sentence-case)
                    // can update their internal state, even for .nocase-protected spans.
                    let transformed = transform_text(s.as_ref());
                    let render_text = if frame.case_protected {
                        s.to_string()
                    } else {
                        transformed
                    };
                    frame.push_rendered(fmt.text(&render_text), render_text.chars().last());
                }
            }
            Event::Symbol(sym) => {
                if let Some(frame) = stack.last_mut() {
                    frame.push_rendered(fmt.text(sym.as_ref()), sym.chars().last());
                }
            }
            Event::LeftSingleQuote => {
                if let Some(frame) = stack.last_mut() {
                    quote_state.render_event(frame, fmt, context, true, true);
                }
            }
            Event::RightSingleQuote => {
                if let Some(frame) = stack.last_mut() {
                    quote_state.render_event(frame, fmt, context, true, frame.prev_opens_quote());
                }
            }
            Event::LeftDoubleQuote => {
                if let Some(frame) = stack.last_mut() {
                    quote_state.render_event(frame, fmt, context, false, true);
                }
            }
            Event::RightDoubleQuote => {
                if let Some(frame) = stack.last_mut() {
                    quote_state.render_event(frame, fmt, context, false, frame.prev_opens_quote());
                }
            }
            Event::Softbreak | Event::Hardbreak => {
                if let Some(frame) = stack.last_mut() {
                    frame.push_rendered(fmt.text(" "), Some(' '));
                }
            }
            _ => {}
        }
    }

    stack
        .into_iter()
        .next()
        .map(|frame| (frame.children.join(""), frame.has_explicit_link))
        .unwrap_or_default()
}

/// Render djot inline markup and map events to `OutputFormat` methods.
///
/// Parses the input as djot inline markup and transforms container and text
/// events into formatted output. Block-level containers are collapsed to their
/// text content. Inline containers (emphasis, strong, links, etc.) are rendered
/// using the format's methods.
///
/// # Arguments
/// * `src` - Input string with djot inline markup
/// * `fmt` - `OutputFormat` implementation for rendering
///
/// # Returns
/// Formatted string with markup applied according to the `OutputFormat`'s methods
pub fn render_djot_inline<F: OutputFormat<Output = String>>(src: &str, fmt: &F) -> String {
    render_djot_inline_internal(src, fmt, InlineRenderContext::default(), str::to_string).0
}

/// Render djot inline markup with an ambient inline rendering context.
pub fn render_djot_inline_with_context<F: OutputFormat<Output = String>>(
    src: &str,
    fmt: &F,
    context: InlineRenderContext,
) -> String {
    render_djot_inline_internal(src, fmt, context, str::to_string).0
}

/// Render djot inline markup while transforming text leaves and returning link metadata.
pub(crate) fn render_djot_inline_with_transform<F, G>(
    src: &str,
    fmt: &F,
    transform_text: G,
) -> (String, bool)
where
    F: OutputFormat<Output = String>,
    G: FnMut(&str) -> String,
{
    render_djot_inline_internal(src, fmt, InlineRenderContext::default(), transform_text)
}

/// Render djot inline markup with text transforms and ambient context.
pub(crate) fn render_djot_inline_with_transform_and_context<F, G>(
    src: &str,
    fmt: &F,
    context: InlineRenderContext,
    transform_text: G,
) -> (String, bool)
where
    F: OutputFormat<Output = String>,
    G: FnMut(&str) -> String,
{
    render_djot_inline_internal(src, fmt, context, transform_text)
}

/// Render org-mode inline markup by walking the orgize event stream.
///
/// Parses `src` as org-mode and maps inline elements to `OutputFormat` methods:
/// bold (`*text*`) → `strong`, italic (`/text/`) → `emph`, verbatim/code →
/// `text` (stripped), links (`[[url][desc]]`) → `link`, plain text → `text`.
/// Container elements (Bold, Italic) are collected via a stack so nested
/// markup is handled correctly.
pub fn render_org_inline<F: OutputFormat<Output = String>>(src: &str, fmt: &F) -> String {
    use orgize::Event;
    use orgize::Org;
    use orgize::elements::Element;

    let org = Org::parse(src);
    // Stack of (tag, accumulated_children) for open containers.
    // Tags: 0 = Bold, 1 = Italic, 2 = root paragraph accumulator.
    let mut stack: Vec<(u8, String)> = vec![(2, String::new())];

    for event in org.iter() {
        match event {
            Event::Start(Element::Bold) => stack.push((0, String::new())),
            Event::Start(Element::Italic) => stack.push((1, String::new())),
            Event::End(Element::Bold) => {
                if let Some((0, inner)) = stack.pop() {
                    let rendered = fmt.strong(inner);
                    if let Some(top) = stack.last_mut() {
                        top.1.push_str(&rendered);
                    }
                }
            }
            Event::End(Element::Italic) => {
                if let Some((1, inner)) = stack.pop() {
                    let rendered = fmt.emph(inner);
                    if let Some(top) = stack.last_mut() {
                        top.1.push_str(&rendered);
                    }
                }
            }
            Event::Start(Element::Link(link)) => {
                let desc = link.desc.as_deref().unwrap_or(&link.path);
                let rendered = fmt.link(&link.path, fmt.text(desc));
                if let Some(top) = stack.last_mut() {
                    top.1.push_str(&rendered);
                }
            }
            Event::Start(Element::Text { value }) => {
                if let Some(top) = stack.last_mut() {
                    top.1.push_str(&fmt.text(value));
                }
            }
            Event::Start(Element::Verbatim { value } | Element::Code { value }) => {
                if let Some(top) = stack.last_mut() {
                    top.1.push_str(&fmt.text(value));
                }
            }
            _ => {}
        }
    }

    stack.into_iter().next().map(|(_, s)| s).unwrap_or_default()
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::indexing_slicing,
    clippy::todo,
    clippy::unimplemented,
    clippy::unreachable,
    clippy::get_unwrap,
    reason = "Panicking is acceptable and often desired in tests."
)]
mod tests {
    use super::*;
    use crate::render::html::Html;
    use crate::render::plain::PlainText;
    use crate::render::typst::Typst;

    #[test]
    fn test_djot_emphasis_plain() {
        let fmt = PlainText;
        let result = render_djot_inline("_foo_", &fmt);
        // PlainText.emph() wraps content in _..._
        assert_eq!(result, "_foo_");
    }

    #[test]
    fn test_djot_strong_single_asterisk() {
        let fmt = PlainText;
        // jotdown uses * for strong (bold), not **
        let result = render_djot_inline("*bar*", &fmt);
        // PlainText.strong() wraps content in **...**
        assert_eq!(result, "**bar**");
    }

    #[test]
    fn test_djot_unicode_math() {
        let fmt = PlainText;
        let result = render_djot_inline("H₂O", &fmt);
        assert_eq!(result, "H₂O");
    }

    #[test]
    fn test_djot_plain_no_markup() {
        let fmt = PlainText;
        let result = render_djot_inline("plain text with no markup", &fmt);
        assert_eq!(result, "plain text with no markup");
    }

    #[test]
    fn test_djot_combined_formatting() {
        let fmt = PlainText;
        // In djot, _text_ is emphasis and *text* is strong
        let result = render_djot_inline("_emphasized *bold* text_", &fmt);
        // Emphasis wraps in _..._. Inside that, strong wraps in **...**
        assert_eq!(result, "_emphasized **bold** text_");
    }

    #[test]
    fn test_djot_link() {
        let fmt = PlainText;
        // In djot, [text](url) is a link
        let result = render_djot_inline("[click here](https://example.com)", &fmt);
        // PlainText.link() just renders the link text (ignores URL)
        assert_eq!(result, "click here");
    }

    #[test]
    fn test_djot_nested_formatting_preserves_typst_markup() {
        let fmt = Typst;
        let result = render_djot_inline("_emphasized *bold* text_", &fmt);
        assert_eq!(result, "#emph[emphasized *bold* text]");
    }

    #[test]
    fn test_djot_nested_link_preserves_inner_markup_html() {
        let fmt = Html;
        let result = render_djot_inline("[_linked emphasis_](https://example.com)", &fmt);
        assert_eq!(
            result,
            r#"<a href="https://example.com"><em>linked emphasis</em></a>"#
        );
    }

    #[test]
    fn test_djot_quotes_inside_emphasis_open_correctly() {
        let fmt = PlainText;
        let result = render_djot_inline("_\"Parmenides\" dialogue_", &fmt);
        assert_eq!(result, "_“Parmenides” dialogue_");
    }

    #[test]
    fn test_djot_quotes_with_ambient_quote_depth_use_inner_marks() {
        let fmt = PlainText;
        let result = render_djot_inline_with_context(
            "\"Parmenides\" dialogue",
            &fmt,
            InlineRenderContext { quote_depth: 1 },
        );
        assert_eq!(result, "‘Parmenides’ dialogue");
    }

    #[test]
    fn test_djot_nested_quotes_alternate_marks() {
        let fmt = PlainText;
        let result = render_djot_inline("\"outer \"inner\" claim\"", &fmt);
        assert_eq!(result, "“outer ‘inner’ claim”");
    }

    #[test]
    fn test_djot_quotes_inside_emphasis_use_ambient_quote_depth() {
        let fmt = PlainText;
        let result = render_djot_inline_with_context(
            "_\"Parmenides\" dialogue_",
            &fmt,
            InlineRenderContext { quote_depth: 1 },
        );
        assert_eq!(result, "_‘Parmenides’ dialogue_");
    }

    #[test]
    fn test_org_plain_text() {
        let fmt = PlainText;
        let result = render_org_inline("plain text with no markup", &fmt);
        assert_eq!(result, "plain text with no markup");
    }

    #[test]
    fn test_org_bold() {
        let fmt = PlainText;
        // PlainText.strong() wraps in **...**
        let result = render_org_inline("*bold*", &fmt);
        assert_eq!(result, "**bold**");
    }

    #[test]
    fn test_org_italic() {
        let fmt = PlainText;
        // PlainText.emph() wraps in _..._
        let result = render_org_inline("/italic/", &fmt);
        assert_eq!(result, "_italic_");
    }
}