Skip to content
This repository has been archived by the owner on Nov 29, 2022. It is now read-only.

Commit

Permalink
Ignore SGR codes if they are not colors
Browse files Browse the repository at this point in the history
  • Loading branch information
hSaria committed Apr 27, 2022
1 parent 01e0477 commit 9635152
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
9 changes: 7 additions & 2 deletions chromaterm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@
# The format of a palette color
PALETTE_COLOR_RE = re.compile(r'\b([bf])\.([a-z0-9-_]+)\b')

# Select Graphic Rendition sequence (any type)
SGR_RE = re.compile(br'\x1b\[[0-9;]*m')
# Select Graphic Rendition sequence (any type or only colors)
SGR_RE = re.compile(br'\x1b\x5b[\x30-\x3f]*[\x20-\x2f]*\x6d')
SGR_COLOR_RE = re.compile(br'\x1b\x5b[0-9;]*\x6d')


class Color:
Expand Down Expand Up @@ -171,6 +172,10 @@ def decode_sgr(source_color_code, is_reset=False):
source_color_code (bytes): Bytes to be split into individual colors.
is_reset (bool): Consider all identified colors as resets.
'''
# Includes non-color characters; don't touch it
if not SGR_COLOR_RE.search(source_color_code):
return [[source_color_code, False, None]]

make_sgr = lambda code_id: b'\x1b[' + code_id + b'm'
colors = []
codes = source_color_code.lstrip(b'\x1b[').rstrip(b'm').split(b';')
Expand Down
2 changes: 1 addition & 1 deletion tests/test___init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def test_color_decode_sgr_full_reset():

def test_color_decode_sgr_malformed():
'''Malformed colors.'''
for code in [b'38;5', b'38;2;1;1', b'38;5;123;38;2;1;1']:
for code in [b'38;5', b'38;2;1;1', b'38;5;123;38;2;1;1', b'>1;']:
colors = chromaterm.Color.decode_sgr(make_sgr(code))
assert len(colors) == 1

Expand Down

0 comments on commit 9635152

Please sign in to comment.