Skip to content

fix(html): escape square brackets and backslashes in image alt text - #2523

Open
bodapatisaikrishna wants to merge 1 commit into
microsoft:mainfrom
bodapatisaikrishna:fix/escape-image-alt-brackets
Open

bodapatisaikrishna wants to merge 1 commit into
microsoft:mainfrom
bodapatisaikrishna:fix/escape-image-alt-brackets

Conversation

@bodapatisaikrishna

Copy link
Copy Markdown

Problem

When converting HTML images to Markdown, image alt text is taken directly from the element attribute and formatted as ![<alt>](<src>). In Markdown/CommonMark syntax, the image description is delimited by square brackets [...].

If the alt text contains unescaped square brackets:

  1. An unescaped closing bracket (e.g. alt="Photo ] 1") prematurely closes the image description delimiter, resulting in ![Photo ] 1](url) which fails Markdown image parsing.
  2. An unbalanced opening bracket (e.g. alt="Photo [1") prevents Markdown parsers from matching the image delimiter or misinterprets subsequent text as a nested link (![Photo [1](url) -> <p>![Photo <a href="url">1</a></p>).
  3. Link-like text inside alt (e.g. alt="Click [here](url)") breaks CommonMark image parsing because image descriptions cannot contain nested links.

Solution

In _CustomMarkdownify.convert_img, backslash-escape literal backslashes and square brackets (\ -> \\, [ -> \[, ] -> \]) before assembling the ![<alt>](<src>) Markdown image syntax:

  • Preserves the verbatim content when parsed back into HTML.
  • Keeps plain inline text conversion unaltered when images are converted as inline text.

Testing

Added regression tests in test_html_converter.py covering:

  • Unbalanced closing brackets (])
  • Unbalanced opening brackets ([)
  • Balanced brackets ([Q3])
  • Link-like patterns ([here](url))
  • Literal backslashes (\)
  • Preserving raw alt text in inline mode

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant