pretty-print a line at a time in a table? #965
-
Hi all, I'm the author of Scalene (https://github.com/emeryberger/scalene), which uses Rich (thanks for creating it!). A user pointed out that Scalene currently does pretty-printing a line at a time, which is not quite right, since it doesn't render comments correctly, and I have not yet been able to come up with a solution (issue here: https://github.com/emeryberger/scalene/issues/115). In short, I've been trying to use Pointers would be greatly appreciated - thanks in advance! Current (note the incorrect rendering of the docstring at line 20): |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi Emery, I think you were one of the earliest adopters of Rich. I didn't consider this use-case so this may not be pretty. But the 'trick' is to render a single Syntax object in to lines. Rendering generates a list of Segments which can then be used to create a new renderable. The following seems to work: from rich import print
from rich.console import Console
from rich.syntax import Syntax
from rich.table import Table
code = '''
class SyntaxTheme(ABC):
"""Base class for a syntax theme."""
@abstractmethod
def get_style_for_token(self, token_type: TokenType) -> Style:
"""Get a style for a given Pygments token."""
raise NotImplementedError # pragma: no cover
@abstractmethod
def get_background_style(self) -> Style:
"""Get the background color."""
raise NotImplementedError # pragma: no cover
'''
console = Console()
syntax = Syntax(code, "python", theme="default")
class SyntaxLine:
def __init__(self, segments):
self.segments = segments
def __rich_console__(self, console, options):
yield from self.segments
lines = [SyntaxLine(segments) for segments in console.render_lines(syntax)]
table = Table("Line No", "Foo", "Line")
for line_no, line in enumerate(lines, 1):
table.add_row(str(line_no), "f" * line_no, line)
print(table) btw you might want to pin Rich to a more recent version. There have been a lot of updates! |
Beta Was this translation helpful? Give feedback.
Hi Emery,
I think you were one of the earliest adopters of Rich.
I didn't consider this use-case so this may not be pretty. But the 'trick' is to render a single Syntax object in to lines. Rendering generates a list of Segments which can then be used to create a new renderable.
The following seems to work: