The ext crate¶
rs-rich-ext holds everything this port adds on top of Python rich. The core
crate, rs-rich, stays a faithful mirror of upstream; this crate builds on its
public API and never changes how a plain rich::Console behaves. Read
Extensions for why the split exists and how to opt in.
A compiler-style diagnostic, from Diagnostics:
let diagnostic = Diagnostic::error("mismatched types")
.code("E0308")
.location(Location::new("src/main.rs", Some(12), Some(5)))
.cause("expected `u16`, found `&str`");
console.print(&diagnostic);
and KPI cards, a status matrix and a timeline from Charts, laid
out with core's Layout:
The code
fn dashboard() -> Layout {
let card = |c: KpiCard| Layout::with_renderable(Box::new(c.expand(true)));
let mut cards = Layout::new().size(6);
cards.split_row(vec![
card(
KpiCard::new("Requests", 1240.0)
.unit("/s")
.previous(1180.0)
.trend(trend(0.0)),
),
card(
KpiCard::new("Errors", 7.0)
.delta(2.0)
.higher_is_better(false)
.trend(trend(5.0))
.status(Status::Warning),
),
]);
let checks = StatusMatrix::new()
.columns(["eu", "us", "ap"])
.row("api", ["pass", "pass", "flaky"])
.row("worker", ["pass", "fail", "pass"]);
let deploy = Timeline::new()
.span("build", 0.0, 18.0)
.span("test", 12.0, 34.0)
.span("rollout", 36.0, 52.0)
.milestone("live", 60.0)
.unit("s");
let mut root = Layout::new();
root.split_column(vec![
cards,
Layout::with_renderable(Box::new(Panel::new(Box::new(checks)).title("checks"))).size(6),
Layout::with_renderable(Box::new(Panel::new(Box::new(deploy)).title("deploy"))),
]);
root
}
Every module is listed below with the feature it needs. "none" means it is
always available. The use path is rich_ext::<module>.
Output and diagnostics¶
| Module | What it gives you | Feature | Guide |
|---|---|---|---|
ConsoleExt, registry |
install_extensions() and ExtensionRegistry: explicit installation of highlighters |
none | Extensions |
theme |
extended_theme(): upstream's theme plus error/warning/info/success, CLI help, diff and workflow styles (STYLE_TABLES) |
none | Extensions |
highlighter |
NumberHighlighter, the default extension |
none | Extensions |
hyperlink |
Hyperlinker: OSC 8 links for URLs, paths, path:line:col, #123; editor URL templates |
none | Extensions |
sanitize |
sanitize_terminal_controls: make untrusted text inert |
none | Extensions |
encoding |
Encoding: strict, explicit UTF-8/UTF-16 decoding |
none | Extensions |
diagnostic |
Diagnostic: compiler-style errors with snippets, labels, suggestions; DiagnosticInfo for error types; from_anyhow |
none; anyhow for from_anyhow |
Diagnostics |
stacktrace |
Parse Rust, Python, Java and JavaScript traces into one StackTrace; panic_hook |
none | Diagnostics |
dashboard |
DiagnosticsDashboard: counts, top codes and diagnostics grouped by file |
none | Diagnostics |
event |
StructuredEvent: typed log records that render compact or expanded |
none | Logging |
log_handler |
RichHandler: upstream's logging.RichHandler layout |
none | Logging |
adapters |
LogAdapter (the log facade) and EventLayer (a tracing layer), both feeding an EventSink |
log, tracing |
Logging |
target |
RenderTarget and TargetKind: explicit, deterministic destinations |
none | Live and layout |
layout |
LayoutNode, Constraint, allocate, OverflowPolicy, Overflowing: bounded layouts |
none | Live and layout |
frame |
Frame: a render as rows of styled runs, with exact and merged ANSI encoding, cells and a cell diff |
none | Live and layout |
live |
LiveCoordinator: several live regions and printed lines through one writer |
none | Live and layout |
surface |
Surface: render any renderable into rectangles of the terminal (full screen or inline) and write only the cells that changed; the screen and painter intuiTUIve draws with |
none | Positioned drawing |
macros |
rich_table!, rich_panel!, rich_tree!, rich_progress!, rich_dbg!; with macros, rich_println!, rich_eprintln!, rich_trace! |
none; macros for the print macros |
Macros |
richf!, style!, theme_key!, markup!, #[derive(Rich)] |
Compile-time checked markup and styles; derive rendering (re-exported from rs-rich-macros) |
macros |
Macros |
derive |
RichRecord, Field, render and table: the runtime behind the derive |
none | Macros |
inspect, #[derive(Inspect)], rich_inspect! |
Inspect: upstream's rich.inspect report on a value, from data the derive collects; #[inspect] on an impl block lists methods |
none; macros for the derive and #[inspect] |
Inspect |
Workflows, tables and status¶
| Module | What it gives you | Feature | Guide |
|---|---|---|---|
workflow |
CommandRecord/CommandView/CommandRunner: a process's output, exit status and duration, folded, with a live spinner; TaskTree: nested tasks with aggregate status and cancellation; CompletionSummary |
none | Workflows |
transfer |
Transfer, Transfers, transfer_columns(), TransferReader/TransferWriter: download and upload progress with rate, ETA, retries and cancellation |
none | Transfers and status |
countdown |
Backoff, RetryStatus, RateLimit, CountdownBar, CountdownWait: retry and rate-limit countdowns |
none | Transfers and status |
notify |
Notification, Notifications: transient toasts with expiry |
none | Transfers and status |
cancel |
CancelToken: one cancellation flag, with child tokens, shared by the modules above |
none | Workflows |
table |
TableData: stable multi-column sort, grouping and aggregates; StreamingTable: keyed rows that re-render only what changed; VirtualTable: one window of a large row source in constant memory; PlainRows, PlainTree: data into a core Table or Tree as plain text |
none | Tables |
markdown_export |
GfmDocument, ToGfm: tables, trees, panels, rules, text and code as GitHub-flavoured Markdown for PR comments; fit_github_comment for GitHub's size limit |
none | Markdown for GitHub |
badge, size_bar |
Badge/Badges: status, label, link and metadata chips; SizeBar: a size against a total or limit |
none | Badges and redaction |
chart |
Sparkline, BarChart (stacked groups too), Histogram, LineChart (Braille line and scatter), PieChart (pies and donuts), Gauge, BulletChart, Heatmap, StatusMatrix, KpiCard, Timeline, LevelMeter (with PeakHold), Spectrogram, BarSpectrum and Persistence, with Scale, ValueFormat and Charset; every chart has an ASCII form and reads without colour. In the shell: rich chart |
none | Charts |
gradient |
GradientText: a Text coloured along two or more colours, across, down or corner to corner, degrading by colour system |
none | Charts |
qr |
QrCode: QR codes drawn with half blocks in a quiet zone, with ErrorCorrection levels and an ASCII form |
qr |
Charts |
format |
Sizes, rates, durations, relative times, timestamps, percentages and numbers as people read them | none | Badges and redaction |
filetype |
icon_for/icon_with: Yazi's default file icons and colours (dark and light); style_for: its type colours; mime_for, mime_for_path, mime_from_bytes, mime_batch: MIME types by name and magic bytes; nerd_font(): whether a Nerd Font is likely |
none | Files, spectra and warm-ups |
fs |
user_name, group_name (Unix); local_time, short_local_time: times in the local zone |
none; local-time for the times |
Files, spectra and warm-ups |
listing |
Entry, read_dir(dir, hidden, sort): a directory's entries sorted as Yazi sorts them (Sort, SortBy); readable_size, permissions, owner: line-mode cells; find_ranges: smart-case matches; walk(root): a lazy depth-first tree walk |
none | Files, spectra and warm-ups |
open |
Rules::yazi(), Rule, Opener, Launch: Yazi's [opener]/[open] tables, the openers for a MIME type or name glob; editor(), system_opener() |
none | Files, spectra and warm-ups |
file_ops |
run(Op, cancel, progress): copy, move, delete and trash with progress and cancellation; Conflict, unique, under |
none | Files, spectra and warm-ups |
trash |
put, list, restore, purge: the FreeDesktop trash (Linux and the BSDs; an Unsupported error elsewhere); Trash::at(dir) |
none | Files, spectra and warm-ups |
git |
status(dir): git status --porcelain=v1 -z per file, directories taking the greatest change inside; parse_porcelain |
none (runs git) |
Files, spectra and warm-ups |
archive |
entries(path), extract(path, dest), extract_with: tar, tar.gz and zip, never writing outside dest |
archive |
Files, spectra and warm-ups |
dsp |
fft (any length), hann, spectrum and spectrum_full; test signals (tone, partials, noise, mix); trigger(samples, level, depth, Edge); bands, Falloff, peak_hz; note_hz("A4"), NoteTable, nearest_note(hz) |
none | Files, spectra and warm-ups |
sql |
SqlHighlighter: SQL highlighting with no syntect (dialect words, Jinja blocks for dbt); highlight for a Text, tokenize for the tokens |
sql |
Code highlighters |
syntax |
preload(languages): warm the default highlighter on a worker thread |
syntax (default) |
Files, spectra and warm-ups |
redact |
Redactor (experimental, best effort: check its output): mask secrets in strings, ANSI text and rendered segments before they are exported or recorded |
none | Badges and redaction |
Structured data and CLI authoring¶
| Module | What it gives you | Feature | Guide |
|---|---|---|---|
data |
One document tree for JSON, INI and dotenv; Explorer, tables, flatten, search, diff, redaction; print_json/print_table/print_tree for serde values |
data; yaml, toml, xml for those formats; jsonpath for JSONPath selectors |
Structured data |
deps, schema |
DepTree/WhyTree: cargo metadata as a dependency tree with duplicate versions marked, and what pulls a crate in; SchemaTree/SchemaDiff: a JSON Schema as a tree with local $refs resolved, and what changed between two; the format-neutral schema model they read, with JSON Schema and SQL DDL (schema::sql) mapped into it, SchemaDiff::models for any two, and SchemaTimeline for a series of versions |
data |
Dependency graphs and JSON Schemas |
document |
DocumentRegistry and DocumentFormat: Markdown, reStructuredText, Org, AsciiDoc and man pages (man, mdoc, tbl) behind one interface, detected by file name and content; DocumentView draws the shared model in Markdown's look |
syntax (default) |
Documents |
cli_doc |
From one CommandSpec: help, errors as diagnostics, shell completions, Markdown and man pages, config reference and precedence |
none; clap for CommandSpec::from_clap and cli_doc::clap |
CLI authoring |
cli |
The rich binary's extension options (--encoding, --gif-mode) |
none | CLI authoring |
Testing and QA¶
| Module | What it gives you | Feature | Guide |
|---|---|---|---|
diff |
Myers diff engine, DiffView (unified or side by side, text or ANSI), SourceDiff, git patch rendering |
none | Diffs and test reports |
diff::test_report |
TestReport from JUnit XML or libtest JSON |
test-report |
Diffs and test reports |
diff::assert |
assert_rich_eq! and friends: assertions that panic with a rendered diff |
testing |
Diffs and test reports |
testing |
RenderSnapshot: deterministic render snapshots as JSON for downstream tests |
testing |
QA |
qa |
Approved screenshots, layout stress, render lint, explain, profiling, seeded fuzzing, capability matrix, benchmarks | testing |
QA |
Capabilities and accessibility¶
| Module | What it gives you | Feature | Guide |
|---|---|---|---|
capabilities |
Capabilities::system() / detect: what the terminal supports, and why |
none; serde to serialize reports |
Capabilities |
fidelity |
Fidelity levels and Degrade: render anything without colour, without styles, or ASCII only |
none | Capabilities |
a11y |
semantic::AccessibleText for screen readers; policy::AccessibilityPolicy (reduced motion, high contrast, monochrome); contrast::check_theme |
none; serde to serialize findings |
Accessibility |
ansi_explain |
explain: decode escape sequences into words |
none; serde to serialize explanations |
ANSI explained |
source_view |
SourceView: source with line numbers and search highlights |
none | CLI viewers |
hex, unicode_inspect, env_inspect |
HexView, UnicodeView, EnvView / PathView: bytes, graphemes and environment |
none | CLI viewers |
Feature flags¶
syntax and markdown are on by default (core's two features, and what
needs them); every other feature is off.
| Feature | Enables | Extra dependencies |
|---|---|---|
syntax, markdown (default) |
Highlighted source_view, SourceDiff and PatchView; rst, document (its Markdown provider with markdown), cli_doc::markdown_view |
rs-rich's syntax and markdown (syntect, pulldown-cmark) |
macros |
richf!, style!, theme_key!, markup!, #[derive(Rich)], print macros |
rs-rich-macros |
anyhow |
Diagnostic::from_anyhow |
anyhow |
log |
adapters::LogAdapter; RichHandler as an EventSink |
log |
tracing |
adapters::EventLayer; RichHandler as an EventSink |
tracing, tracing-subscriber |
data |
rich_ext::data with JSON, INI and dotenv; deps and schema |
serde, serde_json |
yaml, toml, xml |
Those formats in data (each implies data) |
saphyr-parser, toml, quick-xml |
jsonpath |
JSONPath selectors in data |
none |
clap |
CommandSpec::from_clap, cli_doc::clap::parse_or_exit |
clap |
testing |
testing, qa, diff::assert |
serde, serde_json |
test-report |
diff::test_report |
serde, serde_json, quick-xml |
local-time |
fs::local_time, fs::short_local_time |
chrono (clock: iana-time-zone) |
serde |
Serialize for capability reports, contrast findings and ANSI explanations |
serde |
sql |
sql::SqlHighlighter, a SQL code highlighter with Jinja blocks, and sql::highlight |
none |
dylib-plugins, wasm-plugins |
Loading runtime plugins: native libraries, or sandboxed WASM modules (Extending) | libloading, wasmi |
Examples¶
Every guide page has a runnable example in crates/rich-ext/examples, named
guide_<topic>. Each prints to the terminal, or with -- --svg DIR writes the
screenshots used on these pages:
cargo run -p rs-rich-ext --example guide_extensions
cargo run -p rs-rich-ext --example guide_diagnostics --features anyhow
cargo run -p rs-rich-ext --example guide_logging --features log,tracing
cargo run -p rs-rich-ext --example guide_live_layout
cargo run -p rs-rich-ext --example guide_macros --features macros
cargo run -p rs-rich-ext --example guide_inspect --features macros
cargo run -p rs-rich-ext --example guide_charts
cargo run -p rs-rich-ext --example guide_sources --features data,toml
cargo run -p rs-rich-ext --example guide_documents
cargo run -p rs-rich-ext --example guide_transforms --features jsonpath
cargo run -p rs-rich-ext --example guide_highlighters --features testing,syntax
See also¶
- Tutorial: the core library, from the first
Consoleto live output. - Extending: extension points and the plugin roadmap.
- Divergences: where the core deliberately differs from upstream.
- API:
rs-rich-exton docs.rs.