Skip to content

Image alt text loses backslash escapes #1210

Description

@kdeldycke

What version of myst-parser are you using?

5.1.0

What version dependencies are you using?

  • markdown-it-py 4.2.0
  • docutils 0.22.4
  • Python 3.14.7

What operating system are you using?

Mac

Describe the Bug

The alt attribute of an image loses every backslash escape and every entity of its alt text: ![C:\Python26](x.png) gives alt="C:ython26".

renderInlineAsText reads text tokens only. An escape or an entity inside an image is a text_special token with no children:

def renderInlineAsText(self, tokens: list[SyntaxTreeNode]) -> str: # noqa: N802
"""Special kludge for image `alt` attributes to conform CommonMark spec.
Don't try to use it! Spec requires to show `alt` content with stripped markup,
instead of simple escaping.
"""
result = ""
for token in tokens or []:
if token.type == "text":
result += token.content
# elif token.type == "image":
# result += self.renderInlineAsText(token.children)
else:
result += self.renderInlineAsText(token.children or [])
return result

markdown-it 15.0.0 fixed the token side: markdown-it/markdown-it@974e2d7 makes text_join convert those tokens to text inside image alt text. markdown-it-py 4.2.0 does not have that change.

Expected Behavior

alt="a * b", alt="a & b" and alt="C:\Python26".

To Reproduce

from docutils.core import publish_parts
from myst_parser.parsers.docutils_ import Parser

for src in (
    r"![a \* b](x.png)",
    "![a & b](x.png)",
    r"![C:\Python26](x.png)",
    r"[a \* b & c](https://example.com)",
):
    print(publish_parts(src, parser=Parser(), writer_name="html5")["body"], end="")

Output:

<p><img alt="a  b" src="x.png" /></p>
<p><img alt="a  b" src="x.png" /></p>
<p><img alt="C:ython26" src="x.png" /></p>
<p><a class="reference external" href="https://example.com">a * b &amp; c</a></p>

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions