From 18b5a88b1a104aac899c99d7e04ec4f35b18abb4 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Mon, 23 Nov 2026 22:42:11 +0800 Subject: [PATCH] Preserve selected HTML subtrees with a passthrough option --- README.rst | 24 ++++++ markdownify/__init__.py | 58 ++++++++++++-- markdownify/__init__.pyi | 4 +- markdownify/main.py | 3 + tests/test_passthrough.py | 154 ++++++++++++++++++++++++++++++++++++++ tests/types.py | 4 + 6 files changed, 239 insertions(+), 8 deletions(-) create mode 100644 tests/test_passthrough.py diff --git a/README.rst b/README.rst index 059a68f..89fecf9 100644 --- a/README.rst +++ b/README.rst @@ -60,6 +60,30 @@ convert A list of tags to convert. This option can't be used with the ``strip`` option. +passthrough + Preserve selected elements and their complete subtrees as HTML. Accepts a tag + name, an iterable of tag names (case-insensitive), or a callable receiving a + BeautifulSoup Tag and returning whether to preserve it. Defaults to ``None``. + Selection takes precedence over ``strip``, ``convert`` and custom converters; + descendants of a selected element are not converted or passed to the callable. + Other elements continue to be converted normally. For example:: + + md('', passthrough=['foo']) + # '* bar' + + md(html, passthrough=lambda el: el.name == 'iframe' and el.get('id') == 'video') + md(html, passthrough=lambda el: el.name == 'span' and el.has_attr('custom-style')) + + Regular expressions and other attribute criteria can be used inside the + callable. The command-line option ``--passthrough iframe foo`` accepts tag + names. HTML is serialized by BeautifulSoup, so quote style, attribute order, + entity spellings and parser whitespace normalization may differ from the + input; this is not a byte-for-byte copy. Comments and parsed whitespace + inside preserved subtrees are retained. + Paragraphs containing preserved HTML are not rewrapped, and enclosing + Markdown lists/blockquotes still apply their normal indentation. Preserve + the whole table when multiline raw HTML needs an HTML table container. + autolinks A boolean indicating whether the "automatic link" style should be used when a ``a`` tag's contents match its href. Defaults to ``True``. diff --git a/markdownify/__init__.py b/markdownify/__init__.py index d946d2c..24619c0 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -174,6 +174,10 @@ def _next_block_content_sibling(el): return None +class _RawHtml(str): + """Keep preservation context through ancestors without converter state.""" + + class MarkdownConverter(object): class DefaultOptions: autolinks = True @@ -189,6 +193,7 @@ class DefaultOptions: heading_style = UNDERLINED keep_inline_images_in = [] newline_style = SPACES + passthrough = None strip = None strip_document = STRIP strip_pre = STRIP @@ -212,6 +217,18 @@ def __init__(self, **options): raise ValueError('You may specify either tags to strip or tags to' ' convert, but not both.') + passthrough = self.options['passthrough'] + if passthrough is not None and not callable(passthrough): + if isinstance(passthrough, str): + passthrough = (passthrough,) + try: + passthrough = tuple(passthrough) + except TypeError: + raise TypeError('passthrough must contain tag names or be a callable') + if not all(isinstance(tag, str) for tag in passthrough): + raise TypeError('passthrough must contain tag names or be a callable') + self.options['passthrough'] = frozenset(tag.lower() for tag in passthrough) + # If a string or list is passed to bs4_options, assume it is a 'features' specification if not isinstance(self.options['bs4_options'], dict): self.options['bs4_options'] = {'features': self.options['bs4_options']} @@ -224,7 +241,16 @@ def convert(self, html): return self.convert_soup(soup) def convert_soup(self, soup): - return self.process_tag(soup, parent_tags=set()) + text = self.process_tag(soup, parent_tags=set()) + return str(text) if isinstance(text, _RawHtml) else text + + def should_passthrough_tag(self, node): + if node.name == '[document]': + return False + passthrough = self.options['passthrough'] + if callable(passthrough): + return bool(passthrough(node)) + return passthrough is not None and node.name.lower() in passthrough def process_element(self, node, parent_tags=None): if isinstance(node, NavigableString): @@ -239,6 +265,13 @@ def process_tag(self, node, parent_tags=None): # Collect child elements to process, ignoring whitespace-only text elements # adjacent to the inner/outer boundaries of block elements. + if self.should_passthrough_tag(node): + text = str(node) + if (should_remove_whitespace_outside(node) + and '_inline' not in parent_tags and '_noformat' not in parent_tags): + text = '\n\n' + text + '\n\n' + return _RawHtml(text) + should_remove_inside = should_remove_whitespace_inside(node) def _can_ignore(el): @@ -292,6 +325,7 @@ def _can_ignore(el): # Remove empty string values. child_strings = [s for s in child_strings if s] + contains_raw_html = any(isinstance(s, _RawHtml) for s in child_strings) # Collapse newlines at child element boundaries, if needed. if node.name == 'pre' or node.find_parent('pre'): @@ -322,9 +356,11 @@ def _can_ignore(el): # apply this tag's final conversion function convert_fn = self.get_conv_fn_cached(node.name) if convert_fn is not None: + if contains_raw_html: + parent_tags = parent_tags | {'_passthrough'} text = convert_fn(node, text, parent_tags=parent_tags) - return text + return _RawHtml(text) if contains_raw_html and text else text def convert__document_(self, el, text, parent_tags): """Final document-level formatting for BeautifulSoup object (node.name == "[document]")""" @@ -545,7 +581,8 @@ def _indent_for_dd(match): def convert_dt(self, el, text, parent_tags): # remove newlines from term text text = (text or '').strip() - text = re_all_whitespace.sub(' ', text) + if '_passthrough' not in parent_tags: + text = re_all_whitespace.sub(' ', text) if '_inline' in parent_tags: return ' ' + text + ' ' if not text: @@ -569,7 +606,8 @@ def convert_hN(self, n, el, text, parent_tags): if style == UNDERLINED and n <= 2: line = '=' if n == 1 else '-' return self.underline(text, line) - text = re_all_whitespace.sub(' ', text) + if '_passthrough' not in parent_tags: + text = re_all_whitespace.sub(' ', text) hashes = '#' * n if style == ATX_CLOSED: return '\n\n%s %s %s\n\n' % (hashes, text, hashes) @@ -667,7 +705,7 @@ def convert_p(self, el, text, parent_tags): if '_inline' in parent_tags: return ' ' + text.strip(' \t\r\n') + ' ' text = text.strip(' \t\r\n') - if self.options['wrap']: + if self.options['wrap'] and '_passthrough' not in parent_tags: # Preserve newlines (and preceding whitespace) resulting # from
tags. Newlines in the input have already been # replaced by spaces. @@ -737,13 +775,19 @@ def convert_td(self, el, text, parent_tags): colspan = 1 if 'colspan' in el.attrs and el['colspan'].isdigit(): colspan = max(1, min(1000, int(el['colspan']))) - return ' ' + text.strip().replace("\n", " ") + ' |' * colspan + text = text.strip() + if '_passthrough' not in parent_tags: + text = text.replace("\n", " ") + return ' ' + text + ' |' * colspan def convert_th(self, el, text, parent_tags): colspan = 1 if 'colspan' in el.attrs and el['colspan'].isdigit(): colspan = max(1, min(1000, int(el['colspan']))) - return ' ' + text.strip().replace("\n", " ") + ' |' * colspan + text = text.strip() + if '_passthrough' not in parent_tags: + text = text.replace("\n", " ") + return ' ' + text + ' |' * colspan def convert_tr(self, el, text, parent_tags): cells = el.find_all(['td', 'th']) diff --git a/markdownify/__init__.pyi b/markdownify/__init__.pyi index 2494011..4623d82 100644 --- a/markdownify/__init__.pyi +++ b/markdownify/__init__.pyi @@ -1,5 +1,5 @@ from _typeshed import Incomplete -from typing import Callable, Union +from typing import Callable, Iterable, Union ATX: str ATX_CLOSED: str @@ -30,6 +30,7 @@ def markdownify( heading_style: str = ..., keep_inline_images_in: list[str] = ..., newline_style: str = ..., + passthrough: Union[str, Iterable[str], Callable[[Incomplete], bool], None] = ..., strip: Union[list[str], None] = ..., strip_document: Union[str, None] = ..., strip_pre: Union[str, None] = ..., @@ -58,6 +59,7 @@ class MarkdownConverter: heading_style: str = ..., keep_inline_images_in: list[str] = ..., newline_style: str = ..., + passthrough: Union[str, Iterable[str], Callable[[Incomplete], bool], None] = ..., strip: Union[list[str], None] = ..., strip_document: Union[str, None] = ..., strip_pre: Union[str, None] = ..., diff --git a/markdownify/main.py b/markdownify/main.py index ba70671..afd4c28 100755 --- a/markdownify/main.py +++ b/markdownify/main.py @@ -23,6 +23,9 @@ def main(argv=sys.argv[1:]): parser.add_argument('-c', '--convert', nargs='*', help="A list of tags to convert. This option can't be used with " "the --strip option.") + parser.add_argument('--passthrough', nargs='*', + help="Tag names to preserve as HTML, including their children. " + "Takes precedence over --strip and --convert.") parser.add_argument('-a', '--autolinks', action='store_true', help="A boolean indicating whether the 'automatic link' style " "should be used when a 'a' tag's contents match its href.") diff --git a/tests/test_passthrough.py b/tests/test_passthrough.py new file mode 100644 index 0000000..a92e85f --- /dev/null +++ b/tests/test_passthrough.py @@ -0,0 +1,154 @@ +from io import StringIO +import re + +from bs4 import BeautifulSoup +import pytest + +from markdownify import ATX, MarkdownConverter, markdownify +from markdownify.main import main + + +def test_iframe_keeps_attributes_entities_and_neighbors(): + iframe = '' + assert markdownify('

