Skip to content

Commit 32eb546

Browse files
committed
from_ansi method
1 parent f0d0da8 commit 32eb546

File tree

2 files changed

+18
-13
lines changed

2 files changed

+18
-13
lines changed

rich/text.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -254,10 +254,10 @@ def from_ansi(
254254
end: str = "\n",
255255
tab_size: Optional[int] = 8,
256256
) -> "Text":
257-
"""Create a Text object from pre-formatted ANSI.
257+
"""Create a Text object from a string containing ANSI escape codes.
258258
259259
Args:
260-
text (str): A string containing ANSI color codes.
260+
text (str): A string containing escape codes.
261261
style (Union[str, Style], optional): Base style for text. Defaults to "".
262262
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
263263
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
@@ -267,14 +267,18 @@ def from_ansi(
267267
"""
268268
from .ansi import AnsiDecoder
269269

270-
decoded_text = AnsiDecoder().decode_line(text)
271-
decoded_text.justify = justify
272-
decoded_text.overflow = overflow
273-
decoded_text.no_wrap = no_wrap
274-
decoded_text.end = end
275-
decoded_text.tab_size = tab_size
276-
decoded_text.stylize(style)
277-
return decoded_text
270+
joiner = Text(
271+
"\n",
272+
justify=justify,
273+
overflow=overflow,
274+
no_wrap=no_wrap,
275+
end=end,
276+
tab_size=tab_size,
277+
style=style,
278+
)
279+
decoder = AnsiDecoder()
280+
result = joiner.join(line for line in decoder.decode(text))
281+
return result
278282

279283
@classmethod
280284
def styled(

tests/test_text.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,12 @@ def test_from_markup():
9797

9898
def test_from_ansi():
9999
text = Text.from_ansi("Hello, \033[1mWorld!\033[0m")
100-
text2 = Text.from_ansi("Hello, \033[1mWorld!\033[0m", style="red")
101100
assert str(text) == "Hello, World!"
102101
assert text._spans == [Span(7, 13, Style(bold=True))]
103-
assert str(text2) == "Hello, World!"
104-
assert text2._spans == [Span(7, 13, Style(bold=True)), Span(0, 13, "red")]
102+
103+
text = Text.from_ansi("Hello, \033[1m\nWorld!\033[0m")
104+
assert str(text) == "Hello, \nWorld!"
105+
assert text._spans == [Span(8, 14, Style(bold=True))]
105106

106107

107108
def test_copy():

0 commit comments

Comments
 (0)