Closed maharjun closed 8 years ago
The following patch should do the trick. It performs perfectly with any color input I throw at it
diff --git a/terminaltables/width_and_alignment.py b/terminaltables/width_and_alignment.py
index 8df1e0d..1079459 100644
--- a/terminaltables/width_and_alignment.py
+++ b/terminaltables/width_and_alignment.py
@@ -1,6 +1,9 @@
"""Functions that handle alignment, padding, widths, etc."""
import unicodedata
+import re
+
+isColorANSISeq = re.compile(r'\x1b\[([0-9]+;)*[0-9]*m')
def string_width(string):
@@ -19,6 +22,9 @@ def string_width(string):
if hasattr(string, 'value_no_colors'):
string = string.value_no_colors
+ # Remove color escape sequences
+ string = re.sub(isColorANSISeq, "", string)
+
# Convert to unicode.
try:
decoded = string.decode('u8')
Since the current functionality relating to colors is only limited to calculating the string_width, I would suggest a single line addition that removes ANSI color control sequences from the string before calculating the length. The reason I suggest it is, this leaves the user the freedom to use his color library of choice (e.g. colorama). For example, now that I use colorama extensively in my project, switching to colorclass becomes a bit of a pain now.