Combine Text and Syntax? #3363
-
I am trying to pretty print a log of bash commands and their output. I'd like to indicate what the command is run by root by putting a "# " prompt at the beginning, but I can't figure out how to do this while a) highlighting only the command portion, not the "#" prompt, and b) respecting the width of the Console. I tried separate prints, but this overflows the console width by 2 characters, because the second print doesn't realize it's not starting at the beginning of the line: c.print('#', end = ' ') ; c.print(Syntax('long ${commaaaaaand} goes here', 'bash', word_wrap=True) Output (at width=10):
Just including the # in the string itself doesn't work, because then the Syntax object thinks that the whole command is a bash comment. I had hoped you could combine Text and Syntax objects, like c.print(Text("# ") + Syntax('long ${commaaaaaand} goes here', 'bash', word_wrap=True)) But that isn't supported, nor is combining two Syntax objects. Any idea how to accomplish this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I've had a quick bash at this (pun intended). Probably not exactly what you're looking for, but might help point you in the right direction. from rich.console import Console
from rich.syntax import Syntax
from rich.text import Text
console = Console(width=10)
prefix_text = Text("# ")
syntax = Syntax("long ${commaaaaaand} goes here", "bash", word_wrap=True)
syntax_text = syntax.highlight(
syntax.code, # `Syntax.highlight` returns a `Text` instance
)
combined_text = prefix_text.append_text(syntax_text)
console.print(combined_text) |
Beta Was this translation helpful? Give feedback.
I've had a quick bash at this (pun intended). Probably not exactly what you're looking for, but might help point you in the right direction.