Skip to content
This repository has been archived by the owner on Dec 7, 2021. It is now read-only.

Pad centered colored text consistently #60

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
13 changes: 9 additions & 4 deletions terminaltables/width_and_alignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,18 @@ def align_and_pad_cell(string, align, inner_dimensions, padding, space=' '):

# Horizontally align and pad.
for i, line in enumerate(lines):
new_width = inner_dimensions[0] + len(line) - visible_width(line)
lpad, rpad = padding[:2]
extra_padding = inner_dimensions[0] - visible_width(line)
if 'right' in align:
lines[i] = line.rjust(padding[0] + new_width, space) + (space * padding[1])
lpad += extra_padding
elif 'center' in align:
lines[i] = (space * padding[0]) + line.center(new_width, space) + (space * padding[1])
# Replicate Python's str.center() logic, but using visible_width() instead of len().
left = extra_padding // 2 + (extra_padding & inner_dimensions[0] & 1)
lpad += left
rpad += extra_padding - left
else:
lines[i] = (space * padding[0]) + line.ljust(new_width + padding[1], space)
rpad += extra_padding
lines[i] = (space * lpad) + line + (space * rpad)

return lines

Expand Down
5 changes: 5 additions & 0 deletions tests/test_width_and_alignment/test_align_and_pad_cell.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@
('蓝色', 'center', 6, [' 蓝色 ']),
(u'שלום', 'center', 6, [u' \u05e9\u05dc\u05d5\u05dd ']),
(u'معرب', 'center', 6, [u' \u0645\u0639\u0631\u0628 ']),

('0000', 'center', 7, [' 0000 ']),
(colored('0000', 'blue'), 'center', 7, [' \x1b[34m0000\x1b[0m ']),
('00:00', 'center', 8, [' 00:00 ']),
(colored('00:00', 'blue'), 'center', 8, [' \x1b[34m00:00\x1b[0m ']),
])
def test_width(string, align, width, expected):
"""Test width and horizontal alignment.
Expand Down