From 8627676ce1cbb573ecc799141c35f302cbc20af9 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sat, 5 Dec 2026 19:38:49 +0000 Subject: Escape HTML tag and entity characters in Markdown writer --- NEWS | 6 ++++++ mammoth/writers/markdown.py | 2 +- tests/writers/markdown_tests.py | 13 ++++++++++++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/NEWS b/NEWS index daf4a2a..63f0e29 100644 --- a/NEWS +++ b/NEWS @@ -1,3 +1,9 @@ +# 1.13.1 + +* Escape HTML tag and entity characters in Markdown writer. This avoids some + cases where source documents could inject arbitrary HTML into the converted + document. + # 1.13.0 * Read the children of w:customXml elements. diff --git a/mammoth/writers/markdown.py b/mammoth/writers/markdown.py index 79779de..5429cc2 100644 --- a/mammoth/writers/markdown.py +++ b/mammoth/writers/markdown.py @@ -204,4 +204,4 @@ class MarkdownWriter(Writer): def _escape_markdown(value): - return re.sub(r"([\`\*_\{\}\[\]\(\)\#\+\-\.\!])", r"\\\1", re.sub("\\\\", "\\\\\\\\", value)) + return re.sub(r"([\`\*_\{\}\[\]\(\)\#\+\-\.\!<>&])", r"\\\1", re.sub("\\\\", "\\\\\\\\", value)) diff --git a/tests/writers/markdown_tests.py b/tests/writers/markdown_tests.py index cb91905..af0f9d2 100644 --- a/tests/writers/markdown_tests.py +++ b/tests/writers/markdown_tests.py @@ -1,6 +1,6 @@ from __future__ import unicode_literals -from mammoth.writers.markdown import MarkdownWriter +from mammoth.writers.markdown import MarkdownWriter, _escape_markdown from ..testing import assert_equal @@ -208,6 +208,17 @@ def test_numbering_is_separate_for_nested_list_and_parent_list(): assert_equal("1. Fruit\n\t1. Apple\n\t2. Banana\n2. Condiments\n\n", writer.as_string()) +def test_html_tag_characters_are_escaped(): + escaped = _escape_markdown("
") + + assert_equal(r"\
", escaped) + + +def test_html_entity_characters_are_escaped(): + escaped = _escape_markdown("&") + + assert_equal(r"\&", escaped) + def _create_writer(): return MarkdownWriter() -- cgit v1.2.3