asciidoc-parser 0.29.3

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
use std::sync::LazyLock;

use regex::Regex;

use crate::{Parser, Span, content::Content};

/// Represents a single author as (typically) described on the [author line].
///
/// The attributes `firstname`, `middlename`, `lastname`, and `authorinitials`
/// are automatically derived from the full value of the author string. When
/// assigned implicitly via the author line, the value includes all of the
/// characters and words prior to the semicolon (`;`), angle bracket (`<`), or
/// the end of the line. Note that when using the implicit author line, the full
/// name can have a maximum of three space-separated names. If it has more, then
/// the full name is assigned to the `firstname` attribute. You can adjoin names
/// using an underscore (`_`) character.
///
/// [author line]: https://docs.asciidoctor.org/asciidoc/latest/document/author-line/
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Author {
    name: String,
    firstname: String,
    middlename: Option<String>,
    lastname: Option<String>,
    email: Option<String>,
}

impl Author {
    /// Parse a single author from `source`.
    ///
    /// `names_only` distinguishes the two contexts in which Asciidoctor parses
    /// an author. The implicit author line (`names_only == false`) recognizes
    /// at most three space-separated names via the [`AUTHOR`] pattern and,
    /// failing that, stores the whole line as the author. An author
    /// supplied through an attribute entry such as `:author:` (`names_only
    /// == true`) is instead partitioned by splitting on whitespace into at
    /// most three parts, so a name with four or more parts still assigns
    /// its trailing parts to `lastname` (see issue #758).
    pub(crate) fn parse(source: &str, parser: &Parser, names_only: bool) -> Option<Self> {
        let source = source.trim();
        if source.is_empty() {
            return None;
        }

        // Parse the raw input first to extract components, then apply attribute
        // substitution to individual components afterwards. Special case: If the entire
        // input is a single attribute reference, treat the expanded result as a single
        // name.
        let is_single_attribute = source.trim().starts_with('{')
            && source.trim().ends_with('}')
            && source.matches('{').count() == 1;

        if is_single_attribute {
            // Entire input is a single attribute reference: Expand and treat as single
            // name.
            let expanded_source = apply_author_subs(source, parser);

            if names_only {
                // An attribute-entry value is partitioned *after* its references
                // are expanded, so a reference that resolves to a multi-part name
                // (or one with a trailing email) yields the same metadata as the
                // equivalent literal value.
                Some(partition_names_only(&expanded_source))
            } else {
                let name_with_spaces = replace_underscores_with_spaces(expanded_source);
                Some(Self {
                    name: name_with_spaces.clone(),
                    firstname: name_with_spaces,
                    middlename: None,
                    lastname: None,
                    email: None,
                })
            }
        } else if let Some(captures) = AUTHOR.captures(source) {
            // Raw input matches author pattern: Extract components then apply
            // substitutions.

            // Extract raw components first.
            let firstname =
                replace_underscores_with_spaces(apply_author_subs(&captures[1], parser));
            let mut middlename = captures
                .get(2)
                .map(|m| replace_underscores_with_spaces(apply_author_subs(m.as_str(), parser)));
            let mut lastname = captures
                .get(3)
                .map(|m| replace_underscores_with_spaces(apply_author_subs(m.as_str(), parser)));
            let email = captures
                .get(4)
                .map(|m| apply_author_subs(m.as_str(), parser));

            if middlename.is_some() && lastname.is_none() {
                lastname = middlename;
                middlename = None;
            }

            // Reconstruct the full name from its parsed parts so that any interior
            // whitespace that appeared between the names in the source is condensed
            // to a single space (matching Asciidoctor).
            let name = join_name_parts(&firstname, middlename.as_deref(), lastname.as_deref());

            Some(Self {
                name,
                firstname,
                middlename,
                lastname,
                email,
            })
        } else if source.contains('{') {
            // Input contains attributes that prevent regex match: Expand first, then try
            // parsing.
            let expanded_source = apply_author_subs(source, parser);

            if let Some(captures) = AUTHOR.captures(&expanded_source) {
                // After expansion, it matches the pattern: Parse normally.
                let firstname = replace_underscores_with_spaces(captures[1].to_string());
                let mut middlename = captures
                    .get(2)
                    .map(|m| replace_underscores_with_spaces(m.as_str().to_string()));
                let mut lastname = captures
                    .get(3)
                    .map(|m| replace_underscores_with_spaces(m.as_str().to_string()));
                let email = captures.get(4).map(|m| m.as_str().to_string());

                if middlename.is_some() && lastname.is_none() {
                    lastname = middlename;
                    middlename = None;
                }

                // Reconstruct the full name from its parsed parts so interior
                // whitespace between the names is condensed (matching Asciidoctor).
                let name = join_name_parts(&firstname, middlename.as_deref(), lastname.as_deref());

                Some(Self {
                    name,
                    firstname,
                    middlename,
                    lastname,
                    email,
                })
            } else if names_only {
                // An attribute-entry value that still fails the pattern after
                // expansion is partitioned by the names-only rules, so a
                // reference resolving to a four-plus-part name behaves like its
                // literal equivalent. The expanded value is used before any HTML
                // encoding so a trailing `<email>` can still be split off.
                Some(partition_names_only(&expanded_source))
            } else {
                // Even after expansion, doesn't match: Treat as single name with HTML encoding.
                let mut expanded_name = expanded_source;

                if expanded_name.contains('<') && expanded_name.contains('>') {
                    let span = crate::Span::new(&expanded_name);
                    let mut content = crate::content::Content::from(span);
                    crate::content::SubstitutionStep::SpecialCharacters.apply(
                        &mut content,
                        parser,
                        None,
                    );
                    expanded_name = content.rendered().to_string();
                }

                let name_with_spaces = replace_underscores_with_spaces(expanded_name);
                Some(Self {
                    name: name_with_spaces.clone(),
                    firstname: name_with_spaces,
                    middlename: None,
                    lastname: None,
                    email: None,
                })
            }
        } else if names_only {
            // Input comes from an attribute entry (e.g. `:author:`) and does not
            // match the author pattern – typically a name with four or more parts
            // or one containing punctuation such as a comma. Asciidoctor still
            // partitions it by splitting on whitespace into at most three parts,
            // assigning any trailing parts to `lastname`.
            Some(partition_names_only(source))
        } else {
            // Input doesn't contain attributes and doesn't match the author pattern.
            // Asciidoctor stores the whole line as the author, condensing interior
            // whitespace and keeping any angle brackets literal. Underscores are left
            // literal here: Asciidoctor only converts underscore-joined names while
            // partitioning a *matching* line, not in this fallback.
            let name = condense_whitespace(source);
            Some(Self {
                name: name.clone(),
                firstname: name,
                middlename: None,
                lastname: None,
                email: None,
            })
        }
    }

