asciidoc-parser 0.29.1

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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
use std::{borrow::Cow, fmt::Write as _, sync::LazyLock};

use regex::{Captures, Regex, Replacer};

use crate::{
    Parser, Span,
    attributes::{Attrlist, AttrlistContext},
    content::{Content, SubstitutionGroup, substitution_step::substitute_attributes_in_text},
    parser::{QuoteScope, QuoteType},
    warnings::WarningType,
};

/// Records one inline passthrough (`+++…+++`, `++…++`, `$$…$$`, `pass:[…]`, or
/// an inline STEM macro) that the substitution pipeline extracted from a
/// block's content before running the other substitutions, and restores
/// afterward.
///
/// The collection of these for a block is observable via
/// [`Content::passthroughs`](crate::content::Content::passthroughs), analogous
/// to Asciidoctor's internal `@passthroughs` array. It exposes, for each
/// entry, the stored (unescaped) source [`text`](Self::text) and the resolved
/// [`subs`](Self::subs) that are applied to that text on restore.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Passthrough {
    pub(crate) text: String,
    pub(crate) subs: SubstitutionGroup,
    pub(crate) type_: Option<QuoteType>,
    pub(crate) attrlist: Option<String>,
}

impl Passthrough {
    /// Returns the stored, unescaped source text of this passthrough – the text
    /// that is substituted back in (after applying [`subs`](Self::subs)) when
    /// the passthrough is restored.
    ///
    /// This mirrors the `:text` of an entry in Asciidoctor's `@passthroughs`
    /// array.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the resolved substitution group applied to this passthrough's
    /// [`text`](Self::text) when it is restored, i.e. the ordered set of
    /// substitution steps in effect for it.
    ///
    /// For example, `+++…+++` resolves to [`SubstitutionGroup::None`] (no
    /// substitutions), while `++…++` and `$$…$$` resolve to
    /// [`SubstitutionGroup::Verbatim`] (special characters). This mirrors the
    /// resolved `:subs` of an entry in Asciidoctor's `@passthroughs` array.
    pub fn subs(&self) -> &SubstitutionGroup {
        &self.subs
    }
}

/// Saves content of passthrough (`+++`-bracketed) passages for later
/// re-expansion.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Passthroughs(pub(crate) Vec<Passthrough>);

impl Passthroughs {
    pub(crate) fn extract_from(content: &mut Content<'_>, parser: &Parser) -> Self {
        let mut passthroughs = Self(vec![]);

        // TRANSLATION GUIDE:
        // * compat_mode => always false
        // * passthroughs => self.saved_spans
        // * old_behavior => appears to affect the entire span

        {
            let text = content.rendered.as_ref();
            if text.contains("++") || text.contains("$$") || text.contains("ss:") {
                let source = content.original();
                let replacer = InlinePassMacroReplacer {
                    passthroughs: &mut passthroughs,
                    parser,
                    source,
                };

                if let Cow::Owned(new_result) = INLINE_PASS_MACRO.replace_all(text, replacer) {
                    content.rendered = new_result.into();
                }
            }
        }

        {
            let text = content.rendered.as_ref();
            if text.contains('+') || text.contains("-]") {
                let replacer = InlinePassReplacer(&mut passthroughs);

                if let Cow::Owned(new_result) = INLINE_PASS.replace_all(text, replacer) {
                    content.rendered = new_result.into();
                }
            }
        }

        // Inline STEM macros (`stem:[…]`, `asciimath:[…]`, `latexmath:[…]`) are
        // implicit passthroughs. They are extracted last so that any earlier
        // passthrough placeholders nested inside a STEM expression are preserved
        // and recursively restored. (Mirrors the `text.gsub InlineStemMacroRx`
        // block in Ruby Asciidoctor's substitutors.rb.)
        {
            let text = content.rendered.as_ref();
            if text.contains(':') && (text.contains("stem:") || text.contains("math:")) {
                let original = content.original();
                let replacer = InlineStemMacroReplacer {
                    passthroughs: &mut passthroughs,
                    parser,
                    source: original,
                };

                if let Cow::Owned(new_result) = INLINE_STEM_MACRO.replace_all(text, replacer) {
                    content.rendered = new_result.into();
                }
            }
        }

        passthroughs
    }

