asciidoc-parser 0.29.0

Parser for AsciiDoc format
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
528
529
530
531
532
533
534
535
536
537
538
//! Generic block captioning and numbering.
//!
//! Some block contexts are *captionable*: when such a block has a title, it is
//! given a caption that prepends a label and an automatically incremented
//! number to that title (e.g. an example block titled "Onomatopoeia" renders
//! "Example 1. Onomatopoeia"). This mirrors Asciidoctor, where the behavior is
//! granted not by a dedicated block type but by the block's context appearing
//! in a lookup table that maps it to the document attribute supplying its
//! label.
//!
//! The caption and the bare number are computed once, during parsing, and
//! stored as first-class members of the block (see [`IsBlock::caption`] and
//! [`IsBlock::number`]); the converter simply concatenates the caption prefix
//! and the title. Numbers are assigned in document order as blocks finish
//! parsing, so a nested captioned block is numbered before its container.
//!
//! [`IsBlock::caption`]: crate::blocks::IsBlock::caption
//! [`IsBlock::number`]: crate::blocks::IsBlock::number

use crate::{
    Parser, attributes::Attrlist, blocks::is_built_in_context, document::InterpretedValue,
};

/// Maps a block context to the document attribute that supplies its caption
/// label, or `None` if the context is not captionable.
///
/// This mirrors Asciidoctor's `CAPTION_ATTRIBUTE_NAMES`. The label attribute
/// for each context defaults to a locale-specific value (e.g. `example-caption`
/// defaults to "Example", `table-caption` to "Table"); unsetting it disables
/// numbering for that context.
pub(crate) fn caption_attribute_name(context: &str) -> Option<&'static str> {
    match context {
        "example" => Some("example-caption"),
        "figure" => Some("figure-caption"),
        "listing" => Some("listing-caption"),
        "table" => Some("table-caption"),
        _ => None,
    }
}

/// The caption prefix and bare number assigned to a block.
///
/// The `prefix` is the text prepended to the block's title (e.g. `"Example 1.
/// "`, including the trailing separator and space). The `number` is the bare
/// counter value (e.g. `1`); it is `None` when an explicit caption override is
/// in effect (overrides are not numbered) and also when an auto-numbered
/// block's context counter holds a non-integer value (see [`Caption::number`]).
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct Caption {
    /// The caption prefix prepended to the title (e.g. `"Example 1. "`).
    pub(crate) prefix: String,

    /// The bare counter value, or `None` when the block is not numbered.
    ///
    /// This is `None` for an explicit (unnumbered) caption override. Because a
    /// context's caption number is the document attribute `<context>-number`
    /// (shared with `{counter:<context>-number}`), it is *also* `None` for an
    /// auto-numbered block when that attribute has been set to a non-integer
    /// value (e.g. `:table-number: A`): the prefix still shows the value, but
    /// there is no bare integer to expose here.
    pub(crate) number: Option<usize>,
}

/// Computes the caption for a block from its raw context and attribute list.
///
/// This is the entry point used while parsing a block. It resolves the
/// captioning context (a block style naming a built-in context, such as
/// `[example]` over an open block, takes precedence over the raw context –
/// mirroring [`resolved_context`]) and the explicit caption override, then
/// delegates to [`assign_caption`]:
///
/// * a `[caption=...]` attribute supplies a verbatim, unnumbered override;
/// * a collapsible example has its caption suppressed (kept unnumbered),
///   exactly as Asciidoctor's parser does.
///
/// [`resolved_context`]: crate::blocks::IsBlock::resolved_context
pub(crate) fn assign_block_caption(
    parser: &mut Parser,
    raw_context: &str,
    attrlist: Option<&Attrlist<'_>>,
    has_title: bool,
) -> Option<Caption> {
    let resolved_context = attrlist
        .and_then(|attrlist| attrlist.block_style())
        .filter(|style| is_built_in_context(style))
        .unwrap_or(raw_context);

    let explicit_caption =
        if let Some(caption) = attrlist.and_then(|attrlist| attrlist.named_attribute("caption")) {
            Some(caption.value().to_string())
        } else if resolved_context == "example"
            && attrlist.is_some_and(|attrlist| attrlist.has_option("collapsible"))
        {
            Some(String::new())
        } else {
            None
        };

    assign_caption(
        parser,
        resolved_context,
        has_title,
        explicit_caption.as_deref(),
    )
}

