Fix column wrapping breaking ANSI escape codes (fixes #307) #308
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
In
tabulate._CustomTextWrap._handle_long_word
, ANSI escape codes may be broken in the middle, resulting wrongly formatted tables. That happens because the length of the string is checked inwhile self._len(chunk[:i]) <= space_left:
, which may strip ANSI codes after they were broken by indexing into their middle.To solve that, we instead calculate the length of the string without ANSI codes, then index into it:
while len(_strip_ansi(chunk)[:i]) <= space_left:
. That gives the amount of printable characters that should be included. Then we iterate through the escape codes present until we reach that many printable characters, and add the escape code lengths to figure out how much of the original string should be included.Tests included.
Test code:
Result before patch:
Result after patch:
Fixes #307.