mirror of https://github.com/Textualize/rich.git
from_ansi method
This commit is contained in:
parent
f0d0da81c0
commit
32eb5465ea
24
rich/text.py
24
rich/text.py
|
@ -254,10 +254,10 @@ class Text(JupyterMixin):
|
|||
end: str = "\n",
|
||||
tab_size: Optional[int] = 8,
|
||||
) -> "Text":
|
||||
"""Create a Text object from pre-formatted ANSI.
|
||||
"""Create a Text object from a string containing ANSI escape codes.
|
||||
|
||||
Args:
|
||||
text (str): A string containing ANSI color codes.
|
||||
text (str): A string containing escape codes.
|
||||
style (Union[str, Style], optional): Base style for text. Defaults to "".
|
||||
justify (str, optional): Justify method: "left", "center", "full", "right". Defaults to None.
|
||||
overflow (str, optional): Overflow method: "crop", "fold", "ellipsis". Defaults to None.
|
||||
|
@ -267,14 +267,18 @@ class Text(JupyterMixin):
|
|||
"""
|
||||
from .ansi import AnsiDecoder
|
||||
|
||||
decoded_text = AnsiDecoder().decode_line(text)
|
||||
decoded_text.justify = justify
|
||||
decoded_text.overflow = overflow
|
||||
decoded_text.no_wrap = no_wrap
|
||||
decoded_text.end = end
|
||||
decoded_text.tab_size = tab_size
|
||||
decoded_text.stylize(style)
|
||||
return decoded_text
|
||||
joiner = Text(
|
||||
"\n",
|
||||
justify=justify,
|
||||
overflow=overflow,
|
||||
no_wrap=no_wrap,
|
||||
end=end,
|
||||
tab_size=tab_size,
|
||||
style=style,
|
||||
)
|
||||
decoder = AnsiDecoder()
|
||||
result = joiner.join(line for line in decoder.decode(text))
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
def styled(
|
||||
|
|
|
@ -97,11 +97,12 @@ def test_from_markup():
|
|||
|
||||
def test_from_ansi():
|
||||
text = Text.from_ansi("Hello, \033[1mWorld!\033[0m")
|
||||
text2 = Text.from_ansi("Hello, \033[1mWorld!\033[0m", style="red")
|
||||
assert str(text) == "Hello, World!"
|
||||
assert text._spans == [Span(7, 13, Style(bold=True))]
|
||||
assert str(text2) == "Hello, World!"
|
||||
assert text2._spans == [Span(7, 13, Style(bold=True)), Span(0, 13, "red")]
|
||||
|
||||
text = Text.from_ansi("Hello, \033[1m\nWorld!\033[0m")
|
||||
assert str(text) == "Hello, \nWorld!"
|
||||
assert text._spans == [Span(8, 14, Style(bold=True))]
|
||||
|
||||
|
||||
def test_copy():
|
||||
|
|
Loading…
Reference in New Issue