Convert a Rich Text object to a string. This function's purpose is to render a Rich Text object, including any styles (e.g., color, bold), to a plain Python string with ANSI style sequences. It differs from `text.plain`, which strips all formatting. :param text: the text object to
(text: Text)
| 643 | |
| 644 | |
| 645 | def rich_text_to_string(text: Text) -> str: |
| 646 | """Convert a Rich Text object to a string. |
| 647 | |
| 648 | This function's purpose is to render a Rich Text object, including any styles (e.g., color, bold), |
| 649 | to a plain Python string with ANSI style sequences. It differs from `text.plain`, which strips |
| 650 | all formatting. |
| 651 | |
| 652 | :param text: the text object to convert |
| 653 | :return: the resulting string with ANSI styles preserved. |
| 654 | :raises TypeError: if text is not a rich.text.Text object |
| 655 | """ |
| 656 | # Strictly enforce Text type. While console.print() can render any object, |
| 657 | # this function is specifically tailored to convert Text instances to strings. |
| 658 | if not isinstance(text, Text): |
| 659 | raise TypeError(f"rich_text_to_string() expected a rich.text.Text object, but got {type(text).__name__}") |
| 660 | |
| 661 | console = Console( |
| 662 | force_terminal=True, |
| 663 | color_system="truecolor", |
| 664 | soft_wrap=True, |
| 665 | no_color=False, |
| 666 | theme=get_theme(), |
| 667 | ) |
| 668 | with console.capture() as capture: |
| 669 | console.print(text, end="") |
| 670 | return capture.get() |
| 671 | |
| 672 | |
| 673 | def indent(renderable: RenderableType, level: int) -> Padding: |