    /// Parse the single author described by an `:author:` attribute entry.
    ///
    /// `raw` is the entry's raw (pre-substitution) value and `substituted` is
    /// its substituted value (the stored attribute value). When the entry is a
    /// whole-value `pass:[…]` macro its substituted value is the resolved
    /// content, so that value is partitioned – with any generated markup
    /// stripped – rather than the raw macro syntax (see
    /// [`parse_substituted_names_only`]). Every other value is partitioned from
    /// the raw value as before, so plain names, attribute references, and
    /// inline emails are unaffected.
    ///
    /// [`parse_substituted_names_only`]: Self::parse_substituted_names_only
    pub(crate) fn parse_from_entry(
        raw: &str,
        substituted: Option<&str>,
        parser: &Parser,
    ) -> Option<Self> {
        if crate::document::is_attribute_entry_pass_macro(raw) {
            substituted.and_then(Self::parse_substituted_names_only)
        } else {
            Self::parse(raw, parser, true)
        }
    }

    /// Parse a single author from a value that has *already* been through
    /// attribute-value substitution and now carries generated inline HTML –
    /// typically the rendered output of a `pass:[…]` macro in an `:author:`
    /// entry.
    ///
    /// This mirrors the `<`-branch of Asciidoctor's `process_authors` under
    /// `names_only`: the full rendered value – with name-joiner underscores
    /// turned to spaces – becomes the author's `name`, while the name parts are
    /// partitioned from the value with its HTML tags removed, so the formatting
    /// does not leak into `firstname`/`middlename`/`lastname`. As in
    /// Asciidoctor, no email is split off here – an email supplied through a
    /// companion `:email:` entry is attached later.
    pub(crate) fn parse_substituted_names_only(substituted: &str) -> Option<Self> {
        let substituted = substituted.trim();
        if substituted.is_empty() {
            return None;
        }

        let name = replace_underscores_with_spaces(substituted.to_string());
        let stripped = strip_xml_tags(substituted);

        let mut segments = split_whitespace_max3(&stripped);

        if segments.is_empty() {
            // The value was nothing but markup: keep the rendered value as the
            // single name.
            return Some(Self {
                firstname: name.clone(),
                name,
                middlename: None,
                lastname: None,
                email: None,
            });
        }

        let firstname = replace_underscores_with_spaces(segments.remove(0));
        let (middlename, lastname) = match segments.len() {
            0 => (None, None),

            1 => (
                None,
                Some(replace_underscores_with_spaces(segments.remove(0))),
            ),

            _ => (
                Some(replace_underscores_with_spaces(segments.remove(0))),
                Some(replace_underscores_with_spaces(segments.remove(0))),
            ),
        };

        Some(Self {
            name,
            firstname,
            middlename,
            lastname,
            email: None,
        })
    }

