Skip to content

Commit e6a24aa

Browse files
committed
fix astanin#241 - escape pipe character in github and pipe formats
1 parent 46c9fe3 commit e6a24aa

2 files changed

Lines changed: 15 additions & 5 deletions

File tree

tabulate/__init__.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
from collections import namedtuple
1818
from collections.abc import Iterable, Sized
1919
import dataclasses
20-
from decimal import Decimal
2120
from dataclasses import dataclass
21+
from decimal import Decimal
2222
from functools import partial, reduce
2323
from html import escape as htmlescape
2424
import io
@@ -333,6 +333,9 @@ def make_header_line(is_header, colwidths, colaligns):
333333
_latex_row = DataRow("", "&", "\\\\", LATEX_ESCAPE_RULES)
334334

335335

336+
GITHUB_ESCAPE_RULES = {r"|": r"\|"}
337+
338+
336339
def _rst_escape_first_column(rows, headers):
337340
def escape_empty(val):
338341
if isinstance(val, (str, bytes)) and not val.strip():
@@ -528,8 +531,8 @@ def escape_empty(val):
528531
linebelowheader=_pipe_line_with_colons,
529532
linebetweenrows=None,
530533
linebelow=None,
531-
headerrow=DataRow("|", "|", "|"),
532-
datarow=DataRow("|", "|", "|"),
534+
headerrow=DataRow("|", "|", "|", GITHUB_ESCAPE_RULES),
535+
datarow=DataRow("|", "|", "|", GITHUB_ESCAPE_RULES),
533536
padding=1,
534537
with_header_hide=["lineabove"],
535538
),
@@ -2515,16 +2518,23 @@ def _build_simple_row(padded_cells: list[list], rowfmt: DataRow) -> str:
25152518
escape_map: dict = rowfmt.escape_map
25162519

25172520
if escape_map:
2521+
25182522
def escape_char(c):
25192523
return escape_map.get(c, c)
2524+
25202525
escaped_cells = ["".join(map(escape_char, cell)) for cell in padded_cells]
25212526
else:
25222527
escaped_cells = padded_cells
25232528

25242529
return (begin + sep.join(escaped_cells) + end).rstrip()
25252530

25262531

2527-
def _build_row(padded_cells: list[list], colwidths: list[int], colaligns: list[str], rowfmt: Union[DataRow, Callable]) -> str:
2532+
def _build_row(
2533+
padded_cells: list[list],
2534+
colwidths: list[int],
2535+
colaligns: list[str],
2536+
rowfmt: Union[DataRow, Callable],
2537+
) -> str:
25282538
"Return a string which represents a row of data cells."
25292539
if not rowfmt:
25302540
return None

test/test_regression.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -596,5 +596,5 @@ def test_asciidoc_without_trailing_whitespace():
596596
def test_github_escape_pipe_character():
597597
"Regression: github format must escape pipe character with a backslash (issue #241)"
598598
result = tabulate([["foo|bar"]], headers=("spam|eggs",), tablefmt="github")
599-
expected = '| spam\\|eggs |\n|-------------|\n| foo\\|bar |'
599+
expected = "| spam\\|eggs |\n|:------------|\n| foo\\|bar |"
600600
assert_equal(expected, result)

0 commit comments

Comments
 (0)