aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2026-09-26 22:52:30 +0100
committerMichael Williamson <mike@zwobble.org>2026-09-26 22:52:30 +0100
commit2c722f1d1f3cb4b45174c73f1193278720b0847a (patch)
treedf2690a6dcbe87e7243aa110534f82633f0896a5
parent8dd0ce0b69e3987c0b2282bdf1cb2e9f6abaf57d (diff)
Escape markdown image alt text and src
-rw-r--r--mammoth/writers/markdown.py2
-rw-r--r--tests/writers/markdown_tests.py16
2 files changed, 15 insertions, 3 deletions
diff --git a/mammoth/writers/markdown.py b/mammoth/writers/markdown.py
index 5c69876..79779de 100644
--- a/mammoth/writers/markdown.py
+++ b/mammoth/writers/markdown.py
@@ -72,7 +72,7 @@ def _image(attributes, markdown_state):
src = attributes.get("src", "")
alt_text = attributes.get("alt", "")
if src or alt_text:
- return _WriterOutput("![{0}]({1})".format(alt_text, src), "")
+ return _WriterOutput("![{0}]({1})".format(_escape_markdown(alt_text), _escape_markdown(src)), "")
else:
return _default_output
diff --git a/tests/writers/markdown_tests.py b/tests/writers/markdown_tests.py
index 2e5b39d..cb91905 100644
--- a/tests/writers/markdown_tests.py
+++ b/tests/writers/markdown_tests.py
@@ -118,13 +118,25 @@ def test_links_have_anchors_before_opening_square_bracket():
def test_image_elements_are_written_as_markdown_images():
writer = _create_writer()
writer.self_closing("img", {"src": "http://example.com/image.jpg", "alt": "Alt Text"})
- assert_equal("![Alt Text](http://example.com/image.jpg)", writer.as_string())
+ assert_equal("![Alt Text](http://example\\.com/image\\.jpg)", writer.as_string())
+
+
+def test_image_alt_text_is_escaped():
+ writer = _create_writer()
+ writer.self_closing("img", {"src": "http://example.com/image.jpg", "alt": "Alt Text]Oops"})
+ assert_equal("![Alt Text\\]Oops](http://example\\.com/image\\.jpg)", writer.as_string())
+
+
+def test_image_src_is_escaped():
+ writer = _create_writer()
+ writer.self_closing("img", {"src": "http://example.com/image.jpg)Oops", "alt": "Alt Text"})
+ assert_equal("![Alt Text](http://example\\.com/image\\.jpg\\)Oops)", writer.as_string())
def test_images_are_written_even_if_they_dont_have_alt_text():
writer = _create_writer()
writer.self_closing("img", {"src": "http://example.com/image.jpg"})
- assert_equal("![](http://example.com/image.jpg)", writer.as_string())
+ assert_equal("![](http://example\\.com/image\\.jpg)", writer.as_string())
def test_images_are_written_even_if_they_dont_have_a_src_attribute():