    /// Overrides the author's email address, unless `email` is `None`.
    ///
    /// Used when an author is assembled from `author_N` document attributes,
    /// where the name and the companion `email_N` attribute are parsed
    /// separately.
    pub(crate) fn with_email(mut self, email: Option<String>) -> Self {
        if let Some(email) = email {
            self.email = Some(email);
        }

        self
    }

    /// Returns the full name of the author.
    ///
    /// The name includes the entire author declaration except for email.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the first, forename, or given name of the author.
    ///
    /// The first space-separated name in the value of the `author` attribute is
    /// automatically assigned to `firstname`.
    pub fn firstname(&self) -> &str {
        &self.firstname
    }

    /// Returns the middle name or initial of the author.
    ///
    /// If author contains three space-separated names, the second name is
    /// assigned to the `middlename` attribute.
    pub fn middlename(&self) -> Option<&str> {
        self.middlename.as_deref()
    }

    /// Returns the last, surname, or family name of the author.
    ///
    /// If the author name contains two or three space-separated names, the last
    /// of those names is assigned to the `lastname` attribute.
    pub fn lastname(&self) -> Option<&str> {
        self.lastname.as_deref()
    }

    /// Returns the email address or URL associated with the author.
    ///
    /// When assigned via the author line, it’s enclosed in a pair of angle
    /// brackets (`< >`). A URL can be used in place of the email address.
    pub fn email(&self) -> Option<&str> {
        self.email.as_deref()
    }

    /// Returns the initials of the author.
    ///
    /// The first character of the `firstname`, `middlename`, and `lastname`
    /// attribute values are assigned to the `authorinitials` attribute. The
    /// value of the `authorinitials` attribute will consist of three characters
    /// or less depending on how many parts are in the author’s name.
    pub fn initials(&self) -> String {
        format!(
            "{first}{middle}{last}",
            first = first_char_or_empty_string(&self.firstname),
            middle = opt_first_char_or_empty_string(self.middlename.as_deref()),
            last = opt_first_char_or_empty_string(self.lastname.as_deref()),
        )
    }
}

/// Populates the derived author document attributes from a resolved author
/// list, mirroring Asciidoctor's `process_authors`.
///
/// The first author sets the unsuffixed keys (`author`, `firstname`,
/// `authorinitials`, …); each subsequent author sets its `_N` companions. Once
/// a second author appears, the first author is also mirrored onto its `_1`
/// companions. The `authors` attribute is rewritten to the comma-joined list of
/// resolved author names.
///
/// This intentionally does **not** honor `authorinitials_from_entry`: the
/// derived `authorinitials` always overwrites an explicit `:authorinitials:`
/// entry for the `authors` and `author_N` forms. Only a single `:author:` entry
/// (handled inline in [`Header::parse`](crate::document::Header)) preserves an
/// explicit override, exactly as Asciidoctor does – its `authorinitials`
/// deletion guard lives only in the `author` branch of `process_authors`, not
/// the `authors`/indexed branches.
pub(crate) fn set_author_metadata(parser: &mut Parser, authors: &[Author]) {
    for (idx, author) in authors.iter().enumerate() {
        set_author_keys(parser, author, if idx == 0 { None } else { Some(idx + 1) });

        // The `_1` companions are only assigned once a second author is seen.
        if idx == 1
            && let Some(first) = authors.first()
        {
            set_author_keys(parser, first, Some(1));
        }
    }

    let joined = authors
        .iter()
        .map(Author::name)
        .collect::<Vec<_>>()
        .join(", ");

    parser.set_attribute_by_value_from_header("authors", joined);
}

/// Sets the author attributes for a single author, either as the unsuffixed
/// keys (`index` is `None`) or the `_N` companions (`index` is `Some(n)`).
fn set_author_keys(parser: &mut Parser, author: &Author, index: Option<usize>) {
    let key = |name: &str| match index {
        None => name.to_string(),
        Some(n) => format!("{name}_{n}"),
    };

    parser.set_attribute_by_value_from_header(key("author"), author.name());

    parser.set_attribute_by_value_from_header(key("firstname"), author.firstname());

    if let Some(middlename) = author.middlename() {
        parser.set_attribute_by_value_from_header(key("middlename"), middlename);
    }

    if let Some(lastname) = author.lastname() {
        parser.set_attribute_by_value_from_header(key("lastname"), lastname);
    }

    parser.set_attribute_by_value_from_header(key("authorinitials"), author.initials());

    if let Some(email) = author.email() {
        parser.set_attribute_by_value_from_header(key("email"), email);
    }
}

fn first_char_or_empty_string(s: &str) -> String {
    s.chars().next().map_or(String::new(), |c| c.to_string())
}

fn opt_first_char_or_empty_string(s: Option<&str>) -> String {
    s.map(first_char_or_empty_string).unwrap_or_default()
}

/// Replace underscores with spaces in a name component.
fn replace_underscores_with_spaces(name: String) -> String {
    name.replace('_', " ")
}

/// Remove HTML tags from `source`, mirroring Asciidoctor's `XmlSanitizeRx`
/// (`/<[^>]+>/`). Used to partition an author value whose substitution produced
/// inline markup (see [`Author::parse_substituted_names_only`]).
fn strip_xml_tags(source: &str) -> String {
    XML_TAG.replace_all(source, "").into_owned()
}

/// Join an author's parsed name parts with a single space.
///
/// Asciidoctor reconstructs the full name from its partitioned parts, which
/// condenses any interior whitespace that appeared between the names in the
/// source down to a single space.
fn join_name_parts(firstname: &str, middlename: Option<&str>, lastname: Option<&str>) -> String {
    let mut name = String::from(firstname);

    if let Some(middlename) = middlename {
        name.push(' ');
        name.push_str(middlename);
    }

    if let Some(lastname) = lastname {
        name.push(' ');
        name.push_str(lastname);
    }

    name
}

