aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2026-09-26 22:50:02 +0100
committerMichael Williamson <mike@zwobble.org>2026-09-26 22:50:02 +0100
commit8dd0ce0b69e3987c0b2282bdf1cb2e9f6abaf57d (patch)
tree31be4541a78834deda4c0e6df7f386eb1ece9935
parent2a5cf02b98fe7d20ba7af5395f0af1f22e2c4210 (diff)
Escape markdown link hrefs
-rw-r--r--mammoth/writers/markdown.py2
-rw-r--r--tests/writers/markdown_tests.py14
2 files changed, 12 insertions, 4 deletions
diff --git a/mammoth/writers/markdown.py b/mammoth/writers/markdown.py
index c78fd3f..5c69876 100644
--- a/mammoth/writers/markdown.py
+++ b/mammoth/writers/markdown.py
@@ -61,7 +61,7 @@ def _hyperlink(attributes, markdown_state):
href = attributes.get("href", "")
if href:
return _WriterOutput(
- "[", "]({0})".format(href),
+ "[", "]({0})".format(_escape_markdown(href)),
anchor_position="before",
)
else:
diff --git a/tests/writers/markdown_tests.py b/tests/writers/markdown_tests.py
index 28f74fc..2e5b39d 100644
--- a/tests/writers/markdown_tests.py
+++ b/tests/writers/markdown_tests.py
@@ -4,7 +4,7 @@ from mammoth.writers.markdown import MarkdownWriter
from ..testing import assert_equal
-def test_special_markdown_characters_are_escaped():
+def test_special_markdown_characters_in_text_are_escaped():
writer = _create_writer()
writer.text(r"\*")
assert_equal(r"\\\*", writer.as_string())
@@ -72,7 +72,15 @@ def test_anchor_tags_are_written_as_hyperlinks():
writer.start("a", {"href": "http://example.com"});
writer.text("Hello");
writer.end("a");
- assert_equal("[Hello](http://example.com)", writer.as_string())
+ assert_equal("[Hello](http://example\\.com)", writer.as_string())
+
+
+def test_special_markdown_characters_in_anchor_href_are_escaped():
+ writer = _create_writer()
+ writer.start("a", {"href": "http://example.com)Oops"})
+ writer.text("Hello")
+ writer.end("a")
+ assert_equal("[Hello](http://example\\.com\\)Oops)", writer.as_string())
def test_anchor_tags_without_href_attribute_are_treated_as_ordinary_text():
@@ -104,7 +112,7 @@ def test_links_have_anchors_before_opening_square_bracket():
writer.start("a", {"href": "http://example.com", "id": "start"})
writer.text("Hello")
writer.end("a")
- assert_equal('<a id="start"></a>[Hello](http://example.com)', writer.as_string())
+ assert_equal('<a id="start"></a>[Hello](http://example\\.com)', writer.as_string())
def test_image_elements_are_written_as_markdown_images():