Created
March 15, 2023 15:45
-
-
Save harkabeeparolus/6f40d5d147ab14348e6d3b7c134b7787 to your computer and use it in GitHub Desktop.
Indent text in Rich, optionally with different indent on the first line.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Indent Rich text or renderable.""" | |
from dataclasses import dataclass | |
from typing import Optional | |
from rich.abc import RichRenderable | |
from rich.console import Console, ConsoleOptions, RenderResult | |
from rich.segment import Segment | |
@dataclass | |
class Indent: | |
"""Indent a Rich renderable, with a different indent for the first line.""" | |
renderable: RichRenderable | |
level: int | |
first_line_level: Optional[int] = None | |
def __rich_console__( | |
self, console: Console, options: ConsoleOptions | |
) -> RenderResult: | |
segments = console.render(self.renderable, options) | |
lines = Segment.split_lines(segments) | |
printing_first_line = True | |
indent = ( | |
self.first_line_level if self.first_line_level is not None else self.level | |
) | |
for line in lines: | |
yield Segment(" " * indent) | |
yield from line | |
yield Segment("\n") | |
if printing_first_line: | |
printing_first_line = False | |
indent = self.level | |
if __name__ == "__main__": | |
from rich.table import Table | |
from rich.text import Text | |
con = Console() | |
lorem = Text( | |
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod " | |
"tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, " | |
"quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo " | |
"consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse " | |
"cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non " | |
"proident, sunt in culpa qui officia deserunt mollit anim id est laborum." | |
) | |
hanging = Indent(lorem, level=10, first_line_level=0) | |
con.rule("Normal printing") | |
con.print(hanging) | |
con.line(2) | |
table = Table("Normal", "Hanging") | |
table.add_row(lorem, hanging) | |
con.print(table) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment