Skip to content

Commit cf782b1

Browse files
committed
colors: bug fix handling markup with no text
1 parent 09eac27 commit cf782b1

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

easypy/colors.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -137,12 +137,13 @@ def __new__(cls, text):
137137
if match:
138138
stl, *parts = match.groups()
139139
stl = stl.strip("_")
140-
part = next(filter(None, parts))
141-
for l in part.splitlines():
142-
self.tokens.append(self.ColoredToken(l, stl))
143-
self.tokens.append(self.Token("\n"))
144-
if not part.endswith("\n"):
145-
del self.tokens[-1]
140+
part = next(filter(None, parts), "") # default to "", in case there's no text in the token
141+
if part:
142+
for l in part.splitlines():
143+
self.tokens.append(self.ColoredToken(l, stl))
144+
self.tokens.append(self.Token("\n"))
145+
if not part.endswith("\n"):
146+
del self.tokens[-1]
146147
else:
147148
self.tokens.append(self.Token(part))
148149
self.uncolored = "".join(str.__str__(token) for token in self.tokens)
@@ -336,7 +337,8 @@ def colorize(text):
336337

337338
def _subfunc(match_obj):
338339
colorizer = Colorizer.from_markup(match_obj.group(1))
339-
return colorizer(next(filter(None, match_obj.groups()[1:])))
340+
token = next(filter(None, match_obj.groups()[1:]), "")
341+
return colorizer(token) if token else ""
340342

341343
return RE_PARSE_COLOR_MARKUP.sub(_subfunc, text)
342344

tests/test_colors.py

+18-1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,23 @@ def test_colors():
1919

2020
assert len(opts) == 1
2121
[ret] = opts
22-
2322
assert ret == "\x1b[1;44;31mXXX\x1b[0m"
2423
assert uncolored(ret) == "XXX"
24+
25+
26+
def test_empty_markup():
27+
from easypy.colors import Colorized, colorize
28+
29+
opts = {
30+
colorize("BLUE<<>>"),
31+
colorize("BLUE@[]@"),
32+
colorize("BLUE@{}@"),
33+
str(Colorized("BLUE<<>>")),
34+
str(Colorized("BLUE@[]@")),
35+
str(Colorized("BLUE@{}@")),
36+
}
37+
38+
assert len(opts) == 1
39+
[ret] = opts
40+
41+
assert ret == ""

0 commit comments

Comments
 (0)