asciidoc-parser 0.19.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
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
use std::{fmt::Debug, sync::LazyLock};

use regex::Regex;

use crate::{
    Parser,
    attributes::Attrlist,
    parser::{ResolvedReference, SafeMode},
};

/// An implementation of `InlineSubstitutionRenderer` is used when converting
/// the basic raw text of a simple block to the format which will ultimately be
/// presented in the final converted output.
///
/// An implementation is provided for HTML output; alternative implementations
/// (not provided in this crate) could support other output formats.
pub trait InlineSubstitutionRenderer: Debug {
    /// Renders the substitution for a special character.
    ///
    /// The renderer should write the appropriate rendering to `dest`.
    fn render_special_character(&self, type_: SpecialCharacter, dest: &mut String);

    /// Renders the content of a [quote substitution].
    ///
    /// The renderer should write the appropriate rendering to `dest`.
    ///
    /// [quote substitution]: https://docs.asciidoctor.org/asciidoc/latest/subs/quotes/
    fn render_quoted_substitition(
        &self,
        type_: QuoteType,
        scope: QuoteScope,
        attrlist: Option<Attrlist<'_>>,
        id: Option<String>,
        body: &str,
        dest: &mut String,
    );

    /// Renders the content of a [character replacement].
    ///
    /// The renderer should write the appropriate rendering to `dest`.
    ///
    /// [character replacement]: https://docs.asciidoctor.org/asciidoc/latest/subs/replacements/
    fn render_character_replacement(&self, type_: CharacterReplacementType, dest: &mut String);

    /// Renders a line break.
    ///
    /// The renderer should write an appropriate rendering of line break to
    /// `dest`.
    ///
    /// This is used in the implementation of [post-replacement substitutions].
    ///
    /// [post-replacement substitutions]: https://docs.asciidoctor.org/asciidoc/latest/subs/post-replacements/
    fn render_line_break(&self, dest: &mut String);

    /// Renders an image.
    ///
    /// The renderer should write an appropriate rendering of the specified
    /// image to `dest`.
    fn render_image(&self, params: &ImageRenderParams, dest: &mut String);

    /// Construct a URI reference or data URI to the target image.
    ///
    /// If the `target_image_path` is a URI reference, then leave it untouched.
    ///
    /// The `target_image_path` is resolved relative to the directory retrieved
    /// from the specified document-scoped attribute key, if provided.
    ///
    /// NOT YET IMPLEMENTED:
    /// If the `data-uri` attribute is set on the document, and the safe mode
    /// level is less than `SafeMode::SECURE`, the image will be safely
    /// converted to a data URI by reading it from the same directory. If
    /// neither of these conditions are satisfied, a relative path (i.e., URL)
    /// will be returned.
    ///
    /// ## Parameters
    ///
    /// * `target_image_path`: path to the target image
    /// * `parser`: Current document parser state
    /// * `asset_dir_key`: If provided, the attribute key used to look up the
    ///   directory where the image is located. If not provided, `imagesdir` is
    ///   used.
    ///
    /// ## Return
    ///
    /// Returns a string reference or data URI for the target image that can be
    /// safely used in an image tag.
    fn image_uri(
        &self,
        target_image_path: &str,
        parser: &Parser,
        asset_dir_key: Option<&str>,
    ) -> String;

    /// Renders an icon.
    ///
    /// The renderer should write an appropriate rendering of the specified
    /// icon to `dest`.
    fn render_icon(&self, params: &IconRenderParams, dest: &mut String);

    /// Construct a reference or data URI to an icon image for the specified
    /// icon name.
    ///
    /// The target image path is derived from the icon name. If the name already
    /// carries a file extension, it is used verbatim; otherwise the value of
    /// the `icontype` attribute (defaulting to `png`) is appended. In both
    /// cases the path is resolved relative to the `iconsdir` attribute.
    /// This mirrors the icon macro's image mode, where `icontype` is only
    /// consulted when the icon type must be inferred (i.e. the target has
    /// no file extension).
    ///
    /// The target image path is then passed through the `image_uri()` method.
    /// If the `data-uri` attribute is set on the document, the image will be
    /// safely converted to a data URI.
    ///
    /// The return value of this method can be safely used in an image tag.
    fn icon_uri(&self, name: &str, _attrlist: &Attrlist, parser: &Parser) -> String {
        let icon = if has_extname(name) {
            name.to_owned()
        } else {
            let icontype = parser
                .attribute_value("icontype")
                .as_maybe_str()
                .unwrap_or("png")
                .to_owned();

            format!("{name}.{icontype}")
        };

        self.image_uri(&icon, parser, Some("iconsdir"))
    }

    /// Renders a link.
    ///
    /// The renderer should write an appropriate rendering of the specified
    /// link, to `dest`.
    fn render_link(&self, params: &LinkRenderParams, dest: &mut String);

    /// Renders an anchor.
    ///
    /// The rendered should write an appropriate rendering of the specified
    /// anchor with ID and possible ref text (only used by some renderers).
    fn render_anchor(&self, id: &str, reftext: Option<String>, dest: &mut String);

    /// Renders a cross-reference.
    ///
    /// When [`XrefRenderParams::resolved`] is `Some`, the reference resolved to
    /// a destination; the renderer should link to it. When it is `None`, the
    /// reference could not be resolved and the renderer should emit a sensible
    /// fallback (e.g. a link to the raw target with bracketed text).
    fn render_xref(&self, params: &XrefRenderParams, dest: &mut String);

    /// Renders a [callout] number that annotates a line in a verbatim block.
    ///
    /// The renderer should write an appropriate rendering of the callout number
    /// to `dest`. The rendering typically depends on whether font-based or
    /// image-based icons are enabled (via the `icons` document attribute).
    ///
    /// [callout]: https://docs.asciidoctor.org/asciidoc/latest/verbatim/callouts/
    fn render_callout(&self, params: &CalloutRenderParams, dest: &mut String);