/// Partition an author value that does not match the [`AUTHOR`] pattern using
/// Asciidoctor's `names_only` rules (the path taken for an attribute-entry
/// value such as `:author:`).
///
/// A trailing `<email>` (or URL) is first split off so it is not absorbed into
/// the name – mirroring the email group of the author pattern and Asciidoctor's
/// XML sanitization of a names-only value. The remaining name is then split on
/// whitespace into at most three segments (Ruby's `String#split(nil, 3)`, which
/// also drops leading whitespace). The trailing segment retains its interior
/// text – so a four-plus-part name keeps its later parts in `lastname` – but
/// has repeating spaces condensed to a single space. Each segment then has
/// underscore joiners replaced with spaces.
///
/// `source` may already have attribute references substituted (the expanded
/// value of a reference such as `{full-name}`); in that case any email it
/// carries is likewise already substituted.
fn partition_names_only(source: &str) -> Author {
    let source = source.trim();

    let (name_source, email) = match NAMES_ONLY_EMAIL.captures(source) {
        Some(captures) => (
            captures.get(1).map_or(source, |m| m.as_str()),
            Some(captures[2].to_string()),
        ),
        None => (source, None),
    };

    let mut segments = split_whitespace_max3(name_source);

    let firstname = replace_underscores_with_spaces(segments.remove(0));
    let (middlename, lastname) = match segments.len() {
        0 => (None, None),
        1 => (
            None,
            Some(replace_underscores_with_spaces(segments.remove(0))),
        ),
        _ => (
            Some(replace_underscores_with_spaces(segments.remove(0))),
            Some(replace_underscores_with_spaces(segments.remove(0))),
        ),
    };

    let name = join_name_parts(&firstname, middlename.as_deref(), lastname.as_deref());

    Author {
        name,
        firstname,
        middlename,
        lastname,
        email,
    }
}

/// Split `source` on runs of whitespace into at most three segments, mirroring
/// Ruby's `String#split(nil, 3)`. Leading whitespace is dropped and the first
/// two whitespace runs delimit the first two segments; the remainder becomes
/// the third segment, with its repeating spaces condensed to a single space
/// (Ruby's `String#squeeze ' '`).
///
/// Only ASCII whitespace is treated as a delimiter, matching Ruby's split
/// (which does not break on non-breaking or other Unicode spaces), so a name
/// joined by such a space stays a single segment. The returned vector always
/// has at least one element because the caller has already rejected empty
/// input.
fn split_whitespace_max3(source: &str) -> Vec<String> {
    let is_ascii_ws = |c: char| c.is_ascii_whitespace();

    let mut segments: Vec<String> = Vec::with_capacity(3);
    let mut rest = source;

    for _ in 0..2 {
        rest = rest.trim_start_matches(is_ascii_ws);
        match rest.find(is_ascii_ws) {
            Some(index) => {
                segments.push(rest[..index].to_string());
                rest = &rest[index..];
            }
            None => break,
        }
    }

    rest = rest.trim_start_matches(is_ascii_ws);
    if !rest.is_empty() {
        segments.push(condense_whitespace(rest));
    }

    segments
}

/// Condense runs of spaces into a single space, mirroring Ruby's
/// `String#tr_s(' ', ' ')`, which Asciidoctor applies to an author line that
/// does not match the author pattern.
fn condense_whitespace(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut prev_was_space = false;

    for c in s.chars() {
        if c == ' ' {
            if !prev_was_space {
                result.push(' ');
            }
            prev_was_space = true;
        } else {
            result.push(c);
            prev_was_space = false;
        }
    }

    result
}

/// Matches a single HTML tag, mirroring Asciidoctor's `XmlSanitizeRx`.
static XML_TAG: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(r"<[^>]+>").unwrap()
});

