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
5 changes: 5 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ table_infer_header
or ``<th>``). When set to ``True``, the first body row is used as the header row.
Defaults to ``False``, which leaves the header row empty.

Table cells spanning multiple rows or columns are followed by empty cells
in the covered positions, preserving column alignment. A ``rowspan="0"``
extends to the end of its row group; spans do not cross between ``<thead>``,
``<tbody>`` and ``<tfoot>`` sections. Cell content is emitted only once.

wrap, wrap_width
If ``wrap`` is set to ``True``, all text paragraphs are wrapped at
``wrap_width`` characters. Defaults to ``False`` and ``80``.
Expand Down
52 changes: 51 additions & 1 deletion markdownify/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from bs4 import BeautifulSoup, Comment, Doctype, NavigableString, Tag
from copy import copy
from itertools import groupby
from textwrap import fill
import re

Expand Down Expand Up @@ -174,6 +176,51 @@ def _next_block_content_sibling(el):
return None


def _table_span(cell, attribute, maximum, minimum=1):
try:
value = int(cell.get(attribute, 1))
except (TypeError, ValueError):
return 1
return min(maximum, value) if value >= minimum else 1


def _expand_table_rowspans(table):
"""Pad occupied slots on a copy, leaving caller-owned soup untouched."""
if not any(cell.has_attr('rowspan') and cell.find_parent('table') is table
for cell in table.find_all(['td', 'th'])):
return table
table = copy(table)
rows = [row for row in table.find_all('tr') if row.find_parent('table') is table]
# A rowspan cannot cross a thead/tbody/tfoot boundary. Direct tr children
# constitute an implicit group, including when the parser inserts no tbody.
for _, group in groupby(rows, key=lambda row: id(row.parent)):
group = list(group)
occupied = {}
for index, row in enumerate(group):
following = {column: (remaining - 1, tag)
for column, (remaining, tag) in occupied.items()
if remaining > 1}
column = 0
for cell in row.find_all(['td', 'th'], recursive=False):
while column in occupied:
cell.insert_before(Tag(name=occupied[column][1]))
column += 1
colspan = _table_span(cell, 'colspan', 1000)
rowspan = _table_span(cell, 'rowspan', len(group) - index, minimum=0)
if rowspan == 0:
rowspan = len(group) - index
if rowspan > 1:
for offset in range(colspan):
following[column + offset] = (rowspan - 1, cell.name)
column += colspan
# A carried cell may be at the end, or the row may have no cells.
if occupied:
for column in range(column, max(occupied) + 1):
row.append(Tag(name=occupied.get(column, (0, 'td'))[1]))
occupied = following
return table


class MarkdownConverter(object):
class DefaultOptions:
autolinks = True
Expand Down Expand Up @@ -237,6 +284,9 @@ def process_tag(self, node, parent_tags=None):
if parent_tags is None:
parent_tags = set()

if node.name == 'table':
node = _expand_table_rowspans(node)

# Collect child elements to process, ignoring whitespace-only text elements
# adjacent to the inner/outer boundaries of block elements.
should_remove_inside = should_remove_whitespace_inside(node)
Expand Down Expand Up @@ -746,7 +796,7 @@ def convert_th(self, el, text, parent_tags):
return ' ' + text.strip().replace("\n", " ") + ' |' * colspan

def convert_tr(self, el, text, parent_tags):
cells = el.find_all(['td', 'th'])
cells = el.find_all(['td', 'th'], recursive=False)
is_first_row = el.find_previous_sibling() is None
is_headrow = (
all([cell.name == 'th' for cell in cells])
Expand Down
76 changes: 76 additions & 0 deletions tests/test_table_rowspan.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import pytest
from bs4 import BeautifulSoup

from markdownify import MarkdownConverter, markdownify


def test_rowspan_keeps_following_cells_in_their_columns():
html = '''<table><tr><th>A</th><th>B</th><th>C</th></tr>
<tr><td rowspan="3"><b>one</b></td><td>two</td><td rowspan="2">three</td></tr>
<tr><td>four</td></tr><tr><td>five</td><td>six</td></tr></table>'''
assert markdownify(html) == (
'| A | B | C |\n| --- | --- | --- |\n'
'| **one** | two | three |\n| | four | |\n| | five | six |'
)


def test_rowspan_and_colspan():
html = '''<table><tr><td rowspan="2" colspan="2">one</td><td>two</td></tr>
<tr><td><a href="/three">three</a></td></tr></table>'''
assert markdownify(html, table_infer_header=True) == (
'| one | | two |\n| --- | --- | --- |\n| | | [three](/three) |'
)


@pytest.mark.parametrize('span', ['0', '99', '65534'])
def test_rowspan_stops_at_the_row_group(span):
html = '''<table><thead><tr><th>A</th><th>B</th></tr></thead>
<tbody><tr><td rowspan="%s">one</td><td>two</td></tr>
<tr><td>three</td></tr></tbody>
<tbody><tr><td>four</td><td>five</td></tr></tbody></table>''' % span
output = markdownify(html)
assert '| | three |' in output
assert '| four | five |' in output
assert output.count('three') == 1


@pytest.mark.parametrize('span', ['-1', 'undefined', '', '1.5'])
def test_invalid_rowspan_is_ignored(span):
html = '<table><tr><td rowspan="%s">one</td></tr><tr><td>two</td></tr></table>' % span
assert markdownify(html) == '| |\n| --- |\n| one |\n| two |'


def test_rowspan_fills_an_empty_row():
html = '<table><tr><td rowspan="2">one</td></tr><tr></tr></table>'
assert markdownify(html) == '| |\n| --- |\n| one |\n| |'


def test_rowspan_does_not_change_the_callers_soup_or_leak_between_tables():
html = '<table><tr><td rowspan="2">one</td><td>two</td></tr><tr><td>three</td></tr></table>'
soup = BeautifulSoup(html, 'html.parser')
original = str(soup)
converter = MarkdownConverter()
first = converter.convert_soup(soup)
assert '| | three |' in first
assert converter.convert_soup(soup) == first
assert str(soup) == original
assert converter.convert('<table><tr><td>next</td></tr></table>') == '| |\n| --- |\n| next |'


def test_nested_tables_have_independent_rowspans():
inner = '<table><tr><td rowspan="2">inner</td><td>x</td></tr><tr><td>y</td></tr></table>'
html = '<table><tr><td rowspan="2">outer</td><td>%s</td></tr><tr><td>end</td></tr></table>' % inner
output = markdownify(html)
assert '| | end |' in output
assert '| | y |' in output
assert output.count('outer') == 1
assert output.count('inner') == 1


def test_rowspan_preserves_custom_cell_conversion():
class Converter(MarkdownConverter):
def convert_td(self, el, text, parent_tags):
return super().convert_td(el, text.upper(), parent_tags)

html = '<table><tr><td rowspan="2">one</td><td>two</td></tr><tr><td>three</td></tr></table>'
assert '| ONE | TWO |\n| | THREE |' in Converter().convert(html)