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<strong> </strong>
reference` became `furtherreference`, and `<b>First</b><b> </b><b>Last</b>`
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.
main
Lukas 2026-10-07 19:31:48 +02:00 committed by GitHub
parent dabbdaf156
commit e7aaf8ae02
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 70 additions and 0 deletions

View File

@ -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<strong> </strong>reference`` became ``furtherreference``.
Unwrapping leaves the whitespace as plain text. Innermost elements go
first, so ``<b><i> </i></b>`` 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")

View File

@ -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"<p>further<strong> </strong>reference</p>"
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)

View File

@ -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 = {
"<p>further<strong> </strong>reference</p>": "further reference",
"<p><b>First</b><b> </b><b>Last</b></p>": "**First** **Last**",
"<p>Hello<code> </code>world</p>": "Hello world",
"<p>one<em>&#160;</em>two</p>": "one\xa0two",
'<p>see<a href="https://example.com"> </a>here</p>': "see here",
"<p>a<b><i> </i></b>b</p>": "a b",
"<p>x<sub> </sub>y<sup> </sup>z<kbd> </kbd>w</p>": "x y z w",
"<p>v<del> </del>w<s> </s>x<samp> </samp>y</p>": "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(
"<p><strong>bold</strong> <code>code</code> <em>em</em> "
'<del>gone</del> <a href="https://example.com">link</a> '
"keep<b></b>empty "
'<a href="https://example.com"><img alt="pic" src="https://example.com/a.png"></a></p>'
)
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")