Skip to content

Commit

Permalink
Parse escape codes in Pretty repr (#2470)
Browse files Browse the repository at this point in the history
* Parse ANSI escape codes in pretty reprs

* Fix mypy issue

* Test parse escape codes in Pretty repr

* Add CHANGELOG entry for parsing escape codes in Pretty reprs

Co-authored-by: Will McGugan <willmcgugan@gmail.com>
  • Loading branch information
darrenburns and willmcgugan committed Aug 17, 2022
1 parent 828db35 commit 0425c79
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions rich/pretty.py
Expand Up @@ -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,
Expand Down Expand Up @@ -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()))
9 changes: 3 additions & 6 deletions 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")


Expand Down
14 changes: 14 additions & 0 deletions tests/test_pretty.py
Expand Up @@ -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:
Expand Down

0 comments on commit 0425c79

Please sign in to comment.