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

Support for Colored Text w/o relying on colorclass #20

Closed
maharjun opened this issue May 1, 2016 · 1 comment
Closed

Support for Colored Text w/o relying on colorclass #20

maharjun opened this issue May 1, 2016 · 1 comment

Comments

@maharjun
Copy link

maharjun commented May 1, 2016

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.

@maharjun
Copy link
Author

maharjun commented May 1, 2016

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')

Robpol86 added a commit that referenced this issue May 14, 2016
Started adding support for colorama, termcolor, and regular ANSI color
codes. Using same regex used by colorclass in
https://github.com/Robpol86/colorclass/blob/169b5c7e/colorclass/parse.py#L12

Started testing RTL characters. Using arabic and hebrew in tests.

Begun working on:
#20
#23
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant