Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions myst_parser/mdit_to_docutils/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,10 +482,11 @@ def renderInlineAsText(self, tokens: list[SyntaxTreeNode]) -> str: # noqa: N802
result = ""

for token in tokens or []:
if token.type == "text":
if token.type in {"text", "text_special"}:
# An escape or entity is a text_special token with no children.
# Its content is the character the alt text must keep
# (executablebooks/MyST-Parser#1210).
result += token.content
# elif token.type == "image":
# result += self.renderInlineAsText(token.children)
else:
result += self.renderInlineAsText(token.children or [])
return result
Expand Down
30 changes: 30 additions & 0 deletions tests/test_image_alt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Image alt text keeps CommonMark escapes and entities."""

from docutils.core import publish_parts

from myst_parser.parsers.docutils_ import Parser


def _html(source: str) -> str:
return publish_parts(source, parser=Parser(), writer_name="html5")["body"].strip()


def test_image_alt_keeps_escapes_and_entities():
"""Escapes and entities inside an image alt are not dropped.

markdown-it-py represents them as ``text_special`` tokens with no children.
Reading only ``text`` tokens used to drop the character
(executablebooks/MyST-Parser#1210). The same source in a link already
rendered the character.
"""
assert _html(r"![a \* b](x.png)") == '<p><img alt="a * b" src="x.png" /></p>'
assert _html("![a &amp; b](x.png)") == '<p><img alt="a &amp; b" src="x.png" /></p>'
assert (
_html(r"![C:\Python26](x.png)")
== '<p><img alt="C:\\Python26" src="x.png" /></p>'
)
assert (
_html(r"[a \* b &amp; c](https://example.com)")
== '<p><a class="reference external" href="https://example.com">'
"a * b &amp; c</a></p>"
)