diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b95a4790..8cb38c28e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Parse ANSI escape sequences in pretty repr https://github.com/Textualize/rich/pull/2470 - Add support for `FORCE_COLOR` env var https://github.com/Textualize/rich/pull/2449 ### Fixed diff --git a/rich/pretty.py b/rich/pretty.py index ae8b150f0..002508f7a 100644 --- a/rich/pretty.py +++ b/rich/pretty.py @@ -333,7 +333,7 @@ def __rich_console__( max_depth=self.max_depth, expand_all=self.expand_all, ) - pretty_text = Text( + pretty_text = Text.from_ansi( pretty_str, justify=self.justify or options.justify, overflow=self.overflow or options.overflow, @@ -1007,4 +1007,10 @@ class StockKeepingUnit(NamedTuple): from rich import print - print(Pretty(data, indent_guides=True, max_string=20)) + # print(Pretty(data, indent_guides=True, max_string=20)) + + class Thing: + def __repr__(self) -> str: + return "Hello\x1b[38;5;239m World!" + + print(Pretty(Thing())) diff --git a/rich/repr.py b/rich/repr.py index 8bdfdae2a..99e927322 100644 --- a/rich/repr.py +++ b/rich/repr.py @@ -1,21 +1,18 @@ -from functools import partial import inspect -import sys - +from functools import partial from typing import ( Any, Callable, Iterable, List, Optional, - overload, - Union, Tuple, Type, TypeVar, + Union, + overload, ) - T = TypeVar("T") diff --git a/tests/test_pretty.py b/tests/test_pretty.py index 353dae972..9346b3908 100644 --- a/tests/test_pretty.py +++ b/tests/test_pretty.py @@ -266,6 +266,20 @@ def test_small_width(): assert result == expected +def test_ansi_in_pretty_repr(): + class Hello: + def __repr__(self): + return "Hello \x1b[38;5;239mWorld!" + + pretty = Pretty(Hello()) + + console = Console(file=io.StringIO(), record=True) + console.print(pretty) + result = console.export_text() + + assert result == "Hello World!\n" + + @skip_py36 def test_broken_repr(): class BrokenRepr: