From e7aaf8ae02608d1d9e0f84aa864106a5f1ae78a3 Mon Sep 17 00:00:00 2001 From: Lukas <103962359+L4XB@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:31:48 +0200 Subject: [PATCH] fix(docreader): keep the space held by a whitespace-only inline element (#3978) markdownify renders an emphasis, code or link element whose text is only whitespace as "", and the whitespace goes with it. HTML and MHTML uploads therefore lost word boundaries: `further reference` became `furtherreference`, and `First Last` became `**First****Last**`. Editors produce that markup whenever a single space between two words carries different formatting. Before conversion, unwrap such elements so their whitespace stays as plain text. Only elements with no child elements are touched, innermost first, so a linked image keeps its link and nested wrappers come off completely. --- docreader/parser/mhtml_parser.py | 31 +++++++++++++++++++++++++++ docreader/tests/test_html_parser.py | 7 ++++++ docreader/tests/test_mhtml_parser.py | 32 ++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+) diff --git a/docreader/parser/mhtml_parser.py b/docreader/parser/mhtml_parser.py index 8103d11f..d79ecdd4 100644 --- a/docreader/parser/mhtml_parser.py +++ b/docreader/parser/mhtml_parser.py @@ -31,6 +31,23 @@ _AD_DOMAINS = ( _UNKNOWN_8BIT = frozenset({"unknown-8bit", "unknown"}) +# Inline elements that markdownify renders as "" when their text is only +# whitespace, taking that whitespace with them. +_WHITESPACE_DROPPING_INLINE_TAGS = ( + "a", + "b", + "code", + "del", + "em", + "i", + "kbd", + "s", + "samp", + "strong", + "sub", + "sup", +) + def _header_str(value) -> str: """Normalize a MIME header to str, recovering 8-bit UTF-8 bytes. @@ -270,6 +287,7 @@ class MHTMLParser(BaseParser): self._strip_internal_links(soup) if image_aliases: self._rewrite_image_sources(soup, image_aliases, base_location) + self._unwrap_whitespace_only_inline(soup) text_fallback = soup.get_text(separator="\n", strip=True) markdown_text = md(str(soup), heading_style="ATX") result = self._normalize_markdown(markdown_text) @@ -295,6 +313,19 @@ class MHTMLParser(BaseParser): """Backward-compatible wrapper for existing internal callers and tests.""" return self.html_to_markdown(html_content, image_aliases, base_location) + @staticmethod + def _unwrap_whitespace_only_inline(soup: BeautifulSoup) -> None: + """Keep the whitespace held by an otherwise empty inline element. + + markdownify drops such an element together with its whitespace, so + ``further reference`` became ``furtherreference``. + Unwrapping leaves the whitespace as plain text. Innermost elements go + first, so `` `` is unwrapped completely. + """ + for tag in reversed(soup.find_all(_WHITESPACE_DROPPING_INLINE_TAGS)): + if tag.find(True) is None and not tag.get_text().strip(): + tag.unwrap() + @staticmethod def _normalize_markdown(markdown_text: str) -> str: text = markdown_text.replace("\r\n", "\n").replace("\r", "\n") diff --git a/docreader/tests/test_html_parser.py b/docreader/tests/test_html_parser.py index 0694f7da..68edd901 100644 --- a/docreader/tests/test_html_parser.py +++ b/docreader/tests/test_html_parser.py @@ -58,6 +58,13 @@ class HTMLParserTest(unittest.TestCase): self.assertIn("[Guide](./guide.html)", document.content) self.assertIn("[Section](#section)", document.content) + def test_parse_keeps_space_held_by_whitespace_only_inline_element(self): + html = b"

further reference

" + + document = HTMLParser(file_name="space.html", file_type="html").parse(html) + + self.assertEqual("further reference", document.content) + def test_registry_routes_html_extensions_to_html_parser(self): self.assertIs(registry.get_parser_class("", "html"), HTMLParser) self.assertIs(registry.get_parser_class("", "htm"), HTMLParser) diff --git a/docreader/tests/test_mhtml_parser.py b/docreader/tests/test_mhtml_parser.py index 1d98fa76..a0bd050b 100644 --- a/docreader/tests/test_mhtml_parser.py +++ b/docreader/tests/test_mhtml_parser.py @@ -242,6 +242,38 @@ class MHTMLParserTest(unittest.TestCase): self.assertEqual(markdown, "alpha \nbeta") + def test_html_to_markdown_keeps_whitespace_of_whitespace_only_inline_elements(self): + parser = MHTMLParser(file_name="article.mhtml", file_type="mhtml") + cases = { + "

further reference

": "further reference", + "

First Last

": "**First** **Last**", + "

Hello world

": "Hello world", + "

one two

": "one\xa0two", + '

see here

': "see here", + "

a b

": "a b", + "

x y z w

": "x y z w", + "

v w x y

": "v w x y", + } + for html_content, expected in cases.items(): + with self.subTest(html=html_content): + self.assertEqual(parser._html_to_markdown(html_content), expected) + + def test_html_to_markdown_still_converts_inline_elements_with_content(self): + markdown = MHTMLParser( + file_name="article.mhtml", file_type="mhtml" + )._html_to_markdown( + "

bold code em " + 'gone link ' + "keepempty " + 'pic

' + ) + + self.assertEqual( + markdown, + "**bold** `code` *em* ~~gone~~ [link](https://example.com) keepempty " + "[![pic](https://example.com/a.png)](https://example.com)", + ) + def test_normalize_markdown_preserves_two_space_hard_break(self): markdown = MHTMLParser._normalize_markdown("alpha \nbeta")