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: 7 additions & 0 deletions packages/markitdown/src/markitdown/converters/_markdownify.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ def convert_a(
if self.options["default_title"] and not title:
title = href
title_part = ' "%s"' % title.replace('"', r"\"") if title else ""
# Escape [ and ] in link text per CommonMark §6.1; otherwise inner
# brackets cause nested-link ambiguity and renderers like GitHub
# silently truncate the text at the first unescaped ']' (#1302).
if href:
text = text.replace("[", r"\[").replace("]", r"\]")
return (
"%s[%s](%s%s)%s" % (prefix, text, href, title_part, suffix)
if href
Expand All @@ -97,6 +102,8 @@ def convert_img(
title_part = ' "%s"' % title.replace('"', r"\"") if title else ""
# Remove all line breaks from alt
alt = alt.replace("\n", " ")
# Escape [ and ] in alt text for the same reason as convert_a (#1302).
alt = alt.replace("[", r"\[").replace("]", r"\]")
if (
convert_as_inline
and el.parent.name not in self.options["keep_inline_images_in"]
Expand Down
19 changes: 19 additions & 0 deletions packages/markitdown/tests/test_module_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,24 @@ def test_markitdown_llm() -> None:
validate_strings(result, PPTX_TEST_STRINGS)


def test_html_link_text_bracket_escaping() -> None:
"""Brackets in <a> text and <img> alt must be backslash-escaped so
downstream Markdown parsers don't mis-parse them as nested / reference-
style links (issue #1302)."""
markitdown = MarkItDown()

html = (
b"<html><body><p>"
b'See <a href="https://example.com/">Learn [GPT]</a> and '
b'<img src="https://example.com/x.png" alt="Alt [with] brackets"/>.'
b"</p></body></html>"
)
result = markitdown.convert_stream(io.BytesIO(html), file_extension=".html")

assert r"[Learn \[GPT\]](https://example.com/)" in result.text_content
assert r"![Alt \[with\] brackets](https://example.com/x.png)" in result.text_content


if __name__ == "__main__":
"""Runs this file's tests from the command line."""
for test in [
Expand All @@ -547,6 +565,7 @@ def test_markitdown_llm() -> None:
test_markitdown_exiftool,
test_markitdown_llm_parameters,
test_markitdown_llm,
test_html_link_text_bracket_escaping,
]:
print(f"Running {test.__name__}...", end="")
test()
Expand Down