From 3da719aca6c27049bf7fb272dc7d19c7712d289e Mon Sep 17 00:00:00 2001 From: longint2 <251122526+longint2@users.noreply.github.com> Date: Sat, 5 Dec 2026 23:35:49 +0800 Subject: [PATCH] Escape cell delimiters in Org tables --- README.md | 3 ++- tabulate/__init__.py | 5 +++-- test/test_output.py | 14 ++++++++++++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0283a0c..403f32e 100644 --- a/README.md +++ b/README.md @@ -512,7 +512,8 @@ format: `orgtbl` follows the conventions of Emacs [org-mode](http://orgmode.org/manual/Tables.html), and is editable also -in the minor orgtbl-mode. Hence its name: +in the minor orgtbl-mode. Vertical bars inside cell values and headers are +escaped as `\vert{}` so that they do not create extra columns. For example: ```pycon >>> print(tabulate(table, headers, tablefmt="orgtbl")) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 12a2950..c2f09d6 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -328,6 +328,7 @@ def make_header_line(is_header, colwidths, colaligns): GITHUB_ESCAPE_RULES = {r"|": r"\|"} +ORGTBL_ESCAPE_RULES = {"|": r"\vert{}"} def _rst_escape_first_column(rows, headers): @@ -535,8 +536,8 @@ def escape_empty(val): linebelowheader=Line("|", "-", "+", "|"), linebetweenrows=None, linebelow=None, - headerrow=DataRow("|", "|", "|"), - datarow=DataRow("|", "|", "|"), + headerrow=DataRow("|", "|", "|", ORGTBL_ESCAPE_RULES), + datarow=DataRow("|", "|", "|", ORGTBL_ESCAPE_RULES), padding=1, with_header_hide=None, ), diff --git a/test/test_output.py b/test/test_output.py index ea3da87..7b04b66 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2114,6 +2114,20 @@ def test_orgtbl(): assert_equal(expected, result) +@mark.parametrize("headers", [[], ["left|right", "value"]]) +@mark.parametrize("value", ["a|b", "a|b\nc|d"]) +def test_orgtbl_escapes_cell_delimiters(headers, value): + result = tabulate([[value, "*bold*"]], headers=headers, tablefmt="orgtbl") + data_lines = [line for line in result.splitlines() if "+" not in line] + assert all(line.count("|") == 3 for line in data_lines) + assert r"a\vert{}b" in result + assert "*bold*" in result + if headers: + assert r"left\vert{}right" in result + if "\n" in value: + assert r"c\vert{}d" in result + + def test_orgtbl_headerless(): "Output: orgtbl without headers" expected = "\n".join(["| spam | 41.9999 |", "| eggs | 451 |"])