    pub(crate) fn restore_to(&self, content: &mut Content<'_>, parser: &Parser) {
        if self.0.is_empty() {
            return;
        }

        if let Cow::Owned(new_result) = PASS_WITH_INDEX.replace_all(
            content.rendered().as_ref(),
            PassthroughRestoreReplacer(self, parser),
        ) {
            content.rendered = new_result.into();
        }

        // A deferred cross-reference's explicit text is pulled out of the main
        // rendered string before this point, so any passthrough placeholder it
        // carries (e.g. `<<id, `+[literal]+`>>`) must be restored here too –
        // otherwise the placeholder sentinels leak into the link text.
        content.restore_deferred_xref_passthroughs(|text| {
            if let Cow::Owned(restored) =
                PASS_WITH_INDEX.replace_all(text, PassthroughRestoreReplacer(self, parser))
            {
                *text = restored;
            }
        });
    }

    pub(super) fn push(&mut self, passthrough: Passthrough, dest: &mut String) {
        let index = self.0.len();
        self.0.push(passthrough);

        dest.push('\u{96}');

        // Append the index in place with `write!`, avoiding the temporary
        // `String` a `push_str(&format!(...))` would allocate.
        let _ = write!(dest, "{index}");

        dest.push('\u{97}');
    }
}

/// Matches several variants of the passthrough inline macro, which may span
/// multiple lines.
///
/// ## Examples
///
/// * `+++text+++`
/// * `$$text$$`
/// * `pass:quotes[text]`
///
/// NOTE: We have to support an empty `pass:[]` for compatibility with
/// AsciiDoc.py.
static INLINE_PASS_MACRO: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)
        (?:
            # Optional: attrlist
            (?:
                (\\?)              # Group 1: optional backslash before [
                \[
                    ([^\[\]]+)     # Group 2: attrlist contents
                \]
            )?
            
            (\\{0,2})              # Group 3: optional escape prefix (e.g., \ or \\)

            # Passthrough span delimiters: +++, ++, or $$
            (?:
                (\+\+\+) (.*?) (\+\+\+) |   # Groups 4,5,6: triple plus
                (\+\+)   (.*?) (\+\+)   |   # Groups 7,8,9: double plus
                (\$\$)   (.*?) (\$\$)       # Groups 10,11,12: double dollar
            )

        |

            # Alternative: pass-through directive
            (\\?)                       # Group 13: optional escape before pass
            pass:
                ([a-z]+(?:,[a-z-]+)*)?  # Group 14: optional substitution step list
                \[
                     (|.*?[^\\])        # Group 15: optional content
                                        # (avoiding escape of trailing bracket)
                \]
        )"#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlinePassMacroReplacer<'p> {
    passthroughs: &'p mut Passthroughs,
    parser: &'p Parser,
    source: Span<'p>,
}

impl Replacer for InlinePassMacroReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        if caps.get(4).is_some() {
            // +++
            self.handle_quoted_text(caps, 5, dest);
        } else if caps.get(7).is_some() {
            // ++
            self.handle_quoted_text(caps, 8, dest);
        } else if caps.get(10).is_some() {
            // %%
            self.handle_quoted_text(caps, 11, dest);
        } else {
            // NOTE: We don't look for nested `pass:[]` macros.

            if caps.get(13).is_some_and(|m| !m.as_str().is_empty()) {
                // Honor escape of `pass:` macro.
                dest.push_str("pass:");
                if let Some(subs) = caps.get(14) {
                    dest.push_str(subs.as_str());
                }
                dest.push('[');
                dest.push_str(&caps[15]);
                dest.push(']');
                return;
            }

            // Resolve the substitution list. An explicit but unrecognized
            // substitution name (e.g. `pass:bogus[…]`) is warned about and
            // skipped while any recognized names in the list are still
            // honored, mirroring Asciidoctor's `resolve_subs`.
            let subs = match caps.get(14).map(|m| m.as_str()) {
                None => SubstitutionGroup::None,
                Some(subs_list) => {
                    let (group, invalid) = SubstitutionGroup::from_custom_string(None, subs_list);

                    if !invalid.is_empty() {
                        self.parser.record_substitution_warning(
                            self.source,
                            WarningType::InvalidSubstitutionTypeForPassthroughMacro(
                                invalid.join(", "),
                            ),
                        );
                    }

                    group
                }
            };

            let mut text = caps[15].to_string();
            if !text.is_empty() {
                text = text.replace("\\]", "]");
            }

            self.passthroughs.push(
                Passthrough {
                    text,
                    subs,
                    type_: None,
                    attrlist: None,
                },
                dest,
            );
        }
    }
}

impl InlinePassMacroReplacer<'_> {
    fn handle_quoted_text(
        &mut self,
        caps: &Captures<'_>,
        quoted_text_index: usize,
        dest: &mut String,
    ) {
        let escape_count = caps.get(3).map_or(0, |m| m.len());

        let boundary = caps.get(4).or_else(|| caps.get(7)).or_else(|| caps.get(10));
        let boundary = boundary.map(|m| m.as_str()).unwrap_or_default();

        let quoted_text = caps.get(5).or_else(|| caps.get(8)).or_else(|| caps.get(11));
        let quoted_text = quoted_text.map(|m| m.as_str()).unwrap_or_default();

        let mut old_behavior = false;

        let attrlist: Option<String> = if let Some(attrlist) = caps.get(2) {
            let attrlist = attrlist.as_str();

            if escape_count > 0 {
                dest.push_str(caps[1].as_ref());
                dest.push('[');
                dest.push_str(caps[2].as_ref());
                dest.push(']');
                dest.push_str(&("\\".repeat(escape_count - 1)));
                dest.push_str(caps[quoted_text_index - 1].as_ref());
                dest.push_str(caps[quoted_text_index].as_ref());
                dest.push_str(caps[quoted_text_index - 1].as_ref());
                return;
            }

            if &caps[1] == "\\" {
                dest.push_str(&format!("[{attrlist}]", attrlist = &caps[2]));
                None
            } else if boundary == "++" {
                if attrlist == "x-" {
                    old_behavior = true;
                    Some("".to_owned())
                } else if attrlist.ends_with(" x-") {
                    old_behavior = true;
                    Some(attrlist[0..attrlist.len() - 3].to_owned())
                } else {
                    Some(attrlist.to_owned())
                }
            } else {
                Some(attrlist.to_owned())
            }
        } else if escape_count > 0 {
            // NOTE: We don't look for nested unconstrained pass macros.
            dest.push_str(&("\\".repeat(escape_count - 1)));
            dest.push_str(boundary);
            dest.push_str(quoted_text);
            dest.push_str(boundary);
            return;
        } else {
            None
        };

        let passthrough = if let Some(attrlist) = attrlist {
            if old_behavior {
                Passthrough {
                    text: caps
                        .get(quoted_text_index)
                        .map(|m| m.as_str().to_owned())
                        .unwrap_or_default(),
                    subs: SubstitutionGroup::Normal,
                    type_: Some(QuoteType::Monospaced),
                    attrlist: Some(attrlist),
                }
            } else {
                Passthrough {
                    text: caps
                        .get(quoted_text_index)
                        .map(|m| m.as_str().to_owned())
                        .unwrap_or_default(),
                    subs: if boundary == "+++" {
                        SubstitutionGroup::None
                    } else {
                        SubstitutionGroup::Verbatim
                    },
                    type_: Some(QuoteType::Unquoted),
                    attrlist: Some(attrlist),
                }
            }
        } else {
            Passthrough {
                text: caps
                    .get(quoted_text_index)
                    .map(|m| m.as_str().to_owned())
                    .unwrap_or_default(),
                subs: if boundary == "+++" {
                    SubstitutionGroup::None
                } else {
                    SubstitutionGroup::Verbatim
                },
                type_: None,
                attrlist: None,
            }
        };

        self.passthroughs.push(passthrough, dest);
    }
}

static PASS_WITH_INDEX: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new("\u{96}(\\d+)\u{97}").unwrap()
});

