Skip to content

Commit

Permalink
fix: Prevent text wrapping when already within width (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
DenverCoder1 authored Oct 20, 2023
1 parent c6735c1 commit 32a7b6f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
19 changes: 12 additions & 7 deletions table2ascii/table_to_ascii.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ def __determine_alignments(

return list(alignments)

def __widest_line(self, value: SupportsStr) -> int:
"""Returns the width of the longest line in a multi-line string"""
text = str(value)
return max(self.__str_width(line) for line in text.splitlines()) if len(text) else 0

def __auto_column_widths(self) -> list[int]:
"""Get the minimum number of characters needed for the values in each column in the table
with 1 space of padding on each side.
Expand All @@ -138,18 +143,13 @@ def __auto_column_widths(self) -> list[int]:
The minimum number of characters needed for each column
"""

def widest_line(value: SupportsStr) -> int:
"""Returns the width of the longest line in a multi-line string"""
text = str(value)
return max(self.__str_width(line) for line in text.splitlines()) if len(text) else 0

def get_column_width(row: Sequence[SupportsStr], column: int) -> int:
"""Get the width of a cell in a column"""
value = row[column]
next_value = row[column + 1] if column < self.__columns - 1 else None
if value is Merge.LEFT or next_value is Merge.LEFT:
return 0
return widest_line(value)
return self.__widest_line(value)

column_widths = []
# get the width necessary for each column
Expand Down Expand Up @@ -306,7 +306,12 @@ def __wrap_long_lines_in_merged_cells(
if row[other_col_index] is not Merge.LEFT:
break
merged_width += self.__column_widths[other_col_index] + len(column_separator)
cell = textwrap.fill(str(cell), merged_width - self.__cell_padding * 2)
cell = str(cell)
# if the text is too wide, wrap it
inner_cell_width = merged_width - self.__cell_padding * 2
if self.__widest_line(cell) > inner_cell_width:
cell = textwrap.fill(cell, inner_cell_width)
# add the wrapped cell to the row
wrapped_row.append(cell)
return wrapped_row

Expand Down
19 changes: 19 additions & 0 deletions tests/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,3 +305,22 @@ def test_east_asian_wide_characters_and_zero_width_no_wcwidth():
"╚════╩═══════════════╝"
)
assert text == expected


def test_multiline_cells_with_wrappable_lines():
text = t2a(
header=["Test"],
body=[["Line One...\nSecond Line...\nLineNumThree\nLineFour\nFive FinalLine"]],
)
expected = (
"╔════════════════╗\n"
"║ Test ║\n"
"╟────────────────╢\n"
"║ Line One... ║\n"
"║ Second Line... ║\n"
"║ LineNumThree ║\n"
"║ LineFour ║\n"
"║ Five FinalLine ║\n"
"╚════════════════╝"
)
assert text == expected

0 comments on commit 32a7b6f

Please sign in to comment.