static AUTHOR: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?x)
            ^

            # Group 1: First name (required)
            ([a-zA-Z0-9_\p{L}\p{N}&\#;][a-zA-Z0-9_\p{L}\p{N}\-'.&\#;]*)

            # Group 2: Middle name (optional)
            (?:\ +([a-zA-Z0-9_\p{L}\p{N}&\#;][a-zA-Z0-9_\p{L}\p{N}\-'.&\#;]*))?

            # Group 3: Last name (optional)
            (?:\ +([a-zA-Z0-9_\p{L}\p{N}&\#;][a-zA-Z0-9_\p{L}\p{N}\-'.&\#;]*))?

            # Group 4: Email address (optional)
            (?:\ +<([^>]+)>)?

            $
        "#,
    )
    .unwrap()
});

/// Splits a names-only author value into its name portion (group 1) and a
/// trailing `<email>` (group 2). The name must contain at least one
/// non-whitespace character and is followed by whitespace before the bracketed
/// email, matching the email group of [`AUTHOR`] for a value that otherwise
/// fails the full pattern (e.g. a name with four or more parts).
static NAMES_ONLY_EMAIL: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(r"^(.*\S)\s+<([^>]+)>$").unwrap()
});

/// Returns whether `source` matches the author pattern – at most three
/// space-separated names with an optional trailing `<email>`.
///
/// The `:author:` attribute-entry path uses this to tell whether a plain-name
/// value was partitioned by the fallback whitespace split (a name with four or
/// more parts, or one containing punctuation such as a comma) rather than by
/// the pattern. Only in the fallback case is the stored `author` value replaced
/// with the reconstructed, whitespace-condensed name (issue #758).
pub(crate) fn matches_author_pattern(source: &str) -> bool {
    AUTHOR.is_match(source.trim())
}

fn apply_author_subs(source: &str, parser: &Parser) -> String {
    let span = Span::new(source);
    let mut content = Content::from(span);

    use crate::content::SubstitutionStep;

    // Apply attribute references first.
    SubstitutionStep::AttributeReferences.apply(&mut content, parser, None);

    // Apply HTML encoding:
    // - Single attribute reference (like {full-author}): No HTML encoding.
    // - Single attribute in email position (like <{email}>): No HTML encoding.
    // - Multiple attributes or complex patterns: HTML encoding.
    // - Don't HTML encode if the content only has pre-existing HTML entities.
    let is_simple_single_attribute = source.trim().starts_with('{')
        && source.trim().ends_with('}')
        && source.matches('{').count() == 1;

    let has_multiple_attributes = source.matches('{').count() > 1;

    // Check if we should apply HTML encoding.
    let rendered = content.rendered();
    let has_angle_brackets = rendered.contains('<') && rendered.contains('>');
    let has_unencoded_ampersand = rendered.contains('&') && !rendered.contains("&amp;");

    if !is_simple_single_attribute
        && has_multiple_attributes
        && (has_angle_brackets || has_unencoded_ampersand)
    {
        SubstitutionStep::SpecialCharacters.apply(&mut content, parser, None);
    }

    content.rendered().to_string()
}

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

    use super::Author;

    // The `<`-branch of Asciidoctor's `process_authors` (`names_only`), reached
    // when an `:author:` attribute value's substitution produced inline HTML.
    // The rendered markup – with name-joiner underscores turned to spaces –
    // becomes `name`, while the name parts are partitioned from the tag-stripped
    // text so the formatting does not leak into them. No email is split off.
    mod parse_substituted_names_only {
        use super::Author;

        #[test]
        fn empty_input_is_none() {
            assert!(Author::parse_substituted_names_only("").is_none());
            assert!(Author::parse_substituted_names_only("   ").is_none());
        }

        #[test]
        fn markup_with_no_text_keeps_rendered_value_as_single_name() {
            // Stripping the tags leaves nothing to partition, so the rendered
            // markup stands as the whole name and `firstname`.
            let author = Author::parse_substituted_names_only("<a href=\"x\"></a>").unwrap();
            assert_eq!(author.name(), "<a href=\"x\"></a>");
            assert_eq!(author.firstname(), "<a href=\"x\"></a>");
            assert_eq!(author.middlename(), None);
            assert_eq!(author.lastname(), None);
            assert_eq!(author.email(), None);
        }

        #[test]
        fn single_name_part() {
            let author = Author::parse_substituted_names_only("<strong>Solo</strong>").unwrap();
            assert_eq!(author.name(), "<strong>Solo</strong>");
            assert_eq!(author.firstname(), "Solo");
            assert_eq!(author.middlename(), None);
            assert_eq!(author.lastname(), None);
        }

        #[test]
        fn first_and_last_name() {
            let author = Author::parse_substituted_names_only("<em>Kismet</em> Chameleon").unwrap();
            assert_eq!(author.firstname(), "Kismet");
            assert_eq!(author.middlename(), None);
            assert_eq!(author.lastname(), Some("Chameleon"));
        }

        #[test]
        fn first_middle_and_last_name() {
            let author =
                Author::parse_substituted_names_only("<em>Kismet</em> R. Chameleon").unwrap();
            assert_eq!(author.firstname(), "Kismet");
            assert_eq!(author.middlename(), Some("R."));
            assert_eq!(author.lastname(), Some("Chameleon"));
        }

        #[test]
        fn underscores_join_name_parts_and_the_rendered_name() {
            // Underscores act as name joiners: within a part they become a
            // space, and the full `name` has them replaced too.
            let author = Author::parse_substituted_names_only("<b>Ze_Project</b> team").unwrap();
            assert_eq!(author.name(), "<b>Ze Project</b> team");
            assert_eq!(author.firstname(), "Ze Project");
            assert_eq!(author.lastname(), Some("team"));
            assert_eq!(author.email(), None);
        }
    }

    // The entry dispatcher routes a *whole-value* `pass:[…]` macro to its
    // substituted value (the resolved content) and every other value to the
    // raw-value partitioning, so the literal macro syntax never leaks into the
    // name parts.
    mod parse_from_entry {
        use super::Author;
        use crate::Parser;

        #[test]
        fn pass_macro_with_markup_is_partitioned_from_the_substituted_value() {
            // The raw is the macro syntax; the substituted value is its rendered
            // output, which is what gets partitioned (tags stripped).
            let parser = Parser::default();
            let author = Author::parse_from_entry(
                "pass:n[https://example.org/x[Ze *team*]]",
                Some("<a href=\"https://example.org/x\">Ze <strong>team</strong></a>"),
                &parser,
            )
            .unwrap();

            assert_eq!(author.firstname(), "Ze");
            assert_eq!(author.lastname(), Some("team"));
        }

        #[test]
        fn pass_macro_resolving_to_plain_text_uses_the_substituted_value() {
            // A pass macro whose result has no markup must still be partitioned
            // from the substituted value, never the raw `pass:…[…]` syntax.
            let parser = Parser::default();
            let author =
                Author::parse_from_entry("pass:n[Doc Writer]", Some("Doc Writer"), &parser)
                    .unwrap();

            assert_eq!(author.name(), "Doc Writer");
            assert_eq!(author.firstname(), "Doc");
            assert_eq!(author.lastname(), Some("Writer"));
        }

        #[test]
        fn non_pass_value_uses_raw_partitioning() {
            // A value that is not a whole-value pass macro is partitioned from
            // the raw value as before (the substituted value is not consulted).
            let parser = Parser::default();
            let author =
                Author::parse_from_entry("Doc Writer", Some("Doc Writer"), &parser).unwrap();

            assert_eq!(author.firstname(), "Doc");
            assert_eq!(author.lastname(), Some("Writer"));
        }

        #[test]
        fn empty_pass_macro_yields_no_author() {
            // `pass:[]` resolves to an empty value, which describes no author.
            let parser = Parser::default();
            assert!(Author::parse_from_entry("pass:[]", Some(""), &parser).is_none());
        }
    }
}