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
6 changes: 6 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,12 @@ keep_inline_images_in
that should be allowed to contain inline images, for example ``['td']``.
Defaults to an empty list.

table_cell_block_breaks
Set to ``True`` to separate paragraphs, divs and list items inside a table
cell with ``<br>``. For example, ``<td><div>One</div><div>Two</div></td>``
produces a cell containing ``One<br>Two``. The Markdown renderer must
support inline HTML. Defaults to ``False``.

table_infer_header
Controls handling of tables with no header row (as indicated by ``<thead>``
or ``<th>``). When set to ``True``, the first body row is used as the header row.
Expand Down
33 changes: 33 additions & 0 deletions markdownify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ class DefaultOptions:
strong_em_symbol = ASTERISK
sub_symbol = ''
sup_symbol = ''
table_cell_block_breaks = False
table_infer_header = False
wrap = False
wrap_width = 80
Expand Down Expand Up @@ -279,6 +280,9 @@ def _can_ignore(el):
or node.name in {'td', 'th'} # table cells
):
parent_tags_for_children.add('_inline')
if (self.options['table_cell_block_breaks'] and node.name in {'td', 'th'}
and self.should_convert_tag(node.name)):
parent_tags_for_children.add('_table_cell_blocks')

# if this tag is a preformatted element, add a '_noformat' parent pseudo-tag
if node.name in {'pre', 'code', 'kbd', 'samp'}:
Expand All @@ -289,6 +293,8 @@ def _can_ignore(el):
self.process_element(el, parent_tags=parent_tags_for_children)
for el in children_to_convert
]
if '_table_cell_blocks' in parent_tags_for_children and '_noformat' not in parent_tags_for_children:
child_strings = self._separate_table_cell_blocks(children_to_convert, child_strings)

# Remove empty string values.
child_strings = [s for s in child_strings if s]
Expand Down Expand Up @@ -733,6 +739,33 @@ def convert_caption(self, el, text, parent_tags):
def convert_figcaption(self, el, text, parent_tags):
return '\n\n' + text.strip() + '\n\n'

def _separate_table_cell_blocks(self, children, child_strings):
lines = []
inline = []
for child, text in zip(children, child_strings):
if not text:
continue
if child.name in ('div', 'p', 'ul', 'ol', 'li') and self.should_convert_tag(child.name):
block = text.strip()
if block:
lines.extend([''.join(inline).strip(), block])
inline = []
else:
inline.append(text)
if not lines:
return child_strings
lines.append(''.join(inline).strip())
lines = [line for line in lines if line]
if len(lines) < 2:
return child_strings

# A surrounding tag may pass this text through to adjacent words.
# Trim whitespace only at the boundaries replaced by a break.
original = ''.join(text for text in child_strings if text)
leading = original[:len(original) - len(original.lstrip())]
trailing = original[len(original.rstrip()):]
return [leading + '<br>'.join(lines) + trailing]

def convert_td(self, el, text, parent_tags):
colspan = 1
if 'colspan' in el.attrs and el['colspan'].isdigit():
Expand Down
2 changes: 2 additions & 0 deletions markdownify/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ def main(argv=sys.argv[1:]):
"should be converted to markdown images instead, this option can "
"be set to a list of parent tags that should be allowed to "
"contain inline images.")
parser.add_argument('--table-cell-block-breaks', action='store_true',
help='Separate paragraphs, divs and list items in table cells with <br>.')
parser.add_argument('--table-infer-header', dest='table_infer_header',
action='store_true',
help="When a table has no header row (as indicated by '<thead>' "
Expand Down
36 changes: 36 additions & 0 deletions tests/test_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,3 +319,39 @@ def test_table_infer_header():
assert md(table_with_colspan, table_infer_header=True) == '\n\n| Name | | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'
assert md(table_with_undefined_colspan, table_infer_header=True) == '\n\n| Name | Age |\n| --- | --- |\n| Jill | Smith |\n\n'
assert md(table_with_colspan_missing_head, table_infer_header=True) == '\n\n| Name | | Age |\n| --- | --- | --- |\n| Jill | Smith | 50 |\n| Eve | Jackson | 94 |\n\n'


def test_table_cell_block_breaks():
html = (
'<table><tr><th><div>First</div><div>Second</div></th></tr>'
'<tr><td><ul><li>Item one</li><li>Item two</li></ul></td></tr></table>'
)
assert md(html) == '\n\n| First Second |\n| --- |\n| * Item one * Item two |\n\n'
assert md(html, table_cell_block_breaks=True) == (
'\n\n| First<br>Second |\n| --- |\n| * Item one<br>* Item two |\n\n'
)


def test_table_cell_block_breaks_keep_inline_content_and_ignore_empty_blocks():
html = (
'<table><tr><th>Header</th></tr><tr><td>'
'A\n <em>word</em><div><p><b>Bold</b></p><p></p><p>part</p></div>End'
'</td></tr></table>'
)
assert md(html, table_cell_block_breaks=True) == (
'\n\n| Header |\n| --- |\n| A *word*<br>**Bold**<br>part<br>End |\n\n'
)


def test_table_cell_block_breaks_preserve_spaces_around_a_transparent_wrapper():
html = (
'<table><tr><th>Header</th></tr><tr><td>'
'Intro<aside><p>Alpha</p><p>Beta</p></aside>Tail'
'</td></tr></table>'
)
expected = '\n\n| Header |\n| --- |\n| Intro Alpha<br>Beta Tail |\n\n'
assert md(html, table_cell_block_breaks=True) == expected

html = html.replace('aside', 'div')
assert md(html, table_cell_block_breaks=True, strip=['div']) == expected
assert md(html, table_cell_block_breaks=True, convert=['table', 'tr', 'th', 'td', 'p']) == expected