Skip to content
Closed
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
1 change: 1 addition & 0 deletions news/557.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix table column maximum widths not wrapping cell contents.
14 changes: 9 additions & 5 deletions src/cleo/ui/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from typing import cast

from cleo.formatters.formatter import Formatter
from cleo.io.outputs.output import Output
from cleo.io.io import IO
from cleo.ui.table_cell import TableCell
from cleo.ui.table_cell_style import TableCellStyle
from cleo.ui.table_separator import TableSeparator
Expand All @@ -20,7 +20,7 @@
if TYPE_CHECKING:
from collections.abc import Iterator

from cleo.io.io import IO
from cleo.io.outputs.output import Output

Row = list[str | TableCell]
Rows = list[Row | TableSeparator]
Expand Down Expand Up @@ -103,7 +103,7 @@ def set_column_widths(self, widths: list[int]) -> Table:
return self

def set_column_max_width(self, column_index: int, width: int) -> Table:
self._column_widths[column_index] = width
self._column_max_widths[column_index] = width

return self

Expand Down Expand Up @@ -424,8 +424,12 @@ def _build_table_rows(self, rows: Rows) -> Iterator[Row | TableSeparator]:
if column in self._column_max_widths and self._column_max_widths[
column
] < len(self._io.remove_format(cell)):
assert isinstance(self._io, Output)
cell = self._io.formatter.format_and_wrap(
formatter = (
self._io.output.formatter
if isinstance(self._io, IO)
else self._io.formatter
)
cell = formatter.format_and_wrap(
cell, self._column_max_widths[column] * colspan
)

Expand Down
17 changes: 17 additions & 0 deletions tests/ui/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,3 +481,20 @@ def test_style_for_side_effects(io: BufferedIO) -> None:
output2 = io.fetch_output()

assert output1 != output2


def test_column_max_width_wraps_cell(io: BufferedIO) -> None:
table = Table(io)
table.set_rows([["abcdefghijklmnopqrstuvwxyz"]])
table.set_column_max_width(0, 10)

table.render()

expected = """\
+------------+
| abcdefghij |
| klmnopqrst |
| uvwxyz |
+------------+
"""
assert io.fetch_output() == expected
Loading