    /// Renders an [index term].
    ///
    /// A *flow* (visible) index term ([`IndexTermRenderParams::visible_term`]
    /// is `Some`) appears in the flow of text, so the renderer should write
    /// the term text to `dest`. A *concealed* index term ([`visible_term`]
    /// is `None`) does not appear in the rendered text, so the renderer
    /// should typically write nothing.
    ///
    /// Note that the built-in HTML5 converter never builds an index catalog;
    /// index terms only contribute markup in output formats (such as DocBook or
    /// PDF) that generate an index.
    ///
    /// [index term]: https://docs.asciidoctor.org/asciidoc/latest/sections/user-index/
    /// [`visible_term`]: IndexTermRenderParams::visible_term
    fn render_index_term(&self, params: &IndexTermRenderParams, dest: &mut String);

    /// Renders a [button] UI macro (`btn:[label]`).
    ///
    /// `text` is the already-normalized button label. The renderer should write
    /// an appropriate rendering (e.g. `<b class="button">label</b>`) to `dest`.
    ///
    /// [button]: https://docs.asciidoctor.org/asciidoc/latest/macros/ui-macros/
    fn render_button(&self, text: &str, dest: &mut String);

    /// Renders a [keyboard] UI macro (`kbd:[keys]`).
    ///
    /// `keys` holds one entry per key in the shortcut. A single-element slice
    /// is a lone key; multiple entries form a key sequence. The renderer
    /// should write an appropriate rendering (e.g. a lone `<kbd>` element,
    /// or a `<span class="keyseq">` wrapping several `<kbd>` elements) to
    /// `dest`.
    ///
    /// [keyboard]: https://docs.asciidoctor.org/asciidoc/latest/macros/keyboard-macro/
    fn render_keyboard(&self, keys: &[String], dest: &mut String);

    /// Renders a [menu] UI macro (`menu:menu[submenu > … > item]`).
    ///
    /// The renderer should write an appropriate rendering to `dest`.
    ///
    /// [menu]: https://docs.asciidoctor.org/asciidoc/latest/macros/ui-macros/
    fn render_menu(&self, params: &MenuRenderParams, dest: &mut String);

    /// Renders the inline reference produced by a [`footnote`] macro.
    ///
    /// The footnote's *text* is not rendered here (it is extracted to the
    /// document's footnote list); this method renders only the superscript
    /// marker that appears in the flow of text and links to the footnote.
    ///
    /// See [`FootnoteRenderParams`] for the three cases the renderer must
    /// handle (a defining occurrence, a reference to an earlier footnote, and
    /// an unresolved reference).
    ///
    /// [`footnote`]: https://docs.asciidoctor.org/asciidoc/latest/macros/footnote/
    fn render_footnote(&self, params: &FootnoteRenderParams, dest: &mut String);
}

/// Specifies which special character is being replaced in a call to
/// [`InlineSubstitutionRenderer::render_special_character`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SpecialCharacter {
    /// Replace `<` character.
    Lt,

    /// Replace `>` character.
    Gt,

    /// Replace `&` character.
    Ampersand,
}

/// Specifies which [quote type] is being rendered.
///
/// [quote type]: https://docs.asciidoctor.org/asciidoc/latest/subs/quotes/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QuoteType {
    /// Strong (often bold) formatting.
    Strong,

    /// Word(s) surrounded by smart double quotes.
    DoubleQuote,

    /// Word(s) surrounded by smart single quotes.
    SingleQuote,

    /// Monospace (code) formatting.
    Monospaced,

    /// Emphasis (often italic) formatting.
    Emphasis,

    /// Text range (span) formatted with zero or more styles.
    Mark,

    /// Superscript formatting.
    Superscript,

    /// Subscript formatting.
    Subscript,

    /// Surrounds a block of text that may need a `<span>` or similar tag.
    Unquoted,

    /// Inline AsciiMath expression, surrounded by AsciiMath math delimiters.
    AsciiMath,

    /// Inline LaTeX math expression, surrounded by LaTeX inline math
    /// delimiters.
    LatexMath,
}

/// Specifies whether the block is aligned to word boundaries or not.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum QuoteScope {
    /// The quoted section was aligned to word boundaries.
    Constrained,

    /// The quoted section may not have been aligned to word boundaries.
    Unconstrained,
}

/// Specifies which [character replacement] is being rendered.
///
/// [character replacement]: https://docs.asciidoctor.org/asciidoc/latest/subs/replacements/
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CharacterReplacementType {
    /// Copyright `(C)`.
    Copyright,

    /// Registered `(R)`.
    Registered,

    /// Trademark `(TM)`.
    Trademark,

    /// Em-dash surrounded by spaces ` -- `.
    EmDashSurroundedBySpaces,

    /// Em-dash without space `--`.
    EmDashWithoutSpace,

    /// Ellipsis `...`.
    Ellipsis,

    /// Single right arrow `->`.
    SingleRightArrow,

    /// Double right arrow `=>`.
    DoubleRightArrow,

    /// Single left arrow `<-`.
    SingleLeftArrow,

    /// Double left arrow `<=`.
    DoubleLeftArrow,

    /// Typographic apostrophe `'` within a word.
    TypographicApostrophe,

    /// Character reference `&___;`.
    CharacterReference(String),
}

/// Provides parsed parameters for an image to be rendered.
#[derive(Clone, Debug)]
pub struct ImageRenderParams<'a> {
    /// Target (the reference to the image).
    pub target: &'a str,

    /// Alt text (either explicitly set or defaulted).
    pub alt: String,

    /// Width. The data type is not checked; this may be any string.
    pub width: Option<&'a str>,

    /// Height. The data type is not checked; this may be any string.
    pub height: Option<&'a str>,

    /// Attribute list.
    pub attrlist: &'a Attrlist<'a>,

    /// Parser. The rendered may find document settings (such as an image
    /// directory) in the parser's document attributes.
    pub parser: &'a Parser,
}

/// Provides parsed parameters for an icon to be rendered.
#[derive(Clone, Debug)]
pub struct IconRenderParams<'a> {
    /// Target (the reference to the image).
    pub target: &'a str,

    /// Alt text (either explicitly set or defaulted).
    pub alt: String,

    /// Size. The data type is not checked; this may be any string.
    pub size: Option<&'a str>,

    /// Attribute list.
    pub attrlist: &'a Attrlist<'a>,

    /// Parser. The rendered may find document settings (such as an image
    /// directory) in the parser's document attributes.
    pub parser: &'a Parser,
}

/// Provides parsed parameters for an icon to be rendered.
#[derive(Clone, Debug)]
pub struct LinkRenderParams<'a> {
    /// Target (the target of this link).
    pub target: String,

    /// Link text.
    pub link_text: String,

    /// Roles (CSS classes) for this link not specified in the attrlist.
    pub extra_roles: Vec<&'a str>,

    /// Target window selection (passed through to `window` function in HTML).
    pub window: Option<&'static str>,

    /// What type of link is being rendered?
    pub type_: LinkRenderType,

    /// Attribute list.
    pub attrlist: &'a Attrlist<'a>,

    /// Parser. The rendered may find document settings (such as an image
    /// directory) in the parser's document attributes.
    pub parser: &'a Parser,
}

/// What type of link is being rendered?
#[derive(Clone, Debug)]
pub enum LinkRenderType {
    /// TEMPORARY: I don't know the different types of links yet.
    Link,
}

/// Provides parameters for rendering a [callout] number.
///
/// [callout]: https://docs.asciidoctor.org/asciidoc/latest/verbatim/callouts/
#[derive(Clone, Debug)]
pub struct CalloutRenderParams<'a> {
    /// The callout number to display. For automatically-numbered callouts
    /// (`<.>`), this is the resolved sequential number.
    pub number: &'a str,

    /// The guard surrounding the callout in the source. This controls whether
    /// (and how) the line-comment or XML-comment characters that hide the
    /// callout in the raw source are preserved in the output when icons are not
    /// enabled.
    pub guard: CalloutGuard<'a>,

    /// Parser. The renderer reads the `icons`, `iconsdir`, and `icontype`
    /// document attributes to decide how to render the callout.
    pub parser: &'a Parser,
}

/// Describes the characters that guard (hide) a callout number in verbatim
/// source.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CalloutGuard<'a> {
    /// A line-comment (or absent) guard. Holds the line-comment prefix that
    /// precedes the callout in the source (e.g. `# `), or an empty string when
    /// the callout is not tucked behind a line comment. When icons are not
    /// enabled, the prefix is preserved ahead of the rendered callout number.
    LineComment(&'a str),

    /// An XML comment guard (`<!--N-->`). When icons are not enabled, the XML
    /// comment delimiters are preserved around the rendered callout number.
    Xml,
}

/// Provides parameters for rendering a cross-reference.
#[derive(Clone, Debug)]
pub struct XrefRenderParams<'a> {
    /// The raw, uninterpreted cross-reference target as written in the source.
    pub target: &'a str,

    /// Explicit link text supplied in the cross-reference, if any.
    pub provided_text: Option<&'a str>,

    /// Target window selection from a `window` attribute on the `xref:` macro
    /// (e.g. `_blank`), or `None`. When `_blank`, the renderer also emits
    /// `rel="noopener"`, mirroring the link macro.
    pub window: Option<&'a str>,

    /// Roles supplied via a `role` attribute on the `xref:` macro. Empty when
    /// none were given.
    pub roles: &'a [String],

    /// The resolved destination, or `None` if the reference is unresolved.
    pub resolved: Option<&'a ResolvedReference>,
}

/// Provides parameters for rendering an [index term].
///
/// [index term]: https://docs.asciidoctor.org/asciidoc/latest/sections/user-index/
#[derive(Clone, Debug)]
pub struct IndexTermRenderParams<'a> {
    /// For a *flow* (visible) index term (`((term))` or `indexterm2:[term]`),
    /// the already-substituted primary term text to display in the flow of
    /// text. `None` for a *concealed* index term (`(((p, s, t)))` or
    /// `indexterm:[p, s, t]`), which produces no visible output.
    pub visible_term: Option<&'a str>,
}

/// Provides parameters for rendering a [menu] UI macro.
///
/// [menu]: https://docs.asciidoctor.org/asciidoc/latest/macros/ui-macros/
#[derive(Clone, Debug)]
pub struct MenuRenderParams<'a> {
    /// The top-level menu name.
    pub menu: &'a str,

    /// Zero or more intermediate submenu names, in order from outermost to
    /// innermost.
    pub submenus: &'a [String],

    /// The final menu item, if any. `None` renders a bare menu reference (a
    /// `menu:File[]` with no items).
    pub menuitem: Option<&'a str>,

    /// Parser, used to read the `icons` document attribute when choosing how to
    /// render the caret between menu levels.
    pub parser: &'a Parser,
}

