Skip to content
Projets

À propos

Beautiful terminal output for Rust inspired by Python's Rich: tables, panels, syntax highlighting, progress bars, and full-color rendering

Design et médias

Comment ces chiffres sont mesurés

What you can do

  • Markup syntax ([bold red]text[/]) - Yes - No - No - No
  • Tables with auto-sizing - Yes - No - No - No
  • Panels and boxes - Yes - No - No - No
  • Progress bars & spinners - Yes - No - No - No

Progression mesurée des étoiles

in 24h
0
in 7 days
Historique en cours
in 15 days
Historique en cours
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

rich_rust

rich_rust - Beautiful terminal output for Rust

codecov Crates.io Documentation License: MIT

Beautiful terminal output for Rust, inspired by Python's Rich.

Quick Install

cargo add rich_rust

Or with all features: cargo add rich_rust --features full


Run the Demo

See rich_rust in action with the Nebula Deploy demo — a complete showcase of terminal UI capabilities wrapped in a fictional deployment narrative.

# Full demo with all features (recommended)
cargo run --bin demo_showcase --features showcase

# Quick mode for faster run
cargo run --bin demo_showcase --features showcase -- --quick

# CI-safe mode (non-blocking, deterministic output)
cargo run --bin demo_showcase --features showcase -- --quick --no-live --no-interactive

# List available scenes
cargo run --bin demo_showcase --features showcase -- --list-scenes

# Run a specific scene
cargo run --bin demo_showcase --features showcase -- --scene hero

What the demo showcases:

  • Typography — styled text, colors, bold/italic/underline, themes
  • Tables — alignment, borders, headers, badges, ASCII fallback
  • Panels — box styles, titles, padding, nested layouts
  • Trees — hierarchical data, custom guides, icons
  • Progress — bars, spinners, live updates
  • Syntax — code highlighting for 100+ languages (Rust, YAML, TOML, etc.)
  • Markdown — CommonMark + GFM rendering
  • JSON — pretty-printed, theme-aware output
  • Tracing — structured logging integration
  • Export — HTML/SVG capture of terminal output

TL;DR

The Problem

Building beautiful terminal UIs in Rust is tedious. You either:

  • Write raw ANSI escape codes (error-prone, unreadable)
  • Use low-level crates that require boilerplate for simple things
  • Miss features like automatic terminal capability detection, tables, progress bars

The Solution

rich_rust brings Python Rich's ergonomic API to Rust: styled text, tables, panels, progress bars, syntax highlighting, and more. Zero unsafe code, automatic terminal detection.

Why Use rich_rust?

Feature rich_rust Raw ANSI colored termion
Markup syntax ([bold red]text[/]) Yes No No No
Tables with auto-sizing Yes No No No
Panels and boxes Yes No No No
Progress bars & spinners Yes No No No
Syntax highlighting Yes No No No
Markdown rendering Yes No No No
Auto color downgrade Yes No Partial No
Unicode width handling Yes No No Partial

Quick Example

use rich_rust::prelude::*;

fn main() {
    let console = Console::new();

    // Styled text with markup
    console.print("[bold green]Success![/] Operation completed.");
    console.print("[red on white]Error:[/] [italic]File not found[/]");

    // Horizontal rule
    console.rule(Some("Configuration"));

    // Tables
    let mut table = Table::new()
        .title("Users")
        .with_column(Column::new("Name"))
        .with_column(Column::new("Role").justify(JustifyMethod::Right));

    table.add_row_cells(["Alice", "Admin"]);
    table.add_row_cells(["Bob", "User"]);

    console.print_renderable(&table);

    // Panels
    let panel = Panel::from_text("Hello, World!")
        .title("Greeting")
        .width(40);

    console.print_renderable(&panel);
}

Output:

Success! Operation completed.
Error: File not found
─────────────────── Configuration ───────────────────
┌─────────────────────── Users ───────────────────────┐
│ Name   │   Role │
├────────┼────────┤
│ Alice  │  Admin │
│ Bob    │   User │
└────────────────────────────────────────────────────┘
┌─────────── Greeting ───────────┐
│ Hello, World!                  │
└────────────────────────────────┘

Design Philosophy

1. Zero Unsafe Code

#![forbid(unsafe_code)]

The entire codebase uses safe Rust. No segfaults, no data races, no undefined behavior.

2. Python Rich Compatibility

API and behavior closely follow Python Rich. If you know Rich, you know rich_rust. The RICH_SPEC.md documents every behavioral detail.

3. Renderable Extensibility

Instead of Python's duck typing, rich_rust uses explicit render methods and an optional measurement trait:

use rich_rust::console::{Console, ConsoleOptions};
use rich_rust::measure::{Measurement, RichMeasure};
use rich_rust::segment::Segment;

struct MyRenderable;

impl MyRenderable {
    fn render(&self, width: usize) -> Vec<Segment> {
        vec![Segment::plain(format!("width={width}"))]
    }
}

impl RichMeasure for MyRenderable {
    fn rich_measure(&self, _console: &Console, _options: &ConsoleOptions) -> Measurement {
        Measurement::exact(10)
    }
}

Renderables expose render(...) -> Vec<Segment>. Implement RichMeasure to participate in layout width calculations.

Built-in Text, strings, tables, and panels provide natural width measurements, so they work with Columns::push_measurable and measured Align, Padding, and Constrain wrappers. Measurement accounts for visible text, markup/emoji settings, tab stops, panel padding, and captions without drawing children.

Constrain::new_measurable(child, Some(width)) accepts owned or borrowed children and preserves their natural measurements. It retains the child's thread-safety bounds, so owned thread-safe children can also be used in Live and Layout. Constrain::new_boxed retains the lifetime and bounds of an explicit trait object; a None width passes the original rendering options through unchanged.

For a fitting panel containing a child that normally expands, use Panel::with_measurable to allocate the child's natural width before rendering:

let panel = Panel::default()
    .expand(false)
    .with_measurable(Panel::from_text("Ready"));
let columns = Columns::default()
    .push_measurable(panel)
    .push_measurable(Text::new("Queue: 3"))
    .gutter(1)
    .expand(false);
console.print_renderable(&columns);

The existing with_renderable constructor continues to accept children without a measurement; use the measured variant when fitting an expanding child.

4. Automatic Terminal Detection

rich_rust detects terminal capabilities at runtime:

  • Color support (4-bit, 8-bit, 24-bit truecolor)
  • Terminal dimensions
  • Unicode support
  • Legacy Windows console

Colors automatically downgrade to what the terminal supports.

5. Minimal Dependencies

Core functionality has few dependencies. Optional features (syntax highlighting, markdown, JSON, tracing) are behind feature flags to keep compile times fast.


Comparison vs Alternatives

Feature rich_rust Python Rich colored termcolor owo-colors
Language Rust Python Rust Rust Rust
Markup parsing [bold]text[/] [bold]text[/] No No No
Tables Yes Yes No No No
Panels/Boxes Yes Yes No No No
Progress bars Yes Yes No No No
Trees Yes Yes No No No
Syntax highlighting Yes (syntect) Yes (Pygments) No No No
Markdown Yes Yes Yes No No
JSON pretty-print Yes Yes No No No
Color downgrade Auto Auto Partial Yes No
Zero unsafe Yes N/A Yes Yes Yes
No runtime Yes No (Python) Yes Yes Yes
Single binary Yes No Yes Yes Yes

When to use rich_rust:

  • You want Python Rich's features in Rust
  • You need tables, panels, or progress bars
  • You want markup syntax for styling
  • You're building CLI tools that need beautiful output

When to use alternatives:

  • colored: Simple color-only needs, minimal dependencies
  • termcolor: Cross-platform color with Windows support
  • owo-colors: Zero-allocation, const colors
  • Python Rich: You're writing Python

Installation

From crates.io

cargo add rich_rust

With Optional Features

# Syntax highlighting
cargo add rich_rust --features syntax

# Markdown rendering
cargo add rich_rust --features markdown

# JSON pretty-printing
cargo add rich_rust --features json

# Tracing integration
cargo add rich_rust --features tracing

# All features
cargo add rich_rust --features full

From Source

git clone https://github.com/Dicklesworthstone/rich_rust
cd rich_rust
cargo build --release

Cargo.toml

[dependencies]
rich_rust = "0.1"

# Or with features:
rich_rust = { version = "0.1", features = ["full"] }

Quick Start

1. Create a Console

use rich_rust::prelude::*;

let console = Console::new();

2. Print Styled Text

// Using markup syntax
console.print("[bold]Bold[/] and [italic red]italic red[/]");

// Using explicit style
console.print_styled("Styled text", Style::new().bold().underline());

// Plain text (no markup parsing)
console.print_plain("[brackets] are literal here");

Ordinary string printing and prepared Text wrap at the console's configured width. A per-print width may narrow that allocation. String tabs use the console's tab size; prepared Text keeps its own formatting, tab size, and terminator. PrintOptions::with_soft_wrap(true) lets the terminal wrap instead; explicit overflow and no-wrap options still take precedence. Capture and exports retain the formatted output.

Use print_items to wrap adjacent strings and prepared text together. A renderable such as a panel or table can appear between text runs.

use rich_rust::prelude::*;

let console = Console::new();
let result = Text::styled("passed", Style::new().bold());
console.print_items_with_options(
    &["Build".into(), (&result).into()],
    &PrintOptions::new().with_sep(" · "),
);

3. Create a Table

let mut table = Table::new()
    .title("Data")
    .with_column(Column::new("Key"))
    .with_column(Column::new("Value").justify(JustifyMethod::Right));

table.add_row_cells(["version", "1.0.0"]);
table.add_row_cells(["status", "active"]);

console.print_renderable(&table);

For a borderless label/value layout, use a grid. Both table constructors create unnamed columns when a row supplies more cells than the table currently has.

let grid = Table::grid()
    .padding(1, 0)
    .with_row_cells(["Version", "1.0.0"])
    .with_row_cells(["Status", "active"]);
console.print_renderable(&grid);

Cells can also hold renderables. The table lays them out at the column width each time it renders, so the same table can be printed at different widths.

use rich_rust::prelude::*;

let mut dashboard = Table::grid().padding(1, 0);
let status = Panel::from_text("Online").title("Service");
dashboard.add_row_cells([TableEntry::from("API"), TableEntry::measurable(status)]);
Console::new().print_renderable(&dashboard);

TableEntry::measurable retains a child's natural width, so nested tables and panels fit their content before wrapping to the available space. Measurement never renders the child. TableEntry::renderable accepts children without that protocol and shares the space left by the other columns. Tables implement RichMeasure themselves and can be used with fitting panels, measured Groups, and automatic Columns packing. Measurements include visible headers and footers, text tab stops, column constraints, and the same bounded padding used when rendering.

For expanded tables, positive column ratios divide the entire flexible width after reserving the other columns. Equal ratios therefore stay balanced even when the initial text lengths differ. An explicit table width enables the same allocation. A zero ratio keeps that column sized from its content; a table minimum width alone adds space in proportion to content widths.

4. Create a Panel

let panel = Panel::from_text("Important message here")
    .title("Notice")
    .subtitle("v1.0")
    .width(50);

console.print_renderable(&panel);

5. Print a Rule

// Simple rule
console.rule(None);

// Rule with title
console.rule(Some("Section"));

// Styled rule
let rule = Rule::with_title("Custom")
    .style(Style::parse("cyan bold").unwrap_or_default())
    .align_left();
console.print_renderable(&rule);

Feature Reference

Markup Syntax

