Sign in

    rich

    A port of Rich (rich text and beautiful formatting in the terminal) to MoonBit

    terminal
    rich
    ansi
    tui
    console
    Download zip
    Author
    Version
    0.1.0
    License
    MIT
    Last updated
    23 days ago
    Downloads
    26

    #rich.mbt

    A port of Rich 15.0 — rich text and beautiful formatting in the terminal — to MoonBit.

    Rendering is byte-for-byte compatible with Python Rich: the upstream test suite is ported test by test, and extra cases are compared against the Python implementation.

    #Usage

    ///|
    test "print markup and a table" {
    let file = @rich.StringIO::new()
    let console = @rich.Console::new(file~, width=30, color_system=None)
    console.print("Hello, [bold magenta]World[/]!")
    let table = @rich.Table::new(headers=["Name", "Value"])
    table.add_row(["foo", "1"])
    table.add_row(["bar", "2"])
    console.print(table)
    inspect(
    file.getvalue(),
    content=(
    #|Hello, World!
    #|┏━━━━━━┳━━━━━━━┓
    #|┃ Name ┃ Value ┃
    #|┡━━━━━━╇━━━━━━━┩
    #|│ foo │ 1 │
    #|│ bar │ 2 │
    #|└──────┴───────┘
    #|
    ),
    )
    }

    @rich.print writes to standard output with the global console:

    ///|
    fn main {
    @rich.print("[bold red]alert![/] Something happened") catch {
    _ => ()
    }
    }

    More renderables live in their own packages, as in upstream (rich.panel.Panel → @panel.Panel):

    ///|
    fn main raise {
    let console = @rich.Console::new()
    console.print(@panel.Panel::new("Hello, [red]World!", title="Greeting"))
    let tree = @tree.Tree::new("Rich Tree")
    tree.add("foo").add("bar") |> ignore
    console.print(tree)
    console.print(
    @syntax.Syntax::new(
    "def f(x):\n return x + 1",
    "python",
    line_numbers=true,
    ),
    )
    console.print(@markdown.Markdown::new("# Title\n\n* one\n* **two**"))
    let data : Json = { "numbers": [1, 2, 3], "ok": true }
    console.print(@pretty.Pretty::new(data))
    let progress = @progress.Progress::new()
    progress.start()
    let task = progress.add_task("Working...", total=Some(10.0))
    for _ in 0..<10 {
    progress.advance(task) // refreshes when the refresh interval has passed
    }
    progress.stop()
    }

    In async code (native), @aio refreshes from a timer like upstream's refresh thread, so spinners and elapsed times keep moving while the body awaits:

    ///|
    async fn main {
    let progress = @progress.Progress::new()
    @aio.run_progress(progress, () => {
    let task = progress.add_task("Downloading", total=Some(3.0))
    for _ in 0..<3 {
    @async.sleep(500) // network IO, subprocesses, ...
    progress.advance(task)
    }
    })
    }

    Run the feature demo (python -m rich):

    moon run cmd/demo

    #The rich command

    cmd/rich is a port of Textualize's rich-cli: it renders files and text in the terminal (Markdown, syntax highlighting, JSON, CSV/TSV tables, Jupyter notebooks, console markup, rules, panels, alignment, padding, HTML/SVG export). It runs on native and wasm, e.g. with moonx from mooncakes:

    moonx bobzhang/rich/cmd/rich README.md # Markdown moonx bobzhang/rich/cmd/rich main.py -n -g # line numbers, indent guides moonx bobzhang/rich/cmd/rich data.csv --head 10 # CSV as a table moonx bobzhang/rich/cmd/rich "Hello [b]World[/b]!" -p -a rounded -c moonx bobzhang/rich/cmd/rich "Section" --rule --rule-style red cat data.json | moonx bobzhang/rich/cmd/rich - --json --force-terminal moonx bobzhang/rich/cmd/rich --help

    or from a checkout, moon run cmd/rich -- README.md. Options and output follow rich-cli 1.8 (see rich --help); fetching URLs, --inspect and reStructuredText rendering are not supported, and --pager uses $PAGER (see DEVIATIONS.md). The rendering is a pure function in bobzhang/rich/cli (@cli.run(args, files=..., stdin=...)).

    #Packages

    PackageUpstream module(s)
    bobzhang/richconsole, text, style, segment, markup, table, rule, padding, align, constrain, styled, box, measure, containers, control, json, ansi, highlighter, theme, emoji, filesize, _log_render, _ratio, _wrap, export (text/HTML/SVG)
    bobzhang/rich/cellscells, _unicode_data (all Unicode versions)
    bobzhang/rich/colorcolor, color_triplet, palette, terminal_theme
    bobzhang/rich/emoji_emoji_codes, _emoji_replace
    bobzhang/rich/panelpanel
    bobzhang/rich/columnscolumns
    bobzhang/rich/treetree
    bobzhang/rich/barbar
    bobzhang/rich/layoutlayout
    bobzhang/rich/spinnerspinner, _spinners
    bobzhang/rich/progress_barprogress_bar
    bobzhang/rich/livelive, live_render
    bobzhang/rich/statusstatus
    bobzhang/rich/progressprogress
    bobzhang/rich/aiothe refresh thread: timer-driven Live/Progress/Status on moonbitlang/async (native)
    bobzhang/rich/prettypretty, repr
    bobzhang/rich/scopescope
    bobzhang/rich/syntaxsyntax (via pygments.mbt)
    bobzhang/rich/tracebacktraceback (renders caller-built traces)
    bobzhang/rich/markdownmarkdown (via moonbit-community/cmark)
    bobzhang/rich/promptprompt
    bobzhang/rich/logginglogging (RichHandler over a LogRecord)
    bobzhang/rich/demo, cmd/demo__main__ (the feature card)
    bobzhang/rich/cli, cmd/richrich-cli (the rich command)

    #Compatibility

    • The upstream test suite is ported test by test; around 1,500 tests run on native, js and wasm-gc, including thousands of differential cases generated with Python Rich (scripts/*_oracle.py), the full feature card at width 100, all 652 CommonMark spec examples for Markdown and 36 languages × 13 themes for Syntax.
    • MoonBit has no threads and no runtime introspection: Live/Progress refresh on updates (or tick()), or from a timer with @aio in async code; pretty works through the PrettyRepr trait; tracebacks are rendered from data you provide; inspect and Jupyter support are not ported.

    See DESIGN.md for the architecture and DEVIATIONS.md for every difference from upstream.

    #Performance

    cmd/bench renders nine workloads to an in-memory console (truecolor, width 100); scripts/bench.py does the same with upstream Rich. Both print ms per iteration (best of three rounds after a warm-up), and --dump prints the rendered output instead: all nine are byte-identical to upstream's (link ids aside).

    moon run --target native --release cmd/bench # or: -- table syntax moon build --target wasm-gc --release cmd/bench moonrun _build/wasm-gc/release/build/cmd/bench/bench.wasm .venv/bin/python scripts/bench.py

    ms per iteration on an Apple M2 Ultra (Python 3.14, Rich 15.0; wasm runs with moonrun):

    WorkloadPythonnativewasm-gcwasm
    feature card (python -m rich)10.80.930.972.48
    table, 1,000 rows × 6 columns with markup36120.220.159.3
    200 KB text, styled spans, justify="full"23519.822.051.0
    2,000 lines of markup (repr highlighting)54082.9118209
    Pretty of a 300-item document11613.618.936.7
    Syntax, 2,000 lines of Python, line numbers11210.515.229.4
    Markdown of Rich's README23.22.532.666.71
    Progress with 100 tasks13.41.090.903.03
    JSON of a 300-item document91.89.4411.024.2

    Much of the remaining time in the markup, Pretty and JSON workloads is regular-expression matching for highlighting (the same patterns upstream runs), and in Syntax the Pygments lexer.

    #License

    MIT, like upstream Rich (Copyright (c) 2020 Will McGugan).

    ConsoleFile

    pub(open) trait ConsoleFile {
    fn write(Self, String) -> Unit raise
    fn flush(Self) -> Unit raise = _
    fn isatty(Self) -> Bool = _
    fn encoding(Self) -> String = _
    }

    A file-like object the console writes to (upstream IO[str]).

    Highlighter

    pub(open) trait Highlighter {
    fn highlight(Self, Text) -> Unit raise
    }

    A highlighter applies styles to text in place.

    IntoColumn

    pub(open) trait IntoColumn {
    fn into_column(Self) -> Column
    fn into_table_column(Self, highlight~ : Bool) -> Column = _
    }

    Things accepted as table headers: strings and columns.

    IntoStyle

    pub(open) trait IntoStyle {
    fn into_style_type(Self) -> StyleType
    }

    Types accepted where upstream takes Union[str, Style].
    impl IntoStyle for String

    IntoText

    pub(open) trait IntoText {
    fn into_text_type(Self) -> TextType
    }

    Types accepted where upstream takes Union[str, Text].
    impl IntoText for String

    Pager

    pub(open) trait Pager {
    fn show(Self, String) -> Unit raise
    }

    Base trait for a pager.

    RenderHook

    pub(open) trait RenderHook {
    fn process_renderables(Self, Array[&Renderable]) -> Array[&Renderable] raise
    }

    Hook that may process renderables before they are rendered.

    Renderable

    pub(open) trait Renderable {
    fn rich_console(Self, Console, ConsoleOptions) -> Array[RenderItem] raise
    fn rich_measure(Self, Console, ConsoleOptions) -> Measurement? raise = _
    fn text_kind(Self) -> TextKind = _
    fn vertical_align(Self) -> VerticalAlignMethod? = _
    }

    Something that may be rendered by a Console: upstream's __rich_console__ (required) and __rich_measure__ (optional).

    String and Text implement it; any other type can implement rich_console, returning segments and/or nested renderables.
    impl Renderable for Color

    TextPart

    pub(open) trait TextPart {
    fn append_to(Self, Text) -> Unit
    }

    A part for Text::assemble: a string, a Text, or a (string, style) tuple.
    impl TextPart for String
    impl TextPart for Tuple2[String, S]

    RichError

    pub(all) suberror RichError {
    StyleSyntaxError(String)
    MissingStyle(String)
    StyleStackError(String)
    NotRenderableError(String)
    MarkupError(String)
    LiveError(String)
    NoAltScreen(String)
    WriteError(String)
    NoEmoji(String)
    ValueError(String)
    } derive(
    Debug
    )

    Errors raised by Rich. Constructors mirror the upstream exception classes.
    impl Show for RichError

    Align

    pub struct Align {
    renderable : &Renderable
    align : AlignMethod
    style : StyleType?
    vertical : VerticalAlignMethod?
    pad : Bool
    width : Int?
    height : Int?
    }

    Align a renderable by adding spaces if necessary.
    impl Renderable for Align

    Align::center

    fn Align::center(renderable : &Renderable, style? : &IntoStyle, vertical? : VerticalAlignMethod, pad? : Bool, width? : Int, height? : Int) -> Align

    Align a renderable to the center.

    Align::left

    fn Align::left(renderable : &Renderable, style? : &IntoStyle, vertical? : VerticalAlignMethod, pad? : Bool, width? : Int, height? : Int) -> Align

    Align a renderable to the left.

    Align::new

    fn Align::new(renderable : &Renderable, align : AlignMethod, style? : &IntoStyle, vertical? : VerticalAlignMethod, pad? : Bool, width? : Int, height? : Int) -> Align

    Align::right

    fn Align::right(renderable : &Renderable, style? : &IntoStyle, vertical? : VerticalAlignMethod, pad? : Bool, width? : Int, height? : Int) -> Align

    Align a renderable to the right.

    AlignMethod

    pub(all) enum AlignMethod {
    Left
    Center
    Right
    } derive(Eq, Hash,
    Debug
    )

    Horizontal alignment.

    AlignMethod::to_string

    fn AlignMethod::to_string(self : AlignMethod) -> String

    AnsiDecoder

    pub struct AnsiDecoder {
    // private fields
    }

    Translate ANSI codes in to styled Text.

    AnsiDecoder::decode

    fn AnsiDecoder::decode(self : AnsiDecoder, terminal_text : String) -> Array[Text]

    Decode ANSI codes in terminal output, one Text per line.

    AnsiDecoder::decode_line

    fn AnsiDecoder::decode_line(self : AnsiDecoder, line : String) -> Text

    Decode a line containing ANSI codes.

    AnsiDecoder::new

    Box

    pub struct Box {
    name : String
    box_ : String
    ascii : Bool
    top_left : String
    top : String
    top_divider : String
    top_right : String
    head_left : String
    head_vertical : String
    head_right : String
    head_row_left : String
    head_row_horizontal : String
    head_row_cross : String
    head_row_right : String
    mid_left : String
    mid_vertical : String
    mid_right : String
    row_left : String
    row_horizontal : String
    row_cross : String
    row_right : String
    foot_row_left : String
    foot_row_horizontal : String
    foot_row_cross : String
    foot_row_right : String
    foot_left : String
    foot_vertical : String
    foot_right : String
    bottom_left : String
    bottom : String
    bottom_divider : String
    bottom_right : String
    } derive(Eq,
    Debug
    )

    Defines characters to render boxes.

    ┌─┬┐ top │ ││ head ├─┼┤ head_row │ ││ mid ├─┼┤ row ├─┼┤ foot_row │ ││ foot └─┴┘ bottom
    impl Show for Box

    Box::get_bottom

    fn Box::get_bottom(self : Box, widths : ArrayView[Int]) -> String

    Get the bottom of a simple box.

    Box::get_plain_headed_box

    fn Box::get_plain_headed_box(self : Box) -> Box

    If this box uses special characters for the borders of the header, return the equivalent box that does not.

    Box::get_row

    fn Box::get_row(self : Box, widths : ArrayView[Int], level? : RowLevel, edge? : Bool) -> String

    Get the top of a simple box.

    Box::get_top

    fn Box::get_top(self : Box, widths : ArrayView[Int]) -> String

    Get the top of a simple box.

    Box::new

    fn Box::new(box_ : String, ascii? : Bool, name? : String) -> Box raise RichError

    Create a box from 8 lines of 4 characters.

    Box::repr

    fn Box::repr(_self : Box) -> String

    Upstream repr(box).

    Box::substitute

    fn Box::substitute(self : Box, options : ConsoleOptions, safe? : Bool) -> Box

    Substitute this box for another if it won't render due to platform issues.

    Column

    pub(all) struct Column {
    header : &Renderable
    footer : &Renderable
    header_style : StyleType
    footer_style : StyleType
    style : StyleType
    justify : JustifyMethod
    vertical : VerticalAlignMethod
    overflow : OverflowMethod
    width : Int?
    min_width : Int?
    max_width : Int?
    ratio : Int?
    no_wrap : Bool
    highlight : Bool
    // private fields
    }

    Defines a column within a Table.

    Column::cells

    fn Column::cells(self : Column) -> Array[&Renderable]

    The cells in the column.

    Column::copy

    fn Column::copy(self : Column) -> Column

    A copy of the column without its cells.

    Column::flexible

    fn Column::flexible(self : Column) -> Bool

    Check if this column is flexible.

    Column::new

    fn Column::new(header? : &Renderable, footer? : &Renderable, header_style? : &IntoStyle, footer_style? : &IntoStyle, style? : &IntoStyle, justify? : JustifyMethod, vertical? : VerticalAlignMethod, overflow? : OverflowMethod, width? : Int, min_width? : Int, max_width? : Int, ratio? : Int, no_wrap? : Bool, highlight? : Bool) -> Column

    Console

    pub(all) struct Console {
    stderr : Bool
    quiet : Bool
    tab_size : Int
    record : Bool
    soft_wrap : Bool
    legacy_windows : Bool
    safe_box : Bool
    no_color : Bool
    is_interactive : Bool
    is_jupyter : Bool
    style : StyleType?
    highlighter : &Highlighter
    get_datetime : () -> Double
    get_time : () -> Double
    // private fields
    }

    A high level console interface.

    Console::begin_capture

    fn Console::begin_capture(self : Console) -> Unit

    Begin capturing console output. Call end_capture to exit capture mode and return output.

    Console::bell

    fn Console::bell(self : Console) -> Unit raise

    Play a 'bell' sound (if supported by the terminal).

    Console::buffered

    fn Console::buffered(self : Console, f : () -> Unit raise) -> Unit raise

    Run f with output buffered (upstream with console:).

    Console::capture

    fn Console::capture(self : Console, f : () -> Unit raise) -> String raise

    Capture the output of f instead of writing it to the console.

    Console::clear

    fn Console::clear(self : Console, home? : Bool) -> Unit raise

    Clear the screen.

    Console::clear_live

    fn Console::clear_live(self : Console) -> Unit

    Remove the top-most live display.

    Console::color_system

    fn Console::color_system(self : Console) -> String?

    The color system name: "standard", "256", "truecolor", "windows", or None.

    Console::color_system_enum

    The detected or configured color system.

    Console::control

    fn Console::control(self : Console, controls : ArrayView[Control]) -> Unit raise

    Insert non-printing control codes.

    Console::encoding

    fn Console::encoding(self : Console) -> String

    The encoding of the console file, e.g. "utf-8".

    Console::end_capture

    fn Console::end_capture(self : Console) -> String raise

    End capture mode and return captured string.

    Console::enter_buffer

    fn Console::enter_buffer(self : Console) -> Unit

    Enter a buffer context: all output is buffered until the matching exit_buffer.

    Console::exit_buffer

    fn Console::exit_buffer(self : Console) -> Unit raise

    Leave a buffer context, and render content if required.

    Console::export_html

    fn Console::export_html(self : Console, theme? :
    TerminalTheme
    , clear? : Bool, code_format? : String, inline_styles? : Bool) -> String

    Generate HTML from console contents (requires record=true).

    Console::export_svg

    fn Console::export_svg(self : Console, title? : String, theme? :
    TerminalTheme
    , clear? : Bool, code_format? : String, font_aspect_ratio? : Double, unique_id? : String) -> String

    Generate an SVG from the console contents (requires record=true).

    Console::export_text

    fn Console::export_text(self : Console, clear? : Bool, styles? : Bool) -> String

    Generate text from console contents (requires record=true).

    Console::file

    fn Console::file(self : Console) -> &ConsoleFile

    The file the console writes to.

    Console::get_style

    fn Console::get_style(self : Console, name : &IntoStyle, default? : StyleType) -> Style raise RichError

    Get a Style instance by its theme name or parse a definition.

    Console::height

    fn Console::height(self : Console) -> Int

    The height of the console.

    Console::input

    fn Console::input(self : Console, prompt? : &IntoText, markup? : Bool, emoji? : Bool, password? : Bool, stream? : () -> String raise) -> String raise

    Display a prompt and wait for input from the user.

    stream replaces stdin: it is called once and returns the next line like Python's stream.readline() (with its newline, "" at end of input); as upstream, the result is then returned as is.

    Console::is_alt_screen

    fn Console::is_alt_screen(self : Console) -> Bool

    Check if the alt screen was enabled.

    Console::is_dumb_terminal

    fn Console::is_dumb_terminal(self : Console) -> Bool

    Detect dumb terminal.

    Console::is_terminal

    fn Console::is_terminal(self : Console) -> Bool

    Check if the console is writing to a terminal.

    Console::line

    fn Console::line(self : Console, count? : Int) -> Unit raise

    Write new line(s).

    Console::live_stack

    fn Console::live_stack(self : Console) -> Array[Int]

    The ids of the active live displays (innermost last).

    Console::log

    #callsite(autofill(loc))
    fn Console::log(self : Console, object : &Renderable, sep? : String, end? : String, style? : &IntoStyle, justify? : JustifyMethod, emoji? : Bool, markup? : Bool, highlight? : Bool, loc~ : SourceLoc) -> Unit raise

    Log rich content to the terminal, with the time and the caller location.

    Console::log_many

    #callsite(autofill(loc))
    fn Console::log_many(self : Console, objects : ArrayView[&Renderable], sep? : String, end? : String, style? : &IntoStyle, justify? : JustifyMethod, emoji? : Bool, markup? : Bool, highlight? : Bool, loc~ : SourceLoc) -> Unit raise

    Log several objects (see log).

    Console::measure

    fn Console::measure(self : Console, renderable : &Renderable, options? : ConsoleOptions) -> Measurement raise

    Measure a renderable.

    Console::new

    fn Console::new(color_system? : String?, force_terminal? : Bool, force_jupyter? : Bool, force_interactive? : Bool, soft_wrap? : Bool, theme? : Theme, stderr? : Bool, file? : &ConsoleFile, quiet? : Bool, width? : Int, height? : Int, style? : &IntoStyle, no_color? : Bool, tab_size? : Int, record? : Bool, markup? : Bool, emoji? : Bool, emoji_variant? : EmojiVariant, highlight? : Bool, log_time? : Bool, log_path? : Bool, log_time_format? : String, log_time_formatter? : (Double) -> Text, highlighter? : &Highlighter, legacy_windows? : Bool, safe_box? : Bool, get_datetime? : () -> Double, get_time? : () -> Double, environ? : Map[String, String]) -> Console raise RichError

    Create a console.

    color_system is Some("auto") (detect), Some("standard"), Some("256"), Some("truecolor"), Some("windows"), or None for no color. environ replaces the process environment (for testing). log_time_formatter (upstream: a callable log_time_format) formats the time of log instead of log_time_format.

    Console::options

    fn Console::options(self : Console) -> ConsoleOptions

    Default console options.

    Console::out

    fn Console::out(self : Console, text : String, end? : String, style? : &IntoStyle, highlight? : Bool) -> Unit raise

    Low-level output: no pretty printing, wrapping or markup, but optional highlighting and a basic style.

    Console::out_many

    fn Console::out_many(self : Console, objects : ArrayView[String], sep? : String, end? : String, style? : &IntoStyle, highlight? : Bool) -> Unit raise

    Low-level output of several strings joined with sep (upstream out(*objects, sep=...)).

    Console::pager

    fn Console::pager(self : Console, f : () -> Unit raise, pager? : &Pager, styles? : Bool, links? : Bool) -> Unit raise

    Run f, then send everything it printed to a pager.

    Console::pop_render_hook

    fn Console::pop_render_hook(self : Console) -> Unit

    Pop the last render hook from the stack.

    Console::pop_theme

    fn Console::pop_theme(self : Console) -> Unit raise RichError

    Remove theme from top of stack, restoring previous theme.

    Console::print

    fn Console::print(self : Console, object : &Renderable, sep? : String, end? : String, style? : &IntoStyle, justify? : JustifyMethod, overflow? : OverflowMethod, no_wrap? : Bool, emoji? : Bool, markup? : Bool, highlight? : Bool, width? : Int, height? : Int, crop? : Bool, soft_wrap? : Bool, new_line_start? : Bool) -> Unit raise

    Print to the console.

    Console::print_json

    fn Console::print_json(self : Console, json? : String, data? : Json, indent? : Int?, indent_str? : String, highlight? : Bool, ensure_ascii? : Bool, sort_keys? : Bool) -> Unit raise

    Pretty print JSON. json is a JSON string; otherwise data is encoded.

    Console::print_many

    fn Console::print_many(self : Console, objects : ArrayView[&Renderable], sep? : String, end? : String, style? : &IntoStyle, justify? : JustifyMethod, overflow? : OverflowMethod, no_wrap? : Bool, emoji? : Bool, markup? : Bool, highlight? : Bool, width? : Int, height? : Int, crop? : Bool, soft_wrap? : Bool, new_line_start? : Bool) -> Unit raise

    Print several objects to the console. Adjacent strings and Texts are joined with sep; other renderables are printed on their own.

    Console::push_render_hook

    fn Console::push_render_hook(self : Console, hook : &RenderHook) -> Unit

    Add a new render hook to the stack.

    Console::push_theme

    fn Console::push_theme(self : Console, theme : Theme, inherit_styles? : Bool) -> Unit

    Push a new theme on to the top of the stack.

    Console::render

    fn Console::render(self : Console, renderable : &Renderable, options? : ConsoleOptions) -> Array[Segment] raise

    Render an object in to segments.

    Console::render_lines

    fn Console::render_lines(self : Console, renderable : &Renderable, options? : ConsoleOptions, style? : Style, pad? : Bool, new_lines? : Bool) -> Array[Array[Segment]] raise

    Render objects in to a list of lines.

    Console::render_str

    fn Console::render_str(self : Console, text : String, style? : &IntoStyle, justify? : JustifyMethod, overflow? : OverflowMethod, emoji? : Bool?, markup? : Bool?, highlight? : Bool?, highlighter? : &Highlighter) -> Text raise

    Convert a string to a Text instance (markup, emoji and highlighting follow the console defaults unless overridden).

    Console::repr

    fn Console::repr(self : Console) -> String

    Upstream repr(console).

    Console::rule

    fn Console::rule(self : Console, title? : &IntoText, characters? : String, style? : &IntoStyle, align? : AlignMethod) -> Unit raise

    Draw a line with an optional centered title.

    Console::save_html

    fn Console::save_html(self : Console, path : String, theme? :
    TerminalTheme
    , clear? : Bool, code_format? : String, inline_styles? : Bool) -> Unit raise

    Generate HTML from console contents and write it to a file.

    Console::save_svg

    fn Console::save_svg(self : Console, path : String, title? : String, theme? :
    TerminalTheme
    , clear? : Bool, code_format? : String, font_aspect_ratio? : Double, unique_id? : String) -> Unit raise

    Generate an SVG from the console contents and save it to a file.

    Console::save_text

    fn Console::save_text(self : Console, path : String, clear? : Bool, styles? : Bool) -> Unit raise

    Generate text from console contents and save it to a file.

    Console::screen

    fn Console::screen(self : Console, f : (ScreenContext) -> Unit raise, hide_cursor? : Bool, style? : &IntoStyle) -> Unit raise

    Run f in the alternate screen (upstream with console.screen() asscreen:).

    Console::screen_context

    fn Console::screen_context(self : Console, hide_cursor? : Bool, style? : &IntoStyle) -> ScreenContext

    Create a screen context; call enter / exit, or use Console::screen.

    Console::set_alt_screen

    fn Console::set_alt_screen(self : Console, enable? : Bool) -> Bool raise

    Enable or disable the alternative screen mode. Returns true if the control codes were written.

    Console::set_file

    fn Console::set_file(self : Console, file : &ConsoleFile) -> Unit

    Set a new file to write to.

    Console::set_height

    fn Console::set_height(self : Console, height : Int) -> Unit

    Set the height of the console.

    Console::set_live

    fn Console::set_live(self : Console, live_id : Int) -> Bool

    Register a live display. Returns true if it is the top-most one.

    Console::set_size

    fn Console::set_size(self : Console, width : Int, height : Int) -> Unit

    Set a new size for the terminal.

    Console::set_width

    fn Console::set_width(self : Console, width : Int) -> Unit

    Set the width of the console.

    Console::set_window_title

    fn Console::set_window_title(self : Console, title : String) -> Bool raise

    Set the title of the console terminal window.

    Console::show_cursor

    fn Console::show_cursor(self : Console, show? : Bool) -> Bool raise

    Show or hide the cursor.

    Console::size

    fn Console::size(self : Console) -> ConsoleDimensions

    The size of the console.

    Console::update_screen

    fn Console::update_screen(self : Console, renderable : &Renderable, region? : Region, options? : ConsoleOptions) -> Unit raise

    Update the screen at a given offset (alt screen only).

    Console::update_screen_lines

    fn Console::update_screen_lines(self : Console, lines : Array[Array[Segment]], x? : Int, y? : Int) -> Unit raise

    Update lines of the screen at a given offset (alt screen only).

    Console::use_theme

    fn Console::use_theme(self : Console, theme : Theme, f : () -> Unit raise, inherit_styles? : Bool) -> Unit raise

    Use a different theme for the duration of f.

    Console::width

    fn Console::width(self : Console) -> Int

    The width of the console.

    ConsoleDimensions

    pub(all) struct ConsoleDimensions {
    width : Int
    height : Int
    } derive(Eq,
    Debug
    )

    Size of the terminal.

    ConsoleOptions

    pub(all) struct ConsoleOptions {
    size : ConsoleDimensions
    legacy_windows : Bool
    min_width : Int
    max_width : Int
    is_terminal : Bool
    encoding : String
    max_height : Int
    justify : JustifyMethod?
    overflow : OverflowMethod?
    no_wrap : Bool?
    highlight : Bool?
    markup : Bool?
    height : Int?
    }

    Options for Renderable::rich_console.

    ConsoleOptions::ascii_only

    fn ConsoleOptions::ascii_only(self : ConsoleOptions) -> Bool

    Check if renderables should use ascii only.

    ConsoleOptions::copy

    Return a copy of the options.

    ConsoleOptions::reset_height

    fn ConsoleOptions::reset_height(self : ConsoleOptions) -> ConsoleOptions

    Return a copy of the options with height set to None.

    ConsoleOptions::update

    fn ConsoleOptions::update(self : ConsoleOptions, width? : Int, min_width? : Int, max_width? : Int, justify? : JustifyMethod?, overflow? : OverflowMethod?, no_wrap? : Bool?, highlight? : Bool?, markup? : Bool?, height? : Int?) -> ConsoleOptions

    Update values, return a copy. Omitted arguments are left unchanged (upstream NO_CHANGE); Some(None)-style values reset an option.

    ConsoleOptions::update_dimensions

    fn ConsoleOptions::update_dimensions(self : ConsoleOptions, width : Int, height : Int) -> ConsoleOptions

    Update the width and height.

    ConsoleOptions::update_height

    fn ConsoleOptions::update_height(self : ConsoleOptions, height : Int) -> ConsoleOptions

    Update the height.

    ConsoleOptions::update_width

    fn ConsoleOptions::update_width(self : ConsoleOptions, width : Int) -> ConsoleOptions

    Update just the width (sets both min_width and max_width).

    Constrain

    pub struct Constrain {
    renderable : &Renderable
    width : Int?
    }

    Constrain the width of a renderable to a given number of characters.

    Constrain::new

    fn Constrain::new(renderable : &Renderable, width? : Int?) -> Constrain

    Control

    pub struct Control {
    segment : Segment
    }

    A renderable that inserts a control code (non printable but may move cursor).
    impl Show for Control

    Control::alt_screen

    fn Control::alt_screen(enable : Bool) -> Control

    Enable or disable alt screen.

    Control::bell

    fn Control::bell() -> Control

    Ring the 'bell'.

    Control::clear

    fn Control::clear() -> Control

    Clear the screen.

    Control::home

    fn Control::home() -> Control

    Move cursor to 'home' position.

    Control::move_

    fn Control::move_(x? : Int, y? : Int) -> Control

    Move cursor relative to current position.

    Control::move_to

    fn Control::move_to(x : Int, y : Int) -> Control

    Move cursor to absolute position.

    Control::move_to_column

    fn Control::move_to_column(x : Int, y? : Int) -> Control

    Move to the given column, optionally add offset to row.

    Control::new

    fn Control::new(codes : Array[ControlCode]) -> Control

    Control::show_cursor

    fn Control::show_cursor(show : Bool) -> Control

    Show or hide the cursor.

    Control::title

    fn Control::title(title : String) -> Control

    Set the terminal window title.

    ControlCode

    pub(all) enum ControlCode {
    Code(ControlType)
    CodeInt(ControlType, Int)
    CodeStr(ControlType, String)
    CodeXY(ControlType, Int, Int)
    } derive(Eq, Hash,
    Debug
    )

    A control code with its parameters.

    ControlType

    pub(all) enum ControlType {
    Bell
    CarriageReturn
    Home
    Clear
    ShowCursor
    HideCursor
    EnableAltScreen
    DisableAltScreen
    CursorUp
    CursorDown
    CursorForward
    CursorBackward
    CursorMoveToColumn
    CursorMoveTo
    EraseInLine
    SetWindowTitle
    } derive(Eq, Hash,
    Debug
    )

    Non-printable control codes which typically translate to ANSI codes.

    ControlType::to_int

    fn ControlType::to_int(self : ControlType) -> Int

    Edge

    pub(all) struct Edge {
    size : Int?
    ratio : Int
    minimum_size : Int
    } derive(Eq,
    Debug
    )

    An edge for ratio_resolve.

    Emoji

    pub struct Emoji {
    name : String
    style : StyleType
    variant : EmojiVariant?
    // private fields
    }

    A single emoji character.
    impl Renderable for Emoji
    impl Show for Emoji

    Emoji::new

    fn Emoji::new(name : String, style? : &IntoStyle, variant? : EmojiVariant) -> Emoji raise RichError

    Create an emoji by name, e.g. "smiley". Raises NoEmoji if there is no such emoji.

    Emoji::replace

    fn Emoji::replace(text : String) -> String

    Replace emoji markup with corresponding unicode characters.

    Emoji::repr

    fn Emoji::repr(self : Emoji) -> String

    Upstream repr(emoji), e.g. <emoji 'smiley'>.

    EmojiVariant

    pub(all) enum EmojiVariant {
    Emoji
    Text
    } derive(Eq,
    Debug
    )

    Emoji variants.

    EmojiVariant::to_string

    fn EmojiVariant::to_string(self : EmojiVariant) -> String

    Group

    pub struct Group {
    renderables : Array[&Renderable]
    fit : Bool
    }

    Takes a group of renderables and returns a renderable object that renders the group.
    impl Renderable for Group

    Group::new

    fn Group::new(renderables : Array[&Renderable], fit? : Bool) -> Group

    ISO8601Highlighter

    pub struct ISO8601Highlighter {
    // private fields
    }

    Highlights ISO8601 date time strings.

    ISO8601Highlighter::new

    JSON

    pub struct JSON {
    text : Text
    }

    A renderable which pretty prints JSON.
    impl Renderable for JSON

    JSON::from_data

    fn JSON::from_data(data : Json, indent? : Int?, indent_str? : String, highlight? : Bool, ensure_ascii? : Bool, sort_keys? : Bool) -> JSON raise

    Pretty print a MoonBit Json value.

    JSON::from_value

    fn JSON::from_value(data : JsonValue, indent? : Int?, indent_str? : String, highlight? : Bool, ensure_ascii? : Bool, sort_keys? : Bool) -> JSON raise

    Pretty print a JsonValue.

    JSON::new

    fn JSON::new(json : String, indent? : Int?, indent_str? : String, highlight? : Bool, ensure_ascii? : Bool, sort_keys? : Bool) -> JSON raise

    Pretty print a JSON string.

    JSONHighlighter

    pub struct JSONHighlighter {
    }

    Highlights JSON.

    JSONHighlighter::new

    JsonValue

    pub(all) enum JsonValue {
    JNull
    JBool(Bool)
    JInt(String)
    JFloat(Double)
    JString(String)
    JArray(Array[JsonValue])
    JObject(Array[(String, JsonValue)])
    } derive(Eq,
    Debug
    )

    A JSON value that keeps object key order and the text of numbers (so that 1 and 1.0 are printed back as Python would).

    JsonValue::dumps

    fn JsonValue::dumps(self : JsonValue, indent? : Int?, indent_str? : String, ensure_ascii? : Bool, sort_keys? : Bool) -> String

    Python json.dumps. indent is the number of spaces (None for a single line); sort_keys sorts object keys.

    JsonValue::from_json

    fn JsonValue::from_json(json : Json) -> JsonValue

    Convert a MoonBit Json value. Integral numbers without a textual representation are treated as integers.

    JsonValue::parse

    fn JsonValue::parse(text : String) -> JsonValue raise RichError

    Parse JSON text (Python json.loads).

    JustifyMethod

    pub(all) enum JustifyMethod {
    Default
    Left
    Center
    Right
    Full
    } derive(Eq, Hash,
    Debug
    )

    Justify methods.

    JustifyMethod::parse

    fn JustifyMethod::parse(s : String) -> JustifyMethod?

    Parse a justify method name ("default", "left", ...).

    JustifyMethod::to_string

    fn JustifyMethod::to_string(self : JustifyMethod) -> String

    Lines

    pub struct Lines {
    lines : Array[Text]
    }

    A list of Text lines which renders each line.
    impl Renderable for Lines

    Lines::append

    fn Lines::append(self : Lines, line : Text) -> Unit

    Lines::extend_

    fn Lines::extend_(self : Lines, lines : ArrayView[Text]) -> Unit

    Lines::get

    fn Lines::get(self : Lines, index : Int) -> Text

    The line at index (negative indices count from the end, as in Python). Aborts if out of range.

    Lines::iter

    fn Lines::iter(self : Lines) -> Iter[Text]

    Lines::justify

    fn Lines::justify(self : Lines, console : Console, width : Int, justify? : JustifyMethod, overflow? : OverflowMethod) -> Unit raise

    Justify and overflow text to a given width.

    Lines::length

    fn Lines::length(self : Lines) -> Int

    Lines::new

    fn Lines::new(lines : ArrayView[Text]) -> Lines

    Lines::pop

    fn Lines::pop(self : Lines, index? : Int) -> Text?

    Remove and return the line at index (default: the last line; negative indices count from the end). None if out of range.

    Lines::repr

    fn Lines::repr(self : Lines) -> String

    Upstream repr(lines).

    Lines::set

    fn Lines::set(self : Lines, index : Int, value : Text) -> Unit

    Replace the line at index (negative indices count from the end).

    Lines::slice

    fn Lines::slice(self : Lines, start? : Int, end? : Int) -> Array[Text]

    Lines start..end with Python slice semantics (upstream lines[a:b]).

    LogRender

    pub struct LogRender {
    show_time : Bool
    show_level : Bool
    show_path : Bool
    time_format : String
    time_formatter : (Double) -> Text?
    omit_repeated_times : Bool
    level_width : Int?
    // private fields
    }

    Renders the layout of Console.log (and RichHandler).

    LogRender::new

    fn LogRender::new(show_time? : Bool, show_level? : Bool, show_path? : Bool, time_format? : String, time_formatter? : (Double) -> Text, omit_repeated_times? : Bool, level_width? : Int?) -> LogRender

    time_format is a C strftime format; time_formatter overrides it with a function from the time (seconds since the epoch) to a Text.

    LogRender::render

    fn LogRender::render(self : LogRender, console : Console, renderables : Array[&Renderable], log_time? : Double, time_format? : String, level? : &IntoText, path? : String, line_no? : Int, link_path? : String) -> Table raise

    Build the log line as a grid table.

    MarkupItem

    pub(all) enum MarkupItem {
    PlainText(Int, String)
    TagAt(Int, Tag)
    } derive(Eq,
    Debug
    )

    An item of parsed markup (upstream _parse yields (position, text, tag) tuples): text or a tag, at a position.

    Measurement

    pub(all) struct Measurement {
    minimum : Int
    maximum : Int
    } derive(Eq,
    Debug
    )

    Stores the minimum and maximum widths (in cells) required to render an object.
    impl Show for Measurement

    Measurement::clamp

    fn Measurement::clamp(self : Measurement, min_width? : Int, max_width? : Int) -> Measurement

    Clamp a measurement within the specified range.

    Measurement::get

    fn Measurement::get(console : Console, options : ConsoleOptions, renderable : &Renderable) -> Measurement raise

    Get a measurement for a renderable.

    Measurement::new

    fn Measurement::new(minimum : Int, maximum : Int) -> Measurement

    Measurement::normalize

    fn Measurement::normalize(self : Measurement) -> Measurement

    Ensure that minimum <= maximum and minimum >= 0.

    Measurement::span

    fn Measurement::span(self : Measurement) -> Int

    Difference between maximum and minimum.

    Measurement::with_maximum

    fn Measurement::with_maximum(self : Measurement, width : Int) -> Measurement

    Get a measurement where the widths are <= width.

    Measurement::with_minimum

    fn Measurement::with_minimum(self : Measurement, width : Int) -> Measurement

    Get a measurement where the widths are >= width.

    NewLine

    pub struct NewLine {
    count : Int
    }

    A renderable to generate new line(s).

    NewLine::new

    fn NewLine::new(count? : Int) -> NewLine

    NullFile

    pub struct NullFile {
    }

    A file that discards everything (upstream NullFile).

    NullFile::new

    fn NullFile::new() -> NullFile

    NullHighlighter

    pub struct NullHighlighter {
    }

    A highlighter that doesn't highlight.

    NullHighlighter::new

    OverflowMethod

    pub(all) enum OverflowMethod {
    Fold
    Crop
    Ellipsis
    Ignore
    } derive(Eq, Hash,
    Debug
    )

    Overflow methods.

    OverflowMethod::parse

    fn OverflowMethod::parse(s : String) -> OverflowMethod?

    Parse an overflow method name.

    OverflowMethod::to_string

    fn OverflowMethod::to_string(self : OverflowMethod) -> String

    Padding

    pub struct Padding {
    renderable : &Renderable
    top : Int
    right : Int
    bottom : Int
    left : Int
    style : StyleType
    expand : Bool
    }

    Draw space around content.

    Padding::indent

    fn Padding::indent(renderable : &Renderable, level : Int) -> Padding

    Make padding instance to render an indent.

    Padding::new

    fn Padding::new(renderable : &Renderable, pad? : ArrayView[Int], style? : &IntoStyle, expand? : Bool) -> Padding raise RichError

    Padding::repr

    fn Padding::repr(self : Padding) -> String

    PyValue

    pub(all) enum PyValue {
    PyNone
    PyBool(Bool)
    PyInt(Int64)
    PyFloat(Double)
    PyStr(String)
    PyBytes(String)
    PyTuple(Array[PyValue])
    PyList(Array[PyValue])
    PySet(Array[PyValue])
    PyDict(Array[(PyValue, PyValue)])
    } derive(Eq,
    Debug
    )

    A Python literal value (as parsed by ast.literal_eval).
    impl ToJson for PyValue

    PyValue::repr

    fn PyValue::repr(self : PyValue) -> String

    Python repr() of the value.

    RegexHighlighter

    pub struct RegexHighlighter {
    highlights : Array[
    Regex
    ]
    base_style : String
    }

    Applies highlighting from a list of regular expressions, where group names are translated to styles prefixed by base_style.

    RegexHighlighter::new

    fn RegexHighlighter::new(highlights : Array[String], base_style? : String) -> RegexHighlighter raise
    RegexError

    Create a highlighter from regular expressions (Python re syntax).

    Region

    pub(all) struct Region {
    x : Int
    y : Int
    width : Int
    height : Int
    } derive(Eq,
    Debug
    )

    Defines a rectangular region of the screen.

    RenderItem

    pub(all) enum RenderItem {
    Seg(Segment)
    Child(&Renderable)
    }

    An item produced by Renderable::rich_console: a segment, or another renderable to be rendered in turn.

    Renderables

    pub struct Renderables {
    renderables : Array[&Renderable]
    }

    A list of renderables that renders its contents in order.

    Renderables::append

    fn Renderables::append(self : Renderables, renderable : &Renderable) -> Unit

    Renderables::iter

    fn Renderables::iter(self : Renderables) -> Iter[&Renderable]

    Iterate over the renderables.

    Renderables::new

    fn Renderables::new(renderables? : Array[&Renderable]) -> Renderables

    ReprHighlighter

    pub struct ReprHighlighter {
    // private fields
    }

    Highlights the text typically produced from __repr__ methods.

    ReprHighlighter::new

    Row

    pub(all) struct Row {
    style : StyleType?
    end_section : Bool
    }

    Information regarding a row.

    RowLevel

    pub(all) enum RowLevel {
    Head
    Row
    Foot
    Mid
    } derive(Eq,
    Debug
    )

    Row levels for Box::get_row.

    Rule

    pub struct Rule {
    title : TextType
    characters : String
    style : StyleType
    end : String
    align : AlignMethod
    }

    A console renderable to draw a horizontal rule (line).
    impl Renderable for Rule

    Rule::new

    fn Rule::new(title? : &IntoText, characters? : String, style? : &IntoStyle, end? : String, align? : AlignMethod) -> Rule raise RichError

    Rule::repr

    fn Rule::repr(self : Rule) -> String

    Screen

    pub struct Screen {
    renderable : &Renderable
    style : StyleType?
    application_mode : Bool
    }

    A renderable that fills the terminal screen and crops excess.

    Screen::new

    fn Screen::new(renderables : Array[&Renderable], style? : &IntoStyle, application_mode? : Bool) -> Screen

    ScreenContext

    pub struct ScreenContext {
    console : Console
    hide_cursor : Bool
    screen : Screen
    // private fields
    }

    A context that enables the alternate screen (upstream ScreenContext, returned by console.screen()).

    ScreenContext::enter

    fn ScreenContext::enter(self : ScreenContext) -> Unit raise

    Enable the alternate screen (and hide the cursor).

    ScreenContext::exit

    fn ScreenContext::exit(self : ScreenContext) -> Unit raise

    Restore the normal screen (and the cursor).

    ScreenContext::update

    fn ScreenContext::update(self : ScreenContext, renderables? : Array[&Renderable], style? : &IntoStyle) -> Unit raise

    Update the screen with new renderables (and / or a new style).

    ScreenUpdate

    pub struct ScreenUpdate {
    lines : Array[Array[Segment]]
    x : Int
    y : Int
    }

    Render a list of lines at a given offset.

    ScreenUpdate::new

    fn ScreenUpdate::new(lines : Array[Array[Segment]], x : Int, y : Int) -> ScreenUpdate

    Segment

    pub(all) struct Segment {
    text : String
    style : Style?
    control : Array[ControlCode]?
    } derive(Eq)

    A piece of text with associated style. Segments are produced by the Console render process and are ultimately converted in to strings to be written to the terminal.
    impl Show for Segment

    Segment::adjust_line_length

    fn Segment::adjust_line_length(line : Array[Segment], length : Int, style? : Style, pad? : Bool) -> Array[Segment]

    Adjust a line to a given width (cropping or padding as required).

    Segment::align_bottom

    fn Segment::align_bottom(lines : Array[Array[Segment]], width : Int, height : Int, style : Style?, new_lines? : Bool) -> Array[Array[Segment]]

    Align lines to bottom (adds extra lines above as required).

    Segment::align_middle

    fn Segment::align_middle(lines : Array[Array[Segment]], width : Int, height : Int, style : Style?, new_lines? : Bool) -> Array[Array[Segment]]

    Align lines to middle (adds extra lines above and below as required).

    Segment::align_top

    fn Segment::align_top(lines : Array[Array[Segment]], width : Int, height : Int, style : Style?, new_lines? : Bool) -> Array[Array[Segment]]

    Align lines to top (adds extra lines to bottom as required).

    Segment::apply_style

    fn Segment::apply_style(segments : Array[Segment], style? : Style, post_style? : Style) -> Array[Segment]

    Apply style(s) to segments: each style is replaced by style + segment.style + post_style.

    Segment::cell_length

    fn Segment::cell_length(self : Segment) -> Int

    The number of terminal cells required to display the text (0 for control segments).

    Segment::divide

    fn Segment::divide(segments : Array[Segment], cuts : Array[Int]) -> Array[Array[Segment]]

    Divide segments in to portions at the given cell positions.

    Segment::filter_control

    fn Segment::filter_control(segments : Array[Segment], is_control? : Bool) -> Array[Segment]

    Filter segments by their is_control attribute.

    Segment::get_line_length

    fn Segment::get_line_length(line : ArrayView[Segment]) -> Int

    Get the length of a line of segments (assumes no new lines).

    Segment::get_shape

    fn Segment::get_shape(lines : Array[Array[Segment]]) -> (Int, Int)

    Get the shape (enclosing rectangle) of a list of lines.

    Segment::has_codes

    fn Segment::has_codes(self : Segment) -> Bool

    Upstream bool(segment.control): the segment has at least one control code. Most of the segment helpers test this (rather than is_control).

    Segment::is_control

    fn Segment::is_control(self : Segment) -> Bool

    Check if the segment contains control codes.

    Segment::line

    fn Segment::line() -> Segment

    Make a new line segment.

    Segment::new

    fn Segment::new(text : String, style? : Style, control? : Array[ControlCode]) -> Segment

    Segment::remove_color

    fn Segment::remove_color(segments : Array[Segment]) -> Array[Segment]

    Remove all color from segments.

    Segment::repr

    fn Segment::repr(self : Segment) -> String

    Upstream repr(segment).

    Segment::set_shape

    fn Segment::set_shape(lines : Array[Array[Segment]], width : Int, height? : Int, style? : Style, new_lines? : Bool) -> Array[Array[Segment]]

    Set the shape of a list of lines (enclosing rectangle).

    Segment::simplify

    fn Segment::simplify(segments : Array[Segment]) -> Array[Segment]

    Simplify segments by combining contiguous segments with the same style.

    Segment::split_and_crop_lines

    fn Segment::split_and_crop_lines(segments : Array[Segment], length : Int, style? : Style, pad? : Bool, include_new_lines? : Bool) -> Array[Array[Segment]]

    Split segments in to lines, and crop lines greater than a given length.

    Segment::split_cells

    fn Segment::split_cells(self : Segment, cut : Int) -> (Segment, Segment)

    Split a segment in to two at a given cell position. If the cut point falls in the middle of a 2-cell wide character then it is replaced by two spaces, to preserve the display width.

    Segment::split_lines

    fn Segment::split_lines(segments : Array[Segment]) -> Array[Array[Segment]]

    Split a sequence of segments in to a list of lines.

    Segment::split_lines_terminator

    fn Segment::split_lines_terminator(segments : Array[Segment]) -> Array[(Array[Segment], Bool)]

    Split segments in to lines, with a flag that indicates whether the line was terminated by a new line.
    fn Segment::strip_links(segments : Array[Segment]) -> Array[Segment]

    Remove all links from segments.

    Segment::strip_styles

    fn Segment::strip_styles(segments : Array[Segment]) -> Array[Segment]

    Remove all styles from segments.

    Segment::to_bool

    fn Segment::to_bool(self : Segment) -> Bool

    Upstream bool(segment): the segment contains text.

    SegmentLines

    pub struct SegmentLines {
    lines : Array[Array[Segment]]
    new_lines : Bool
    }

    A renderable to render lines of segments.

    SegmentLines::new

    fn SegmentLines::new(lines : Array[Array[Segment]], new_lines? : Bool) -> SegmentLines

    With new_lines, a new line is added after each line.

    Segments

    pub struct Segments {
    segments : Array[Segment]
    new_lines : Bool
    }

    A simple renderable to render a list of segments.

    Segments::new

    fn Segments::new(segments : Array[Segment], new_lines? : Bool) -> Segments

    With new_lines, a new line is added after each segment.

    Span

    pub(all) struct Span {
    start : Int
    end : Int
    style : StyleType
    } derive(Eq, Hash)

    A marked up region in some text.
    impl Show for Span

    Span::extend_

    fn Span::extend_(self : Span, cells : Int) -> Span

    Extend the span by the given number of cells.

    Span::move_

    fn Span::move_(self : Span, offset : Int) -> Span

    Move start and end by a given offset.

    Span::new

    fn Span::new(start : Int, end : Int, style : &IntoStyle) -> Span

    Span::right_crop

    fn Span::right_crop(self : Span, offset : Int) -> Span

    Crop the span at the given offset.

    Span::split

    fn Span::split(self : Span, offset : Int) -> (Span, Span?)

    Split a span in to 2 from a given offset.

    Span::to_bool

    fn Span::to_bool(self : Span) -> Bool

    Upstream bool(span).

    StdStream

    pub struct StdStream {
    fd : Int
    }

    Standard output or standard error.

    StdStream::stderr

    fn StdStream::stderr() -> StdStream

    The standard error stream.

    StdStream::stdout

    fn StdStream::stdout() -> StdStream

    The standard output stream.

    StringIO

    pub struct StringIO {
    // private fields
    }

    An in-memory text file (upstream io.StringIO).

    StringIO::getvalue

    fn StringIO::getvalue(self : StringIO) -> String

    Everything written so far.

    StringIO::new

    fn StringIO::new(isatty? : Bool) -> StringIO

    Create an in-memory file. With isatty, it claims to be a terminal.

    StringIO::reset

    fn StringIO::reset(self : StringIO) -> Unit

    Discard the contents.

    Style

    pub struct Style {
    // private fields
    }

    A terminal style: a color, a background color and a number of attributes (bold, italic, ...). Attributes have three states: on (Some(true)), off (Some(false)) or not set (None).
    impl IntoStyle for Style
    impl Add for Style
    impl Eq for Style
    impl Hash for Style
    impl Show for Style

    Style::add_opt

    fn Style::add_opt(self : Style, other : Style?) -> Style

    Combine with an optional style (upstream style + None).

    Style::background_style

    fn Style::background_style(self : Style) -> Style

    A Style with background only.

    Style::bgcolor

    The background color, if set.
    fn Style::blink(self : Style) -> Bool?

    Style::blink2

    fn Style::blink2(self : Style) -> Bool?

    Style::bold

    fn Style::bold(self : Style) -> Bool?

    Style::chain

    fn Style::chain(styles : Array[Style]) -> Style

    Combine styles from left to right (upstream Style.chain(*styles)).
    fn Style::clear_meta_and_links(self : Style) -> Style

    Get a copy of this style with link and meta information removed.

    Style::color

    The foreground color, if set.

    Style::combine

    fn Style::combine(styles : ArrayView[Style]) -> Style

    Combine styles from left to right.

    Style::conceal

    fn Style::conceal(self : Style) -> Bool?

    Style::copy

    fn Style::copy(self : Style) -> Style

    Get a copy of this style (links get a new link id).

    Style::dim

    fn Style::dim(self : Style) -> Bool?

    Style::encircle

    fn Style::encircle(self : Style) -> Bool?

    Style::frame

    fn Style::frame(self : Style) -> Bool?

    Style::from_color

    Create a new style with colors and no attributes.

    Style::from_meta

    fn Style::from_meta(meta : Map[String, Json]?) -> Style

    Create a new style with meta data.

    Style::get_html_style

    fn Style::get_html_style(self : Style, theme? :
    TerminalTheme
    ) -> String

    Get a CSS style rule.

    Style::is_null

    fn Style::is_null(self : Style) -> Bool

    A style is "null" if it has no attributes, colors, links or meta. This is the negation of upstream's bool(style).

    Style::italic

    fn Style::italic(self : Style) -> Bool?

    fn Style::link(self : Style) -> String?

    Link URL, if set.
    fn Style::link_id(self : Style) -> String

    The link id, used in the ANSI code for links.

    Style::meta

    fn Style::meta(self : Style) -> Map[String, Json]

    Meta information (empty if not set).

    Style::new

    fn Style::new(color? :
    Color
    , bgcolor? :
    Color
    , bold? : Bool, dim? : Bool, italic? : Bool, underline? : Bool, blink? : Bool, blink2? : Bool, reverse? : Bool, conceal? : Bool, strike? : Bool, underline2? : Bool, frame? : Bool, encircle? : Bool, overline? : Bool, link? : String, meta? : Map[String, Json]) -> Style

    Create a new style.

    Style::normalize

    fn Style::normalize(style : String) -> String

    Normalize a style definition so that styles with the same effect have the same string representation.

    Style::null

    fn Style::null() -> Style

    The "null" style, equivalent to Style::new().

    Style::on

    fn Style::on(meta? : Map[String, Json], handlers? : Map[String, Json]) -> Style

    Create a blank style with meta information; each handler key is stored as "@key".

    Style::overline

    fn Style::overline(self : Style) -> Bool?

    Style::parse

    fn Style::parse(style_definition : String) -> Style raise RichError

    Parse a style definition such as "bold red on white".

    Style::pick_first

    fn Style::pick_first(values : ArrayView[StyleType?]) -> StyleType raise RichError

    Pick the first non-None style (upstream Style.pick_first).

    Style::render

    fn Style::render(self : Style, text? : String, color_system? :
    ColorSystem
    ?, legacy_windows? : Bool) -> String

    Render the ANSI codes for the style around text. With color_system None the text is returned unstyled.

    Style::repr

    fn Style::repr(self : Style) -> String

    Upstream repr(style), e.g. Style(color=Color('red', ...), bold=True).

    Style::reverse

    fn Style::reverse(self : Style) -> Bool?

    Style::strike

    fn Style::strike(self : Style) -> Bool?

    Style::to_bool

    fn Style::to_bool(self : Style) -> Bool

    Upstream bool(style).

    Style::to_definition

    fn Style::to_definition(self : Style) -> String

    Re-generate the style definition from attributes (upstream str(style)).

    Style::transparent_background

    fn Style::transparent_background(self : Style) -> Bool

    Check if the style specified a transparent background.

    Style::underline

    fn Style::underline(self : Style) -> Bool?

    Style::underline2

    fn Style::underline2(self : Style) -> Bool?

    fn Style::update_link(self : Style, link : String?) -> Style

    Get a copy with a different value for link.

    Style::without_color

    fn Style::without_color(self : Style) -> Style

    Get a copy of the style with color removed.

    StyleStack

    pub struct StyleStack {
    // private fields
    }

    A stack of styles.

    StyleStack::current

    fn StyleStack::current(self : StyleStack) -> Style

    The Style at the top of the stack.

    StyleStack::new

    fn StyleStack::new(default_style : Style) -> StyleStack

    StyleStack::pop

    fn StyleStack::pop(self : StyleStack) -> Style

    Pop the last style and return the new current style.

    StyleStack::push

    fn StyleStack::push(self : StyleStack, style : Style) -> Unit

    Push a new style on to the stack, combined with the current style.

    StyleStack::repr

    fn StyleStack::repr(self : StyleStack) -> String

    Upstream repr(stack).

    StyleType

    pub(all) enum StyleType {
    Def(String)
    Style(Style)
    } derive(Eq, Hash)

    A style definition (looked up in the theme, then parsed, at render time) or a Style (upstream StyleType = Union[str, Style]).
    impl Show for StyleType

    StyleType::repr

    fn StyleType::repr(self : StyleType) -> String

    Upstream repr(style) for a str or Style.

    StyleType::to_bool

    fn StyleType::to_bool(self : StyleType) -> Bool

    Upstream bool(style): a non-empty definition or a non-null style.

    Styled

    pub struct Styled {
    renderable : &Renderable
    style : StyleType
    }

    Apply a style to a renderable.

    Styled::new

    fn Styled::new(renderable : &Renderable, style : &IntoStyle) -> Styled

    SystemPager

    pub struct SystemPager {
    command : String?
    }

    Uses the pager installed on the system ($PAGER, or less -r).

    SystemPager::new

    fn SystemPager::new(command? : String) -> SystemPager

    Table

    pub(all) struct Table {
    columns : Array[Column]
    rows : Array[Row]
    title : TextType?
    caption : TextType?
    width : Int?
    min_width : Int?
    box_ : Box?
    safe_box : Bool?
    pad_edge : Bool
    show_header : Bool
    show_footer : Bool
    show_edge : Bool
    show_lines : Bool
    leading : Int
    collapse_padding : Bool
    style : StyleType
    header_style : StyleType
    footer_style : StyleType
    border_style : StyleType?
    title_style : StyleType?
    caption_style : StyleType?
    title_justify : JustifyMethod
    caption_justify : JustifyMethod
    highlight : Bool
    row_styles : Array[StyleType]
    // private fields
    }

    A console renderable to draw a table.
    impl Renderable for Table

    Table::add_column

    fn Table::add_column(self : Table, header? : &Renderable, footer? : &Renderable, header_style? : &IntoStyle, highlight? : Bool, footer_style? : &IntoStyle, style? : &IntoStyle, justify? : JustifyMethod, vertical? : VerticalAlignMethod, overflow? : OverflowMethod, width? : Int, min_width? : Int, max_width? : Int, ratio? : Int, no_wrap? : Bool) -> Unit

    Add a column to the table.

    Table::add_row

    fn Table::add_row(self : Table, renderables : ArrayView[&Renderable], style? : &IntoStyle, end_section? : Bool) -> Unit

    Add a row of renderables.

    Table::add_section

    fn Table::add_section(self : Table) -> Unit

    Add a new section (draw a line after current row).

    Table::expand

    fn Table::expand(self : Table) -> Bool

    Whether the table expands to the available space.

    Table::get_row_style

    fn Table::get_row_style(self : Table, console : Console, index : Int) -> Style raise

    Get the current row style.

    Table::grid

    fn Table::grid(headers? : Array[&IntoColumn], padding? : ArrayView[Int], collapse_padding? : Bool, pad_edge? : Bool, expand? : Bool) -> Table raise RichError

    Get a table with no lines, headers, or footer.

    Table::new

    fn Table::new(headers? : Array[&IntoColumn], title? : &IntoText, caption? : &IntoText, width? : Int, min_width? : Int, box_? : Box, no_box? : Bool, safe_box? : Bool, padding? : ArrayView[Int], collapse_padding? : Bool, pad_edge? : Bool, expand? : Bool, show_header? : Bool, show_footer? : Bool, show_edge? : Bool, show_lines? : Bool, leading? : Int, style? : &IntoStyle, row_styles? : Array[&IntoStyle], header_style? : &IntoStyle, footer_style? : &IntoStyle, border_style? : &IntoStyle, title_style? : &IntoStyle, caption_style? : &IntoStyle, title_justify? : JustifyMethod, caption_justify? : JustifyMethod, highlight? : Bool) -> Table raise RichError

    Create a table. headers are column headers (strings or Columns). box_ is the box style; pass no_box=true for no box.

    Table::padding

    fn Table::padding(self : Table) -> (Int, Int, Int, Int)

    Cell padding as (top, right, bottom, left).

    Table::row_count

    fn Table::row_count(self : Table) -> Int

    The number of rows in the table.

    Table::set_expand

    fn Table::set_expand(self : Table, expand : Bool) -> Unit

    Table::set_padding

    fn Table::set_padding(self : Table, padding : ArrayView[Int]) -> Unit raise RichError

    Set cell padding (1, 2 or 4 values).

    Tag

    pub(all) struct Tag {
    name : String
    parameters : String?
    } derive(Eq,
    Debug
    )

    A tag in console markup.
    impl Show for Tag

    Tag::markup

    fn Tag::markup(self : Tag) -> String

    The markup representation of this tag.

    Text

    pub(all) struct Text {
    style : StyleType
    justify : JustifyMethod?
    overflow : OverflowMethod?
    no_wrap : Bool?
    end : String
    tab_size : Int?
    // private fields
    }

    Text with color / style.
    impl IntoText for Text
    impl Renderable for Text
    impl TextPart for Text
    impl Add for Text
    impl Eq for Text
    impl Show for Text

    Text::align

    fn Text::align(self : Text, align : AlignMethod, width : Int, character? : Char) -> Unit

    Align text to a given width.

    Text::append

    fn Text::append(self : Text, text : &IntoText, style? : &IntoStyle) -> Text raise RichError

    Append a string or Text, with an optional style (only for strings).

    Text::append_str

    fn Text::append_str(self : Text, text : String, style? : &IntoStyle) -> Text

    Append a string with an optional style.

    Text::append_text

    fn Text::append_text(self : Text, text : Text) -> Text

    Append another Text instance. Unlike append, an empty Text with a style adds an empty span (as upstream).

    Text::append_tokens

    fn Text::append_tokens(self : Text, tokens : ArrayView[(String, StyleType?)]) -> Text

    Append (content, style) tokens.

    Text::apply_meta

    fn Text::apply_meta(self : Text, meta : Map[String, Json], start? : Int, end? : Int) -> Unit

    Apply metadata to the text, or a portion of the text.

    Text::assemble

    fn Text::assemble(parts : ArrayView[&TextPart], style? : &IntoStyle, justify? : JustifyMethod, overflow? : OverflowMethod, no_wrap? : Bool, end? : String, tab_size? : Int, meta? : Map[String, Json]) -> Text

    Construct a text instance by combining strings, Texts and (string, style) tuples.

    Text::at

    fn Text::at(self : Text, offset : Int) -> Text

    The character at offset as a Text (upstream text[offset]).

    Text::blank_copy

    fn Text::blank_copy(self : Text, plain? : String) -> Text

    A new Text instance with copied metadata (but not the string or spans).

    Text::cell_len

    fn Text::cell_len(self : Text) -> Int

    The number of cells required to render this text.

    Text::concat

    fn Text::concat(self : Text, other : &IntoText) -> Text

    Concatenate a string or Text (upstream text + other).

    Text::contains

    fn Text::contains(self : Text, other : &IntoText) -> Bool

    Upstream other in text.

    Text::copy

    fn Text::copy(self : Text) -> Text

    A copy of this instance.

    Text::copy_styles

    fn Text::copy_styles(self : Text, text : Text) -> Unit

    Copy styles from another Text instance (must be the same length).

    Text::detect_indentation

    fn Text::detect_indentation(self : Text) -> Int

    Auto-detect indentation of code.

    Text::divide

    fn Text::divide(self : Text, offsets : ArrayView[Int]) -> Lines

    Divide text into a number of lines at given offsets.

    Text::expand_tabs

    fn Text::expand_tabs(self : Text, tab_size? : Int) -> Unit

    Convert tabs to spaces.

    Text::extend_style

    fn Text::extend_style(self : Text, spaces : Int) -> Unit

    Extend the Text given number of spaces where the spaces have the same style as the last character.

    Text::fit

    fn Text::fit(self : Text, width : Int) -> Lines

    Fit the text in to given width by chopping in to lines.

    Text::from_ansi

    fn Text::from_ansi(text : String, style? : &IntoStyle, justify? : JustifyMethod, overflow? : OverflowMethod, no_wrap? : Bool, end? : String, tab_size? : Int) -> Text

    Create a Text instance from a string containing ANSI escape codes.

    Text::from_markup

    fn Text::from_markup(text : String, style? : &IntoStyle, emoji? : Bool, emoji_variant? : EmojiVariant, justify? : JustifyMethod, overflow? : OverflowMethod, end? : String) -> Text raise RichError

    Create a Text instance from console markup.

    Text::get_style_at_offset

    fn Text::get_style_at_offset(self : Text, console : Console, offset : Int) -> Style raise

    Get the style of a character at the given offset.

    Text::highlight_pattern

    fn Text::highlight_pattern(self : Text, pattern : String, style? : &IntoStyle, style_prefix? : String) -> Int raise
    RegexError

    Like highlight_regex, compiling pattern first.

    Text::highlight_regex

    fn Text::highlight_regex(self : Text, re_highlight :
    Regex
    , style? : &IntoStyle, style_fn? : (String) -> StyleType?, style_prefix? : String) -> Int raise
    RegexError

    Highlight text with a regular expression, where group names are translated to styles. style applies to the whole match; style_fn computes the whole-match style from the matched text. Returns the number of matches.

    Text::highlight_words

    fn Text::highlight_words(self : Text, words : ArrayView[String], style : &IntoStyle, case_sensitive? : Bool) -> Int raise
    RegexError

    Highlight words with a style. Returns the number of words highlighted.

    Text::join

    fn Text::join(self : Text, lines : ArrayView[Text]) -> Text

    Join texts together with this instance as the separator.

    Text::length

    fn Text::length(self : Text) -> Int

    Length of the text (in UTF-16 code units).

    Text::markup

    fn Text::markup(self : Text) -> String

    Console markup that renders this Text.

    Text::new

    fn Text::new(text? : String, style? : &IntoStyle, justify? : JustifyMethod, overflow? : OverflowMethod, no_wrap? : Bool, end? : String, tab_size? : Int, spans? : Array[Span]) -> Text

    Create a new Text.

    Text::on

    fn Text::on(self : Text, meta? : Map[String, Json], handlers? : Map[String, Json]) -> Text

    Apply event handlers (used by Textual). Each handler key is prefixed with "@".

    Text::pad

    fn Text::pad(self : Text, count : Int, character? : Char) -> Unit

    Pad left and right with a given number of characters.

    Text::pad_left

    fn Text::pad_left(self : Text, count : Int, character? : Char) -> Unit

    Pad the left with a given character. As upstream, a negative count adds nothing but still moves the spans.

    Text::pad_right

    fn Text::pad_right(self : Text, count : Int, character? : Char) -> Unit

    Pad the right with a given character.

    Text::plain

    fn Text::plain(self : Text) -> String

    The text as a single string.

    Text::remove_suffix

    fn Text::remove_suffix(self : Text, suffix : String) -> Unit

    Remove a suffix if it exists.

    Text::render

    fn Text::render(self : Text, console : Console, end? : String) -> Array[Segment] raise

    Render the text as Segments.

    Text::repr

    fn Text::repr(self : Text) -> String

    Upstream repr(text).

    Text::right_crop

    fn Text::right_crop(self : Text, amount? : Int) -> Unit

    Remove a number of characters from the end of the text.

    Text::rstrip

    fn Text::rstrip(self : Text) -> Unit

    Strip whitespace from end of text.

    Text::rstrip_end

    fn Text::rstrip_end(self : Text, size : Int) -> Unit

    Remove whitespace beyond a certain width at the end of the text.

    Text::set_length

    fn Text::set_length(self : Text, new_length : Int) -> Unit

    Set new length of the text, clipping or padding as required.

    Text::set_plain

    fn Text::set_plain(self : Text, new_text : String) -> Unit

    Set the text to a new value.

    Text::set_spans

    fn Text::set_spans(self : Text, spans : Array[Span]) -> Unit

    Replace the spans (copied).

    Text::slice

    fn Text::slice(self : Text, start? : Int, stop? : Int) -> Text

    A slice of the text (upstream text[start:stop], Python slice semantics for negative and out-of-range indices).

    Text::spans

    fn Text::spans(self : Text) -> Array[Span]

    The spans (a reference to the internal list).

    Text::split

    fn Text::split(self : Text, separator? : String, include_separator? : Bool, allow_blank? : Bool) -> Lines

    Split rich text in to lines, preserving styles.

    Text::styled

    fn Text::styled(text : String, style? : &IntoStyle, justify? : JustifyMethod, overflow? : OverflowMethod) -> Text

    Construct a Text instance with a pre-applied style. A style applied in this way won't be used to pad the text when it is justified.

    Text::stylize

    fn Text::stylize(self : Text, style : &IntoStyle, start? : Int, end? : Int) -> Unit

    Apply a style to the text, or a portion of the text (negative offsets count from the end).

    Text::stylize_before

    fn Text::stylize_before(self : Text, style : &IntoStyle, start? : Int, end? : Int) -> Unit

    Apply a style before other styles already present.

    Text::to_bool

    fn Text::to_bool(self : Text) -> Bool

    Upstream bool(text).

    Text::truncate

    fn Text::truncate(self : Text, max_width : Int, overflow? : OverflowMethod, pad? : Bool) -> Unit

    Truncate text if it is longer than a given width.

    Text::with_indent_guides

    fn Text::with_indent_guides(self : Text, indent_size? : Int, character? : String, style? : &IntoStyle) -> Text

    Add indent guide lines to text.

    Text::wrap

    fn Text::wrap(self : Text, console : Console, width : Int, justify? : JustifyMethod, overflow? : OverflowMethod, tab_size? : Int, no_wrap? : Bool) -> Lines raise

    Word wrap the text.

    TextKind

    pub(all) enum TextKind {
    NotText
    Str(String)
    Text(Text)
    }

    Result of Renderable::text_kind.

    TextType

    pub(all) enum TextType {
    Str(String)
    Text(Text)
    }

    A plain string or a Text instance (upstream TextType).

    TextType::plain

    fn TextType::plain(self : TextType) -> String

    Upstream str(text).

    TextType::to_bool

    fn TextType::to_bool(self : TextType) -> Bool

    Upstream bool(text).

    Theme

    pub struct Theme {
    styles : Map[String, Style]
    }

    A container for style information, used by Console.

    Theme::config

    fn Theme::config(self : Theme) -> String

    Contents of a config file for this theme.

    Theme::from_config

    fn Theme::from_config(config : String, inherit_styles? : Bool) -> Theme raise RichError

    Load a theme from the contents of an INI-style config file with a [styles] section (upstream Theme.from_file, which reads the file with Python's configparser: keys are lower-cased, [DEFAULT] values are inherited, values may continue on indented lines and %% / %(name)s are interpolated). Configparser errors are ValueErrors with the upstream message.

    Theme::new

    fn Theme::new(styles? : Map[String, &IntoStyle], inherit_styles? : Bool) -> Theme raise RichError

    Create a theme. With inherit, the default styles are included. Style definitions are parsed (raising on syntax errors).

    ThemeStack

    pub struct ThemeStack {
    // private fields
    }

    A stack of themes.

    ThemeStack::get

    fn ThemeStack::get(self : ThemeStack, name : String) -> Style?

    Get a style by name from the top-most theme.

    ThemeStack::new

    fn ThemeStack::new(theme : Theme) -> ThemeStack

    ThemeStack::pop_theme

    fn ThemeStack::pop_theme(self : ThemeStack) -> Unit raise RichError

    Pop (and discard) the top-most theme.

    ThemeStack::push_theme

    fn ThemeStack::push_theme(self : ThemeStack, theme : Theme, inherit_styles? : Bool) -> Unit

    Push a theme on the top of the stack.

    VerticalAlignMethod

    pub(all) enum VerticalAlignMethod {
    Top
    Middle
    Bottom
    } derive(Eq, Hash,
    Debug
    )

    Vertical alignment.

    VerticalAlignMethod::to_string

    fn VerticalAlignMethod::to_string(self : VerticalAlignMethod) -> String

    VerticalCenter

    pub struct VerticalCenter {
    renderable : &Renderable
    style : StyleType?
    }

    Vertically aligns a renderable.

    VerticalCenter::new

    fn VerticalCenter::new(renderable : &Renderable, style? : &IntoStyle) -> VerticalCenter

    adler32

    fn adler32(data : Bytes) -> UInt

    zlib's Adler-32 checksum.

    box_ascii

    let box_ascii : Box

    box_ascii2

    let box_ascii2 : Box

    box_ascii_double_head

    let box_ascii_double_head : Box

    box_double

    let box_double : Box

    box_double_edge

    let box_double_edge : Box

    box_heavy

    let box_heavy : Box

    box_heavy_edge

    let box_heavy_edge : Box

    box_heavy_head

    let box_heavy_head : Box

    box_horizontals

    let box_horizontals : Box

    box_markdown

    let box_markdown : Box

    box_minimal

    let box_minimal : Box

    box_minimal_double_head

    let box_minimal_double_head : Box

    box_minimal_heavy_head

    let box_minimal_heavy_head : Box

    box_rounded

    let box_rounded : Box

    box_simple

    let box_simple : Box

    box_simple_head

    let box_simple_head : Box

    box_simple_heavy

    let box_simple_heavy : Box

    box_square

    let box_square : Box

    box_square_double_head

    let box_square_double_head : Box

    color_to_text

    fn color_to_text(color :
    Color
    ) -> Text

    A Text that displays the color (upstream Color.__rich__), e.g. <color 'red' (standard)⬤ > where the dot is drawn in the color.

    compile_regex

    fn compile_regex(pattern : String, flags? : Int) ->
    Regex
    raise
    RegexError

    Compile a regular expression (Python re syntax), with caching.

    console_html_format

    let console_html_format : String

    The default HTML template.

    console_svg_format

    let console_svg_format : String

    The default SVG template.

    default_styles

    fn default_styles() -> Map[String, Style]

    The default styles, by name.

    default_theme

    let default_theme : Theme

    The default theme.

    divide_line

    fn divide_line(text : String, width : Int, fold? : Bool) -> Array[Int]

    Given a string of text and a width (in cells), return the offsets at which the string should be split in order to fit within the width. With fold, words longer than width are folded onto new lines.

    escape

    fn escape(markup : String) -> String

    Escape text so that it won't be interpreted as markup.

    escape_control_codes

    fn escape_control_codes(text : String) -> String

    Replace control codes with their escaped version (e.g. "\b" becomes "\b").

    filesize_decimal

    fn filesize_decimal(size : Int64, precision? : Int, separator? : String) -> String

    Convert a filesize in to a string (powers of 1000, SI prefixes), e.g. 30.0 kB.

    get_console

    fn get_console() -> Console

    Get the global console object (created on first use).

    html_escape

    fn html_escape(text : String) -> String

    Python html.escape(text).

    literal_eval

    fn literal_eval(source : String) -> PyValue raise RichError

    A subset of Python's ast.literal_eval: numbers (not complex), strings and bytes, True, False, None, tuples, lists, sets and dicts. Errors are ValueErrors carrying the upstream message.

    loop_first

    fn[T] loop_first(xs : ArrayView[T]) -> Array[(Bool, T)]

    Pair each item with a flag that is true for the first item (upstream _loop.loop_first).

    loop_first_last

    fn[T] loop_first_last(xs : ArrayView[T]) -> Array[(Bool, Bool, T)]

    Pair each item with flags for first and last (upstream _loop.loop_first_last).

    loop_last

    fn[T] loop_last(xs : ArrayView[T]) -> Array[(Bool, T)]

    Pair each item with a flag that is true for the last item (upstream _loop.loop_last).

    measure_renderables

    fn measure_renderables(console : Console, options : ConsoleOptions, renderables : ArrayView[&Renderable]) -> Measurement raise

    Get a measurement that would fit a number of renderables.

    palette_to_table

    fn palette_to_table(palette :
    Palette
    ) -> Table

    A Table that displays the colors of a palette (upstream Palette.__rich__).

    parse_markup

    fn parse_markup(markup : String) -> Array[MarkupItem]

    Parse markup in to a list of text and tag items (upstream markup._parse).

    pick_bool

    fn pick_bool(values : Array[Bool?]) -> Bool

    Upstream _pick.pick_bool: the first non-None value, or false.

    pick_unit_and_suffix

    fn pick_unit_and_suffix(size : Int64, suffixes : Array[String], base : Int64) -> (Int64, String)

    Pick a suffix and base for the given size.

    print

    fn print(object : &Renderable, end? : String, file? : &ConsoleFile) -> Unit raise

    Print an object with the global console (markup and highlighting enabled). With file, a new console writing to it is used.
    fn print_json(json? : String, data? : Json, indent? : Int?, highlight? : Bool, ensure_ascii? : Bool, sort_keys? : Bool) -> Unit raise

    Pretty print JSON with the global console.
    fn print_many(objects : ArrayView[&Renderable], sep? : String, end? : String, file? : &ConsoleFile) -> Unit raise

    Print several objects separated by sep with the global console.

    py_float_repr

    fn py_float_repr(d : Double) -> String

    Python repr(float).

    py_format

    fn py_format(template : String, fields : Map[String, String]) -> String

    Python str.format with named fields: {name}, {name!r}, {name:spec} (string format specs: fill, alignment, width, precision), and {{ / }} escapes. Unknown fields are left as they are.

    py_format_exp

    fn py_format_exp(d : Double, precision : Int, upper? : Bool) -> String

    Python format(d, ".{precision}e") (scientific notation, correctly rounded).

    py_format_fixed

    fn py_format_fixed(d : Double, precision : Int) -> String

    Python format(d, ".{precision}f"): fixed-point, correctly rounded (round half to even on the exact binary value).

    py_format_g

    fn py_format_g(d : Double) -> String

    Python format(d, "g") (6 significant digits, trailing zeros removed).

    py_format_general

    fn py_format_general(d : Double, precision? : Int, upper? : Bool, alternate? : Bool) -> String

    Python format(d, ".{precision}g") (general format; alternate keeps trailing zeros like %#g).

    py_group_thousands

    fn py_group_thousands(s : String) -> String

    Insert thousands separators (Python's , format option) into the integer part of a formatted number.

    py_json_repr

    fn py_json_repr(value : Json) -> String

    Python repr() of a JSON value interpreted as the Python value it came from (dicts, lists, str, int/float, True/False/None). Integral numbers are shown as ints.

    py_repr

    fn py_repr(s : String) -> String

    Python repr() of a string.

    ratio_distribute

    fn ratio_distribute(total : Int, ratios : ArrayView[Int], minimums? : ArrayView[Int]) -> Array[Int]

    Distribute an integer total in to parts based on ratios.

    ratio_reduce

    fn ratio_reduce(total : Int, ratios : ArrayView[Int], maximums : ArrayView[Int], values : ArrayView[Int]) -> Array[Int]

    Divide an integer total in to parts based on ratios (reducing values).

    ratio_resolve

    fn ratio_resolve(total : Int, edges : ArrayView[Edge]) -> Array[Int]

    Divide total space to satisfy size, ratio, and minimum_size constraints.

    reconfigure

    fn reconfigure(console : Console) -> Unit

    Replace the global console (upstream reconfigure(**kwargs); create the console with Console::new(...) and pass it here).

    regex_escape

    fn regex_escape(s : String) -> String

    Python re.escape.

    render_markup

    fn render_markup(markup : String, style? : StyleType, emoji? : Bool, emoji_variant? : EmojiVariant) -> Text raise RichError

    Render console markup in to a Text instance.

    segments_to_items

    fn segments_to_items(segments : Array[Segment]) -> Array[RenderItem]

    Wrap segments as render items.

    strip_control_codes

    fn strip_control_codes(text : String) -> String

    Remove control codes that would break the layout (bell, backspace, vertical tab, form feed and carriage return).

    unpack_padding

    fn unpack_padding(pad : ArrayView[Int]) -> (Int, Int, Int, Int) raise RichError

    Padding dimensions: 1 value (all sides), 2 values (top/bottom, left/right) or 4 values (top, right, bottom, left).

    words

    fn words(text : String) -> Array[(Int, Int, String)]

    Words of text as (start, end, word) where a word includes the whitespace around it.