/// Provides parameters for rendering the inline marker of a [`footnote`] macro.
///
/// There are three cases the renderer must distinguish:
///
/// * A *defining* occurrence (`index` is `Some`, `is_reference` is `false`):
///   the footnote introduces new text. The marker carries the footnote number
///   and, when the footnote was given an ID, an `id` of its own.
/// * A *reference* to an earlier footnote (`index` is `Some`, `is_reference` is
///   `true`): a later occurrence (`footnote:id[]`) that reuses an existing
///   footnote's number.
/// * An *unresolved* reference (`index` is `None`, `is_reference` is `true`): a
///   reference whose ID was never defined; the renderer emits a visible error
///   marker built from [`text`](Self::text).
///
/// [`footnote`]: https://docs.asciidoctor.org/asciidoc/latest/macros/footnote/
#[derive(Clone, Debug)]
pub struct FootnoteRenderParams<'a> {
    /// The footnote's number, or `None` for an unresolved reference. Normally a
    /// consecutive integer, but the `footnote-number` counter honors any seed
    /// the document sets, so it is passed through as text.
    pub index: Option<&'a str>,

    /// The footnote's own ID, used only on a defining occurrence to produce the
    /// `id="_footnote_<id>"` attribute on the marker.
    pub id: Option<&'a str>,

    /// `true` when this occurrence references an existing footnote (or fails to
    /// resolve one); `false` for the defining occurrence.
    pub is_reference: bool,

    /// For an unresolved reference, the text to show inside the error marker
    /// (the unresolved ID). Ignored in the other cases.
    pub text: &'a str,
}

/// Implementation of [`InlineSubstitutionRenderer`] that renders substitutions
/// for common HTML-based applications.
#[derive(Debug)]
pub struct HtmlSubstitutionRenderer {}

impl HtmlSubstitutionRenderer {
    /// Resolve an image target to a `src`/`data` reference, honoring a
    /// macro-level `imagesdir` attribute.
    ///
    /// A named `imagesdir` attribute _on the image macro itself_ overrides the
    /// document `imagesdir` for this one image (Asciidoctor 2.1+). When it is
    /// absent, resolution falls back to [`image_uri`], which uses the document
    /// `imagesdir`. As with the document attribute, an absolute-URL target
    /// ignores the base entirely.
    ///
    /// [`image_uri`]: InlineSubstitutionRenderer::image_uri
    fn image_src(&self, target: &str, attrlist: &Attrlist, parser: &Parser) -> String {
        match attrlist.named_attribute("imagesdir") {
            Some(imagesdir) => normalize_web_path(target, parser, Some(imagesdir.value()), true),
            None => self.image_uri(target, parser, None),
        }
    }
}

impl InlineSubstitutionRenderer for HtmlSubstitutionRenderer {
    fn render_special_character(&self, type_: SpecialCharacter, dest: &mut String) {
        match type_ {
            SpecialCharacter::Lt => {
                dest.push_str("&lt;");
            }
            SpecialCharacter::Gt => {
                dest.push_str("&gt;");
            }
            SpecialCharacter::Ampersand => {
                dest.push_str("&amp;");
            }
        }
    }

    fn render_quoted_substitition(
        &self,
        type_: QuoteType,
        _scope: QuoteScope,
        attrlist: Option<Attrlist<'_>>,
        mut id: Option<String>,
        body: &str,
        dest: &mut String,
    ) {
        let mut roles: Vec<&str> = attrlist.as_ref().map(|a| a.roles()).unwrap_or_default();

        if let Some(block_style) = attrlist
            .as_ref()
            .and_then(|a| a.nth_attribute(1))
            .and_then(|attr1| attr1.block_style())
        {
            roles.insert(0, block_style);
        }

        if id.is_none() {
            id = attrlist
                .as_ref()
                .and_then(|a| a.nth_attribute(1))
                .and_then(|attr1| attr1.id())
                .map(|id| id.to_owned())
        }

        match type_ {
            QuoteType::Strong => {
                wrap_body_in_html_tag(attrlist.as_ref(), "strong", id, roles, body, dest);
            }

            QuoteType::DoubleQuote => {
                dest.push_str("&#8220;");
                dest.push_str(body);
                dest.push_str("&#8221;");
            }

            QuoteType::SingleQuote => {
                dest.push_str("&#8216;");
                dest.push_str(body);
                dest.push_str("&#8217;");
            }

            QuoteType::Monospaced => {
                wrap_body_in_html_tag(attrlist.as_ref(), "code", id, roles, body, dest);
            }

            QuoteType::Emphasis => {
                wrap_body_in_html_tag(attrlist.as_ref(), "em", id, roles, body, dest);
            }

            QuoteType::Mark => {
                if roles.is_empty() && id.is_none() {
                    wrap_body_in_html_tag(attrlist.as_ref(), "mark", id, roles, body, dest);
                } else {
                    wrap_body_in_html_tag(attrlist.as_ref(), "span", id, roles, body, dest);
                }
            }

            QuoteType::Superscript => {
                wrap_body_in_html_tag(attrlist.as_ref(), "sup", id, roles, body, dest);
            }

            QuoteType::Subscript => {
                wrap_body_in_html_tag(attrlist.as_ref(), "sub", id, roles, body, dest);
            }

            QuoteType::Unquoted => {
                if roles.is_empty() && id.is_none() {
                    dest.push_str(body);
                } else {
                    wrap_body_in_html_tag(attrlist.as_ref(), "span", id, roles, body, dest);
                }
            }

            QuoteType::AsciiMath => {
                dest.push_str(r"\$");
                dest.push_str(body);
                dest.push_str(r"\$");
            }

            QuoteType::LatexMath => {
                dest.push_str(r"\(");
                dest.push_str(body);
                dest.push_str(r"\)");
            }
        }
    }

    fn render_character_replacement(&self, type_: CharacterReplacementType, dest: &mut String) {
        match type_ {
            CharacterReplacementType::Copyright => {
                dest.push_str("&#169;");
            }

            CharacterReplacementType::Registered => {
                dest.push_str("&#174;");
            }

            CharacterReplacementType::Trademark => {
                dest.push_str("&#8482;");
            }

            CharacterReplacementType::EmDashSurroundedBySpaces => {
                dest.push_str("&#8201;&#8212;&#8201;");
            }

            CharacterReplacementType::EmDashWithoutSpace => {
                dest.push_str("&#8212;&#8203;");
            }

            CharacterReplacementType::Ellipsis => {
                dest.push_str("&#8230;&#8203;");
            }

            CharacterReplacementType::SingleLeftArrow => {
                dest.push_str("&#8592;");
            }

            CharacterReplacementType::DoubleLeftArrow => {
                dest.push_str("&#8656;");
            }

            CharacterReplacementType::SingleRightArrow => {
                dest.push_str("&#8594;");
            }

            CharacterReplacementType::DoubleRightArrow => {
                dest.push_str("&#8658;");
            }

            CharacterReplacementType::TypographicApostrophe => {
                dest.push_str("&#8217;");
            }

            CharacterReplacementType::CharacterReference(name) => {
                dest.push('&');
                dest.push_str(&name);
                dest.push(';');
            }
        }
    }