Markup Effect
[bold]text[/] Bold text
[italic]text[/] Italic text
[underline]text[/] Underlined text
[red]text[/] Red foreground
[on blue]text[/] Blue background
[bold red on white]text[/] Combined styles
[#ff0000]text[/] Hex color
[rgb(255,0,0)]text[/] RGB color
[color(196)]text[/] 256-color palette

Text Wrapping and Justification

Normal Console printing wraps text at the active width. Set a prepared Text's justification for full spacing between words:

let mut text = Text::new("A paragraph with enough words to wrap across several lines.");
text.justify = JustifyMethod::Full;
console.print_text(&text);

Only nonfinal wrapped lines are stretched. Explicit line breaks end the paragraph, and final lines retain natural spacing. Styles and hyperlinks survive inserted spaces. Tab stops use terminal cell widths for wide characters and combining marks. Table columns also accept JustifyMethod::Full.

Spaces discarded at a line break do not reduce the width of the next line. This also applies to expanded tabs, so following words and styled Unicode text can use the full available width inside bounded layouts.

Themes (Named Styles)

Python Rich defines many named styles (e.g. rule.line, table.header). rich_rust ports this theme system and lets you add custom names:

use rich_rust::prelude::*;

let theme = Theme::from_style_definitions([("warning", "bold red")], true).unwrap();
let console = Console::builder().theme(theme).build();
console.print("[warning]Danger[/]");

Style Attributes

Style::new()
    .bold()
    .italic()
    .underline()
    .strikethrough()
    .dim()
    .reverse()
    .foreground(Color::parse("red").unwrap())
    .background(Color::parse("white").unwrap())

Color Systems

System Colors Detection
Standard 16 Basic terminals
256-color 256 Most modern terminals
Truecolor 16M iTerm2, Windows Terminal, etc.

Console::builder().no_color() explicitly disables ANSI styling, including attributes and hyperlinks, even when terminal detection or force_terminal(true) would otherwise enable it. A later color_system(...) call re-enables styling; the last explicit color choice wins. Automatic detection respects a nonempty NO_COLOR environment variable. An explicit color system overrides automatic detection.

Terminal controls follow the Console's terminal capabilities independently of color. Nonterminal output omits structured cursor and screen commands. Built-in clear, title, bell, cursor, and alternate-screen helpers also omit commands on dumb terminals. The helpers participate in scoped capture and recording; capturing an alternate-screen command does not change the physical screen. Use the raw terminal::control writer functions when unconditional control sequences are required.

Box Styles

Panel::from_text("content").rounded()  // ╭─╮ (default)
Panel::from_text("content").square()   // ┌─┐
Panel::from_text("content").heavy()    // ┏━┓
Panel::from_text("content").double()   // ╔═╗
Panel::from_text("content").ascii()    // +-+

Progress Bars

let mut bar = ProgressBar::with_total(100).width(40);
bar.update(75);
console.print_renderable(&bar);

Standalone bars adapt to their allocated width, including inside narrow panels. They keep the percentage or a visible bar ahead of long descriptions and optional transfer metrics. Styled Unicode descriptions and links survive cropping; tabs and newlines flatten to one row. Count advances saturate instead of overflowing, unrepresentable ETA estimates return None, and updating a completed bar below its total returns it to active progress.

Multiple Progress Tasks

Progress manages independent tasks in one live display. Cloned handles can be passed to worker threads; advance updates counts atomically. Unknown totals use an animated spinner until set_total or finish_task is called.

use rich_rust::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let progress = Progress::new(Console::new().shared());
    let download = progress.add_task("Downloading", Some(100));
    let scan = progress.add_task("Scanning", None);
    progress.start()?;

    let worker = progress.clone();
    worker.advance(download, 40)?;
    worker.advance(scan, 12)?;
    progress.update(download, 100)?;
    progress.finish_task(scan)?;
    progress.stop()?;
    Ok(())
}

Task snapshots expose counts, active elapsed time, speed, and estimated remaining time. Tasks can be paused, resumed, hidden, reset, or removed. Dropping a worker handle leaves the shared display running; dropping the last handle stops it. By default, files and pipes receive one final snapshot on stop. Custom progress columns use the same immutable task snapshot and share column widths across all visible tasks. Built-in columns include descriptions, bars, spinners, percentages, counts, elapsed/remaining time, file sizes, and transfer rates.

Custom Columns and Tracking

Use with_columns to choose a display, set_field for plain or styled task metadata, and track to count iterator items automatically:

use std::sync::Arc;
use rich_rust::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let progress = Progress::new(Console::new().shared()).with_columns(vec![
        Arc::new(DescriptionColumn),
        Arc::new(BarColumn::new()),
        Arc::new(MofNCompleteColumn),
        Arc::new(TaskFieldColumn::new("file")),
    ]);
    let mut items = progress.track(["main.rs", "lib.rs"], "Reading entries");
    let task = items.task_id();
    progress.start()?;
    for name in items.by_ref() {
        progress.set_field(task, "file", Text::styled(name, Style::new().bold()))?;
    }
    if let Some(error) = items.tracking_error() {
        return Err(error.into());
    }
    progress.stop()?;
    Ok(())
}

ProgressColumn::with_table_column sets width, alignment, and wrapping. Implement ProgressColumn or pass a Fn(&TaskSnapshot) -> Text closure for custom cells. Use set_columns to replace a running display's column configuration. Callbacks run outside the task and lifecycle locks, so a custom column may stop or restart its own display. Uncontended lifecycle calls finish synchronously. A call made during another lifecycle operation publishes its desired state and returns; the current operation applies the latest request before it finishes. Redundant refresh calls coalesce, and is_started() reports the requested state. Fields retain styles and hyperlinks, remain literal text, and survive task reset.

Iterator and I/O Tracking

use rich_rust::prelude::*;
use std::io::{self, Cursor};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let progress = Progress::new(Console::new().shared());
    progress.start()?;

    let mut items = progress.track(1..=3, "Processing");
    let sum: u32 = items.by_ref().sum();
    assert_eq!(sum, 6);
    assert!(items.tracking_error().is_none());

    let read_task = progress.add_task("Reading", Some(7));
    let write_task = progress.add_task("Writing", Some(7));
    let mut reader = progress.wrap_read(Cursor::new(b"payload"), read_task)?;
    let mut writer = progress.wrap_write(Vec::new(), write_task)?;
    io::copy(&mut reader, &mut writer)?;
    assert!(reader.tracking_error().is_none());
    assert!(writer.tracking_error().is_none());
    assert_eq!(writer.into_inner(), b"payload");

    progress.stop()?;
    Ok(())
}

track infers a total only from an exact size hint. It counts items as they are consumed, before the loop body processes them; dropping it early preserves partial progress. Its ProgressIterator adapter (also named ProgressIter) is fused: the first exhaustion stops further polling, and a task created with an unknown total is finished using the consumed count. track_task attaches to an existing task without resetting its total, count, or timing configuration. Exhausting one attached iterator does not finalize that shared task; call finish_task when all producers have completed an unknown-total task.

track_read and track_write create byte-counting tasks; wrap_read and wrap_write attach to existing tasks. They count bytes read or accepted by the writer, including successful partial transfers before a later error. These counts do not imply durable storage. Empty operations, errors, and flushes add no bytes. Readers also support BufRead when the source does: fill_buf peeks without counting, and consume counts the observed bytes. Readers and writers forward Seek without counting changes of position.

Unknown-total I/O tasks remain open after EOF, flush, or drop; call finish_task when the application knows the complete operation succeeded. Task removal or counter overflow is exposed by tracking_error() without discarding iterator items or changing underlying I/O results. Adapters do not start or stop the display.

Trees

let details = Panel::from_text("Ready\nWaiting for work");
let tree = Tree::with_label("Root")
    .child(TreeNode::new("A long label that wraps at the console width"))
    .child(TreeNode::from_renderable(&details));
console.print_renderable(&tree);

Text labels wrap within their allotted width, retaining styles, hyperlinks, and ancestor guides on continuation lines. TreeNode::from_renderable and Tree::from_renderable accept owned or borrowed renderables, including panels and tables, and render them using the enclosing console and available width. tree.render_with_width(width) provides bounded rendering with a default console when working directly with segments.

Tree::style and TreeNode::style set an inherited base style for labels; explicit label spans and child-renderable styles take precedence. Each node's guide_style controls the branches leading to its children, including their continuation lines. Ancestor guides keep their own styles across nested branches. For example, a colored subtree can use a different guide weight:

let tree = Tree::with_label("Jobs")
    .style(Style::parse("cyan")?)
    .guide_style(Style::parse("dim")?)
    .child(TreeNode::new("Active")
        .style(Style::parse("green")?)
        .guide_style(Style::parse("bold green")?)
        .child(TreeNode::new("Building")))
    .child(TreeNode::new("Queued"));

With the default Unicode guides, bold selects heavy branches and underline2 selects double branches. Explicit TreeGuides choices retain their selected alphabet. Guide weight flags select glyphs without adding bold or double underline terminal attributes to the guides. Hidden roots still pass their styles to descendants; sibling overrides remain independent.

TreeNode::from_measurable and Tree::from_measurable also retain a child's RichMeasure implementation. Tree measurement accounts for visible guides, icons, and labels without rendering children. Use Columns::push_measurable(&tree) to preserve that natural width and reflow the tree as the terminal narrows.

TreeNode::label() now returns Option<&Text>: text labels return Some, and renderable labels return None. Callers inspecting a label should handle both.

Columns of Renderables

let cards = Columns::from_renderables([
    Panel::from_text("Build\nready"),
    Panel::from_text("Upload\nwaiting"),
])
.column_count(2)
.gutter(2);
console.print_renderable(&cards);

Columns preserve multiline cells and render owned or borrowed children at their allocated width. Use push to mix renderable types, column_first(true) to fill down columns, or right_to_left(true) to reverse their visual order. Unmeasured renderables conservatively use the available width: set column_count for side-by-side placement, or use push_measurable with a RichMeasure implementation for automatic packing. Packing reevaluates unequal-width groups as the available width changes. The existing equal_width(true).expand(true) spacing follows this crate's established behavior; complete Python Rich layout parity is not claimed.

Render Groups

use rich_rust::renderables::{Group, Panel};
use rich_rust::Text;

let body = Group::new()
    .push_measurable(Text::new("Download complete"))
    .push_measurable(Text::new("Ready to install"));
let panel = Panel::default().expand(false).with_measurable(body);
console.print_renderable(&panel);

Groups stack children vertically, preserve styles and hyperlinks, and avoid adding a blank row after an already terminated panel or table. Explicit height limits apply to the combined flow. Owned groups support Live and Layout; borrowed children work when their lifetimes permit them.

fit(true) is now the default and controls natural-width measurement, matching Python Rich's meaning of the option. It no longer concatenates children inline. Use push_measurable for natural widths and push for unmeasured children, which conservatively use the available width. fit(false) reports the full available width. Boxed children must implement Send + Sync, as with Columns.

Responsive Padding and Alignment

let content = Panel::from_text("Ready\nWaiting for work");
let padded = Padding::from_renderable(content, (1, 2)).expand(false);
let centered = Align::from_measurable(padded)
    .center()
    .vertical(VerticalAlignMethod::Middle)
    .height(10);
console.print_renderable(&centered);

These wrappers accept owned or borrowed renderables and render the child again at the available dimensions on every draw. Explicit heights constrain output; ordinary text can scroll beyond the terminal's current height.

Align::from_measurable measures the child before rendering it once at its natural width, then positions that block inside the available canvas. This allows expanding panels, Syntax, and measured compositions to center or align right without filling the canvas first. Align::with_measurable applies the same behavior to a configured alignment frame. The from_renderable and with_renderable constructors continue to render children at the allocated width.

Live Updates

use rich_rust::prelude::*;

fn main() -> std::io::Result<()> {
    let console = Console::new().shared();
    let live = Live::new(console.clone()).renderable(Text::new("Loading..."));

    live.start(true)?;
    live.update(Text::new("Done!"), true);
    live.stop()?;

    Ok(())
}

For external writers, use live.stdout_proxy() / live.stderr_proxy() to route output through the Live display.

Proxy write_all, formatted writes, and flush now report destination I/O errors. Direct write reports the source bytes it accepted; an output error after acceptance is deferred to the next write or flush, before any new input is accepted. Always flush a proxy to emit its final partial line and observe pending failures. Attempted output is consumed even if the destination failed partway through, so retries do not automatically replay a partially printed line. A buffered tail that has not been attempted remains available.

Cloned Live handles share the display. Dropping a worker's clone leaves the other handles active; the last public handle stops its registration. Nested displays may stop in any order. The first display retains responsibility for cursor, screen, redirection, and refresh settings until the last nested display stops, even if the first display's content has already been removed.

Live render factories run outside the console writer lock. A factory can stop its display without deadlocking ordinary printing; a frame prepared for an obsolete registration is discarded before output. Final rendering and terminal cleanup are serialized with console output, so concurrent log messages stay above the display while its final frame is being prepared.

Static renderables also render from a snapshot outside the content lock, so a render callback can replace its own content. Replaced renderables and factory captures are dropped outside their locks. update(content, true) refreshes immediately and prevents older prepared content from overwriting that refresh. With update(content, false), an in-flight frame may finish its existing snapshot; the next render uses the replacement. A configured render factory continues to take precedence over static content.

If start fails during terminal setup or the initial refresh, it removes that registration and attempts cursor/screen restoration before returning the error. A later start can retry. A child or replacement display started by a callback keeps its own registration. stop now returns the first final-output or cleanup I/O error while still attempting all terminal cleanup controls; dropping the last handle performs the same cleanup on a best-effort basis.

Starts on a shared Console serialize terminal initialization. Teardown restores the Console writer and stdio overrides before a new root can start, then joins reader/pump threads after releasing lifecycle locks. Stopping from a pump callback does not join that calling thread. A new capture request returns WouldBlock until the retiring pump actually exits.

Process-wide stdout/stderr capture has one owner at a time, including when different Consoles request different streams. A conflicting start returns io::ErrorKind::WouldBlock before registering the display or changing cursor and screen state. Reuse the active Console for nested displays, disable both redirection options, or retry after the existing capture finishes shutdown. Ownership is retained through failed setup, terminal restoration, and thread retirement. Redirection checks the current stdout descriptor, so a Console created during capture can retry after the original terminal is restored.

On Unix, each capture owns its saved terminal descriptors and closes them after restoring stdout/stderr. Repeated capture cycles therefore do not accumulate saved handles, and those private copies are not inherited by child processes.

Captured stdout and stderr are buffered by line, with separate Unicode and ANSI state for each stream. Partial reads do not add newlines or mix fragments from different streams. Invalid UTF-8 becomes replacement characters within its own line, and decoded ANSI follows the Console's color policy. On Unix, stopping restores the process descriptors and wakes the capture readers, then each reader drains a finite snapshot of the bytes pending in its pipe. The pump processes all reader messages and flushes partial lines before releasing capture ownership. Quiet inherited or duplicated writers cannot keep those readers alive. Writes through retained pipe handles after shutdown may fail with BrokenPipe; they are not redirected to the restored terminal. Saved terminal descriptors are closed after each capture, including failed startup.

A stop called from the pump's own render callback returns before that pump finishes its pending output. Rendering callbacks and output writers can still take arbitrary time; the finite drain is not a wall-clock deadline. The non-Unix reader path still depends on writer closure. Flushing a process stdout/stderr handle does not send a flush event through its pipe; use a proxy writer and its flush() method when partial output must be displayed immediately.

The capture pump continues draining both streams after a delivery error and attempts both buffered tails. An ordinary stop reports its first delivery error after restoring terminal state and joining the workers, unless an earlier cleanup error takes precedence. A stop called from the pump itself cannot report errors that occur after that callback returns.

When panic unwinding is enabled, a panic in the final renderer or a final render hook resumes after Live attempts the required terminal and stdio cleanup. Dropping the last handle during an existing unwind skips final user rendering and hooks. Cleanup preserves earlier log rows and keeps any child or replacement display started by the callback active. This does not apply to panic = "abort" builds, which terminate without unwinding.

Layouts

use rich_rust::prelude::*;

let mut layout = Layout::new().name("root");
layout.split_column(vec![
    Layout::new()
        .name("header")
        .size(3)
        .renderable(Panel::from_text("Header")),
    Layout::new().name("body").ratio(1),
]);

if let Some(body) = layout.get_mut("body") {
    body.split_row(vec![
        Layout::new().name("left").ratio(1).renderable(Panel::from_text("Left")),
        Layout::new().name("right").ratio(2).renderable(Panel::from_text("Right")),
    ]);
}

console.print_renderable(&layout);

On the alternate screen, layout.refresh_screen(&console, "right")? redraws the named pane after a content update. Redraw the full layout when the terminal size or split geometry changes.

Prompts and Password Input

use rich_rust::console::Console;
use rich_rust::interactive::{Prompt, PromptError};

fn read_password(console: &Console) -> Result<String, PromptError> {
    Prompt::new("Password")
        .password(true)
        .max_length(1024)
        .ask(console)
}

Password mode reads from an actual terminal with echo disabled, preserves leading and trailing spaces, and never displays configured defaults. Input limits apply during entry. Raw mode enabled by the prompt is released after submission, cancellation, or an error; a raw mode already owned by the caller remains active. ask_from accepts a caller-provided buffered reader without changing terminal settings, so the caller owns that reader's echo behavior.

Use IntPrompt for i64, FloatPrompt for f64, or TypedPrompt<T> for any type that implements FromStr:

use rich_rust::prelude::*;

fn read_port(console: &Console) -> Result<u16, PromptError> {
    TypedPrompt::<u16>::new("Port")
        .default(8080)
        .validate(|port| {
            if *port == 0 {
                Err("Choose a port between 1 and 65535.".to_owned())
            } else {
                Ok(())
            }
        })
        .ask(console)
}

Typed prompts retry parsing and validation failures, while EOF, read errors, and input-limit errors return immediately. Ordinary typed input is trimmed at both ends; password input retains its exact whitespace. Parser errors use a generic message that does not expose the input or the parser's error text. Float parsing accepts Rust's f64 syntax, including infinities and NaN; use a validator when only finite values or a particular range are meaningful.

Typed defaults are cloned directly and validated when selected, without parsing their display text. Only .default(value) requires Clone + Display; prompts without defaults need only FromStr. Noninteractive prompts require a default and validate it without reading or printing. Ordinary string defaults also pass through normalization and validation. Displayed defaults remain literal when prompt-label markup is enabled, and password defaults are always hidden.

Select resolves default values and display labels case-insensitively and always returns the selected Choice::value. An unknown configured default is a validation error before any input or output. Choice labels and displayed defaults remain literal, even when markup is enabled for the prompt label.

Logging

use rich_rust::prelude::*;
use log::LevelFilter;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let console = Console::new().shared();
    RichLogger::new(console)
        .level(LevelFilter::Info)
        .show_path(true)
        .init()?;

    log::info!("Server started");
    Ok(())
}

Note: log macros come from the log crate; add log = "0.4" to your Cargo.toml.

Log records use separate time, level, message, and source columns. Wrapped and multiline messages stay aligned, and source basenames link to the original paths and line numbers. Narrow consoles stack fields when the metadata would otherwise leave no room for the message. Styles such as log.message, log.path, and logging.level.warning follow the active console theme.

Messages use ReprHighlighter by default. Configure .highlighter(custom) to supply a highlighter, or .highlighter(rich_rust::highlighter::NullHighlighter) to disable representation highlighting. Keyword highlighting remains controlled separately by .keywords(...).

Tracing: enable rich_rust feature tracing and install RichTracingLayer if you use the tracing ecosystem.

The layer includes parent spans from root to leaf, with current field values, so a request log can read request{id=42}: query{table=users}: completed. Fields recorded after span creation replace their earlier values, and explicit event parents (including parent: None) are respected. Only the event message is parsed as optional Rich markup; span names and structured fields stay literal. Use the layer with a subscriber supporting span lookup, such as tracing_subscriber::registry().

With RichLogger::rich_tracebacks(true), the tracing layer renders the actual source chain of each typed error on an ERROR event, labeled with its field name:

let error = std::io::Error::other("could not read configuration");
tracing::error!(error = &error as &dyn std::error::Error, "request failed");

Error messages and causes remain literal, including markup-looking text. Source cycles and excessive chain depth are bounded. The event and its reports pass through console hooks and output together, so concurrent logs cannot split them. %error and ?error provide formatted text only and retain the existing callsite traceback behavior. Error fields on spans remain contextual field text.

Capturing and paging a report

Console::capture returns the formatted output from a group of print calls. It uses the console's width, colors, and theme. capture_segments returns the individual styled segments. Other threads can keep writing to the same console during either capture.

use rich_rust::prelude::*;

let console = Console::new();
let summary = console.capture(|c| {
    c.print("[bold]Build complete[/]");
    c.print_plain("3 targets passed");
});
let paged = Pager::new().allow_color(false).page(&console, |c| {
    c.print_renderable(&Rule::with_title("Results"));
    c.print_plain("3 targets passed");
});
paged.expect("could not display the report");

Text, HTML and SVG export

Export terminal output to shareable files:

use rich_rust::prelude::*;

let console = Console::builder().record(true).build();
console.print("[bold green]Hello[/]");

let text = console.export_recorded_text(false, false);
assert_eq!(text, "Hello\n");
let ansi = console.export_recorded_text(false, true);
let html = console.export_html(false);  // false = don't clear buffer
let svg = console.export_svg(true);     // true = clear buffer after