Video

' + iframe + '

Caption

', + passthrough=['iframe']) == 'Video\n=====\n\n' + iframe + '\n\n*Caption*' + + +@pytest.mark.parametrize('selector', [['foo'], ('FOO',), 'foo', {'foo'}]) +def test_custom_tag_in_list(selector): + assert markdownify('', + passthrough=selector) == '* bar' + + +def test_preserved_subtree_is_not_converted_or_escaped(): + html = '\n *a_b* &
\n
' + expected = '\n*a_b* &
\n
' + assert markdownify(html, passthrough=['custom-tag'], escape_misc=True) == expected + + +def test_callback_selects_attributes_without_tag_name_cache(): + html = 'a b c' + + def select(el): + return (el.name == 'span' + and (el.has_attr('custom-style') + or re.match(r'keep-\d+$', el.get('id', '')))) + assert markdownify(html, passthrough=select) == ( + 'a b c') + + +def test_selected_parent_does_not_visit_children_or_custom_converters(): + seen = [] + + class Converter(MarkdownConverter): + def convert_b(self, el, text, parent_tags): + raise AssertionError('selected descendants must not be converted') + + def select(el): + seen.append(el.name) + return el.name == 'div' + converter = Converter(passthrough=select) + assert converter.convert('
inside
') == '
inside
' + assert seen == ['div'] + + +@pytest.mark.parametrize('options', [{'strip': ['b']}, {'convert': ['i']}]) +def test_passthrough_overrides_strip_and_convert(options): + assert markdownify('keepconvert', passthrough=['b'], + **options) == 'keep*convert*' + + +def test_passthrough_overrides_selected_custom_converter(): + class Converter(MarkdownConverter): + def convert_iframe(self, el, text, parent_tags): + return 'custom' + converter = Converter(passthrough=['iframe']) + assert converter.convert('') == '' + + +def test_callback_exceptions_propagate_and_reuse_has_no_state(): + error = RuntimeError('predicate failed') + + def select(el): + if el.get('id') == 'bad': + raise error + return el.name == 'foo' + converter = MarkdownConverter(passthrough=select) + with pytest.raises(RuntimeError) as caught: + converter.convert('text') + assert caught.value is error + assert converter.convert('good') == 'good' + + +def test_soup_is_not_mutated_and_generator_option_is_reusable(): + soup = BeautifulSoup('
onetwo
', 'html.parser') + before = str(soup) + converter = MarkdownConverter(passthrough=(tag for tag in ['foo'])) + assert converter.convert_soup(soup) == 'one**two**' + assert converter.convert_soup(soup) == 'one**two**' + assert str(soup) == before + assert type(converter.convert_soup(soup)) is str + assert converter.convert_soup(soup.foo) == 'one' + + +def test_paragraph_containing_raw_html_is_not_rewrapped(): + raw = 'inside words\nnext' + html = '