/// Matches an inline passthrough, which may span multiple lines.
///
/// ## Examples
///
/// * `+text+`
/// * `[x-]+text+`
/// * `[x-]\`text\``
///
/// NOTE: We do not support compat-mode in the Rust implementation.
static INLINE_PASS: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)
            (?:
                                        # Option 1: [... x-] followed by `xxx`
                \b{start-half}              # Must not follow a word
                \[(x-|[^\[\]]+\ x-)\]       # Group 1: [attrlist] with x- suffix
                \`(\S(?:.*?\S)??)\`         # Group 2: `...` content

            |                           # --OR--
                                        # Option 2: [...] followed by +xxx+
                \b{start-half}              # Must not follow a word
                \[([^\[\]]+)\]              # Group 3: [attrlist]
                (\\{0,2})                   # Group 4: optional escapes
                \+(\S(?:.*?\S)??)\+         # Group 5: +...+ content (surrounded by non-space)

            |                           # --OR--
                                        # Option 3: +xxx+ without attrlist
                (?:^|([^\w;:\\]))           # Group 6: consume a preceding char, so a run
                                        # of `+` tokenizes like Asciidoctor's `gsub`
                                        # (which consumes one char before each match)
                (\\)?                       # Group 7: optional escape
                \+(\S(?:.*?\S)??)\+         # Group 8: +...+ content (surrounded by non-space)

            )

            \b{end-half}            # Must not be followed by a word character
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlinePassReplacer<'p>(&'p mut Passthroughs);

impl Replacer for InlinePassReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        if dest.ends_with('\\') || dest.ends_with(':') || dest.ends_with(';') {
            // Honor the prohibited prefix.
            // EDGE CASE: Since we don't have lookarounds in Rust's regex, we have to retry
            // the inline pass replacement here. Possible it might miss a few very obscure
            // cases, but this should cover most cases where the attrlist is off-limits, but
            // the quoted text is still subject to inline pass replacement.
            let replacer = InlinePassReplacer(self.0);

            // Split off the first character (a char boundary, since Option 3
            // may consume a multi-byte preceding character) and retry on the
            // remainder.
            let first_len = caps[0].chars().next().map_or(0, char::len_utf8);
            let (first, rem) = &caps[0].split_at(first_len);
            dest.push_str(first);

            let new_result = INLINE_PASS.replace_all(rem, replacer);
            dest.push_str(&new_result);

            return;
        }

        // Option 3 consumes one preceding character (mirroring Asciidoctor's
        // `InlinePassRx`, whose leading group absorbs the character before the
        // passthrough). Re-emit it verbatim ahead of whatever this match
        // produces. Options 1 and 2 never capture it, so this is a no-op there.
        let preceding = caps.get(6).map_or("", |m| m.as_str());
        dest.push_str(preceding);

        let escapes = caps.get(4).or_else(|| caps.get(7));
        let escape_count = escapes.map_or(0, |m| m.len());

        let format_mark = if caps.get(2).is_some() { '`' } else { '+' };
        let orig_attrlist_body = caps.get(1).or_else(|| caps.get(3)).map(|m| m.as_str());

        let (attrlist_body, old_behavior) = orig_attrlist_body.map_or((None, false), |m| {
            if m == "x-" {
                (Some("".to_string()), true)
            } else if m.ends_with(" x-") {
                (Some(m[0..m.len() - 3].to_string()), true)
            } else {
                (Some(m.to_string()), false)
            }
        });

        let quoted_text = caps.get(2).or_else(|| caps.get(5)).or_else(|| caps.get(8));
        let quoted_text = quoted_text.map_or("", |m| m.as_str());

        if let Some(orig_attrlist_body) = orig_attrlist_body {
            if escape_count > 0 {
                // Honor the escape of the formatting mark.
                dest.push('[');
                dest.push_str(orig_attrlist_body);
                dest.push(']');
                dest.push_str(&("\\".repeat(escape_count - 1)));
                dest.push(format_mark);
                dest.push_str(quoted_text);
                dest.push(format_mark);
                return;
            }
        } else if escape_count > 0 {
            // Honor the escape of the formatting mark.
            dest.push_str(&("\\".repeat(escape_count - 1)));
            dest.push(format_mark);
            dest.push_str(quoted_text);
            dest.push(format_mark);
            return;
        };

        let subs = if attrlist_body.is_some() && old_behavior && format_mark != '`' {
            SubstitutionGroup::Normal
        } else {
            SubstitutionGroup::Verbatim
        };

        let type_ = if attrlist_body.is_some() {
            if old_behavior {
                Some(QuoteType::Monospaced)
            } else {
                Some(QuoteType::Unquoted)
            }
        } else {
            None
        };

        self.0.push(
            Passthrough {
                text: quoted_text.to_string(),
                subs,
                type_,
                attrlist: attrlist_body,
            },
            dest,
        );
    }
}

