Skip to content

output

langroid/utils/output/init.py

PrintColored(color)

Context to temporarily print in a desired color

Source code in langroid/utils/output/printing.py
def __init__(self, color: str):
    self.color = color

print_long_text(color, style, preamble, text, chars=None)

Print text (possibly truncated) after preamble, in the given color/style.

text is printed literally: neither Rich markup nor terminal escape sequences in it are interpreted.

Source code in langroid/utils/output/printing.py
def print_long_text(
    color: str, style: str, preamble: str, text: str, chars: Optional[int] = None
) -> None:
    """Print `text` (possibly truncated) after `preamble`, in the given color/style.

    `text` is printed literally: neither Rich markup nor terminal escape
    sequences in it are interpreted.
    """
    # Strip first, so that `chars` counts printable characters and a truncation
    # boundary cannot fall inside an escape sequence.
    text = text.translate(_STRIP_CONTROL_CHARS)
    if chars is not None:
        text = " ".join(text.split())
        text = text[:chars] + "..." + text[-chars:] if len(text) > 2 * chars else text
    # `text` can be ingested document content or LLM output, so it must not
    # reach Rich's markup parser. Pass it as a `Text` renderable rather than
    # interpolating it into the markup string: `Text.__str__()` is the plain
    # underlying text, so an f-string would hand any `[...]` sequences in it --
    # including terminal-hyperlink tags -- straight to that parser. Escaping
    # the string instead is not enough, because `Text` strips some control
    # characters afterwards, which can re-form a tag the escaping had
    # neutralized. Only `preamble`, `color` and `style`, which callers supply,
    # are treated as markup.
    #
    # Note that printing it as a renderable is also what makes the control-char
    # stripping above load-bearing: a raw escape sequence interpolated into the
    # markup string used to be broken up by Rich's highlighter, which hid this
    # route by accident rather than by design.
    styled_text = Text(text, style=color)
    if style:
        # Layered as a separate span rather than concatenated into one style
        # string, so that `color` and `style` are each resolved on their own
        # (a theme style name such as "repr.number" does not resolve as one
        # word of a longer style string).
        styled_text.stylize(style)
    rprint(f"[{color}]{preamble}", styled_text)