[go: up one dir, main page]

Skip to content

RichLog

A RichLog is a widget which displays scrollable content that may be appended to in realtime.

Call RichLog.write with a string or Rich Renderable to write content to the end of the RichLog. Call RichLog.clear to clear the content.

Tip

See also Log which is an alternative to RichLog but specialized for simple text.

  • Focusable
  • Container

Example

The example below shows an application showing a RichLog with different kinds of data logged.

RichLogApp │   │   previous_value=next(iter_values) │   exceptStopIteration: │   │   return │   first=True▅▅ │   forvalueiniter_values: │   │   yieldfirst,False,previous_value │   │   first=False │   │   previous_value=value │   yieldfirst,True,previous_value ┏━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━┓ laneswimmer             country      time  ┡━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━┩ 4   Joseph Schooling    Singapore    50.39 2   Michael Phelps      United States51.14 5   Chad le Clos        South Africa 51.14 6   László Cseh         Hungary      51.14 3   Li Zhuhao           China        51.26 8   Mehdy Metella       France       51.58 7   Tom Shields         United States51.73 1   Aleksandr SadovnikovRussia       51.84 └──────┴──────────────────────┴───────────────┴───────┘ Write text or any Rich renderable! Key(key='H'character='H'name='upper_h'is_printable=True) Key(key='i'character='i'name='i'is_printable=True)

import csv
import io

from rich.syntax import Syntax
from rich.table import Table

from textual import events
from textual.app import App, ComposeResult
from textual.widgets import RichLog

CSV = """lane,swimmer,country,time
4,Joseph Schooling,Singapore,50.39
2,Michael Phelps,United States,51.14
5,Chad le Clos,South Africa,51.14
6,László Cseh,Hungary,51.14
3,Li Zhuhao,China,51.26
8,Mehdy Metella,France,51.58
7,Tom Shields,United States,51.73
1,Aleksandr Sadovnikov,Russia,51.84"""


CODE = '''\
def loop_first_last(values: Iterable[T]) -> Iterable[tuple[bool, bool, T]]:
    """Iterate and generate a tuple with a flag for first and last value."""
    iter_values = iter(values)
    try:
        previous_value = next(iter_values)
    except StopIteration:
        return
    first = True
    for value in iter_values:
        yield first, False, previous_value
        first = False
        previous_value = value
    yield first, True, previous_value\
'''


class RichLogApp(App):
    def compose(self) -> ComposeResult:
        yield RichLog(highlight=True, markup=True)

    def on_ready(self) -> None:
        """Called  when the DOM is ready."""
        text_log = self.query_one(RichLog)

        text_log.write(Syntax(CODE, "python", indent_guides=True))

        rows = iter(csv.reader(io.StringIO(CSV)))
        table = Table(*next(rows))
        for row in rows:
            table.add_row(*row)

        text_log.write(table)
        text_log.write("[bold magenta]Write text or any Rich renderable!")

    def on_key(self, event: events.Key) -> None:
        """Write Key events to log."""
        text_log = self.query_one(RichLog)
        text_log.write(event)


if __name__ == "__main__":
    app = RichLogApp()
    app.run()

Reactive Attributes

Name Type Default Description
highlight bool False Automatically highlight content.
markup bool False Apply Rich console markup.
max_lines int None Maximum number of lines in the log or None for no maximum.
min_width int 78 Minimum width of renderables.
wrap bool False Enable word wrapping.

Messages

This widget sends no messages.

Bindings

This widget has no bindings.

Component Classes

This widget has no component classes.


Bases: ScrollView

A widget for logging Rich renderables and text.

Parameters:

Name Type Description Default

max_lines

int | None

Maximum number of lines in the log or None for no maximum.

None

min_width

int

Width to use for calls to write with no specified width.

78

wrap

bool

Enable word wrapping (default is off).

False

highlight

bool

Automatically highlight content. By default, the ReprHighlighter is used. To customize highlighting, set highlight=True and then set the highlighter attribute to an instance of Highlighter.

False

markup

bool

Apply Rich console markup.

False

auto_scroll

bool

Enable automatic scrolling to end.

True

name

str | None

The name of the text log.

None

id

str | None

The ID of the text log in the DOM.

None

classes

str | None

The CSS classes of the text log.

None

disabled

bool

Whether the text log is disabled or not.

False

auto_scroll class-attribute instance-attribute

auto_scroll = auto_scroll

Automatically scroll to the end on write.

highlight class-attribute instance-attribute

highlight = highlight

Automatically highlight content.

highlighter instance-attribute

highlighter = ReprHighlighter()

Rich Highlighter used to highlight content when highlight is True

lines instance-attribute

lines = []

The lines currently visible in the log.

markup class-attribute instance-attribute

markup = markup

Apply Rich console markup.

max_lines class-attribute instance-attribute

max_lines = max_lines

Maximum number of lines in the log or None for no maximum.

min_width class-attribute instance-attribute

min_width = min_width

Minimum width of renderables.

wrap class-attribute instance-attribute

wrap = wrap

Enable word wrapping.

clear

clear()

Clear the text log.

Returns:

Type Description
Self

The RichLog instance.

write

write(
    content,
    width=None,
    expand=False,
    shrink=True,
    scroll_end=None,
    animate=False,
)

Write a string or a Rich renderable to the bottom of the log.

Notes

The rendering of content will be deferred until the size of the RichLog is known. This means if you call write in compose or on_mount, the content will not be rendered immediately.

Parameters:

Name Type Description Default

content

RenderableType | object

Rich renderable (or a string).

required

width

int | None

Width to render, or None to use RichLog.min_width. If specified, expand and shrink will be ignored.

None

expand

bool

Permit expanding of content to the width of the content region of the RichLog. If width is specified, then expand will be ignored.

False

shrink

bool

Permit shrinking of content to fit within the content region of the RichLog. If width is specified, then shrink will be ignored.

True

scroll_end

bool | None

Enable automatic scroll to end, or None to use self.auto_scroll.

None

animate

bool

Enable animation if the log will scroll.

False

Returns:

Type Description
Self

The RichLog instance.