    fn render_line_break(&self, dest: &mut String) {
        dest.push_str("<br>");
    }

    fn render_image(&self, params: &ImageRenderParams, dest: &mut String) {
        let src = self.image_src(params.target, params.attrlist, params.parser);
        let alt_encoded = encode_attribute_value(params.alt.clone());

        // The dimension attributes (width, height, and title) are shared by the
        // plain `<img>`, the interactive `<object>`, and the `<object>`'s image
        // fallback. Each fragment carries its own leading space so the pieces
        // concatenate cleanly after `src`/`alt` (or the `data` attribute).
        let mut dimension_attrs = String::new();

        if let Some(width) = params.width {
            dimension_attrs.push_str(&format!(r#" width="{width}""#));
        }

        if let Some(height) = params.height {
            dimension_attrs.push_str(&format!(r#" height="{height}""#));
        }

        if let Some(title) = params.attrlist.named_attribute("title") {
            dimension_attrs.push_str(&format!(
                r#" title="{title}""#,
                title = encode_attribute_value(title.value().to_owned())
            ));
        }

        let format = params
            .attrlist
            .named_attribute("format")
            .map(|format| format.value());

        // The `inline` and `interactive` SVG options are security-sensitive
        // (they embed file contents or a live `<object>`), so they only take
        // effect below the `Secure` safe mode. In `Secure` mode an SVG image
        // renders as an ordinary `<img>`, matching Ruby Asciidoctor.
        let svg_active = (format == Some("svg") || params.target.contains(".svg"))
            && params.parser.safe_mode() < SafeMode::Secure;

        let img = if svg_active && params.attrlist.has_option("inline") {
            // Embed the SVG contents directly. When the contents cannot be read
            // (no handler is registered, or it cannot find the file), fall back
            // to the alt text, mirroring Ruby Asciidoctor.
            read_svg_contents(&src, params.width, params.height, params.parser)
                .unwrap_or_else(|| format!(r#"<span class="alt">{alt}</span>"#, alt = params.alt))
        } else if svg_active && params.attrlist.has_option("interactive") {
            // Render an interactive SVG as an `<object>` element so its embedded
            // scripting and links remain live. A `fallback` image (or, failing
            // that, the alt text) is nested inside for user agents that can't
            // display the object.
            let fallback = if let Some(fallback) = params.attrlist.named_attribute("fallback") {
                let fallback_src = self.image_src(fallback.value(), params.attrlist, params.parser);
                format!(r#"<img src="{fallback_src}" alt="{alt_encoded}"{dimension_attrs}>"#)
            } else {
                format!(r#"<span class="alt">{alt}</span>"#, alt = params.alt)
            };

            format!(
                r#"<object type="image/svg+xml" data="{src}"{dimension_attrs}>{fallback}</object>"#
            )
        } else {
            format!(r#"<img src="{src}" alt="{alt_encoded}"{dimension_attrs}>"#)
        };

        render_icon_or_image(params.attrlist, &img, "image", dest);
    }

    fn image_uri(
        &self,
        target_image_path: &str,
        parser: &Parser,
        asset_dir_key: Option<&str>,
    ) -> String {
        let asset_dir_key = asset_dir_key.unwrap_or("imagesdir");

        // Asciidoctor embeds the image as a data URI when the `data-uri`
        // attribute is set and the safe mode is below `SafeMode::Secure`. That
        // requires reading the image's bytes, which this crate leaves to the
        // caller rather than performing file/network access itself; the
        // `data-uri` attribute is therefore not implemented and the image is
        // always emitted as a normalized web path. Because data-uri embedding is
        // absent, there is no safe-mode-sensitive behavior to gate here.
        let asset_dir = parser
            .attribute_value(asset_dir_key)
            .as_maybe_str()
            .map(|s| s.to_string());

        normalize_web_path(target_image_path, parser, asset_dir.as_deref(), true)
    }

    fn render_icon(&self, params: &IconRenderParams, dest: &mut String) {
        let src = self.icon_uri(params.target, params.attrlist, params.parser);

        let img = if params.parser.is_attribute_set("icons") {
            let icons = params.parser.attribute_value("icons");
            if let Some(icons) = icons.as_maybe_str()
                && icons == "font"
            {
                let mut i_class_attrs: Vec<String> = vec![
                    "fa".to_owned(),
                    format!("fa-{target}", target = params.target),
                ];

                if let Some(size) = params.attrlist.named_or_positional_attribute("size", 1) {
                    i_class_attrs.push(format!("fa-{size}", size = size.value()));
                }

                if let Some(flip) = params.attrlist.named_attribute("flip") {
                    i_class_attrs.push(format!("fa-flip-{flip}", flip = flip.value()));
                } else if let Some(rotate) = params.attrlist.named_attribute("rotate") {
                    i_class_attrs.push(format!("fa-rotate-{rotate}", rotate = rotate.value()));
                }

                format!(
                    r##"<i class="{i_class_attr_val}"{title_attr}></i>"##,
                    i_class_attr_val = i_class_attrs.join(" "),
                    title_attr = if let Some(title) = params.attrlist.named_attribute("title") {
                        format!(r#" title="{title}""#, title = title.value())
                    } else {
                        "".to_owned()
                    }
                )
            } else {
                let mut attrs: Vec<String> = vec![
                    format!(r#"src="{src}""#),
                    format!(
                        r#"alt="{alt}""#,
                        alt = encode_attribute_value(params.alt.to_string())
                    ),
                ];

                if let Some(width) = params.attrlist.named_attribute("width") {
                    attrs.push(format!(r#"width="{width}""#, width = width.value()));
                }

                if let Some(height) = params.attrlist.named_attribute("height") {
                    attrs.push(format!(r#"height="{height}""#, height = height.value()));
                }

                if let Some(title) = params.attrlist.named_attribute("title") {
                    attrs.push(format!(r#"title="{title}""#, title = title.value()));
                }

                format!(
                    "<img {attrs}{void_element_slash}>",
                    attrs = attrs.join(" "),
                    void_element_slash = "",
                )
            }
        } else {
            format!("[{alt}&#93;", alt = params.alt)
        };

        render_icon_or_image(params.attrlist, &img, "icon", dest);
    }

    fn render_link(&self, params: &LinkRenderParams, dest: &mut String) {
        let id = params.attrlist.id();

        let mut roles = params.extra_roles.clone();
        let mut attrlist_roles = params.attrlist.roles().clone();
        roles.append(&mut attrlist_roles);

        let link = format!(
            r##"<a href="{target}"{id}{class}{link_constraint_attrs}>{link_text}</a>"##,
            target = params.target,
            id = if let Some(id) = id {
                format!(r#" id="{id}""#)
            } else {
                "".to_owned()
            },
            class = if roles.is_empty() {
                "".to_owned()
            } else {
                format!(r#" class="{roles}""#, roles = roles.join(" "))
            },
            // title = %( title="#{node.attr 'title'}") if node.attr? 'title'
            // Haven't seen this in the wild yet.
            link_constraint_attrs = link_constraint_attrs(params.attrlist, params.window),
            link_text = params.link_text,
        );

        dest.push_str(&link);
    }

    fn render_anchor(&self, id: &str, _reftext: Option<String>, dest: &mut String) {
        dest.push_str(&format!("<a id=\"{id}\"></a>"));
    }

    fn render_xref(&self, params: &XrefRenderParams, dest: &mut String) {
        let class = if params.roles.is_empty() {
            String::new()
        } else {
            // Roles are author-supplied, so each is escaped before it is joined
            // into the `class` attribute (a stray `"` would otherwise break out
            // of the attribute).
            let roles = params
                .roles
                .iter()
                .map(|role| encode_html_attribute(role))
                .collect::<Vec<_>>()
                .join(" ");
            format!(r#" class="{roles}""#)
        };

        let constraint_attrs = xref_constraint_attrs(params.window);

        match params.resolved {
            Some(resolved) => {
                let text = params
                    .provided_text
                    .map(str::to_string)
                    .or_else(|| resolved.text.clone())
                    .unwrap_or_else(|| format!("[{target}]", target = params.target));

                dest.push_str(&format!(
                    r#"<a href="{href}"{class}{constraint_attrs}>{text}</a>"#,
                    href = resolved.href
                ));
            }

            None => {
                // Unresolved: link to the raw target and show bracketed text,
                // mirroring Asciidoctor's behavior for a missing reference.
                let text = params
                    .provided_text
                    .map(str::to_string)
                    .unwrap_or_else(|| format!("[{target}]", target = params.target));

                dest.push_str(&format!(
                    r##"<a href="#{target}"{class}{constraint_attrs}>{text}</a>"##,
                    target = params.target
                ));
            }
        }
    }

    fn render_callout(&self, params: &CalloutRenderParams, dest: &mut String) {
        let n = params.number;
        let parser = params.parser;

        if parser.attribute_value("icons").as_maybe_str() == Some("font") {
            dest.push_str(&format!(
                r#"<i class="conum" data-value="{n}"></i><b>({n})</b>"#
            ));
        } else if parser.is_attribute_set("icons") {
            let icontype = parser
                .attribute_value("icontype")
                .as_maybe_str()
                .unwrap_or("png")
                .to_owned();

            let icon = format!("callouts/{n}.{icontype}");
            let src = self.image_uri(&icon, parser, Some("iconsdir"));

            dest.push_str(&format!(r#"<img src="{src}" alt="{n}">"#));
        } else {
            match params.guard {
                CalloutGuard::Xml => {
                    dest.push_str(&format!(r#"&lt;!--<b class="conum">({n})</b>--&gt;"#));
                }

                CalloutGuard::LineComment(prefix) => {
                    dest.push_str(prefix);
                    dest.push_str(&format!(r#"<b class="conum">({n})</b>"#));
                }
            }
        }
    }

    fn render_index_term(&self, params: &IndexTermRenderParams, dest: &mut String) {
        // The HTML5 converter does not generate an index, so a concealed index
        // term produces no output and a flow index term renders only its
        // (already-substituted) visible term text.
        if let Some(term) = params.visible_term {
            dest.push_str(term);
        }
    }

    fn render_button(&self, text: &str, dest: &mut String) {
        dest.push_str(&format!(r#"<b class="button">{text}</b>"#));
    }

    fn render_keyboard(&self, keys: &[String], dest: &mut String) {
        if let [key] = keys {
            dest.push_str(&format!("<kbd>{key}</kbd>"));
        } else {
            // The visual separator is always `+`, even when the source used a
            // comma delimiter (e.g. `kbd:[Ctrl,T]`). This matches Asciidoctor's
            // HTML5 output, where the delimiter only selects how keys are split,
            // not how the sequence is displayed.
            dest.push_str(&format!(
                r#"<span class="keyseq"><kbd>{keys}</kbd></span>"#,
                keys = keys.join("</kbd>+<kbd>")
            ));
        }
    }

    fn render_menu(&self, params: &MenuRenderParams, dest: &mut String) {
        let caret = if params.parser.attribute_value("icons").as_maybe_str() == Some("font") {
            r#"&#160;<i class="fa fa-angle-right caret"></i> "#
        } else {
            r#"&#160;<b class="caret">&#8250;</b> "#
        };

        let menu = params.menu;

        if params.submenus.is_empty() {
            if let Some(menuitem) = params.menuitem {
                dest.push_str(&format!(
                    r#"<span class="menuseq"><b class="menu">{menu}</b>{caret}<b class="menuitem">{menuitem}</b></span>"#
                ));
            } else {
                dest.push_str(&format!(r#"<b class="menuref">{menu}</b>"#));
            }
        } else {
            let submenu_joiner = format!(r#"</b>{caret}<b class="submenu">"#);
            dest.push_str(&format!(
                r#"<span class="menuseq"><b class="menu">{menu}</b>{caret}<b class="submenu">{submenus}</b>{caret}<b class="menuitem">{menuitem}</b></span>"#,
                submenus = params.submenus.join(&submenu_joiner),
                menuitem = params.menuitem.unwrap_or_default(),
            ));
        }
    }

    fn render_footnote(&self, params: &FootnoteRenderParams, dest: &mut String) {
        match params.index {
            Some(index) if params.is_reference => {
                // A reference to an already-defined footnote reuses its number
                // but gets no anchor of its own.
                dest.push_str(&format!(
                    r##"<sup class="footnoteref">[<a class="footnote" href="#_footnotedef_{index}" title="View footnote.">{index}</a>]</sup>"##
                ));
            }

            Some(index) => {
                // A defining occurrence. When the footnote carries an ID, the
                // marker is given a matching anchor so it can be linked to.
                let id_attr = params
                    .id
                    .map(|id| format!(r#" id="_footnote_{id}""#))
                    .unwrap_or_default();

                dest.push_str(&format!(
                    r##"<sup class="footnote"{id_attr}>[<a id="_footnoteref_{index}" class="footnote" href="#_footnotedef_{index}" title="View footnote.">{index}</a>]</sup>"##
                ));
            }

            None => {
                // An unresolved reference: the ID was never defined.
                dest.push_str(&format!(
                    r#"<sup class="footnoteref red" title="Unresolved footnote reference.">[{text}]</sup>"#,
                    text = params.text
                ));
            }
        }
    }
}

fn wrap_body_in_html_tag(
    _attrlist: Option<&Attrlist<'_>>,
    tag: &'static str,
    id: Option<String>,
    roles: Vec<&str>,
    body: &str,
    dest: &mut String,
) {
    dest.push('<');
    dest.push_str(tag);

    if let Some(id) = id.as_ref() {
        dest.push_str(" id=\"");
        dest.push_str(id);
        dest.push('"');
    }

    if !roles.is_empty() {
        let roles = roles.join(" ");
        dest.push_str(" class=\"");
        dest.push_str(&roles);
        dest.push('"');
    }

    dest.push('>');
    dest.push_str(body);
    dest.push_str("</");
    dest.push_str(tag);
    dest.push('>');
}

fn render_icon_or_image(attrlist: &Attrlist, img: &str, type_: &'static str, dest: &mut String) {
    let mut img = img.to_string();

    // The `link` attribute value is used verbatim as the `href` (matching Ruby
    // Asciidoctor, which does not special-case `link=self`). This applies to
    // every image, including an inline SVG embedded in the flow of text.
    if let Some(link) = attrlist.named_attribute("link") {
        img = format!(
            r#"<a class="image" href="{link}"{link_constraint_attrs}>{img}</a>"#,
            link = link.value(),
            link_constraint_attrs = link_constraint_attrs(attrlist, None)
        );
    }

    let mut roles: Vec<&str> = attrlist.roles();

    if let Some(float) = attrlist.named_attribute("float") {
        roles.insert(0, float.value());
    }

    roles.insert(0, type_);

    dest.push_str(r#"<span class=""#);
    dest.push_str(&roles.join(" "));
    dest.push_str(r#"">"#);
    dest.push_str(&img);
    dest.push_str("</span>");
}

fn encode_attribute_value(value: String) -> String {
    value.replace('"', "&quot;")
}

/// Escapes a value for safe interpolation into an HTML attribute.
///
/// Unlike [`encode_attribute_value`] (which only guards the quote delimiter to
/// mirror Asciidoctor's image-alt handling), this escapes the full set of
/// characters that could break out of, or corrupt, an attribute value. It is
/// used for author-supplied `xref` `window`/`role` values, which — unlike the
/// hard-coded `window` strings the link macro passes — can contain arbitrary
/// text.
fn encode_html_attribute(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for c in value.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '"' => out.push_str("&quot;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            _ => out.push(c),
        }
    }
    out
}

fn normalize_web_path(
    target: &str,
    parser: &Parser,
    start: Option<&str>,
    preserve_uri_target: bool,
) -> String {
    if preserve_uri_target && is_uri_ish(target) {
        encode_spaces_in_uri(target)
    } else {
        parser.path_resolver.web_path(target, start)
    }
}

fn is_uri_ish(path: &str) -> bool {
    path.contains(':') && URI_SNIFF.is_match(path)
}

/// Reports whether the final path segment of `path` carries a file extension,
/// i.e. it contains a `.` that is neither the first nor the last character of
/// the segment. Mirrors Asciidoctor's `Helpers.extname?`, used by the icon
/// macro to decide whether the `icontype` attribute should be appended.
fn has_extname(path: &str) -> bool {
    let segment = path.rsplit(['/', '\\']).next().unwrap_or(path);
    match segment.rfind('.') {
        Some(i) => i > 0 && i < segment.len() - 1,
        None => false,
    }
}

fn encode_spaces_in_uri(s: &str) -> String {
    s.replace(' ', "%20")
}

/// Matches the opening `<svg …>` tag at the start of an SVG document.
///
/// Like Ruby Asciidoctor's equivalent (`/\A<svg[^>]*>/`), the `[^>]*` stops at
/// the first `>`, so a `>` appearing unencoded inside an attribute value would
/// truncate the match. That cannot happen in well-formed XML (where `>` must be
/// written as `&gt;`), so this only affects malformed input, and then only by
/// leaving the opening tag's dimensions unrewritten.
static SVG_START_TAG_RX: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(r"\A<svg[^>]*>").unwrap()
});

/// Matches a `width`, `height`, or `style` attribute (with its leading
/// whitespace) so they can be stripped from an SVG's opening tag.
static SVG_SNIFF_WIDTH_HEIGHT_RX: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(r#"(?s)\s+(?:width|height|style)=(?:"[^"]*"|'[^']*')"#).unwrap()
});

/// Reads and prepares the raw contents of an SVG file for inline embedding
/// (`image:target.svg[opts=inline]`).
///
/// The SVG contents are supplied by the parser's [`SvgFileHandler`]; when no
/// handler is registered (or it can't find the file) this returns `None` and
/// the caller falls back to rendering the alt text.
///
/// Before returning, the contents are prepared to match Ruby Asciidoctor:
///
/// * any XML preamble or doctype preceding the `<svg>` tag is removed, and
/// * if an explicit `width` and/or `height` was supplied on the macro, the
///   opening `<svg>` tag's own `width`, `height`, and `style` attributes are
///   dropped and the requested dimensions are appended in their place.
///
/// [`SvgFileHandler`]: crate::parser::SvgFileHandler
fn read_svg_contents(
    src: &str,
    width: Option<&str>,
    height: Option<&str>,
    parser: &Parser,
) -> Option<String> {
    let handler = parser.svg_file_handler.as_ref()?;
    let mut svg = handler.resolve_svg(src, parser)?;

    // Strip anything that precedes the opening `<svg>` tag (e.g. `<?xml … ?>`).
    if svg.starts_with('<')
        && let Some(start) = svg.find("<svg")
        && start > 0
    {
        svg = svg[start..].to_string();
    }

    // Rewrite the opening tag's dimensions only when at least one was supplied.
    if (width.is_some() || height.is_some())
        && let Some(start_tag) = SVG_START_TAG_RX.find(&svg).map(|m| m.as_str().to_string())
    {
        let rest = svg[start_tag.len()..].to_string();

        // Attributes between `<svg` and the closing `>`, with any existing
        // width/height/style removed.
        let inner = &start_tag[4..start_tag.len() - 1];
        let mut new_tag = format!("<svg{}", SVG_SNIFF_WIDTH_HEIGHT_RX.replace_all(inner, ""));

        if let Some(width) = width {
            new_tag.push_str(&format!(r#" width="{width}""#));
        }

        if let Some(height) = height {
            new_tag.push_str(&format!(r#" height="{height}""#));
        }

        new_tag.push('>');
        svg = format!("{new_tag}{rest}");
    }

    Some(svg)
}

/// Detects strings that resemble URIs.
///
/// ## Examples
///
/// * `http://domain`
/// * `https://domain`
/// * `file:///path`
/// * `data:info`
///
/// ## Counter-examples (do not match)
///
/// * `c:/sample.adoc`
/// * `c:\sample.adoc`
static URI_SNIFF: LazyLock<Regex> = LazyLock::new(|| {
    #[allow(clippy::unwrap_used)]
    Regex::new(
        r#"(?x)
        \A                             # Anchor to start of string
        \p{Alphabetic}                 # First character must be a letter
        [\p{Alphabetic}\p{Nd}.+-]+     # Followed by one or more alphanum or . + -
        :                              # Literal colon
        /{0,2}                         # Zero to two slashes
    "#,
    )
    .unwrap()
});

/// Builds the `target`/`rel` attributes for a cross-reference whose `xref:`
/// macro carried a `window` attribute. Mirrors the link macro: a `_blank`
/// window automatically adds `rel="noopener"`.
fn xref_constraint_attrs(window: Option<&str>) -> String {
    let Some(window) = window else {
        return String::new();
    };

    let rel_noopener = if window == "_blank" {
        r#" rel="noopener""#
    } else {
        ""
    };

    // The `window` value is author-supplied, so it is escaped before being
    // interpolated into the `target` attribute. The `_blank` comparison above
    // runs on the raw value, which is correct for the well-formed inputs that
    // trigger `rel="noopener"`.
    format!(
        r#" target="{window}"{rel_noopener}"#,
        window = encode_html_attribute(window)
    )
}

fn link_constraint_attrs(attrlist: &Attrlist<'_>, window: Option<&'static str>) -> String {
    let rel = if attrlist.has_option("nofollow") {
        Some("nofollow")
    } else {
        None
    };

    if let Some(window) = attrlist
        .named_attribute("window")
        .map(|a| a.value())
        .or(window)
    {
        let rel_noopener = if window == "_blank" || attrlist.has_option("noopener") {
            if let Some(rel) = rel {
                format!(r#" rel="{rel}" noopener"#)
            } else {
                r#" rel="noopener""#.to_owned()
            }
        } else {
            "".to_string()
        };

        format!(r#" target="{window}"{rel_noopener}"#)
    } else if let Some(rel) = rel {
        format!(r#" rel="{rel}""#)
    } else {
        "".to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::encode_html_attribute;

    #[test]
    fn encode_html_attribute_escapes_special_characters() {
        // Each of the four characters that could break out of or corrupt an
        // HTML attribute value is replaced with its entity; ordinary characters
        // pass through untouched.
        assert_eq!(
            encode_html_attribute(r#"a&b"c<d>e"#),
            "a&amp;b&quot;c&lt;d&gt;e"
        );
        assert_eq!(encode_html_attribute("plain"), "plain");
    }
}