/// Matches a STEM inline macro (`stem`, and its alternatives `asciimath` and
/// `latexmath`), which may span multiple lines.
///
/// ## Examples
///
/// * `stem:[x^2]`
/// * `asciimath:[x != 0]`
/// * `latexmath:[\sqrt{4} = 2]`
///
/// The content group requires at least one character whose final character is
/// not a backslash, so an empty macro (e.g. `stem:[]`) is not recognized.
static INLINE_STEM_MACRO: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?xs)
            (\\?)                          # Group 1: optional escape
            (stem|latexmath|asciimath)     # Group 2: notation
            :
            ([a-z]+(?:,[a-z-]+)*)?         # Group 3: optional substitution list
            \[
                (.*?[^\\])                 # Group 4: expression (last char not a backslash)
            \]
        "#,
    )
    .unwrap()
});

#[derive(Debug)]
struct InlineStemMacroReplacer<'p> {
    passthroughs: &'p mut Passthroughs,
    parser: &'p Parser,
    source: Span<'p>,
}

impl Replacer for InlineStemMacroReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        // Honor the escape: drop the leading backslash and emit the macro
        // literally.
        if caps.get(1).is_some_and(|m| !m.as_str().is_empty()) {
            dest.push_str(&caps[0][1..]);
            return;
        }

        let type_ = match &caps[2] {
            "latexmath" => QuoteType::LatexMath,
            "asciimath" => QuoteType::AsciiMath,

            // `stem`: the notation is resolved from the `stem` document
            // attribute (defaulting to AsciiMath).
            _ => stem_notation(self.parser),
        };

        // Unescape any escaped closing brackets in the expression.
        let mut content = caps[4].to_string();
        if content.contains("\\]") {
            content = content.replace("\\]", "]");
        }

        // Drop legacy enclosing `$…$` around latexmath content (for backwards
        // compatibility with AsciiDoc.py).
        if type_ == QuoteType::LatexMath
            && content.len() >= 2
            && content.starts_with('$')
            && content.ends_with('$')
        {
            content = content[1..content.len() - 1].to_string();
        }

        // Resolve the substitution group. When no explicit substitution list is
        // given, HTML output applies only the special characters substitution.
        // An unrecognized substitution name is warned about and skipped while
        // any recognized names in the list are still honored, mirroring
        // Asciidoctor's `resolve_subs`.
        let subs = match caps.get(3).map(|m| m.as_str()) {
            None => SubstitutionGroup::Stem,
            Some(subs_list) => {
                let (group, invalid) = SubstitutionGroup::from_custom_string(None, subs_list);

                if !invalid.is_empty() {
                    self.parser.record_substitution_warning(
                        self.source,
                        WarningType::InvalidSubstitutionTypeForStemMacro(invalid.join(", ")),
                    );
                }

                group
            }
        };

        self.passthroughs.push(
            Passthrough {
                text: content,
                subs,
                type_: Some(type_),
                attrlist: None,
            },
            dest,
        );
    }
}

/// Resolves the STEM notation to apply for a bare `stem` macro or block from
/// the `stem` document attribute. Any value other than `latexmath`, `latex`, or
/// `tex` (including an unset, empty, or unrecognized value) maps to AsciiMath.
fn stem_notation(parser: &Parser) -> QuoteType {
    match parser.attribute_value("stem").as_maybe_str() {
        Some("latexmath") | Some("latex") | Some("tex") => QuoteType::LatexMath,
        _ => QuoteType::AsciiMath,
    }
}

#[derive(Debug)]
struct PassthroughRestoreReplacer<'p>(&'p Passthroughs, &'p Parser);

impl Replacer for PassthroughRestoreReplacer<'_> {
    fn replace_append(&mut self, caps: &Captures<'_>, dest: &mut String) {
        let index = caps[1].parse::<usize>().unwrap_or_default();

        let Some(pass) = self.0.0.get(index) else {
            dest.push_str(&format!(
                "(INTERNAL ERROR: Unresolved passthrough index {index})"
            ));
            return;
        };

        let span = Span::new(&pass.text);

        let mut subbed_text = Content::from(span);
        pass.subs.apply(&mut subbed_text, self.1, None);

        if let Some(type_) = pass.type_ {
            // Resolve attribute references in the stored attrlist before parsing
            // it. Inline passthroughs are extracted before the substitution
            // pipeline runs, so – unlike the inline quoted-text path, whose
            // attrlist is a slice of the already-substituted buffer – a reference
            // embedded in a passthrough role (e.g. `['{myrole}']++x++`) would
            // otherwise render verbatim. This mirrors Asciidoctor's
            // `parse_quoted_text_attributes`, which runs `sub_attributes` on the
            // attribute list.
            let attrlist_body = pass.attrlist.as_ref().map(|attrlist_body| {
                // The stored attrlist is owned text whose offsets do not refer
                // to the document source, so any `warn`/`drop-line` warning this
                // substitution records cannot be mapped back to a document span.
                // Discard such warnings rather than surface them mislocated
                // against the document root (mirrors the docinfo text path).
                let saved = self.1.substitution_warnings_len();
                let substituted = substitute_attributes_in_text(attrlist_body, self.1);
                self.1.truncate_substitution_warnings(saved);
                substituted
            });

            let attrlist = attrlist_body.as_ref().map(|attrlist_body| {
                let span = Span::new(attrlist_body);
                let maw = Attrlist::parse(span, self.1, AttrlistContext::Inline);
                maw.item.item
            });

            let id = attrlist
                .as_ref()
                .and_then(|attrlist| attrlist.id().map(|id| id.to_string()));

            let mut new_text = String::default();
            self.1.renderer.render_quoted_substitution(
                type_,
                QuoteScope::Unconstrained,
                attrlist,
                id,
                subbed_text.rendered(),
                &mut new_text,
            );

            subbed_text.rendered = new_text.into();
        }

        if subbed_text.rendered().contains('\u{96}') {
            // Recursively apply passthrough replacement and write the result.
            let replacer = PassthroughRestoreReplacer(self.0, self.1);

            let new_result = PASS_WITH_INDEX.replace_all(subbed_text.rendered().as_ref(), replacer);

            dest.push_str(new_result.as_ref());
        } else {
            dest.push_str(subbed_text.rendered());
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::indexing_slicing)]
    #![allow(clippy::panic)]
    #![allow(clippy::unwrap_used)]

    use crate::{
        content::{Passthroughs, SubstitutionStep, passthroughs::Passthrough},
        tests::prelude::*,
    };

    #[test]
    fn inline_double_plus_with_escaped_attrlist() {
        let mut p = Parser::default();
        let maw = crate::blocks::Block::parse(crate::Span::new(r#"abc \[attrs]++text++"#), &mut p);

        let block = maw.item.unwrap().item;

        assert_eq!(
            block,
            Block::Simple(SimpleBlock {
                content: Content {
                    original: Span {
                        data: r#"abc \[attrs]++text++"#,
                        line: 1,
                        col: 1,
                        offset: 0,
                    },
                    rendered: "abc [attrs]text",
                },
                source: Span {
                    data: r#"abc \[attrs]++text++"#,
                    line: 1,
                    col: 1,
                    offset: 0,
                },
                style: SimpleBlockStyle::Paragraph,
                title_source: None,
                title: None,
                caption: None,
                number: None,
                anchor: None,
                anchor_reftext: None,
                attrlist: None,
            },)
        );
    }

    #[test]
    fn content_exposes_extracted_passthrough_collection() {
        // The inline passthroughs extracted while substituting a block's
        // content are retained on the `Content` and observable afterward via
        // the public `passthroughs()` accessor, exposing each entry's stored
        // (unescaped) text and its resolved substitution list. (Not a direct
        // port of a Ruby test; it exercises the accessor surfaced for spec
        // verification.)
        let mut p = Parser::default();

        let maw = crate::blocks::Block::parse(
            crate::Span::new("some ++<code>{code}</code>++ and +++{raw}+++ text"),
            &mut p,
        );

        let crate::blocks::Block::Simple(block) = maw.item.unwrap().item else {
            panic!("expected a simple block");
        };

        let passthroughs = block.content().passthroughs();

        assert_eq!(passthroughs.len(), 2);

        // `++…++` stores the text verbatim and applies the special-characters
        // substitution on restore.
        assert_eq!(passthroughs[0].text(), "<code>{code}</code>");
        assert_eq!(passthroughs[0].subs(), &SubstitutionGroup::Verbatim);

        // `+++…+++` stores the text verbatim and applies no substitutions.
        assert_eq!(passthroughs[1].text(), "{raw}");
        assert_eq!(passthroughs[1].subs(), &SubstitutionGroup::None);
    }

    #[test]
    fn passthrough_attrlist_drop_line_does_not_leak_a_mislocated_warning() {
        // A missing reference in a passthrough's stored attribute list is
        // substituted against temporary (owned) text, so any warning it records
        // carries an offset into that text rather than the document source.
        // Such warnings must be discarded (the offset cannot be mapped back),
        // not surfaced against the document root. Regression guard for the
        // `drop-line`/`warn` attrlist path.
        let mut p = Parser::default().with_intrinsic_attribute(
            "attribute-missing",
            "drop-line",
            ModificationContext::ApiOnly,
        );

        let doc = p.parse("['{missing}']++x++");

        assert_eq!(doc.warnings().count(), 0);
    }

    #[test]
    fn content_without_passthroughs_exposes_an_empty_collection() {
        // Plain content – and content whose substitution group never extracts
        // passthroughs – exposes an empty collection rather than any sentinel.
        let mut p = Parser::default();

        let maw = crate::blocks::Block::parse(crate::Span::new("just plain prose"), &mut p);

        let crate::blocks::Block::Simple(block) = maw.item.unwrap().item else {
            panic!("expected a simple block");
        };

        assert!(block.content().passthroughs().is_empty());
    }

    #[test]
    fn adds_warning_text_for_unresolved_passthrough_id() {
        let mut content =
            crate::content::Content::from(crate::Span::new("pass:q,a[*<{backend}>*]"));
        let parser_for_extract = Parser::default();
        let pt = Passthroughs::extract_from(&mut content, &parser_for_extract);

        assert_eq!(
            content,
            Content {
                original: Span {
                    data: "pass:q,a[*<{backend}>*]",
                    line: 1,
                    col: 1,
                    offset: 0,
                },
                rendered: "\u{96}0\u{97}",
            }
        );

        assert_eq!(
            pt,
            Passthroughs(vec![Passthrough {
                text: "*<{backend}>*".to_owned(),
                subs: SubstitutionGroup::Custom(vec![
                    SubstitutionStep::Quotes,
                    SubstitutionStep::AttributeReferences,
                ]),
                type_: None,
                attrlist: None,
            },],)
        );

        let parser = Parser::default().with_intrinsic_attribute(
            "backend",
            "html5",
            ModificationContext::ApiOnly,
        );

        pt.0[0].subs.apply(&mut content, &parser, None);

        content.rendered = "\u{96}99\u{97}".into();

        pt.restore_to(&mut content, &parser);

        assert_eq!(
            content,
            Content {
                original: Span {
                    data: "pass:q,a[*<{backend}>*]",
                    line: 1,
                    col: 1,
                    offset: 0,
                },
                rendered: "(INTERNAL ERROR: Unresolved passthrough index 99)",
            }
        );
    }
}