From 3940be5fb1e103098dd90794b82a3c736f685bc7 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Mon, 23 Nov 2026 16:23:51 +0800 Subject: [PATCH] Preserve table column alignment across row spans --- README.rst | 5 +++ markdownify/__init__.py | 52 ++++++++++++++++++++++++- tests/test_table_rowspan.py | 76 +++++++++++++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 tests/test_table_rowspan.py diff --git a/README.rst b/README.rst index 059a68f..6467a41 100644 --- a/README.rst +++ b/README.rst @@ -144,6 +144,11 @@ table_infer_header or ````). 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 ````, + ```` and ```` 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``. diff --git a/markdownify/__init__.py b/markdownify/__init__.py index d946d2c..185b650 100644 --- a/markdownify/__init__.py +++ b/markdownify/__init__.py @@ -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 @@ -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 @@ -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) @@ -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]) diff --git a/tests/test_table_rowspan.py b/tests/test_table_rowspan.py new file mode 100644 index 0000000..764644a --- /dev/null +++ b/tests/test_table_rowspan.py @@ -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 = ''' + +
ABC
onetwothree
four
fivesix
''' + assert markdownify(html) == ( + '| A | B | C |\n| --- | --- | --- |\n' + '| **one** | two | three |\n| | four | |\n| | five | six |' + ) + + +def test_rowspan_and_colspan(): + html = ''' +
onetwo
three
''' + 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 = ''' + + +
AB
onetwo
three
fourfive
''' % 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 = '
one
two
' % span + assert markdownify(html) == '| |\n| --- |\n| one |\n| two |' + + +def test_rowspan_fills_an_empty_row(): + html = '
one
' + assert markdownify(html) == '| |\n| --- |\n| one |\n| |' + + +def test_rowspan_does_not_change_the_callers_soup_or_leak_between_tables(): + html = '
onetwo
three
' + 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('
next
') == '| |\n| --- |\n| next |' + + +def test_nested_tables_have_independent_rowspans(): + inner = '
innerx
y
' + html = '
outer%s
end
' % 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 = '
onetwo
three
' + assert '| ONE | TWO |\n| | THREE |' in Converter().convert(html)