Indenting text-block with python Rich library

178 views Asked by At

I'm trying to print a formatted block of markdown text to the terminal using rich.console.print(Markdown(text)) from the Rich library. However, I would like to have this block of text be indented with a tab. Normally I'd use the textwrap module for that, but when using it, rich.Markdown() will interpret it as a code-block, and thus not applying any formatting to the markdown besides giving it a different background.

Example of using textwrap: textwrap

Example of not using textwrap: no textwrap

My Python code:

    pretty_console.console.print("[u bright_blue]All series:[/]")
    for e in display_data:
        pretty_console.console.print(
            f"{e['id'].ljust(max_series_id_length)}: "
            f"[bold]{e['name'].ljust(max_series_name_length)}[/]\n"
        )
        if e['description']:
            text = e['description']
            markdown_text = Markdown(text)
            pretty_console.console.print(markdown_text)

Excuse the Dutch in the pictures, but the language won't really matter in this case.

Does anyone know how to print Rich formatted text with an indent that works too when (soft-) wrapping?

1

There are 1 answers

0
goulashsoup On BEST ANSWER

You can use Padding to indent output:

from rich.console import Console
from rich.padding import Padding

console = Console()
console.print(Padding("my text", pad=(0, 0, 0, 4))) # Indent by 4 spaces.