Skip to content

Commit 023d5af

Browse files
committed
Fixed bug where ANSI style sequences were not correctly handled in utils.truncate_line()
1 parent 8d9f97b commit 023d5af

File tree

4 files changed

+100
-23
lines changed

4 files changed

+100
-23
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* Bug Fixes
33
* Corrected issue where the actual new value was not always being printed in do_set. This occurred in cases where
44
the typed value differed from what the setter had converted it to.
5+
* Fixed bug where ANSI style sequences were not correctly handled in `utils.truncate_line()`.
56
* Enhancements
67
* Renamed set command's `-l/--long` flag to `-v/--verbose` for consistency with help and history commands.
78

cmd2/constants.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
MULTILINE_TERMINATOR = ';'
1515

1616
LINE_FEED = '\n'
17+
HORIZONTAL_ELLIPSIS = '\N{HORIZONTAL ELLIPSIS}'
1718

1819
DEFAULT_SHORTCUTS = {'?': 'help', '!': 'shell', '@': 'run_script', '@@': '_relative_run_script'}
1920

cmd2/utils.py

Lines changed: 61 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -682,8 +682,8 @@ def align_text(text: str, alignment: TextAlignment, *, fill_char: str = ' ',
682682
width: Optional[int] = None, tab_width: int = 4, truncate: bool = False) -> str:
683683
"""
684684
Align text for display within a given width. Supports characters with display widths greater than 1.
685-
ANSI style sequences are safely ignored and do not count toward the display width. This means colored text is
686-
supported. If text has line breaks, then each line is aligned independently.
685+
ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned
686+
independently.
687687
688688
There are convenience wrappers around this function: align_left(), align_center(), and align_right()
689689
@@ -777,8 +777,8 @@ def align_left(text: str, *, fill_char: str = ' ', width: Optional[int] = None,
777777
tab_width: int = 4, truncate: bool = False) -> str:
778778
"""
779779
Left align text for display within a given width. Supports characters with display widths greater than 1.
780-
ANSI style sequences are safely ignored and do not count toward the display width. This means colored text is
781-
supported. If text has line breaks, then each line is aligned independently.
780+
ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned
781+
independently.
782782
783783
:param text: text to left align (can contain multiple lines)
784784
:param fill_char: character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
@@ -800,8 +800,8 @@ def align_center(text: str, *, fill_char: str = ' ', width: Optional[int] = None
800800
tab_width: int = 4, truncate: bool = False) -> str:
801801
"""
802802
Center text for display within a given width. Supports characters with display widths greater than 1.
803-
ANSI style sequences are safely ignored and do not count toward the display width. This means colored text is
804-
supported. If text has line breaks, then each line is aligned independently.
803+
ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned
804+
independently.
805805
806806
:param text: text to center (can contain multiple lines)
807807
:param fill_char: character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
@@ -823,8 +823,8 @@ def align_right(text: str, *, fill_char: str = ' ', width: Optional[int] = None,
823823
tab_width: int = 4, truncate: bool = False) -> str:
824824
"""
825825
Right align text for display within a given width. Supports characters with display widths greater than 1.
826-
ANSI style sequences are safely ignored and do not count toward the display width. This means colored text is
827-
supported. If text has line breaks, then each line is aligned independently.
826+
ANSI style sequences do not count toward the display width. If text has line breaks, then each line is aligned
827+
independently.
828828
829829
:param text: text to right align (can contain multiple lines)
830830
:param fill_char: character that fills the alignment gap. Defaults to space. (Cannot be a line breaking character)
@@ -845,8 +845,15 @@ def align_right(text: str, *, fill_char: str = ' ', width: Optional[int] = None,
845845
def truncate_line(line: str, max_width: int, *, tab_width: int = 4) -> str:
846846
"""
847847
Truncate a single line to fit within a given display width. Any portion of the string that is truncated
848-
is replaced by a '…' character. Supports characters with display widths greater than 1. ANSI style sequences are
849-
safely ignored and do not count toward the display width. This means colored text is supported.
848+
is replaced by a '…' character. Supports characters with display widths greater than 1. ANSI style sequences
849+
do not count toward the display width.
850+
851+
If there are ANSI style sequences in the string after where truncation occurs, this function will append them
852+
to the returned string.
853+
854+
This is done to prevent issues caused in cases like: truncate_string(fg.blue + hello + fg.reset, 3)
855+
In this case, "hello" would be truncated before fg.reset resets the color from blue. Appending the remaining style
856+
sequences makes sure the style is in the same state had the entire string been printed.
850857
851858
:param line: text to truncate
852859
:param max_width: the maximum display width the resulting string is allowed to have
@@ -855,6 +862,7 @@ def truncate_line(line: str, max_width: int, *, tab_width: int = 4) -> str:
855862
:raises: ValueError if text contains an unprintable character like a new line
856863
ValueError if max_width is less than 1
857864
"""
865+
import io
858866
from . import ansi
859867

860868
# Handle tabs
@@ -866,12 +874,48 @@ def truncate_line(line: str, max_width: int, *, tab_width: int = 4) -> str:
866874
if max_width < 1:
867875
raise ValueError("max_width must be at least 1")
868876

869-
if ansi.style_aware_wcswidth(line) > max_width:
870-
# Remove characters until we fit. Leave room for the ellipsis.
871-
line = line[:max_width - 1]
872-
while ansi.style_aware_wcswidth(line) > max_width - 1:
873-
line = line[:-1]
877+
if ansi.style_aware_wcswidth(line) <= max_width:
878+
return line
879+
880+
# Find all style sequences in the line
881+
start = 0
882+
styles = collections.OrderedDict()
883+
while True:
884+
match = ansi.ANSI_STYLE_RE.search(line, start)
885+
if match is None:
886+
break
887+
styles[match.start()] = match.group()
888+
start += len(match.group())
889+
890+
# Add characters one by one and preserve all style sequences
891+
done = False
892+
index = 0
893+
total_width = 0
894+
truncated_buf = io.StringIO()
895+
896+
while not done:
897+
# Check if a style sequence is at this index. These don't count toward display width.
898+
if index in styles:
899+
truncated_buf.write(styles[index])
900+
style_len = len(styles[index])
901+
styles.pop(index)
902+
index += style_len
903+
continue
904+
905+
char = line[index]
906+
char_width = ansi.style_aware_wcswidth(char)
907+
908+
# This char will make the text too wide, add the ellipsis instead
909+
if char_width + total_width >= max_width:
910+
char = constants.HORIZONTAL_ELLIPSIS
911+
char_width = ansi.style_aware_wcswidth(char)
912+
done = True
913+
914+
total_width += char_width
915+
truncated_buf.write(char)
916+
index += 1
874917

875-
line += "\N{HORIZONTAL ELLIPSIS}"
918+
# Append remaining style sequences from original string
919+
truncated_buf.write(''.join(styles.values()))
876920

877-
return line
921+
return truncated_buf.getvalue()

tests/test_utils.py

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import pytest
1111

1212
import cmd2.utils as cu
13+
from cmd2.constants import HORIZONTAL_ELLIPSIS
1314

1415
HELLO_WORLD = 'Hello, world!'
1516

@@ -297,7 +298,13 @@ def test_truncate_line():
297298
line = 'long'
298299
max_width = 3
299300
truncated = cu.truncate_line(line, max_width)
300-
assert truncated == 'lo\N{HORIZONTAL ELLIPSIS}'
301+
assert truncated == 'lo' + HORIZONTAL_ELLIPSIS
302+
303+
def test_truncate_line_already_fits():
304+
line = 'long'
305+
max_width = 4
306+
truncated = cu.truncate_line(line, max_width)
307+
assert truncated == line
301308

302309
def test_truncate_line_with_newline():
303310
line = 'fo\no'
@@ -315,20 +322,44 @@ def test_truncate_line_wide_text():
315322
line = '苹苹other'
316323
max_width = 6
317324
truncated = cu.truncate_line(line, max_width)
318-
assert truncated == '苹苹o\N{HORIZONTAL ELLIPSIS}'
325+
assert truncated == '苹苹o' + HORIZONTAL_ELLIPSIS
319326

320327
def test_truncate_line_split_wide_text():
321328
"""Test when truncation results in a string which is shorter than max_width"""
322329
line = '1苹2苹'
323330
max_width = 3
324331
truncated = cu.truncate_line(line, max_width)
325-
assert truncated == '1\N{HORIZONTAL ELLIPSIS}'
332+
assert truncated == '1' + HORIZONTAL_ELLIPSIS
326333

327334
def test_truncate_line_tabs():
328335
line = 'has\ttab'
329336
max_width = 9
330337
truncated = cu.truncate_line(line, max_width)
331-
assert truncated == 'has t\N{HORIZONTAL ELLIPSIS}'
338+
assert truncated == 'has t' + HORIZONTAL_ELLIPSIS
339+
340+
def test_truncate_with_style():
341+
from cmd2 import ansi
342+
343+
before_style = ansi.fg.blue + ansi.UNDERLINE_ENABLE
344+
after_style = ansi.fg.reset + ansi.UNDERLINE_DISABLE
345+
346+
# Style only before truncated text
347+
line = before_style + 'long'
348+
max_width = 3
349+
truncated = cu.truncate_line(line, max_width)
350+
assert truncated == before_style + 'lo' + HORIZONTAL_ELLIPSIS
351+
352+
# Style before and after truncated text
353+
line = before_style + 'long' + after_style
354+
max_width = 3
355+
truncated = cu.truncate_line(line, max_width)
356+
assert truncated == before_style + 'lo' + HORIZONTAL_ELLIPSIS + after_style
357+
358+
# Style only after truncated text
359+
line = 'long' + after_style
360+
max_width = 3
361+
truncated = cu.truncate_line(line, max_width)
362+
assert truncated == 'lo' + HORIZONTAL_ELLIPSIS + after_style
332363

333364
def test_align_text_fill_char_is_tab():
334365
text = 'foo'
@@ -384,15 +415,15 @@ def test_align_text_wider_than_width_truncate():
384415
fill_char = '-'
385416
width = 8
386417
aligned = cu.align_text(text, cu.TextAlignment.LEFT, fill_char=fill_char, width=width, truncate=True)
387-
assert aligned == 'long te\N{HORIZONTAL ELLIPSIS}'
418+
assert aligned == 'long te' + HORIZONTAL_ELLIPSIS
388419

389420
def test_align_text_wider_than_width_truncate_add_fill():
390421
"""Test when truncation results in a string which is shorter than width and align_text adds filler"""
391422
text = '1苹2苹'
392423
fill_char = '-'
393424
width = 3
394425
aligned = cu.align_text(text, cu.TextAlignment.LEFT, fill_char=fill_char, width=width, truncate=True)
395-
assert aligned == '1\N{HORIZONTAL ELLIPSIS}-'
426+
assert aligned == '1' + HORIZONTAL_ELLIPSIS + fill_char
396427

397428
def test_align_text_has_unprintable():
398429
text = 'foo\x02'

0 commit comments

Comments
 (0)