diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 12a2950..76cb2df 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -187,12 +187,23 @@ def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns): # hard-coded padding _around_ align attribute and value together # rather than padding parameter which affects only the value values_with_attrs = [ - " " + alignment.get(a, "") + c + " " for c, a in zip(cell_values, colaligns) + " " + + alignment.get(a, "") + + _escape_mediawiki_value(c, separator) + + " " + for c, a in zip(cell_values, colaligns) ] colsep = separator * 2 return (separator + colsep.join(values_with_attrs)).rstrip() +def _escape_mediawiki_value(value, separator): + value = value.replace("|", "|") + if separator == "!": + value = value.replace("!", "!") + return value + + def _textile_row_with_attrs(cell_values, colwidths, colaligns): cell_values[0] += " " alignment = {"left": "<.", "right": ">.", "center": "=.", "decimal": ">."} diff --git a/test/test_output.py b/test/test_output.py index ea3da87..1a887fb 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2559,6 +2559,44 @@ def test_mediawiki_headerless(): assert_equal(expected, result) +def test_mediawiki_escapes_pipes_in_cells_and_headers(): + "Output: mediawiki with literal pipes in cell and header content" + # https://github.com/astanin/python-tabulate/issues/499 + expected = "\n".join( + [ + '{| class="wikitable" style="text-align: left;"', + "|+ ", + "|-", + "! h | 1", + "|-", + "| x | y", + "|-", + "| a || b", + "|}", + ] + ) + result = tabulate([["x | y"], ["a || b"]], headers=["h | 1"], tablefmt="mediawiki") + assert_equal(expected, result) + + +def test_mediawiki_escapes_bang_in_headers(): + "Output: mediawiki header cells containing double exclamation marks" + # https://github.com/astanin/python-tabulate/issues/499 + expected = "\n".join( + [ + '{| class="wikitable" style="text-align: left;"', + "|+ ", + "|-", + "! h !! 1", + "|-", + "| value", + "|}", + ] + ) + result = tabulate([["value"]], headers=["h !! 1"], tablefmt="mediawiki") + assert_equal(expected, result) + + def test_moinmoin(): "Output: moinmoin with headers" expected = "\n".join(