From 9ac73f4306e1a835a6426d3b63a9e3a1946f3e1a Mon Sep 17 00:00:00 2001
From: Boulea7 <145515129+Boulea7@users.noreply.github.com>
Date: Thu, 3 Dec 2026 19:27:47 +0800
Subject: [PATCH] Render multiline cells in LaTeX tables
---
README.md | 11 ++++++-----
tabulate/__init__.py | 30 +++++++++++++++++++++++-------
test/test_output.py | 28 ++++++++++++++++++++++++++++
3 files changed, 57 insertions(+), 12 deletions(-)
diff --git a/README.md b/README.md
index 0283a0c..a786a2f 100644
--- a/README.md
+++ b/README.md
@@ -850,10 +850,8 @@ characters.
Multiline cells are supported for data rows and for header rows.
-Further automatic line breaks are not inserted. Of course, some output
-formats such as latex or html handle automatic formatting of the cell
-content on their own, but for those that don't, the newline characters
-in the input cell text are the only means to break a line in cell text.
+Line breaks can come from the input text or the automatic wrapping options
+described below.
Note that some output formats (e.g. simple, or plain) do not represent
row delimiters, so that the representation of multiline cells in such
@@ -1021,7 +1019,10 @@ spam
```
-Multiline cells are not well-supported for the other table formats.
+The `latex`, `latex_booktabs`, and `latex_longtable` formats use LaTeX's
+built-in `\shortstack` for multiline cells. Both explicit line breaks and
+those inserted by `maxcolwidths` or `maxheadercolwidths` render inside the
+same table cell.
### Automating Multilines
While tabulate supports data passed in with multilines entries explicitly provided,
diff --git a/tabulate/__init__.py b/tabulate/__init__.py
index 12a2950..2535cc4 100644
--- a/tabulate/__init__.py
+++ b/tabulate/__init__.py
@@ -242,9 +242,11 @@ def _moin_row_with_attrs(celltag, cell_values, colwidths, colaligns, header=""):
return "".join(values_with_attrs) + "||"
+_LATEX_ALIGNMENTS = {"left": "l", "right": "r", "center": "c", "decimal": "r"}
+
+
def _latex_line_begin_tabular(colwidths, colaligns, booktabs=False, longtable=False):
- alignment = {"left": "l", "right": "r", "center": "c", "decimal": "r"}
- tabular_columns_fmt = "".join([alignment.get(a, "l") for a in colaligns])
+ tabular_columns_fmt = "".join(_LATEX_ALIGNMENTS.get(a, "l") for a in colaligns)
return "\n".join(
[
("\\begin{tabular}{" if not longtable else "\\begin{longtable}{")
@@ -324,7 +326,23 @@ def make_header_line(is_header, colwidths, colaligns):
}
-_latex_row = DataRow("", "&", "\\\\", LATEX_ESCAPE_RULES)
+_LATEX_TRANSLATION = str.maketrans(LATEX_ESCAPE_RULES)
+_latex_raw_row = DataRow("", "&", "\\\\", {})
+
+
+def _latex_row(padded_cells, _colwidths, colaligns):
+ cells = []
+ for index, cell in enumerate(padded_cells):
+ cell = cell.translate(_LATEX_TRANSLATION)
+ if "\n" in cell or "\r" in cell:
+ align = colaligns[index] if index < len(colaligns) else "left"
+ alignment = _LATEX_ALIGNMENTS.get(align, "l")
+ lines = cell.strip(" ").replace("\r\n", "\n").replace("\r", "\n").split("\n")
+ # Group each line so a leading '[' is treated as text after a break.
+ stack = r"\\".join(f"{{{line}}}" for line in lines)
+ cell = rf" \shortstack[{alignment}]{{{stack}}} "
+ cells.append(cell)
+ return _build_simple_row(cells, _latex_raw_row)
GITHUB_ESCAPE_RULES = {r"|": r"\|"}
@@ -650,8 +668,8 @@ def escape_empty(val):
linebelowheader=Line("\\hline", "", "", ""),
linebetweenrows=None,
linebelow=Line("\\hline\n\\end{tabular}", "", "", ""),
- headerrow=DataRow("", "&", "\\\\", {}),
- datarow=DataRow("", "&", "\\\\", {}),
+ headerrow=_latex_raw_row,
+ datarow=_latex_raw_row,
padding=1,
with_header_hide=None,
),
@@ -749,8 +767,6 @@ def escape_empty(val):
# - mediawiki: Replace \n with
# - moinmoin: TBD
# - html: Replace \n with
-# - latex*: Use "makecell" package: In header, replace X\nY with
-# \thead{X\\Y} and in data row, replace X\nY with \makecell{X\\Y}
# - tsv: TBD
# - textile: Replace \n with
(must be well-formed XML)
diff --git a/test/test_output.py b/test/test_output.py
index ea3da87..2597371 100644
--- a/test/test_output.py
+++ b/test/test_output.py
@@ -2767,6 +2767,34 @@ def test_latex_booktabs_headerless():
assert_equal(expected, result)
+@mark.parametrize(
+ ("tablefmt", "environment"),
+ [("latex", "tabular"), ("latex_booktabs", "tabular"), ("latex_longtable", "longtable")],
+)
+def test_latex_wrapped_cells(tablefmt, environment):
+ result = tabulate(
+ [["alpha & beta", 41.5]],
+ headers=["long heading", "value"],
+ tablefmt=tablefmt,
+ maxcolwidths=[7, None],
+ maxheadercolwidths=[8, None],
+ floatfmt=".2f",
+ )
+
+ assert result.splitlines()[0] == rf"\begin{{{environment}}}{{lr}}"
+ assert r"\shortstack[l]{{long}\\{heading}}" in result
+ (data_row,) = [line for line in result.splitlines() if "alpha" in line]
+ assert r"\shortstack[l]{{alpha \&}\\{beta}}" in data_row
+ assert data_row.endswith(r"41.50 \\")
+
+
+def test_latex_escapes_multiline_cells():
+ result = tabulate([["first_\r\n[label] and 10%"]], tablefmt="latex", stralign="right")
+
+ assert result.splitlines()[0] == r"\begin{tabular}{r}"
+ assert r"\shortstack[r]{{first\_}\\{[label] and 10\%}}" in result
+
+
def test_textile():
"Output: textile without header"
result = tabulate(_test_table, tablefmt="textile")