Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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('<ul><li><foo>bar</foo></li></ul>', passthrough=['foo'])
# '* <foo>bar</foo>'

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``.
Expand Down
58 changes: 51 additions & 7 deletions markdownify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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']}
Expand All @@ -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):
Expand All @@ -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):
Expand Down Expand Up @@ -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'):
Expand Down Expand Up @@ -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]")"""
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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 <br> tags. Newlines in the input have already been
# replaced by spaces.
Expand Down Expand Up @@ -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'])
Expand Down
4 changes: 3 additions & 1 deletion markdownify/__init__.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from _typeshed import Incomplete
from typing import Callable, Union
from typing import Callable, Iterable, Union

ATX: str
ATX_CLOSED: str
Expand Down Expand Up @@ -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] = ...,
Expand Down Expand Up @@ -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] = ...,
Expand Down
3 changes: 3 additions & 0 deletions markdownify/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
154 changes: 154 additions & 0 deletions tests/test_passthrough.py
Original file line number Diff line number Diff line change
@@ -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 = '<iframe allowfullscreen="" src="https://example.com/?a=1&amp;b=2"></iframe>'
assert markdownify('<h1>Video</h1>' + iframe + '<p><em>Caption</em></p>',
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('<ul><li><foo>bar</foo></li></ul>',
passthrough=selector) == '* <foo>bar</foo>'


def test_preserved_subtree_is_not_converted_or_escaped():
html = '<custom-tag><!--keep-->\n <b>*a_b*</b> &amp; <br/>\n</custom-tag>'
expected = '<custom-tag><!--keep-->\n<b>*a_b*</b> &amp; <br/>\n</custom-tag>'
assert markdownify(html, passthrough=['custom-tag'], escape_misc=True) == expected


def test_callback_selects_attributes_without_tag_name_cache():
html = '<span custom-style="MyStyle">a</span> <span>b</span> <span id="keep-2">c</span>'

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) == (
'<span custom-style="MyStyle">a</span> b <span id="keep-2">c</span>')


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('<div><b>inside</b></div>') == '<div><b>inside</b></div>'
assert seen == ['div']


@pytest.mark.parametrize('options', [{'strip': ['b']}, {'convert': ['i']}])
def test_passthrough_overrides_strip_and_convert(options):
assert markdownify('<b>keep</b><i>convert</i>', passthrough=['b'],
**options) == '<b>keep</b>*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('<iframe></iframe>') == '<iframe></iframe>'


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('<foo id="bad">text</foo>')
assert caught.value is error
assert converter.convert('<foo>good</foo>') == '<foo>good</foo>'


def test_soup_is_not_mutated_and_generator_option_is_reusable():
soup = BeautifulSoup('<div><foo>one</foo><b>two</b></div>', 'html.parser')
before = str(soup)
converter = MarkdownConverter(passthrough=(tag for tag in ['foo']))
assert converter.convert_soup(soup) == '<foo>one</foo>**two**'
assert converter.convert_soup(soup) == '<foo>one</foo>**two**'
assert str(soup) == before
assert type(converter.convert_soup(soup)) is str
assert converter.convert_soup(soup.foo) == '<foo>one</foo>'


def test_paragraph_containing_raw_html_is_not_rewrapped():
raw = '<span title="many words">inside words\nnext</span>'
html = '<p>before ' + raw + ' after</p><p>one two three four</p>'
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 = '<span title="many words">a\nb</span>'
for html, prefix in [('<h3>' + raw + '</h3>', '### '),
('<dl><dt>' + raw + '</dt></dl>', '')]:
assert markdownify(html, passthrough=['span'], heading_style=ATX) == prefix + raw


def test_raw_html_in_code_uses_actual_backticks_to_choose_delimiter():
assert markdownify('<code><foo>`x`</foo></code>', passthrough=['foo']) == (
'`` <foo>`x`</foo> ``')


def test_multiline_raw_subtree_keeps_list_and_blockquote_indentation():
raw = '<foo>one\ntwo</foo>'
assert markdownify('<ul><li>' + raw + '</li></ul>', passthrough=['foo']) == (
'* <foo>one\n two</foo>')
assert markdownify('<blockquote>' + raw + '</blockquote>', passthrough=['foo']) == (
'> <foo>one\n> two</foo>')


def test_raw_block_keeps_separation_and_nested_html():
raw = '<div><p><b>inside</b></p></div>'
assert markdownify('before' + raw + 'after', passthrough=['div']) == (
'before\n\n' + raw + '\n\nafter')


def test_whole_table_is_preserved():
html = '<table>\n<tr><td><b>A</b></td><td>B</td></tr>\n</table>'
assert markdownify(html, passthrough=['table']) == html


def test_inline_raw_html_survives_table_conversion():
html = '<table><tr><th><span title="a b">c</span></th></tr></table>'
assert markdownify(html, passthrough=['span']) == (
'| <span title="a b">c</span> |\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('<iframe src="video"></iframe>'))
# main's parser reads sys.stdin at invocation time.
main(['--passthrough', 'iframe'])
assert capsys.readouterr().out == '<iframe src="video"></iframe>\n'


def test_disabled_option_keeps_existing_output():
html = '<p><foo><b>bold</b></foo></p>'
for option in (None, [], lambda el: False):
assert markdownify(html, passthrough=option) == '**bold**'
4 changes: 4 additions & 0 deletions tests/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,7 @@ def callback(el: BeautifulSoup) -> Union[str, None]:

markdownify('<pre class="python">test\n foo\nbar</pre>', code_language_callback=callback)
markdownify('<pre class="python">test\n foo\nbar</pre>', code_language_callback=lambda el: None)

markdownify('<iframe></iframe>', passthrough=['iframe'])
markdownify('<iframe></iframe>', passthrough=lambda el: el.name == 'iframe')
MarkdownConverter(passthrough=('iframe', 'foo')).convert('')