/// Computes the caption for a block, following Asciidoctor's `assign_caption`.
///
/// Returns `None` (no caption, no number) when:
/// * the block has no title (`has_title` is `false`) – untitled blocks are
///   never captioned or counted;
/// * an explicit caption override is present but empty (e.g. `[caption=]`, or a
///   collapsible example whose caption is suppressed);
/// * a document-wide `caption` attribute is present but empty (bare `:caption:`
///   or `:caption:` with an empty value); or
/// * the context is not captionable, or its caption attribute is unset.
///
/// When a non-empty explicit `caption` override is supplied (from a
/// `[caption=]` attribute) – or a non-empty document-wide `caption` attribute
/// is present – that value is used verbatim as the prefix, with **no** number
/// assigned. Otherwise the label comes from the context's caption attribute and
/// the document-wide counter for that context is incremented, producing a
/// `"<label> <n>. "` prefix.
pub(crate) fn assign_caption(
    parser: &mut Parser,
    context: &str,
    has_title: bool,
    explicit_caption: Option<&str>,
) -> Option<Caption> {
    // An untitled block is never captioned or counted. Likewise, captioning
    // applies only to captionable contexts: this gate matches Asciidoctor, where
    // `assign_caption` is only invoked when the block's context is a key in
    // `CAPTION_ATTRIBUTE_NAMES`, so an override such as a document-wide `caption`
    // attribute never leaks onto, say, an ordinary titled paragraph.
    if !has_title {
        return None;
    }
    let attr_name = caption_attribute_name(context)?;

    // An explicit caption override (from `[caption=...]`) wins and is never
    // numbered. An explicitly empty override suppresses the caption entirely
    // (this is how a collapsible example is kept unnumbered).
    if let Some(value) = explicit_caption {
        return if value.is_empty() {
            None
        } else {
            Some(Caption {
                prefix: value.to_string(),
                number: None,
            })
        };
    }

    // A *present* document-wide `caption` attribute overrides the per-context
    // label and likewise skips the counter, mirroring Asciidoctor, which treats
    // the attribute as present-or-not (an empty string is truthy in Ruby). A
    // non-empty value is used verbatim as the prefix; an empty one (bare
    // `:caption:`, resolving to `Set`, or `:caption:` with an empty value,
    // resolving to `Value("")`) suppresses the caption entirely – exactly like
    // an empty `[caption=]` override. Only a truly unset (`:caption!:`) or
    // absent attribute falls through to auto-numbering.
    match parser.attribute_value("caption") {
        InterpretedValue::Value(value) if !value.is_empty() => {
            return Some(Caption {
                prefix: value,
                number: None,
            });
        }

        InterpretedValue::Value(_) | InterpretedValue::Set => {
            return None;
        }

        InterpretedValue::Unset => {}
    }

    // Otherwise build "<label> <n>. " from the context's caption attribute,
    // consuming the next value of that context's document-wide counter. When the
    // caption attribute is unset (or empty), the block keeps its title but
    // receives no caption and no number.
    match parser.attribute_value(attr_name) {
        InterpretedValue::Value(label) if !label.is_empty() => {
            // The caption number is the counter named `<context>-number`, shared
            // with any `{counter:<context>-number}` reference in the document.
            // A captioning counter advances (and stays readable as) its
            // attribute even when locked, mirroring Asciidoctor's
            // `increment_and_store_counter`.
            let value = parser.counter_for_caption(&format!("{context}-number"), None);
            let prefix = format!("{label} {value}. ");
            Some(Caption {
                prefix,
                number: value.parse::<usize>().ok(),
            })
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]

    use crate::{blocks::IsBlock, tests::prelude::*};

    /// Returns the (caption, number) of the first nested block in `input`.
    fn first_block_caption(input: &str) -> (Option<String>, Option<usize>) {
        let doc = Parser::default().parse(input);
        let block = doc.child_blocks().next().expect("expected a block");
        (block.caption().map(str::to_string), block.number())
    }

    #[test]
    fn caption_attribute_name_lookup() {
        assert_eq!(
            super::caption_attribute_name("example"),
            Some("example-caption")
        );
        assert_eq!(
            super::caption_attribute_name("figure"),
            Some("figure-caption")
        );
        assert_eq!(
            super::caption_attribute_name("listing"),
            Some("listing-caption")
        );
        assert_eq!(
            super::caption_attribute_name("table"),
            Some("table-caption")
        );
        assert_eq!(super::caption_attribute_name("sidebar"), None);
        assert_eq!(super::caption_attribute_name("paragraph"), None);
    }

    #[test]
    fn untitled_block_is_not_captioned() {
        assert_eq!(first_block_caption("====\nbody.\n===="), (None, None));
    }

    #[test]
    fn titled_example_is_numbered_by_default() {
        assert_eq!(
            first_block_caption(".Title\n====\nbody.\n===="),
            (Some("Example 1. ".to_string()), Some(1))
        );
    }

    #[test]
    fn counter_is_per_context_and_document_wide() {
        // Two titled examples share one sequence; an untitled example between
        // them consumes no number.
        let doc =
            Parser::default().parse(".One\n====\na\n====\n\n====\nb\n====\n\n.Two\n====\nc\n====");
        let numbers: Vec<_> = doc.child_blocks().map(|b| b.number()).collect();
        assert_eq!(numbers, vec![Some(1), None, Some(2)]);
    }

    #[test]
    fn custom_label_from_caption_attribute() {
        assert_eq!(
            first_block_caption(":example-caption: Exhibit\n\n.Title\n====\nbody.\n===="),
            (Some("Exhibit 1. ".to_string()), Some(1))
        );
    }

    #[test]
    fn unset_caption_attribute_disables_numbering() {
        assert_eq!(
            first_block_caption(":!example-caption:\n\n.Title\n====\nbody.\n===="),
            (None, None)
        );
    }

    #[test]
    fn explicit_caption_attribute_is_verbatim_and_unnumbered() {
        assert_eq!(
            first_block_caption("[caption=\"Sample: \"]\n.Title\n====\nbody.\n===="),
            (Some("Sample: ".to_string()), None)
        );
    }

    #[test]
    fn empty_explicit_caption_suppresses_caption() {
        assert_eq!(
            first_block_caption("[caption=]\n.Title\n====\nbody.\n===="),
            (None, None)
        );
    }

    #[test]
    fn document_caption_attribute_overrides_label() {
        // A document-wide `caption` attribute supplies a verbatim, unnumbered
        // label for captionable blocks ...
        assert_eq!(
            first_block_caption(":caption: Sample\n\n.Title\n====\nbody.\n===="),
            (Some("Sample".to_string()), None)
        );

        // ... but it must not leak onto a non-captionable context such as an
        // ordinary titled paragraph.
        assert_eq!(
            first_block_caption(":caption: Sample\n\n.Title\nplain paragraph."),
            (None, None)
        );
    }

    #[test]
    fn empty_document_caption_does_not_produce_xref_signifier() {
        // A block suppressed by an empty document `caption` has no caption at
        // all, so a cross-reference to it falls back to the block title rather
        // than a "<label> <n>" signifier: the block was never numbered, so no
        // signifier must be registered for it.
        assert_eq!(
            rendered_paragraphs(&Parser::default().parse(concat!(
                ":caption:\n\n",
                "[#ex]\n.second example\n====\nbody.\n====\n\n",
                "See <<ex>>.",
            ))),
            vec![
                "body.".to_string(),
                "See <a href=\"#ex\">second example</a>.".to_string(),
            ]
        );
    }

    #[test]
    fn empty_document_caption_attribute_suppresses_caption() {
        // A *present* but empty document `caption` attribute suppresses the
        // caption entirely, matching Asciidoctor. Both the bare form (resolving
        // to `Set`) ...
        assert_eq!(
            first_block_caption(":caption:\n\n.Title\n====\nbody.\n===="),
            (None, None)
        );

        // ... and an explicitly empty value (resolving to `Value("")`) leave the
        // block with just its title and no number.
        assert_eq!(
            first_block_caption(":caption: \n\n.Title\n====\nbody.\n===="),
            (None, None)
        );
    }

    #[test]
    fn empty_document_caption_attribute_consumes_no_counter() {
        // A block suppressed by an empty document `caption` must not advance the
        // context counter: toggling `caption` on, then off, then relabeling must
        // number the surviving example blocks 1 and 2 (not 1 and 3). This
        // mirrors Asciidoctor's `blocks_test.rb` "automatic caption can be turned
        // off and on and modified".
        let doc = Parser::default().parse(concat!(
            ".first example\n====\nan example\n====\n\n",
            ":caption:\n\n",
            ".second example\n====\nanother example\n====\n\n",
            ":caption!:\n:example-caption: Exhibit\n\n",
            ".third example\n====\nyet another example\n====",
        ));

        // The mid-document attribute entries also surface as (uncaptioned)
        // child blocks, so restrict this to the example blocks.
        let captions: Vec<_> = doc
            .child_blocks()
            .filter(|b| b.raw_context().as_ref() == "example")
            .map(|b| b.caption().map(str::to_string))
            .collect();

        assert_eq!(
            captions,
            vec![
                Some("Example 1. ".to_string()),
                None,
                Some("Exhibit 2. ".to_string())
            ]
        );
    }

    #[test]
    fn collapsible_example_is_unnumbered() {
        // A collapsible example suppresses its caption (and number), and does not
        // consume a counter value, so a following example is still "Example 1".
        let doc = Parser::default()
            .parse("[%collapsible]\n====\nhidden\n====\n\n.Title\n====\nbody.\n====");
        let numbers: Vec<_> = doc.child_blocks().map(|b| b.number()).collect();
        assert_eq!(numbers, vec![None, Some(1)]);
    }

    #[test]
    fn listing_caption_is_unset_by_default() {
        // Unlike the other captionable contexts, `listing-caption` is not set by
        // default, so a titled listing keeps only its title.
        assert_eq!(
            first_block_caption(".Title\n----\ncode\n----"),
            (None, None)
        );
    }

    #[test]
    fn listing_block_uses_listing_caption_when_set() {
        assert_eq!(
            first_block_caption(":listing-caption: Listing\n\n.Title\n----\ncode\n----"),
            (Some("Listing 1. ".to_string()), Some(1))
        );
    }

    #[test]
    fn source_block_uses_listing_caption() {
        // A source block resolves to the `listing` context, so it is captioned
        // via `listing-caption` too.
        assert_eq!(
            first_block_caption(
                ":listing-caption: Listing\n\n.Title\n[source,ruby]\n----\nx\n----"
            ),
            (Some("Listing 1. ".to_string()), Some(1))
        );
    }

    #[test]
    fn literal_block_is_never_captioned() {
        // The `literal` context is not captionable even when titled.
        assert_eq!(
            first_block_caption(".Title\n....\ntext\n...."),
            (None, None)
        );
    }

    #[test]
    fn image_uses_figure_caption_and_number() {
        // An image is captioned under the `figure` context: its label comes from
        // `figure-caption` and its number from the `figure-number` counter (both
        // set by default).
        assert_eq!(
            first_block_caption(".Sunset\nimage::sunset.jpg[]"),
            (Some("Figure 1. ".to_string()), Some(1))
        );
    }

    #[test]
    fn image_caption_override_on_macro_wins() {
        // A `caption` attribute on the macro itself is a verbatim, unnumbered
        // override, and it takes precedence over one on the block attribute list.
        assert_eq!(
            first_block_caption(
                "[caption=\"Block. \"]\n.Sunset\nimage::sunset.jpg[caption=\"Photo. \"]"
            ),
            (Some("Photo. ".to_string()), None)
        );
    }

    #[test]
    fn image_caption_override_on_block_attrlist() {
        assert_eq!(
            first_block_caption("[caption=\"Photo. \"]\n.Sunset\nimage::sunset.jpg[]"),
            (Some("Photo. ".to_string()), None)
        );
    }

    #[test]
    fn image_caption_suppressed_when_figure_caption_unset() {
        assert_eq!(
            first_block_caption(":!figure-caption:\n\n.Sunset\nimage::sunset.jpg[]"),
            (None, None)
        );
    }

    #[test]
    fn untitled_image_is_not_captioned() {
        assert_eq!(first_block_caption("image::sunset.jpg[]"), (None, None));
    }

    #[test]
    fn video_and_audio_are_not_captioned() {
        // Only images are captionable media; video and audio never are, even
        // when titled.
        assert_eq!(
            first_block_caption(".Clip\nvideo::movie.mp4[]"),
            (None, None)
        );
        assert_eq!(
            first_block_caption(".Track\naudio::sound.mp3[]"),
            (None, None)
        );
    }

    #[test]
    fn image_numbering_is_sequential() {
        let doc = Parser::default().parse(".First\nimage::a.jpg[]\n\n.Second\nimage::b.jpg[]");
        let numbers: Vec<_> = doc.child_blocks().map(|b| b.number()).collect();
        assert_eq!(numbers, vec![Some(1), Some(2)]);
    }

    #[test]
    fn image_number_is_stored_in_figure_number_attribute() {
        // The number is stored in the `figure-number` counter attribute, so a
        // later reference to it resolves to the assigned value.
        assert_eq!(
            rendered_paragraphs(
                &Parser::default().parse(".Sunset\nimage::sunset.jpg[]\n\n{figure-number}")
            ),
            vec!["1".to_string()]
        );
    }

    #[test]
    fn listing_numbering_is_sequential_when_captioned() {
        let doc = Parser::default()
            .parse(":listing-caption: Listing\n\n.First\n----\na\n----\n\n.Second\n----\nb\n----");
        let numbers: Vec<_> = doc.child_blocks().map(|b| b.number()).collect();
        assert_eq!(numbers, vec![Some(1), Some(2)]);
    }

    #[test]
    fn listing_number_is_stored_in_listing_number_attribute() {
        // The number is stored in the `listing-number` counter attribute.
        assert_eq!(
            rendered_paragraphs(
                &Parser::default().parse(
                    ":listing-caption: Listing\n\n.Out\n----\ncode\n----\n\n{listing-number}"
                )
            ),
            vec!["1".to_string()]
        );
    }

    #[test]
    fn dropped_image_does_not_consume_figure_number() {
        // Under `attribute-missing=drop-line`, an image whose target references a
        // missing attribute is dropped *before* its caption is assigned, so it
        // does not consume the `figure-number` counter: the next titled image is
        // still "Figure 1.".
        let doc = Parser::default().parse(
            ":attribute-missing: drop-line\n\n.Gone\nimage::{undefined}.jpg[]\n\n.Kept\nimage::ok.jpg[]",
        );
        let captions: Vec<_> = doc
            .child_blocks()
            .map(|b| b.caption().map(str::to_string))
            .collect();
        assert_eq!(captions, vec![Some("Figure 1. ".to_string())]);
    }
}