asciidoc_parser/parser/inline_substitution_renderer.rs
1use std::{fmt::Debug, sync::LazyLock};
2
3use regex::Regex;
4
5use crate::{
6 Parser,
7 attributes::Attrlist,
8 parser::{ResolvedReference, SafeMode},
9};
10
11/// An implementation of `InlineSubstitutionRenderer` is used when converting
12/// the basic raw text of a simple block to the format which will ultimately be
13/// presented in the final converted output.
14///
15/// An implementation is provided for HTML output; alternative implementations
16/// (not provided in this crate) could support other output formats.
17pub trait InlineSubstitutionRenderer: Debug {
18 /// Renders the substitution for a special character.
19 ///
20 /// The renderer should write the appropriate rendering to `dest`.
21 fn render_special_character(&self, type_: SpecialCharacter, dest: &mut String);
22
23 /// Renders the content of a [quote substitution].
24 ///
25 /// The renderer should write the appropriate rendering to `dest`.
26 ///
27 /// [quote substitution]: https://docs.asciidoctor.org/asciidoc/latest/subs/quotes/
28 fn render_quoted_substitition(
29 &self,
30 type_: QuoteType,
31 scope: QuoteScope,
32 attrlist: Option<Attrlist<'_>>,
33 id: Option<String>,
34 body: &str,
35 dest: &mut String,
36 );
37
38 /// Renders the content of a [character replacement].
39 ///
40 /// The renderer should write the appropriate rendering to `dest`.
41 ///
42 /// [character replacement]: https://docs.asciidoctor.org/asciidoc/latest/subs/replacements/
43 fn render_character_replacement(&self, type_: CharacterReplacementType, dest: &mut String);
44
45 /// Renders a line break.
46 ///
47 /// The renderer should write an appropriate rendering of line break to
48 /// `dest`.
49 ///
50 /// This is used in the implementation of [post-replacement substitutions].
51 ///
52 /// [post-replacement substitutions]: https://docs.asciidoctor.org/asciidoc/latest/subs/post-replacements/
53 fn render_line_break(&self, dest: &mut String);
54
55 /// Renders an image.
56 ///
57 /// The renderer should write an appropriate rendering of the specified
58 /// image to `dest`.
59 fn render_image(&self, params: &ImageRenderParams, dest: &mut String);
60
61 /// Construct a URI reference or data URI to the target image.
62 ///
63 /// If the `target_image_path` is a URI reference, then leave it untouched.
64 ///
65 /// The `target_image_path` is resolved relative to the directory retrieved
66 /// from the specified document-scoped attribute key, if provided.
67 ///
68 /// NOT YET IMPLEMENTED:
69 /// If the `data-uri` attribute is set on the document, and the safe mode
70 /// level is less than `SafeMode::SECURE`, the image will be safely
71 /// converted to a data URI by reading it from the same directory. If
72 /// neither of these conditions are satisfied, a relative path (i.e., URL)
73 /// will be returned.
74 ///
75 /// ## Parameters
76 ///
77 /// * `target_image_path`: path to the target image
78 /// * `parser`: Current document parser state
79 /// * `asset_dir_key`: If provided, the attribute key used to look up the
80 /// directory where the image is located. If not provided, `imagesdir` is
81 /// used.
82 ///
83 /// ## Return
84 ///
85 /// Returns a string reference or data URI for the target image that can be
86 /// safely used in an image tag.
87 fn image_uri(
88 &self,
89 target_image_path: &str,
90 parser: &Parser,
91 asset_dir_key: Option<&str>,
92 ) -> String;
93
94 /// Renders an icon.
95 ///
96 /// The renderer should write an appropriate rendering of the specified
97 /// icon to `dest`.
98 fn render_icon(&self, params: &IconRenderParams, dest: &mut String);
99
100 /// Construct a reference or data URI to an icon image for the specified
101 /// icon name.
102 ///
103 /// The target image path is derived from the icon name. If the name already
104 /// carries a file extension, it is used verbatim; otherwise the value of
105 /// the `icontype` attribute (defaulting to `png`) is appended. In both
106 /// cases the path is resolved relative to the `iconsdir` attribute.
107 /// This mirrors the icon macro's image mode, where `icontype` is only
108 /// consulted when the icon type must be inferred (i.e. the target has
109 /// no file extension).
110 ///
111 /// The target image path is then passed through the `image_uri()` method.
112 /// If the `data-uri` attribute is set on the document, the image will be
113 /// safely converted to a data URI.
114 ///
115 /// The return value of this method can be safely used in an image tag.
116 fn icon_uri(&self, name: &str, _attrlist: &Attrlist, parser: &Parser) -> String {
117 let icon = if has_extname(name) {
118 name.to_owned()
119 } else {
120 let icontype = parser
121 .attribute_value("icontype")
122 .as_maybe_str()
123 .unwrap_or("png")
124 .to_owned();
125
126 format!("{name}.{icontype}")
127 };
128
129 self.image_uri(&icon, parser, Some("iconsdir"))
130 }
131
132 /// Renders a link.
133 ///
134 /// The renderer should write an appropriate rendering of the specified
135 /// link, to `dest`.
136 fn render_link(&self, params: &LinkRenderParams, dest: &mut String);
137
138 /// Renders an anchor.
139 ///
140 /// The rendered should write an appropriate rendering of the specified
141 /// anchor with ID and possible ref text (only used by some renderers).
142 fn render_anchor(&self, id: &str, reftext: Option<String>, dest: &mut String);
143
144 /// Renders a cross-reference.
145 ///
146 /// When [`XrefRenderParams::resolved`] is `Some`, the reference resolved to
147 /// a destination; the renderer should link to it. When it is `None`, the
148 /// reference could not be resolved and the renderer should emit a sensible
149 /// fallback (e.g. a link to the raw target with bracketed text).
150 fn render_xref(&self, params: &XrefRenderParams, dest: &mut String);
151
152 /// Renders a [callout] number that annotates a line in a verbatim block.
153 ///
154 /// The renderer should write an appropriate rendering of the callout number
155 /// to `dest`. The rendering typically depends on whether font-based or
156 /// image-based icons are enabled (via the `icons` document attribute).
157 ///
158 /// [callout]: https://docs.asciidoctor.org/asciidoc/latest/verbatim/callouts/
159 fn render_callout(&self, params: &CalloutRenderParams, dest: &mut String);
160
161 /// Renders an [index term].
162 ///
163 /// A *flow* (visible) index term ([`IndexTermRenderParams::visible_term`]
164 /// is `Some`) appears in the flow of text, so the renderer should write
165 /// the term text to `dest`. A *concealed* index term ([`visible_term`]
166 /// is `None`) does not appear in the rendered text, so the renderer
167 /// should typically write nothing.
168 ///
169 /// Note that the built-in HTML5 converter never builds an index catalog;
170 /// index terms only contribute markup in output formats (such as DocBook or
171 /// PDF) that generate an index.
172 ///
173 /// [index term]: https://docs.asciidoctor.org/asciidoc/latest/sections/user-index/
174 /// [`visible_term`]: IndexTermRenderParams::visible_term
175 fn render_index_term(&self, params: &IndexTermRenderParams, dest: &mut String);
176
177 /// Renders a [button] UI macro (`btn:[label]`).
178 ///
179 /// `text` is the already-normalized button label. The renderer should write
180 /// an appropriate rendering (e.g. `<b class="button">label</b>`) to `dest`.
181 ///
182 /// [button]: https://docs.asciidoctor.org/asciidoc/latest/macros/ui-macros/
183 fn render_button(&self, text: &str, dest: &mut String);
184
185 /// Renders a [keyboard] UI macro (`kbd:[keys]`).
186 ///
187 /// `keys` holds one entry per key in the shortcut. A single-element slice
188 /// is a lone key; multiple entries form a key sequence. The renderer
189 /// should write an appropriate rendering (e.g. a lone `<kbd>` element,
190 /// or a `<span class="keyseq">` wrapping several `<kbd>` elements) to
191 /// `dest`.
192 ///
193 /// [keyboard]: https://docs.asciidoctor.org/asciidoc/latest/macros/keyboard-macro/
194 fn render_keyboard(&self, keys: &[String], dest: &mut String);
195
196 /// Renders a [menu] UI macro (`menu:menu[submenu > … > item]`).
197 ///
198 /// The renderer should write an appropriate rendering to `dest`.
199 ///
200 /// [menu]: https://docs.asciidoctor.org/asciidoc/latest/macros/ui-macros/
201 fn render_menu(&self, params: &MenuRenderParams, dest: &mut String);
202
203 /// Renders the inline reference produced by a [`footnote`] macro.
204 ///
205 /// The footnote's *text* is not rendered here (it is extracted to the
206 /// document's footnote list); this method renders only the superscript
207 /// marker that appears in the flow of text and links to the footnote.
208 ///
209 /// See [`FootnoteRenderParams`] for the three cases the renderer must
210 /// handle (a defining occurrence, a reference to an earlier footnote, and
211 /// an unresolved reference).
212 ///
213 /// [`footnote`]: https://docs.asciidoctor.org/asciidoc/latest/macros/footnote/
214 fn render_footnote(&self, params: &FootnoteRenderParams, dest: &mut String);
215}
216
217/// Specifies which special character is being replaced in a call to
218/// [`InlineSubstitutionRenderer::render_special_character`].
219#[derive(Clone, Copy, Debug, Eq, PartialEq)]
220pub enum SpecialCharacter {
221 /// Replace `<` character.
222 Lt,
223
224 /// Replace `>` character.
225 Gt,
226
227 /// Replace `&` character.
228 Ampersand,
229}
230
231/// Specifies which [quote type] is being rendered.
232///
233/// [quote type]: https://docs.asciidoctor.org/asciidoc/latest/subs/quotes/
234#[derive(Clone, Copy, Debug, Eq, PartialEq)]
235pub enum QuoteType {
236 /// Strong (often bold) formatting.
237 Strong,
238
239 /// Word(s) surrounded by smart double quotes.
240 DoubleQuote,
241
242 /// Word(s) surrounded by smart single quotes.
243 SingleQuote,
244
245 /// Monospace (code) formatting.
246 Monospaced,
247
248 /// Emphasis (often italic) formatting.
249 Emphasis,
250
251 /// Text range (span) formatted with zero or more styles.
252 Mark,
253
254 /// Superscript formatting.
255 Superscript,
256
257 /// Subscript formatting.
258 Subscript,
259
260 /// Surrounds a block of text that may need a `<span>` or similar tag.
261 Unquoted,
262
263 /// Inline AsciiMath expression, surrounded by AsciiMath math delimiters.
264 AsciiMath,
265
266 /// Inline LaTeX math expression, surrounded by LaTeX inline math
267 /// delimiters.
268 LatexMath,
269}
270
271/// Specifies whether the block is aligned to word boundaries or not.
272#[derive(Clone, Copy, Debug, Eq, PartialEq)]
273pub enum QuoteScope {
274 /// The quoted section was aligned to word boundaries.
275 Constrained,
276
277 /// The quoted section may not have been aligned to word boundaries.
278 Unconstrained,
279}
280
281/// Specifies which [character replacement] is being rendered.
282///
283/// [character replacement]: https://docs.asciidoctor.org/asciidoc/latest/subs/replacements/
284#[derive(Clone, Debug, Eq, PartialEq)]
285pub enum CharacterReplacementType {
286 /// Copyright `(C)`.
287 Copyright,
288
289 /// Registered `(R)`.
290 Registered,
291
292 /// Trademark `(TM)`.
293 Trademark,
294
295 /// Em-dash surrounded by spaces ` -- `.
296 EmDashSurroundedBySpaces,
297
298 /// Em-dash without space `--`.
299 EmDashWithoutSpace,
300
301 /// Ellipsis `...`.
302 Ellipsis,
303
304 /// Single right arrow `->`.
305 SingleRightArrow,
306
307 /// Double right arrow `=>`.
308 DoubleRightArrow,
309
310 /// Single left arrow `<-`.
311 SingleLeftArrow,
312
313 /// Double left arrow `<=`.
314 DoubleLeftArrow,
315
316 /// Typographic apostrophe `'` within a word.
317 TypographicApostrophe,
318
319 /// Character reference `&___;`.
320 CharacterReference(String),
321}
322
323/// Provides parsed parameters for an image to be rendered.
324#[derive(Clone, Debug)]
325pub struct ImageRenderParams<'a> {
326 /// Target (the reference to the image).
327 pub target: &'a str,
328
329 /// Alt text (either explicitly set or defaulted).
330 pub alt: String,
331
332 /// Width. The data type is not checked; this may be any string.
333 pub width: Option<&'a str>,
334
335 /// Height. The data type is not checked; this may be any string.
336 pub height: Option<&'a str>,
337
338 /// Attribute list.
339 pub attrlist: &'a Attrlist<'a>,
340
341 /// Parser. The rendered may find document settings (such as an image
342 /// directory) in the parser's document attributes.
343 pub parser: &'a Parser,
344}
345
346/// Provides parsed parameters for an icon to be rendered.
347#[derive(Clone, Debug)]
348pub struct IconRenderParams<'a> {
349 /// Target (the reference to the image).
350 pub target: &'a str,
351
352 /// Alt text (either explicitly set or defaulted).
353 pub alt: String,
354
355 /// Size. The data type is not checked; this may be any string.
356 pub size: Option<&'a str>,
357
358 /// Attribute list.
359 pub attrlist: &'a Attrlist<'a>,
360
361 /// Parser. The rendered may find document settings (such as an image
362 /// directory) in the parser's document attributes.
363 pub parser: &'a Parser,
364}
365
366/// Provides parsed parameters for an icon to be rendered.
367#[derive(Clone, Debug)]
368pub struct LinkRenderParams<'a> {
369 /// Target (the target of this link).
370 pub target: String,
371
372 /// Link text.
373 pub link_text: String,
374
375 /// Roles (CSS classes) for this link not specified in the attrlist.
376 pub extra_roles: Vec<&'a str>,
377
378 /// Target window selection (passed through to `window` function in HTML).
379 pub window: Option<&'static str>,
380
381 /// What type of link is being rendered?
382 pub type_: LinkRenderType,
383
384 /// Attribute list.
385 pub attrlist: &'a Attrlist<'a>,
386
387 /// Parser. The rendered may find document settings (such as an image
388 /// directory) in the parser's document attributes.
389 pub parser: &'a Parser,
390}
391
392/// What type of link is being rendered?
393#[derive(Clone, Debug)]
394pub enum LinkRenderType {
395 /// TEMPORARY: I don't know the different types of links yet.
396 Link,
397}
398
399/// Provides parameters for rendering a [callout] number.
400///
401/// [callout]: https://docs.asciidoctor.org/asciidoc/latest/verbatim/callouts/
402#[derive(Clone, Debug)]
403pub struct CalloutRenderParams<'a> {
404 /// The callout number to display. For automatically-numbered callouts
405 /// (`<.>`), this is the resolved sequential number.
406 pub number: &'a str,
407
408 /// The guard surrounding the callout in the source. This controls whether
409 /// (and how) the line-comment or XML-comment characters that hide the
410 /// callout in the raw source are preserved in the output when icons are not
411 /// enabled.
412 pub guard: CalloutGuard<'a>,
413
414 /// Parser. The renderer reads the `icons`, `iconsdir`, and `icontype`
415 /// document attributes to decide how to render the callout.
416 pub parser: &'a Parser,
417}
418
419/// Describes the characters that guard (hide) a callout number in verbatim
420/// source.
421#[derive(Clone, Debug, Eq, PartialEq)]
422pub enum CalloutGuard<'a> {
423 /// A line-comment (or absent) guard. Holds the line-comment prefix that
424 /// precedes the callout in the source (e.g. `# `), or an empty string when
425 /// the callout is not tucked behind a line comment. When icons are not
426 /// enabled, the prefix is preserved ahead of the rendered callout number.
427 LineComment(&'a str),
428
429 /// An XML comment guard (`<!--N-->`). When icons are not enabled, the XML
430 /// comment delimiters are preserved around the rendered callout number.
431 Xml,
432}
433
434/// Provides parameters for rendering a cross-reference.
435#[derive(Clone, Debug)]
436pub struct XrefRenderParams<'a> {
437 /// The raw, uninterpreted cross-reference target as written in the source.
438 pub target: &'a str,
439
440 /// Explicit link text supplied in the cross-reference, if any.
441 pub provided_text: Option<&'a str>,
442
443 /// Target window selection from a `window` attribute on the `xref:` macro
444 /// (e.g. `_blank`), or `None`. When `_blank`, the renderer also emits
445 /// `rel="noopener"`, mirroring the link macro.
446 pub window: Option<&'a str>,
447
448 /// Roles supplied via a `role` attribute on the `xref:` macro. Empty when
449 /// none were given.
450 pub roles: &'a [String],
451
452 /// The resolved destination, or `None` if the reference is unresolved.
453 pub resolved: Option<&'a ResolvedReference>,
454}
455
456/// Provides parameters for rendering an [index term].
457///
458/// [index term]: https://docs.asciidoctor.org/asciidoc/latest/sections/user-index/
459#[derive(Clone, Debug)]
460pub struct IndexTermRenderParams<'a> {
461 /// For a *flow* (visible) index term (`((term))` or `indexterm2:[term]`),
462 /// the already-substituted primary term text to display in the flow of
463 /// text. `None` for a *concealed* index term (`(((p, s, t)))` or
464 /// `indexterm:[p, s, t]`), which produces no visible output.
465 pub visible_term: Option<&'a str>,
466}
467
468/// Provides parameters for rendering a [menu] UI macro.
469///
470/// [menu]: https://docs.asciidoctor.org/asciidoc/latest/macros/ui-macros/
471#[derive(Clone, Debug)]
472pub struct MenuRenderParams<'a> {
473 /// The top-level menu name.
474 pub menu: &'a str,
475
476 /// Zero or more intermediate submenu names, in order from outermost to
477 /// innermost.
478 pub submenus: &'a [String],
479
480 /// The final menu item, if any. `None` renders a bare menu reference (a
481 /// `menu:File[]` with no items).
482 pub menuitem: Option<&'a str>,
483
484 /// Parser, used to read the `icons` document attribute when choosing how to
485 /// render the caret between menu levels.
486 pub parser: &'a Parser,
487}
488
489/// Provides parameters for rendering the inline marker of a [`footnote`] macro.
490///
491/// There are three cases the renderer must distinguish:
492///
493/// * A *defining* occurrence (`index` is `Some`, `is_reference` is `false`):
494/// the footnote introduces new text. The marker carries the footnote number
495/// and, when the footnote was given an ID, an `id` of its own.
496/// * A *reference* to an earlier footnote (`index` is `Some`, `is_reference` is
497/// `true`): a later occurrence (`footnote:id[]`) that reuses an existing
498/// footnote's number.
499/// * An *unresolved* reference (`index` is `None`, `is_reference` is `true`): a
500/// reference whose ID was never defined; the renderer emits a visible error
501/// marker built from [`text`](Self::text).
502///
503/// [`footnote`]: https://docs.asciidoctor.org/asciidoc/latest/macros/footnote/
504#[derive(Clone, Debug)]
505pub struct FootnoteRenderParams<'a> {
506 /// The footnote's number, or `None` for an unresolved reference. Normally a
507 /// consecutive integer, but the `footnote-number` counter honors any seed
508 /// the document sets, so it is passed through as text.
509 pub index: Option<&'a str>,
510
511 /// The footnote's own ID, used only on a defining occurrence to produce the
512 /// `id="_footnote_<id>"` attribute on the marker.
513 pub id: Option<&'a str>,
514
515 /// `true` when this occurrence references an existing footnote (or fails to
516 /// resolve one); `false` for the defining occurrence.
517 pub is_reference: bool,
518
519 /// For an unresolved reference, the text to show inside the error marker
520 /// (the unresolved ID). Ignored in the other cases.
521 pub text: &'a str,
522}
523
524/// Implementation of [`InlineSubstitutionRenderer`] that renders substitutions
525/// for common HTML-based applications.
526#[derive(Debug)]
527pub struct HtmlSubstitutionRenderer {}
528
529impl HtmlSubstitutionRenderer {
530 /// Resolve an image target to a `src`/`data` reference, honoring a
531 /// macro-level `imagesdir` attribute.
532 ///
533 /// A named `imagesdir` attribute _on the image macro itself_ overrides the
534 /// document `imagesdir` for this one image (Asciidoctor 2.1+). When it is
535 /// absent, resolution falls back to [`image_uri`], which uses the document
536 /// `imagesdir`. As with the document attribute, an absolute-URL target
537 /// ignores the base entirely.
538 ///
539 /// [`image_uri`]: InlineSubstitutionRenderer::image_uri
540 fn image_src(&self, target: &str, attrlist: &Attrlist, parser: &Parser) -> String {
541 match attrlist.named_attribute("imagesdir") {
542 Some(imagesdir) => normalize_web_path(target, parser, Some(imagesdir.value()), true),
543 None => self.image_uri(target, parser, None),
544 }
545 }
546}
547
548impl InlineSubstitutionRenderer for HtmlSubstitutionRenderer {
549 fn render_special_character(&self, type_: SpecialCharacter, dest: &mut String) {
550 match type_ {
551 SpecialCharacter::Lt => {
552 dest.push_str("<");
553 }
554 SpecialCharacter::Gt => {
555 dest.push_str(">");
556 }
557 SpecialCharacter::Ampersand => {
558 dest.push_str("&");
559 }
560 }
561 }
562
563 fn render_quoted_substitition(
564 &self,
565 type_: QuoteType,
566 _scope: QuoteScope,
567 attrlist: Option<Attrlist<'_>>,
568 mut id: Option<String>,
569 body: &str,
570 dest: &mut String,
571 ) {
572 let mut roles: Vec<&str> = attrlist.as_ref().map(|a| a.roles()).unwrap_or_default();
573
574 if let Some(block_style) = attrlist
575 .as_ref()
576 .and_then(|a| a.nth_attribute(1))
577 .and_then(|attr1| attr1.block_style())
578 {
579 roles.insert(0, block_style);
580 }
581
582 if id.is_none() {
583 id = attrlist
584 .as_ref()
585 .and_then(|a| a.nth_attribute(1))
586 .and_then(|attr1| attr1.id())
587 .map(|id| id.to_owned())
588 }
589
590 match type_ {
591 QuoteType::Strong => {
592 wrap_body_in_html_tag(attrlist.as_ref(), "strong", id, roles, body, dest);
593 }
594
595 QuoteType::DoubleQuote => {
596 dest.push_str("“");
597 dest.push_str(body);
598 dest.push_str("”");
599 }
600
601 QuoteType::SingleQuote => {
602 dest.push_str("‘");
603 dest.push_str(body);
604 dest.push_str("’");
605 }
606
607 QuoteType::Monospaced => {
608 wrap_body_in_html_tag(attrlist.as_ref(), "code", id, roles, body, dest);
609 }
610
611 QuoteType::Emphasis => {
612 wrap_body_in_html_tag(attrlist.as_ref(), "em", id, roles, body, dest);
613 }
614
615 QuoteType::Mark => {
616 if roles.is_empty() && id.is_none() {
617 wrap_body_in_html_tag(attrlist.as_ref(), "mark", id, roles, body, dest);
618 } else {
619 wrap_body_in_html_tag(attrlist.as_ref(), "span", id, roles, body, dest);
620 }
621 }
622
623 QuoteType::Superscript => {
624 wrap_body_in_html_tag(attrlist.as_ref(), "sup", id, roles, body, dest);
625 }
626
627 QuoteType::Subscript => {
628 wrap_body_in_html_tag(attrlist.as_ref(), "sub", id, roles, body, dest);
629 }
630
631 QuoteType::Unquoted => {
632 if roles.is_empty() && id.is_none() {
633 dest.push_str(body);
634 } else {
635 wrap_body_in_html_tag(attrlist.as_ref(), "span", id, roles, body, dest);
636 }
637 }
638
639 QuoteType::AsciiMath => {
640 dest.push_str(r"\$");
641 dest.push_str(body);
642 dest.push_str(r"\$");
643 }
644
645 QuoteType::LatexMath => {
646 dest.push_str(r"\(");
647 dest.push_str(body);
648 dest.push_str(r"\)");
649 }
650 }
651 }
652
653 fn render_character_replacement(&self, type_: CharacterReplacementType, dest: &mut String) {
654 match type_ {
655 CharacterReplacementType::Copyright => {
656 dest.push_str("©");
657 }
658
659 CharacterReplacementType::Registered => {
660 dest.push_str("®");
661 }
662
663 CharacterReplacementType::Trademark => {
664 dest.push_str("™");
665 }
666
667 CharacterReplacementType::EmDashSurroundedBySpaces => {
668 dest.push_str(" — ");
669 }
670
671 CharacterReplacementType::EmDashWithoutSpace => {
672 dest.push_str("—​");
673 }
674
675 CharacterReplacementType::Ellipsis => {
676 dest.push_str("…​");
677 }
678
679 CharacterReplacementType::SingleLeftArrow => {
680 dest.push_str("←");
681 }
682
683 CharacterReplacementType::DoubleLeftArrow => {
684 dest.push_str("⇐");
685 }
686
687 CharacterReplacementType::SingleRightArrow => {
688 dest.push_str("→");
689 }
690
691 CharacterReplacementType::DoubleRightArrow => {
692 dest.push_str("⇒");
693 }
694
695 CharacterReplacementType::TypographicApostrophe => {
696 dest.push_str("’");
697 }
698
699 CharacterReplacementType::CharacterReference(name) => {
700 dest.push('&');
701 dest.push_str(&name);
702 dest.push(';');
703 }
704 }
705 }
706
707 fn render_line_break(&self, dest: &mut String) {
708 dest.push_str("<br>");
709 }
710
711 fn render_image(&self, params: &ImageRenderParams, dest: &mut String) {
712 let src = self.image_src(params.target, params.attrlist, params.parser);
713 let alt_encoded = encode_attribute_value(params.alt.clone());
714
715 // The dimension attributes (width, height, and title) are shared by the
716 // plain `<img>`, the interactive `<object>`, and the `<object>`'s image
717 // fallback. Each fragment carries its own leading space so the pieces
718 // concatenate cleanly after `src`/`alt` (or the `data` attribute).
719 let mut dimension_attrs = String::new();
720
721 if let Some(width) = params.width {
722 dimension_attrs.push_str(&format!(r#" width="{width}""#));
723 }
724
725 if let Some(height) = params.height {
726 dimension_attrs.push_str(&format!(r#" height="{height}""#));
727 }
728
729 if let Some(title) = params.attrlist.named_attribute("title") {
730 dimension_attrs.push_str(&format!(
731 r#" title="{title}""#,
732 title = encode_attribute_value(title.value().to_owned())
733 ));
734 }
735
736 let format = params
737 .attrlist
738 .named_attribute("format")
739 .map(|format| format.value());
740
741 // The `inline` and `interactive` SVG options are security-sensitive
742 // (they embed file contents or a live `<object>`), so they only take
743 // effect below the `Secure` safe mode. In `Secure` mode an SVG image
744 // renders as an ordinary `<img>`, matching Ruby Asciidoctor.
745 let svg_active = (format == Some("svg") || params.target.contains(".svg"))
746 && params.parser.safe_mode() < SafeMode::Secure;
747
748 let img = if svg_active && params.attrlist.has_option("inline") {
749 // Embed the SVG contents directly. When the contents cannot be read
750 // (no handler is registered, or it cannot find the file), fall back
751 // to the alt text, mirroring Ruby Asciidoctor.
752 read_svg_contents(&src, params.width, params.height, params.parser)
753 .unwrap_or_else(|| format!(r#"<span class="alt">{alt}</span>"#, alt = params.alt))
754 } else if svg_active && params.attrlist.has_option("interactive") {
755 // Render an interactive SVG as an `<object>` element so its embedded
756 // scripting and links remain live. A `fallback` image (or, failing
757 // that, the alt text) is nested inside for user agents that can't
758 // display the object.
759 let fallback = if let Some(fallback) = params.attrlist.named_attribute("fallback") {
760 let fallback_src = self.image_src(fallback.value(), params.attrlist, params.parser);
761 format!(r#"<img src="{fallback_src}" alt="{alt_encoded}"{dimension_attrs}>"#)
762 } else {
763 format!(r#"<span class="alt">{alt}</span>"#, alt = params.alt)
764 };
765
766 format!(
767 r#"<object type="image/svg+xml" data="{src}"{dimension_attrs}>{fallback}</object>"#
768 )
769 } else {
770 format!(r#"<img src="{src}" alt="{alt_encoded}"{dimension_attrs}>"#)
771 };
772
773 render_icon_or_image(params.attrlist, &img, "image", dest);
774 }
775
776 fn image_uri(
777 &self,
778 target_image_path: &str,
779 parser: &Parser,
780 asset_dir_key: Option<&str>,
781 ) -> String {
782 let asset_dir_key = asset_dir_key.unwrap_or("imagesdir");
783
784 // Asciidoctor embeds the image as a data URI when the `data-uri`
785 // attribute is set and the safe mode is below `SafeMode::Secure`. That
786 // requires reading the image's bytes, which this crate leaves to the
787 // caller rather than performing file/network access itself; the
788 // `data-uri` attribute is therefore not implemented and the image is
789 // always emitted as a normalized web path. Because data-uri embedding is
790 // absent, there is no safe-mode-sensitive behavior to gate here.
791 let asset_dir = parser
792 .attribute_value(asset_dir_key)
793 .as_maybe_str()
794 .map(|s| s.to_string());
795
796 normalize_web_path(target_image_path, parser, asset_dir.as_deref(), true)
797 }
798
799 fn render_icon(&self, params: &IconRenderParams, dest: &mut String) {
800 let src = self.icon_uri(params.target, params.attrlist, params.parser);
801
802 let img = if params.parser.is_attribute_set("icons") {
803 let icons = params.parser.attribute_value("icons");
804 if let Some(icons) = icons.as_maybe_str()
805 && icons == "font"
806 {
807 let mut i_class_attrs: Vec<String> = vec![
808 "fa".to_owned(),
809 format!("fa-{target}", target = params.target),
810 ];
811
812 if let Some(size) = params.attrlist.named_or_positional_attribute("size", 1) {
813 i_class_attrs.push(format!("fa-{size}", size = size.value()));
814 }
815
816 if let Some(flip) = params.attrlist.named_attribute("flip") {
817 i_class_attrs.push(format!("fa-flip-{flip}", flip = flip.value()));
818 } else if let Some(rotate) = params.attrlist.named_attribute("rotate") {
819 i_class_attrs.push(format!("fa-rotate-{rotate}", rotate = rotate.value()));
820 }
821
822 format!(
823 r##"<i class="{i_class_attr_val}"{title_attr}></i>"##,
824 i_class_attr_val = i_class_attrs.join(" "),
825 title_attr = if let Some(title) = params.attrlist.named_attribute("title") {
826 format!(r#" title="{title}""#, title = title.value())
827 } else {
828 "".to_owned()
829 }
830 )
831 } else {
832 let mut attrs: Vec<String> = vec![
833 format!(r#"src="{src}""#),
834 format!(
835 r#"alt="{alt}""#,
836 alt = encode_attribute_value(params.alt.to_string())
837 ),
838 ];
839
840 if let Some(width) = params.attrlist.named_attribute("width") {
841 attrs.push(format!(r#"width="{width}""#, width = width.value()));
842 }
843
844 if let Some(height) = params.attrlist.named_attribute("height") {
845 attrs.push(format!(r#"height="{height}""#, height = height.value()));
846 }
847
848 if let Some(title) = params.attrlist.named_attribute("title") {
849 attrs.push(format!(r#"title="{title}""#, title = title.value()));
850 }
851
852 format!(
853 "<img {attrs}{void_element_slash}>",
854 attrs = attrs.join(" "),
855 void_element_slash = "",
856 )
857 }
858 } else {
859 format!("[{alt}]", alt = params.alt)
860 };
861
862 render_icon_or_image(params.attrlist, &img, "icon", dest);
863 }
864
865 fn render_link(&self, params: &LinkRenderParams, dest: &mut String) {
866 let id = params.attrlist.id();
867
868 let mut roles = params.extra_roles.clone();
869 let mut attrlist_roles = params.attrlist.roles().clone();
870 roles.append(&mut attrlist_roles);
871
872 let link = format!(
873 r##"<a href="{target}"{id}{class}{link_constraint_attrs}>{link_text}</a>"##,
874 target = params.target,
875 id = if let Some(id) = id {
876 format!(r#" id="{id}""#)
877 } else {
878 "".to_owned()
879 },
880 class = if roles.is_empty() {
881 "".to_owned()
882 } else {
883 format!(r#" class="{roles}""#, roles = roles.join(" "))
884 },
885 // title = %( title="#{node.attr 'title'}") if node.attr? 'title'
886 // Haven't seen this in the wild yet.
887 link_constraint_attrs = link_constraint_attrs(params.attrlist, params.window),
888 link_text = params.link_text,
889 );
890
891 dest.push_str(&link);
892 }
893
894 fn render_anchor(&self, id: &str, _reftext: Option<String>, dest: &mut String) {
895 dest.push_str(&format!("<a id=\"{id}\"></a>"));
896 }
897
898 fn render_xref(&self, params: &XrefRenderParams, dest: &mut String) {
899 let class = if params.roles.is_empty() {
900 String::new()
901 } else {
902 // Roles are author-supplied, so each is escaped before it is joined
903 // into the `class` attribute (a stray `"` would otherwise break out
904 // of the attribute).
905 let roles = params
906 .roles
907 .iter()
908 .map(|role| encode_html_attribute(role))
909 .collect::<Vec<_>>()
910 .join(" ");
911 format!(r#" class="{roles}""#)
912 };
913
914 let constraint_attrs = xref_constraint_attrs(params.window);
915
916 match params.resolved {
917 Some(resolved) => {
918 let text = params
919 .provided_text
920 .map(str::to_string)
921 .or_else(|| resolved.text.clone())
922 .unwrap_or_else(|| format!("[{target}]", target = params.target));
923
924 dest.push_str(&format!(
925 r#"<a href="{href}"{class}{constraint_attrs}>{text}</a>"#,
926 href = resolved.href
927 ));
928 }
929
930 None => {
931 // Unresolved: link to the raw target and show bracketed text,
932 // mirroring Asciidoctor's behavior for a missing reference.
933 let text = params
934 .provided_text
935 .map(str::to_string)
936 .unwrap_or_else(|| format!("[{target}]", target = params.target));
937
938 dest.push_str(&format!(
939 r##"<a href="#{target}"{class}{constraint_attrs}>{text}</a>"##,
940 target = params.target
941 ));
942 }
943 }
944 }
945
946 fn render_callout(&self, params: &CalloutRenderParams, dest: &mut String) {
947 let n = params.number;
948 let parser = params.parser;
949
950 if parser.attribute_value("icons").as_maybe_str() == Some("font") {
951 dest.push_str(&format!(
952 r#"<i class="conum" data-value="{n}"></i><b>({n})</b>"#
953 ));
954 } else if parser.is_attribute_set("icons") {
955 let icontype = parser
956 .attribute_value("icontype")
957 .as_maybe_str()
958 .unwrap_or("png")
959 .to_owned();
960
961 let icon = format!("callouts/{n}.{icontype}");
962 let src = self.image_uri(&icon, parser, Some("iconsdir"));
963
964 dest.push_str(&format!(r#"<img src="{src}" alt="{n}">"#));
965 } else {
966 match params.guard {
967 CalloutGuard::Xml => {
968 dest.push_str(&format!(r#"<!--<b class="conum">({n})</b>-->"#));
969 }
970
971 CalloutGuard::LineComment(prefix) => {
972 dest.push_str(prefix);
973 dest.push_str(&format!(r#"<b class="conum">({n})</b>"#));
974 }
975 }
976 }
977 }
978
979 fn render_index_term(&self, params: &IndexTermRenderParams, dest: &mut String) {
980 // The HTML5 converter does not generate an index, so a concealed index
981 // term produces no output and a flow index term renders only its
982 // (already-substituted) visible term text.
983 if let Some(term) = params.visible_term {
984 dest.push_str(term);
985 }
986 }
987
988 fn render_button(&self, text: &str, dest: &mut String) {
989 dest.push_str(&format!(r#"<b class="button">{text}</b>"#));
990 }
991
992 fn render_keyboard(&self, keys: &[String], dest: &mut String) {
993 if let [key] = keys {
994 dest.push_str(&format!("<kbd>{key}</kbd>"));
995 } else {
996 // The visual separator is always `+`, even when the source used a
997 // comma delimiter (e.g. `kbd:[Ctrl,T]`). This matches Asciidoctor's
998 // HTML5 output, where the delimiter only selects how keys are split,
999 // not how the sequence is displayed.
1000 dest.push_str(&format!(
1001 r#"<span class="keyseq"><kbd>{keys}</kbd></span>"#,
1002 keys = keys.join("</kbd>+<kbd>")
1003 ));
1004 }
1005 }
1006
1007 fn render_menu(&self, params: &MenuRenderParams, dest: &mut String) {
1008 let caret = if params.parser.attribute_value("icons").as_maybe_str() == Some("font") {
1009 r#" <i class="fa fa-angle-right caret"></i> "#
1010 } else {
1011 r#" <b class="caret">›</b> "#
1012 };
1013
1014 let menu = params.menu;
1015
1016 if params.submenus.is_empty() {
1017 if let Some(menuitem) = params.menuitem {
1018 dest.push_str(&format!(
1019 r#"<span class="menuseq"><b class="menu">{menu}</b>{caret}<b class="menuitem">{menuitem}</b></span>"#
1020 ));
1021 } else {
1022 dest.push_str(&format!(r#"<b class="menuref">{menu}</b>"#));
1023 }
1024 } else {
1025 let submenu_joiner = format!(r#"</b>{caret}<b class="submenu">"#);
1026 dest.push_str(&format!(
1027 r#"<span class="menuseq"><b class="menu">{menu}</b>{caret}<b class="submenu">{submenus}</b>{caret}<b class="menuitem">{menuitem}</b></span>"#,
1028 submenus = params.submenus.join(&submenu_joiner),
1029 menuitem = params.menuitem.unwrap_or_default(),
1030 ));
1031 }
1032 }
1033
1034 fn render_footnote(&self, params: &FootnoteRenderParams, dest: &mut String) {
1035 match params.index {
1036 Some(index) if params.is_reference => {
1037 // A reference to an already-defined footnote reuses its number
1038 // but gets no anchor of its own.
1039 dest.push_str(&format!(
1040 r##"<sup class="footnoteref">[<a class="footnote" href="#_footnotedef_{index}" title="View footnote.">{index}</a>]</sup>"##
1041 ));
1042 }
1043
1044 Some(index) => {
1045 // A defining occurrence. When the footnote carries an ID, the
1046 // marker is given a matching anchor so it can be linked to.
1047 let id_attr = params
1048 .id
1049 .map(|id| format!(r#" id="_footnote_{id}""#))
1050 .unwrap_or_default();
1051
1052 dest.push_str(&format!(
1053 r##"<sup class="footnote"{id_attr}>[<a id="_footnoteref_{index}" class="footnote" href="#_footnotedef_{index}" title="View footnote.">{index}</a>]</sup>"##
1054 ));
1055 }
1056
1057 None => {
1058 // An unresolved reference: the ID was never defined.
1059 dest.push_str(&format!(
1060 r#"<sup class="footnoteref red" title="Unresolved footnote reference.">[{text}]</sup>"#,
1061 text = params.text
1062 ));
1063 }
1064 }
1065 }
1066}
1067
1068fn wrap_body_in_html_tag(
1069 _attrlist: Option<&Attrlist<'_>>,
1070 tag: &'static str,
1071 id: Option<String>,
1072 roles: Vec<&str>,
1073 body: &str,
1074 dest: &mut String,
1075) {
1076 dest.push('<');
1077 dest.push_str(tag);
1078
1079 if let Some(id) = id.as_ref() {
1080 dest.push_str(" id=\"");
1081 dest.push_str(id);
1082 dest.push('"');
1083 }
1084
1085 if !roles.is_empty() {
1086 let roles = roles.join(" ");
1087 dest.push_str(" class=\"");
1088 dest.push_str(&roles);
1089 dest.push('"');
1090 }
1091
1092 dest.push('>');
1093 dest.push_str(body);
1094 dest.push_str("</");
1095 dest.push_str(tag);
1096 dest.push('>');
1097}
1098
1099fn render_icon_or_image(attrlist: &Attrlist, img: &str, type_: &'static str, dest: &mut String) {
1100 let mut img = img.to_string();
1101
1102 // The `link` attribute value is used verbatim as the `href` (matching Ruby
1103 // Asciidoctor, which does not special-case `link=self`). This applies to
1104 // every image, including an inline SVG embedded in the flow of text.
1105 if let Some(link) = attrlist.named_attribute("link") {
1106 img = format!(
1107 r#"<a class="image" href="{link}"{link_constraint_attrs}>{img}</a>"#,
1108 link = link.value(),
1109 link_constraint_attrs = link_constraint_attrs(attrlist, None)
1110 );
1111 }
1112
1113 let mut roles: Vec<&str> = attrlist.roles();
1114
1115 if let Some(float) = attrlist.named_attribute("float") {
1116 roles.insert(0, float.value());
1117 }
1118
1119 roles.insert(0, type_);
1120
1121 dest.push_str(r#"<span class=""#);
1122 dest.push_str(&roles.join(" "));
1123 dest.push_str(r#"">"#);
1124 dest.push_str(&img);
1125 dest.push_str("</span>");
1126}
1127
1128fn encode_attribute_value(value: String) -> String {
1129 value.replace('"', """)
1130}
1131
1132/// Escapes a value for safe interpolation into an HTML attribute.
1133///
1134/// Unlike [`encode_attribute_value`] (which only guards the quote delimiter to
1135/// mirror Asciidoctor's image-alt handling), this escapes the full set of
1136/// characters that could break out of, or corrupt, an attribute value. It is
1137/// used for author-supplied `xref` `window`/`role` values, which — unlike the
1138/// hard-coded `window` strings the link macro passes — can contain arbitrary
1139/// text.
1140fn encode_html_attribute(value: &str) -> String {
1141 let mut out = String::with_capacity(value.len());
1142 for c in value.chars() {
1143 match c {
1144 '&' => out.push_str("&"),
1145 '"' => out.push_str("""),
1146 '<' => out.push_str("<"),
1147 '>' => out.push_str(">"),
1148 _ => out.push(c),
1149 }
1150 }
1151 out
1152}
1153
1154fn normalize_web_path(
1155 target: &str,
1156 parser: &Parser,
1157 start: Option<&str>,
1158 preserve_uri_target: bool,
1159) -> String {
1160 if preserve_uri_target && is_uri_ish(target) {
1161 encode_spaces_in_uri(target)
1162 } else {
1163 parser.path_resolver.web_path(target, start)
1164 }
1165}
1166
1167fn is_uri_ish(path: &str) -> bool {
1168 path.contains(':') && URI_SNIFF.is_match(path)
1169}
1170
1171/// Reports whether the final path segment of `path` carries a file extension,
1172/// i.e. it contains a `.` that is neither the first nor the last character of
1173/// the segment. Mirrors Asciidoctor's `Helpers.extname?`, used by the icon
1174/// macro to decide whether the `icontype` attribute should be appended.
1175fn has_extname(path: &str) -> bool {
1176 let segment = path.rsplit(['/', '\\']).next().unwrap_or(path);
1177 match segment.rfind('.') {
1178 Some(i) => i > 0 && i < segment.len() - 1,
1179 None => false,
1180 }
1181}
1182
1183fn encode_spaces_in_uri(s: &str) -> String {
1184 s.replace(' ', "%20")
1185}
1186
1187/// Matches the opening `<svg …>` tag at the start of an SVG document.
1188///
1189/// Like Ruby Asciidoctor's equivalent (`/\A<svg[^>]*>/`), the `[^>]*` stops at
1190/// the first `>`, so a `>` appearing unencoded inside an attribute value would
1191/// truncate the match. That cannot happen in well-formed XML (where `>` must be
1192/// written as `>`), so this only affects malformed input, and then only by
1193/// leaving the opening tag's dimensions unrewritten.
1194static SVG_START_TAG_RX: LazyLock<Regex> = LazyLock::new(|| {
1195 #[allow(clippy::unwrap_used)]
1196 Regex::new(r"\A<svg[^>]*>").unwrap()
1197});
1198
1199/// Matches a `width`, `height`, or `style` attribute (with its leading
1200/// whitespace) so they can be stripped from an SVG's opening tag.
1201static SVG_SNIFF_WIDTH_HEIGHT_RX: LazyLock<Regex> = LazyLock::new(|| {
1202 #[allow(clippy::unwrap_used)]
1203 Regex::new(r#"(?s)\s+(?:width|height|style)=(?:"[^"]*"|'[^']*')"#).unwrap()
1204});
1205
1206/// Reads and prepares the raw contents of an SVG file for inline embedding
1207/// (`image:target.svg[opts=inline]`).
1208///
1209/// The SVG contents are supplied by the parser's [`SvgFileHandler`]; when no
1210/// handler is registered (or it can't find the file) this returns `None` and
1211/// the caller falls back to rendering the alt text.
1212///
1213/// Before returning, the contents are prepared to match Ruby Asciidoctor:
1214///
1215/// * any XML preamble or doctype preceding the `<svg>` tag is removed, and
1216/// * if an explicit `width` and/or `height` was supplied on the macro, the
1217/// opening `<svg>` tag's own `width`, `height`, and `style` attributes are
1218/// dropped and the requested dimensions are appended in their place.
1219///
1220/// [`SvgFileHandler`]: crate::parser::SvgFileHandler
1221fn read_svg_contents(
1222 src: &str,
1223 width: Option<&str>,
1224 height: Option<&str>,
1225 parser: &Parser,
1226) -> Option<String> {
1227 let handler = parser.svg_file_handler.as_ref()?;
1228 let mut svg = handler.resolve_svg(src, parser)?;
1229
1230 // Strip anything that precedes the opening `<svg>` tag (e.g. `<?xml … ?>`).
1231 if svg.starts_with('<')
1232 && let Some(start) = svg.find("<svg")
1233 && start > 0
1234 {
1235 svg = svg[start..].to_string();
1236 }
1237
1238 // Rewrite the opening tag's dimensions only when at least one was supplied.
1239 if (width.is_some() || height.is_some())
1240 && let Some(start_tag) = SVG_START_TAG_RX.find(&svg).map(|m| m.as_str().to_string())
1241 {
1242 let rest = svg[start_tag.len()..].to_string();
1243
1244 // Attributes between `<svg` and the closing `>`, with any existing
1245 // width/height/style removed.
1246 let inner = &start_tag[4..start_tag.len() - 1];
1247 let mut new_tag = format!("<svg{}", SVG_SNIFF_WIDTH_HEIGHT_RX.replace_all(inner, ""));
1248
1249 if let Some(width) = width {
1250 new_tag.push_str(&format!(r#" width="{width}""#));
1251 }
1252
1253 if let Some(height) = height {
1254 new_tag.push_str(&format!(r#" height="{height}""#));
1255 }
1256
1257 new_tag.push('>');
1258 svg = format!("{new_tag}{rest}");
1259 }
1260
1261 Some(svg)
1262}
1263
1264/// Detects strings that resemble URIs.
1265///
1266/// ## Examples
1267///
1268/// * `http://domain`
1269/// * `https://domain`
1270/// * `file:///path`
1271/// * `data:info`
1272///
1273/// ## Counter-examples (do not match)
1274///
1275/// * `c:/sample.adoc`
1276/// * `c:\sample.adoc`
1277static URI_SNIFF: LazyLock<Regex> = LazyLock::new(|| {
1278 #[allow(clippy::unwrap_used)]
1279 Regex::new(
1280 r#"(?x)
1281 \A # Anchor to start of string
1282 \p{Alphabetic} # First character must be a letter
1283 [\p{Alphabetic}\p{Nd}.+-]+ # Followed by one or more alphanum or . + -
1284 : # Literal colon
1285 /{0,2} # Zero to two slashes
1286 "#,
1287 )
1288 .unwrap()
1289});
1290
1291/// Builds the `target`/`rel` attributes for a cross-reference whose `xref:`
1292/// macro carried a `window` attribute. Mirrors the link macro: a `_blank`
1293/// window automatically adds `rel="noopener"`.
1294fn xref_constraint_attrs(window: Option<&str>) -> String {
1295 let Some(window) = window else {
1296 return String::new();
1297 };
1298
1299 let rel_noopener = if window == "_blank" {
1300 r#" rel="noopener""#
1301 } else {
1302 ""
1303 };
1304
1305 // The `window` value is author-supplied, so it is escaped before being
1306 // interpolated into the `target` attribute. The `_blank` comparison above
1307 // runs on the raw value, which is correct for the well-formed inputs that
1308 // trigger `rel="noopener"`.
1309 format!(
1310 r#" target="{window}"{rel_noopener}"#,
1311 window = encode_html_attribute(window)
1312 )
1313}
1314
1315fn link_constraint_attrs(attrlist: &Attrlist<'_>, window: Option<&'static str>) -> String {
1316 let rel = if attrlist.has_option("nofollow") {
1317 Some("nofollow")
1318 } else {
1319 None
1320 };
1321
1322 if let Some(window) = attrlist
1323 .named_attribute("window")
1324 .map(|a| a.value())
1325 .or(window)
1326 {
1327 let rel_noopener = if window == "_blank" || attrlist.has_option("noopener") {
1328 if let Some(rel) = rel {
1329 format!(r#" rel="{rel}" noopener"#)
1330 } else {
1331 r#" rel="noopener""#.to_owned()
1332 }
1333 } else {
1334 "".to_string()
1335 };
1336
1337 format!(r#" target="{window}"{rel_noopener}"#)
1338 } else if let Some(rel) = rel {
1339 format!(r#" rel="{rel}""#)
1340 } else {
1341 "".to_string()
1342 }
1343}
1344
1345#[cfg(test)]
1346mod tests {
1347 use super::encode_html_attribute;
1348
1349 #[test]
1350 fn encode_html_attribute_escapes_special_characters() {
1351 // Each of the four characters that could break out of or corrupt an
1352 // HTML attribute value is replaced with its entity; ordinary characters
1353 // pass through untouched.
1354 assert_eq!(
1355 encode_html_attribute(r#"a&b"c<d>e"#),
1356 "a&b"c<d>e"
1357 );
1358 assert_eq!(encode_html_attribute("plain"), "plain");
1359 }
1360}