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
10 changes: 8 additions & 2 deletions markdownify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@
# Find consecutive backtick sequences in a string
re_backtick_runs = re.compile(r'`+')

# Find pipes that are not already escaped, so they can be escaped inside
# table cells without touching escapes that escape_misc already added
re_escape_table_pipe = re.compile(r'(?<!\\)\|')

# Heading styles
ATX = 'atx'
ATX_CLOSED = 'atx_closed'
Expand Down Expand Up @@ -737,13 +741,15 @@ 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().replace("\n", " ")
return ' ' + re_escape_table_pipe.sub(r'\\|', 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().replace("\n", " ")
return ' ' + re_escape_table_pipe.sub(r'\\|', text) + ' |' * colspan

def convert_tr(self, el, text, parent_tags):
cells = el.find_all(['td', 'th'])
Expand Down
23 changes: 23 additions & 0 deletions tests/test_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,3 +319,26 @@ 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'


table_with_pipes = """<table>
<tr><th>Expression</th></tr>
<tr><td>a|b</td></tr>
<tr><td><code>a|b</code></td></tr>
</table>"""


def test_table_pipes_are_escaped():
assert md(table_with_pipes) == (
'\n\n| Expression |\n| --- |\n'
'| a\\|b |\n'
'| `a\\|b` |\n\n'
)


def test_table_pipes_not_double_escaped():
assert md(table_with_pipes, escape_misc=True) == (
'\n\n| Expression |\n| --- |\n'
'| a\\|b |\n'
'| `a\\|b` |\n\n'
)