Exemplo n.º 1
0
def test_remove_color():
    segments = [
        Segment("foo", Style(bold=True, color="red")),
        Segment("bar", None),
    ]
    assert list(Segment.remove_color(segments)) == [
        Segment("foo", Style(bold=True)),
        Segment("bar", None),
    ]
Exemplo n.º 2
0
def render_to_string(
    text: str | Text,
    *,
    console: Console | None = None,
    strip_styles: bool = False,
) -> str:
    """Render text with rich to string including ANSI codes, etc..

    This function allows to render text with is not automatically printed with rich. For
    example, render warnings with colors or text in exceptions.

    """
    if console is None:
        console = rich.get_console()

    segments = console.render(text)

    output = []
    if console.no_color and console._color_system:
        segments = Segment.remove_color(segments)

    if strip_styles:
        segments = Segment.strip_styles(segments)

    for segment in segments:
        if segment.style:
            output.append(
                segment.style.render(
                    segment.text,
                    color_system=console._color_system,
                    legacy_windows=console.legacy_windows,
                ))
        else:
            output.append(segment.text)

    rendered = "".join(output)
    return rendered