Horiztonal text contatenation and proper way to render to ANSI. #3076
-
I'm currently writing a PR for line-profiler to integrate rich as an optional dependency to make the output prettier. So far it is looking good: To this end, I have a MWE that illustrates my questions. I want to be able to:
I've been able to do this using the following approach:
To illustrate this I have an example where the RHS is a small block of code, and the LHS are line numbers. #https://github.com/pyutils/line_profiler/pull/225
import sys
from rich.syntax import Syntax
from rich.text import Text
from rich.columns import Columns
from rich.console import Console
from rich.highlighter import ReprHighlighter
import textwrap
import io
# The interface must write to a stream (e.g. sys.stdout)
stream = sys.stdout
# Example code for the right-hand-side
rhs_text = textwrap.dedent(
'''
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
fib(1000)
''').strip()
# Line numbers for the left-hand-side text
nlines = rhs_text.count('\n') + 1
lhs_text = '\n'.join(str(i).rjust(4) + ' | ' for i in range(1, nlines + 1)) My current code for processing these into the final output is: # Highlight and format the text
rhs = Syntax(rhs_text, 'python', background_color='default')
lhs = Text(lhs_text)
ReprHighlighter().highlight(lhs)
renderable = Columns([lhs, '', rhs])
tmp = io.StringIO()
write_console = Console(file=tmp, soft_wrap=True, color_system='standard')
write_console.print(renderable)
block = tmp.getvalue()
stream.write(block)
stream.write('\n') This works when the terminal is sufficiently wide. I get a nice render: However, if I make my terminal too small, the columns split the LHS and RHS onto separte lines: Question 1: Is there a way to more directly horizontally concatenate highlighted text objects such that the final output strongly ties the LHS line to the RHS line? Question 2: The way I'm extracting the ANSI representation of the highlighted text seems roundabout. Is this the standard way to do this, or is there a better way? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi Jon. The Have a look at Capturing output for an API to capture ansi text. |
Beta Was this translation helpful? Give feedback.
-
Perfect! Works like a charm. Modified second block: from rich.table import Table
# Highlight and format the text
rhs = Syntax(rhs_text, 'python', background_color='default')
lhs = Text(lhs_text)
ReprHighlighter().highlight(lhs)
table = Table.grid()
table.add_row(lhs, ' ', rhs)
write_console = Console(file=stream, soft_wrap=True, color_system='standard')
write_console.print(table)
stream.write('\n') Result: |
Beta Was this translation helpful? Give feedback.
Hi Jon.
The
Columns
widget is designed to work this way. If you don't want the wrapping behaviour you could useTable.grid()
which creates a borderless table.Have a look at Capturing output for an API to capture ansi text.