before ' + raw + ' after

one two three four

' + assert markdownify(html, passthrough=['span'], wrap=True, wrap_width=8) == ( + 'before ' + raw + ' after\n\none two\nthree\nfour') + + +def test_normalization_does_not_change_preserved_attributes_in_heading_and_term(): + raw = 'a\nb' + for html, prefix in [('

' + raw + '

', '### '), + ('
' + raw + '
', '')]: + assert markdownify(html, passthrough=['span'], heading_style=ATX) == prefix + raw + + +def test_raw_html_in_code_uses_actual_backticks_to_choose_delimiter(): + assert markdownify('`x`', passthrough=['foo']) == ( + '`` `x` ``') + + +def test_multiline_raw_subtree_keeps_list_and_blockquote_indentation(): + raw = 'one\ntwo' + assert markdownify('', passthrough=['foo']) == ( + '* one\n two') + assert markdownify('
' + raw + '
', passthrough=['foo']) == ( + '> one\n> two') + + +def test_raw_block_keeps_separation_and_nested_html(): + raw = '

inside

' + assert markdownify('before' + raw + 'after', passthrough=['div']) == ( + 'before\n\n' + raw + '\n\nafter') + + +def test_whole_table_is_preserved(): + html = '\n\n
AB
' + assert markdownify(html, passthrough=['table']) == html + + +def test_inline_raw_html_survives_table_conversion(): + html = '
c
' + assert markdownify(html, passthrough=['span']) == ( + '| c |\n| --- |') + + +@pytest.mark.parametrize('value', [True, 1, [1], b'iframe']) +def test_invalid_selector_has_clear_error(value): + with pytest.raises(TypeError, match='passthrough'): + MarkdownConverter(passthrough=value) + + +def test_cli_passthrough(monkeypatch, capsys): + monkeypatch.setattr('sys.stdin', StringIO('')) + # main's parser reads sys.stdin at invocation time. + main(['--passthrough', 'iframe']) + assert capsys.readouterr().out == '\n' + + +def test_disabled_option_keeps_existing_output(): + html = '

bold

' + for option in (None, [], lambda el: False): + assert markdownify(html, passthrough=option) == '**bold**' diff --git a/tests/types.py b/tests/types.py index 7424978..1369a32 100644 --- a/tests/types.py +++ b/tests/types.py @@ -68,3 +68,7 @@ def callback(el: BeautifulSoup) -> Union[str, None]: markdownify('
test\n    foo\nbar
', code_language_callback=callback) markdownify('
test\n    foo\nbar
', code_language_callback=lambda el: None) + +markdownify('', passthrough=['iframe']) +markdownify('', passthrough=lambda el: el.name == 'iframe') +MarkdownConverter(passthrough=('iframe', 'foo')).convert('')