Note: The HTML/SVG exports follow Python Rich's export templates (including optional terminal-window chrome). SVG is rendered with SVG primitives (<text>, <rect>, clip paths), so it works in browsers and in many SVG-capable viewers (no <foreignObject> required).

Recorded text and titles remain literal even when they contain template tokens such as {foreground} or {lines}. HTML escapes hyperlink attributes. SVG text, backgrounds, and styled runs share terminal-cell geometry for CJK, emoji, and combining marks, and clipping includes the final row without a trailing newline. Custom SVG identifiers are encoded when necessary for valid XML/CSS references; invalid font ratios fall back to the default geometry.

For a quick demo of export capabilities, run:

cargo run --bin demo_showcase --features showcase -- --export

Syntax Highlighting (requires syntax feature)

use rich_rust::prelude::*;

let code = "fn main() {\n    run();\n}\n";
let syntax = Syntax::new(code, "rust")
    .line_range(1..=3)
    .line_numbers(true)
    .highlight_lines([2])
    .theme("Solarized (dark)");

console.print_renderable(&syntax);

Choose .theme("ansi_dark") or .theme("ansi_light") to use the terminal's native standard/bright colors with a transparent background. Comments are dim, unclassified text keeps the terminal's foreground, and unpadded rows retain their natural width. Explicit padding creates a rectangular block, and background_color(...) supplies a background when desired. Both themes work with highlight, source excerpts, line numbers, and Markdown's block/inline theme builders. A custom theme registry containing the same name takes precedence. Token colors follow Syntect's lexical scopes, so classifications can differ from Pygments for some languages.

Rust highlighting preserves nested block comments, quoted strings, and raw strings across lines, including when line_range starts inside a token. Syntect receives the source tabs and line endings before display formatting, preserving newline-sensitive and tab-sensitive grammar rules. Tabs expand at terminal cell stops, including after wide Unicode characters; indentation guides are drawn after highlighting.

Use Syntax::dedent(true) for indented snippets embedded in Rust source. It removes the whitespace prefix shared by nonblank lines while preserving relative indentation and physical source line numbers. plain_text() retains the original input. Custom syntax sets should be loaded with newline support; load_syntaxes_from_folder now does this automatically.

stylize_range overlays a source range using one-based physical line numbers and zero-based Unicode character columns after dedenting and tab expansion. Ranges retain their alignment through excerpts, wrapping, and cropping; stylize_range_before places a range style beneath existing styles.

In layouts and other containers, Syntax respects allocated width and explicit height, including empty viewports. Tab expansion and padding are bounded by the visible area, while horizontal cropping preserves lexer context for following lines. Direct Syntax::render(None) and render(Some(0)) retain natural-width output.

Enable .word_wrap(Some(usize::MAX)) to wrap code to the available interior. Syntax reserves horizontal padding and the line-number gutter before wrapping, preserving source characters as a panel narrows. A smaller explicit wrap limit still caps the code width. Disabling wrapping keeps horizontal cropping.

Markdown Rendering (requires markdown feature)

use rich_rust::prelude::*;

let md = Markdown::new("# Header\n\nParagraph with **bold**.");
console.print_renderable(&md);

Use Markdown::justify(JustifyMethod::Full) for justified paragraphs, or choose Center or Right. Prose inside lists and blockquotes honors the remaining width after its indentation. Headings, code blocks, and table cells retain their own layout rules.

With both markdown and syntax enabled, code_theme("InspiredGitHub") selects a palette for fenced and indented code blocks. Enable highlighted inline code with inline_code_lexer("rust"); it follows the block palette unless inline_code_theme("base16-ocean.dark") selects a separate one. Inline token styles survive paragraph wrapping, links, emphasis, and table layout.

code_block_style now also applies to highlighted blocks and their padding. Explicit attributes override the syntax theme, while unspecified token colors remain intact. Unknown languages and themes fall back independently and retain literal source text. With only markdown enabled, these syntax configuration methods keep the ordinary styled-code output.

Code blocks reserve their padding before wrapping, so narrow layouts retain the complete source instead of cropping characters at row boundaries. Literal spaces, blank source rows, and four-cell tab stops are preserved. Plain, unlabeled, and indented blocks use rectangular padding like highlighted blocks; side padding shrinks in very small allocations to leave room for wide characters. Empty fences produce a padded blank block.

This fixes a data-loss behavior also present in Python Rich 13.9.4: its narrow fenced-code reference drops both semicolons from a two-statement example. The conformance corpus retains that original output and an independently generated, strictly compared correction. See the conformance notes.

Through Renderable, Markdown honors explicit height limits while retaining styles and hyperlinks in visible rows. Zero-width or zero-height allocations produce no output. For both Markdown and Syntax, terminal max_height alone allows ordinary scrolling output; an explicit height is capped by max_height.

Pretty / Inspect

Rust doesn't have Python-style runtime reflection, so rich_rust's equivalents are Debug-based and deterministic.

use rich_rust::prelude::*;

#[derive(Debug)]
struct Config {
    mode: String,
    retries: usize,
}

let console = Console::new();
let cfg = Config {
    mode: "safe".to_string(),
    retries: 3,
};

console.print_renderable(&Pretty::new(&cfg));
inspect(&console, &cfg);

Pretty collapses standard Debug groups when they fit the available width. Use .compact(true) for compact output or .compact(false) for fully expanded Debug output. It uses the console's pretty theme and configured highlighter; .highlight(false) disables token highlighting for one value, and .style(...) overlays an explicit style. Styles and hyperlinks survive wrapping.

Pretty also implements RichMeasure, so Panel::with_measurable(Pretty::new(&cfg)) can fit a borrowed value without speculative rendering. Measurement invokes Debug once and does not invoke the highlighter. Inspect wraps its literal type name, uses the active console for field tables, and shares any explicit height limit between the header and body. Empty allocations do not format the value.

For large diagnostics, opt into presentation limits:

let bounded = Pretty::new(&cfg).max_depth(2).max_length(8).max_string(80);
console.print_renderable(&bounded);

Depth is counted from zero at the root. Container limits show ... +N for omitted entries, and string limits show a quoted prefix followed by +N for omitted Unicode scalars. Escapes and character literals remain intact. Inspect offers the same builders; with .expand_fields(true), it applies the limits to each field value while retaining every field row. Unrecognized custom Debug output remains unchanged. These options limit the displayed result: the value's Debug implementation still runs and is captured in full.

Tracebacks

Traceback is a renderable inspired by Python Rich's rich.traceback.

You can construct it from explicit frames (deterministic, great for tests/fixtures), or capture a real runtime backtrace when the backtrace feature is enabled.

use rich_rust::prelude::*;

let console = Console::new();
let traceback = Traceback::new(
    vec![
        TracebackFrame::new("<module>", 14),
        TracebackFrame::new("level1", 11),
        TracebackFrame::new("level2", 8),
        TracebackFrame::new("level3", 5),
    ],
    "ZeroDivisionError",
    "division by zero",
);

console.print_exception(&traceback);

For a normal Rust error, Console::print_error renders the message and its Error::source() chain without requiring the backtrace feature:

use rich_rust::Console;

let error = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "settings.toml");
Console::new().print_error(&error);

Traceback::from_error(&error) creates an owned report that can outlive the error. Use .exception_type("ConfigError") to supply a known application type name, or push_frame to attach known stack frames. Cause traversal detects cycles and caps chains at 64 sources, with a visible notice when it stops. Messages retain literal text and wrap at the allocated width; frame filenames remain visible when source files are unavailable.

Automatic capture (requires backtrace feature):

use rich_rust::prelude::*;

let console = Console::new();
let traceback = Traceback::capture("MyError", "something went wrong");
console.print_exception(&traceback);

Architecture

┌─────────────────────────────────────────────────────────────┐
│                         Console                              │
│  (Central coordinator: options, rendering, I/O)             │
└─────────────────────────┬───────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                      Renderables                             │
│  (Text, Table, Panel, Rule, Tree, Progress, Syntax, etc.)   │
│  Expose render() + optional RichMeasure for sizing           │
└─────────────────────────┬───────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                        Segments                              │
│  (Atomic unit: text + optional style + control codes)       │
└─────────────────────────┬───────────────────────────────────┘
                          │
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                     ANSI Codes + Output                      │
│  (Style diffing, escape sequences, terminal write)          │
└─────────────────────────────────────────────────────────────┘

Render Pipeline (Step-by-Step)

  1. Input — A string (optionally with markup) or a renderable (Table, Panel, Tree, etc.).
  2. Markup parsing — [bold red]text[/] is parsed into Text + styled spans.
  3. Renderable layout — Each renderable converts itself into Vec<Segment>.
  4. Segment stream — Segments carry plain text + optional Style + control codes.
  5. ANSI generation — Styles are diffed and rendered to ANSI SGR (or skipped if disabled).
  6. Output — Console writes the final stream to the configured Write.

Module Structure

src/
├── lib.rs           # Crate root, prelude
├── color.rs         # Color system (4/8/24-bit)
├── style.rs         # Style attributes (bold, italic, etc.)
├── segment.rs       # Atomic rendering unit
├── text.rs          # Rich text with spans
├── markup/          # Markup parser ([bold]...[/])
├── measure.rs       # Width measurement protocol
├── console.rs       # Console I/O coordinator
├── terminal.rs      # Terminal detection
├── cells.rs         # Unicode cell width
├── box.rs           # Box drawing characters
└── renderables/
    ├── align.rs     # Alignment
    ├── columns.rs   # Multi-column layout
    ├── padding.rs   # Padding
    ├── panel.rs     # Boxed panels
    ├── progress.rs  # Progress bars, spinners
    ├── rule.rs      # Horizontal rules
    ├── table.rs     # Tables with auto-sizing
    ├── tree.rs      # Hierarchical trees
    ├── syntax.rs    # Syntax highlighting (optional)
    ├── markdown.rs  # Markdown rendering (optional)
    └── json.rs      # JSON pretty-print (optional)

Feature Parity (Python Rich)

See FEATURE_PARITY.md for the authoritative matrix and RICH_SPEC.md for detailed behavior notes.

Implemented

  • Markup ([bold red]text[/]), styles, colors, hyperlinks, and ANSI decoding
  • Styled Text composition that keeps child hyperlinks and local overrides
  • Tables, panels, rules, trees, columns, padding, alignment
  • Natural Table measurement and measured nested cells for composed layouts
  • Owned/borrowed renderable Tree labels and Columns entries, with multiline layout
  • Terminal control renderable (Control) + control-code helpers
  • Progress bars, spinners, shared tasks, custom columns/fields, and iterator/I/O tracking
  • Live updating / dynamic refresh (Live)
  • Layout engine (Layout) with bounded integer allocation and named alternate-screen refresh
  • Logging handler integration (RichLogger)
  • HTML/SVG export (Console::export_html / Console::export_svg)
  • Syntax highlighting (feature syntax) (see FEATURE_PARITY.md for remaining parity gaps)
  • Markdown rendering with active console themes and explicit style overrides (feature markdown)
  • JSON pretty-print (feature json) (see FEATURE_PARITY.md for remaining parity gaps)
  • Traceback rendering (Traceback, Console::print_exception) (explicit frames for deterministic tests; optional Traceback::capture via feature backtrace)
  • Unicode width handling + auto color downgrade

Notes

  • rich_rust is output-focused, but it also includes small, pragmatic interactive helpers (prompts, pager, status) for common CLI workflows.
  • These capabilities do not imply complete Python Rich API or output parity. The matrix records covered reference cases and remaining limitations, including Columns measurement and spacing differences.

Demo Showcase: demo_showcase

We’re building a standalone demo_showcase binary that shows off rich_rust end-to-end in a single cohesive narrative (product-grade visuals, not just a grab bag of examples).

Narrative

Nebula Deploy — a fictional deployment/release assistant. It naturally justifies a live dashboard, progress, structured data views, and a deliberate failure for traceback/debug tooling.

Scene Flow

--list-scenes must output stable names (used by --scene <name>), in this order (with a one-line purpose + any feature-gate notes):

Scene Purpose Exercises
hero Introduce Nebula Deploy and the visual "brand". markup, Style/Theme, Emoji, Rule/Panel
dashboard Show the live split-screen dashboard (services + pipeline + logs). Layout, Live, Progress, logging
markdown Show a runbook / release notes view. Markdown (feature markdown)
syntax Show a config/code snippet view. Syntax (feature syntax)
json Show an API payload view. Json (feature json)
table Show data tables with various styles. Table with sorting, alignment
panels Show boxed content with titles. Panel with borders, padding
tree Show hierarchical data structures. Tree with nested nodes
layout Show split-screen layouts. Layout with columns/rows
emoji_links Show emoji and hyperlink support. Emoji, OSC8 links
debug_tools Walk through a failure and recovery workflow. Pretty/Inspect, Traceback
tracing Show tracing integration. RichTracingLayer (feature tracing)
traceback Show error tracebacks. Traceback rendering
export Export the run to artifacts for sharing. Console::export_html, Console::export_svg
outro Wrap up with a crisp summary and next steps. Table, Tree, Rule

Feature-gated scenes must self-report clearly when disabled (and how to enable the required --features ...).

CLI Contract (Explicit + Stable)

The goal is (a) safe in CI/pipes and (b) tunable for maximum “wow” in a real terminal.

demo_showcase --help should read like a real CLI:

demo_showcase — Nebula Deploy (rich_rust showcase)

USAGE:
    demo_showcase [OPTIONS]

OPTIONS:
    --list-scenes               List available scenes and exit
    --scene <name>              Run a single scene (see --list-scenes)
    --seed <u64>                Seed deterministic demo data (default: 0)
    --quick                     Reduce sleeps/runtime (CI-friendly)
    --speed <multiplier>        Animation speed multiplier (default: 1.0)

    --interactive               Force interactive mode
    --no-interactive            Disable prompts/pager/etc
    --live                      Force live refresh
    --no-live                   Disable live refresh; print snapshots
    --screen                    Use alternate screen (requires live)
    --no-screen                 Disable alternate screen

    --force-terminal            Treat stdout as a TTY (even when piped)
    --width <cols>              Override console width
    --height <rows>             Override console height
    --color-system <mode>       auto|none|standard|eight_bit|truecolor
    --emoji                     Enable emoji (default)
    --no-emoji                  Disable emoji
    --safe-box                  Use ASCII-safe box characters
    --no-safe-box               Use Unicode box characters (default)
    --links                     Enable OSC8 hyperlinks
    --no-links                  Disable OSC8 hyperlinks

    --export                    Write an HTML/SVG bundle to a temp dir
    --export-dir <path>         Write an HTML/SVG bundle to a directory

    -h, --help                  Print help and exit

Export Usage

Export captures the full demo output and writes two files:

  • demo_showcase.html — Standalone HTML with inline CSS. Opens in any browser.
  • demo_showcase.svg — Scalable vector graphic rendered with SVG text and shapes.
# Quick export to temp directory (prints path)
cargo run --bin demo_showcase --features showcase -- --export

# Export to specific directory
cargo run --bin demo_showcase --features showcase -- --export-dir ./output

# Recommended flags for clean export
cargo run --bin demo_showcase --features showcase -- \
    --export-dir ./output \
    --no-interactive \
    --color-system truecolor \
    --width 100 \
    --quick

Viewing exported files:

  • HTML: Open directly in any browser. Colors and styles are preserved.
  • SVG: Open in any modern browser (Chrome, Firefox, Safari). The SVG uses only standard SVG primitives (text, rects, clip paths), so it is broadly compatible.

Defaults ("auto")

  • interactive=auto means: interactive only when stdout is a TTY and TERM is not dumb/unknown.
  • live=auto means: live = interactive.
  • screen=auto means: screen = live && interactive (TTY-only).
  • links=auto means: hyperlinks only when interactive; override with --links / --no-links.
  • FORCE_COLOR may force color output, but must not enable interactive/live behavior; use --force-terminal to intentionally override TTY checks.

Safety requirements

  • If stdout is not a TTY and --force-terminal is not set:
    • disable live refresh and alternate screen
    • disable prompt/pager helpers
    • print static snapshots only
  • No scene may require user input to terminate.
  • No infinite loops; any animation must be time-bounded and/or gated on TTY.
  • Unknown flags must yield a concise error plus a --help hint.
  • --scene must validate known names and print an “available scenes” list on error.

Implementation note: keep CLI parsing dependency-light (hand-rolled; no large CLI frameworks).


Troubleshooting

Colors not showing

Symptom: Text prints without colors in terminal.

Causes & Fixes:

  1. Piped output: Colors disabled when stdout isn't a TTY. Use FORCE_COLOR=1 env var.
  2. Terminal doesn't support colors: Try a modern terminal (iTerm2, Windows Terminal).
  3. TERM variable: Ensure TERM is set correctly (xterm-256color, etc.).

Unicode characters garbled

Symptom: Box characters display as ? or mojibake.

Fixes:

  1. Use .ascii() variant: Panel::from_text("...").ascii()
  2. Set terminal encoding to UTF-8
  3. Use a font with box-drawing characters (most monospace fonts have them)

Table columns too wide/narrow

Symptom: Table layout doesn't fit terminal.

Fixes:

  1. Get terminal width: console.width()
  2. Set explicit column widths: Column::new("...").width(20)
  3. Set min/max widths: Column::new("...").min_width(10).max_width(40)

Markup not parsing

Symptom: [bold]text[/] prints literally.

Fixes:

  1. Use console.print() not console.print_plain()
  2. Check for unbalanced brackets
  3. Escape literal brackets: \[not markup\]

Windows console issues

Symptom: Escape codes visible or wrong colors on Windows.

Fixes:

  1. Use Windows Terminal (modern) instead of cmd.exe
  2. Enable virtual terminal processing: SetConsoleMode with ENABLE_VIRTUAL_TERMINAL_PROCESSING
  3. rich_rust auto-detects this, but old cmd.exe may not support it

Limitations

  • No input: This is an output library; use crossterm or dialoguer for input
  • Limited input: rich_rust includes prompts/pager/status helpers, but it is not a full TUI/input widget framework. For complex input, use crates like dialoguer, rustyline, or inquire.
  • No async: Rendering is synchronous; wrap in spawn_blocking if needed
  • Live redirection: Live can redirect process-wide stdout/stderr in interactive terminals (TTY-only). In piped/non-interactive contexts it stays disabled; use live.stdout_proxy() / live.stderr_proxy() for external writers. Capture has one process-wide owner; another root requesting capture receives WouldBlock until that owner finishes shutdown. Nested displays on the same Console share its existing capture.
  • HTML/SVG export: Exports use Rich-style templates with corrections for literal content, Unicode cell geometry, and final-row clipping; exact byte-for-byte parity is not claimed.

FAQ

Q: How does this compare to Python Rich?

A: rich_rust targets feature-for-feature parity with Python Rich. When behavior differs, treat it as a bug (or an explicitly documented, test-covered deviation) and track it until resolved.

Q: Is this production-ready?

A: It's in active development (v0.1.x). Core features work well, but the API may change. Pin your version in Cargo.toml.

Q: Can I use this in a TUI application?

A: rich_rust is for styled output, not interactive TUIs. For interactive apps, use ratatui, cursive, or tui-rs (which can potentially use rich_rust for styled text rendering).

Q: Why not just use Python Rich via PyO3?

A: Native Rust has no Python runtime dependency, compiles to a single binary, and avoids FFI overhead. If you're already in Rust, stay in Rust.

Q: How do I contribute?

A: See the "About Contributions" section below.

Q: What's the minimum Rust version?

A: Rust 2024 edition (nightly required currently). Check rust-toolchain.toml for specifics.


About Contributions

Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via gh and independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.


License

MIT License (with OpenAI/Anthropic Rider). See LICENSE for details.


Made with Rust by Jeffrey Emanuel

Explorer des projets similaires

Chargement…