Skip to main content

Crate gilt

Crate gilt 

Source
Expand description

§gilt – Rich Terminal Formatting for Rust

Crates.io Documentation License: MIT

A Rust port of Python’s rich library – beautiful terminal output with styles, tables, trees, syntax highlighting, progress bars, and more, all rendered as ANSI escape sequences.

§Quick Start

Add gilt to your Cargo.toml:

[dependencies]
gilt = "0.6"

Then use the prelude for convenient access to common types:

use gilt::prelude::*;

let mut console = Console::builder().width(80).build();
console.begin_capture();
console.print_text("Hello, [bold magenta]gilt[/bold magenta]!");
let output = console.end_capture();
assert!(output.contains("Hello"));

For quick one-off output, use the global console functions:

gilt::print_text("Hello, [bold]world[/bold]!");
gilt::inspect(&vec![1, 2, 3]);

§The Console

Console is the central type in gilt. It manages terminal capabilities, drives the rendering pipeline, and handles output buffering, capture, and export.

§Creating a Console

use gilt::console::Console;

// Defaults: auto-detect terminal size, TrueColor, markup on
let console = Console::new();

// Builder pattern for full control
let console = Console::builder()
    .width(120)
    .color_system("truecolor")
    .record(true)       // enable export_html / export_svg
    .no_color(false)
    .build();

§Printing

let mut console = Console::builder().width(80).build();

// Print with rich markup
console.print_text("[bold red]Error:[/bold red] something went wrong");

// Print any Renderable (Panel, Table, Tree, ...)
let panel = Panel::new(Text::new("inside a box", Style::null()));
console.print(&panel);

§Capture and Export

Capture lets you collect console output as a plain string instead of writing to the terminal:

let mut console = Console::builder().width(60).build();
console.begin_capture();
console.print_text("[bold]Captured![/bold]");
let plain = console.end_capture();
assert!(plain.contains("Captured!"));

For rich export, enable record(true) on the builder, then call export_text, export_html, or export_svg:

let mut console = Console::builder().width(60).record(true).build();
console.print_text("[green]Recorded[/green]");
let html = console.export_html(None, true, true);
assert!(html.contains("<span"));

§Text and Styling

§Style

Style represents a combination of foreground/background color, text attributes (bold, italic, underline, …), extended underline styles, and hyperlinks.

use gilt::style::Style;

// Parse from a human-readable definition
let style = Style::parse("bold red on white").unwrap();
let subtle = Style::parse("dim italic #808080").unwrap();

// Combine styles with the + operator (right side wins on conflicts)
let combined = style + subtle;

§Markup

gilt supports inline markup tags in strings, similar to BBCode:

let mut c = Console::builder().width(60).build();
c.begin_capture();
c.print_text("[bold]Bold[/bold], [italic green]green italic[/italic green]");
let out = c.end_capture();
assert!(out.contains("Bold"));

Closing tags match their opening tag, or use [/] to close the most recent: "[bold red]error[/] normal text".

§Text

Text is the fundamental rich-text type, storing a plain string plus styled spans.

use gilt::text::Text;
use gilt::style::Style;

// Plain text
let text = Text::new("Hello, world!", Style::null());

// Styled text (entire string has one style)
let bold = Text::styled("Important", Style::parse("bold").unwrap());

// From markup (parses [tags])
let rich = Text::from_markup("[red]Error:[/red] file not found").unwrap();
assert!(rich.plain().contains("Error:"));

§Stylize Trait

The Stylize trait provides a fluent, Rust-idiomatic API for building styled text directly from string literals:

use gilt::styled_str::Stylize;

let styled = "Hello".bold().red().on_blue();
assert_eq!(styled.text, "Hello");

StyledStr implements Renderable, so it can be passed directly to Console::print.

§Widgets

§Panel

Panel wraps content in a bordered box with optional title and subtitle.

use gilt::prelude::*;
use gilt::box_chars::DOUBLE;

// Expanding panel (fills available width)
let panel = Panel::new(Text::new("content", Style::null()))
    .with_title("My Panel")
    .with_box_chars(&DOUBLE)
    .with_border_style(Style::parse("blue").unwrap());

// Fit-to-content panel
let compact = Panel::fit(Text::new("snug", Style::null()));

§Table

Table renders data in Unicode box-drawing tables with column alignment, row striping, headers, footers, and style control.

use gilt::table::Table;

let mut table = Table::new(&["Name", "Age", "City"]);
table.add_row(&["Alice", "30", "Paris"]);
table.add_row(&["Bob", "25", "London"]);

let output = format!("{}", table);
assert!(output.contains("Alice"));

Builder methods customise every aspect of the table:

use gilt::table::Table;
use gilt::box_chars::ROUNDED;

let table = Table::new(&["Key", "Value"])
    .with_title("Config")
    .with_box_chars(Some(&ROUNDED))
    .with_border_style("cyan")
    .with_row_styles(vec!["".into(), "dim".into()])
    .with_expand(true);

Use Table::grid for borderless side-by-side layout:

use gilt::table::Table;

let mut grid = Table::grid(&["A", "B"]);
grid.add_row(&["left", "right"]);

§Tree

Tree renders hierarchical data with Unicode guide lines.

use gilt::prelude::*;

let mut tree = Tree::new(Text::new("root", Style::null()));
let child = tree.add(Text::new("child 1", Style::null()));
child.add(Text::new("grandchild", Style::null()));
tree.add(Text::new("child 2", Style::null()));

Guide style affects line weight: default is thin lines, bold gives thick lines, and underline2 selects double lines.

§Rule

Rule draws a horizontal line, optionally with a centered title.

use gilt::rule::Rule;

let rule = Rule::new();                           // plain line
let titled = Rule::with_title("Section Header");  // line with title

§Columns

Columns lays out items in an auto-fitting multi-column grid.

use gilt::columns::Columns;

let mut cols = Columns::new();
cols.add_renderable("one");
cols.add_renderable("two");
cols.add_renderable("three");

§Layout

Layout splits the terminal into rows and columns with flexible or fixed sizing, like a split-pane window manager.

use gilt::layout::Layout;

let mut root = Layout::new(None, Some("root".into()), None, None, Some(1), None);
root.split_row(vec![
    Layout::new(Some("Left pane".into()), Some("left".into()), None, None, Some(1), None),
    Layout::new(Some("Right pane".into()), Some("right".into()), None, None, Some(2), None),
]);

§Terminal Features

§Syntax Highlighting

Syntax highlights source code using syntect with 150+ language grammars. (Requires the syntax feature, enabled by default.)

use gilt::syntax::Syntax;

let code = r#"fn main() { println!("hello"); }"#;
let syntax = Syntax::new(code, "rust")
    .with_line_numbers(true)
    .with_theme("base16-ocean.dark");

§Markdown

Markdown renders Markdown to the terminal with headings, lists, code blocks, and emphasis. (Requires the markdown feature, enabled by default.)

use gilt::markdown::Markdown;

let md = Markdown::new("# Hello\n\nThis is **bold** and *italic*.");

§JSON Pretty-Printing

Json parses and syntax-highlights JSON data. (Requires the json feature, enabled by default.)

use gilt::json::{Json, JsonOptions};

let json = Json::new(r#"{"name": "gilt", "version": "0.6.0"}"#, JsonOptions::default()).unwrap();

The global convenience function makes it even simpler:

gilt::print_json(r#"{"key": "value"}"#);

§Progress Bars

Progress provides a multi-task progress display with customisable columns (text, bar, spinner, time, speed) and live terminal updates.

use gilt::progress::Progress;

let mut progress = Progress::new(vec![]);
let task = progress.add_task("Downloading", Some(100.0));
progress.start();
for _ in 0..100 {
    progress.advance(task, 1.0);
}
progress.stop();

§Iterator Progress

The ProgressIteratorExt trait adds .progress() to any iterator:

use gilt::progress::ProgressIteratorExt;

let items: Vec<i32> = (0..100).progress("Processing").collect();

§Live Display

Live renders content that updates in-place using cursor control codes.

use gilt::live::Live;
use gilt::text::Text;
use gilt::style::Style;

let mut live = Live::new(Text::new("Loading...", Style::null()));
live.start();
// ... update content ...
live.update_renderable(Text::new("Done!", Style::null()), true);
live.stop();

§Status Spinner

Status displays a spinner animation with a status message.

use gilt::status::Status;

let mut status = Status::new("Loading...");
status.start();
status.update().status("Processing...").apply();
status.stop();

§Rust-Native Features

These features go beyond what Python’s rich provides, taking advantage of Rust’s type system and ecosystem.

§Gradients

Gradient renders text with smoothly interpolated true-color gradients.

use gilt::gradient::Gradient;
use gilt::color::Color;

let g = Gradient::two_color("Hello!", Color::from_rgb(255, 0, 0), Color::from_rgb(0, 0, 255));
let rainbow = Gradient::rainbow("All the colors!");

§Sparkline

Sparkline renders numeric data as compact inline Unicode bar charts.

use gilt::sparkline::Sparkline;

let spark = Sparkline::new(&[1.0, 3.0, 5.0, 7.0, 5.0, 3.0, 1.0]);
let output = format!("{}", spark);
assert!(!output.is_empty());

§Canvas

Canvas provides a Braille dot-matrix for high-resolution terminal graphics. Each character cell encodes a 2x4 pixel grid, giving sub-character resolution.

use gilt::canvas::Canvas;

let mut c = Canvas::new(10, 5);
c.line(0, 0, 19, 19);   // diagonal line
c.rect(2, 2, 10, 10);   // rectangle
c.circle(10, 10, 8);    // circle

§Diff

Diff computes and renders colored line-level diffs in unified or side-by-side format.

use gilt::diff::{Diff, DiffStyle};

let old = "line 1\nline 2\nline 3\n";
let new = "line 1\nline 2 modified\nline 3\nline 4\n";
let diff = Diff::new(old, new).with_labels("before", "after");
let sbs = Diff::side_by_side(old, new);

§Figlet

Figlet renders large ASCII art text using a built-in 5x7 block font.

use gilt::figlet::Figlet;

let banner = Figlet::new("HI");
let output = format!("{}", banner);
assert!(!output.is_empty());

§Inspect

Inspect displays structured information about any Debug value in a styled panel, showing the type name and formatted representation.

use gilt::inspect::Inspect;
use gilt::console::Console;

let data = vec![1, 2, 3];
let widget = Inspect::new(&data)
    .with_title("My Data")
    .with_label("numbers");

let mut c = Console::builder().width(80).force_terminal(true).build();
c.begin_capture();
c.print(&widget);
let output = c.end_capture();
assert!(output.contains("Vec"));

Or use the global shorthand:

gilt::inspect(&vec![1, 2, 3]);

§CsvTable

CsvTable converts CSV data into a rich Table.

use gilt::csv_table::CsvTable;

let csv = CsvTable::from_csv_str("name,age\nAlice,30\nBob,25").unwrap();
let table = csv.to_table();

§Derive Macros

With the derive feature enabled, gilt provides seven proc-macro derives that automatically generate widget conversions from struct definitions:

DeriveGeneratesMethod
TableTable from a slice of structsType::to_table(&items)
PanelPanel from a single structvalue.to_panel()
TreeTree from a structvalue.to_tree()
ColumnsColumns from a structvalue.to_columns()
RuleRule from a structvalue.to_rule()
InspectInspect panel from a structvalue.to_inspect()
RenderableRenderable trait implconsole.print(&value)
use gilt::Table;

#[derive(Table)]
#[table(title = "Employees", box_style = "ROUNDED")]
struct Employee {
    #[column(header = "Full Name", style = "bold")]
    name: String,
    #[column(justify = "right")]
    age: u32,
    #[column(skip)]
    internal_id: u64,
    #[column(header = "Dept", style = "green")]
    department: String,
}

let employees = vec![
    Employee { name: "Alice".into(), age: 30, internal_id: 1, department: "Eng".into() },
];
let table = Employee::to_table(&employees);

Enable in Cargo.toml:

gilt = { version = "0.6", features = ["derive"] }

§Feature Gates

FeatureDefaultCrate DependenciesDescription
jsonYesserde, serde_jsonJSON pretty-printing via Json
markdownYespulldown-cmarkTerminal Markdown via Markdown
syntaxYessyntectSyntax highlighting via Syntax
interactiveYesrpasswordPassword prompts and selection menus
loggingYeslogLogging handler
tracingNotracing, tracing-subscriberGiltLayer subscriber
deriveNogilt-derive7 proc-macro derives
mietteNomietteGiltMietteHandler
eyreNoeyreGiltEyreHandler
anstyleNoanstyleBidirectional From conversions
csvNocsvCSV file reading (built-in parser always available)
readlineNorustylineReadline-based prompt completions

For a minimal build with no heavy dependencies:

gilt = { version = "0.6", default-features = false }

§Integrations

§miette – Diagnostic Reporting

Install gilt as the miette report handler for beautifully styled diagnostic output. (Requires the miette feature.)

gilt::miette_handler::install();

§eyre – Error Reporting

Install gilt as the eyre report handler. (Requires the eyre feature.)

gilt::eyre_handler::install().unwrap();

§tracing – Structured Logging

Use GiltLayer as a tracing subscriber layer for colored, formatted log output. (Requires the tracing feature.)

use gilt::tracing_layer::GiltLayer;
use tracing_subscriber::prelude::*;

tracing_subscriber::registry()
    .with(GiltLayer::new())
    .init();

§anstyle – Type Conversions

With the anstyle feature, gilt Color and Style types gain bidirectional From conversions with their anstyle counterparts, enabling interop with clap, owo-colors, and the anstyle ecosystem.

§Advanced

§Theme System

gilt’s Theme maps style names (like "table.header" or "bold red") to Style instances. The default theme provides sensible styling for all built-in widgets. Push custom themes onto the console’s theme stack:

use gilt::console::Console;
use gilt::theme::Theme;
use gilt::style::Style;
use std::collections::HashMap;

let mut styles = HashMap::new();
styles.insert("info".to_string(), Style::parse("bold cyan").unwrap());

let mut console = Console::new();
console.push_theme(Theme::new(Some(styles), true));
// All rendering now uses the custom "info" style
console.pop_theme();

§Custom Renderables

Implement the Renderable trait to create your own widgets:

use gilt::console::{Console, ConsoleOptions, Renderable};
use gilt::segment::Segment;

struct Greeting { name: String }

impl Renderable for Greeting {
    fn gilt_console(&self, _console: &Console, _options: &ConsoleOptions) -> Vec<Segment> {
        vec![
            Segment::text(&format!("Hello, {}!", self.name)),
            Segment::line(),
        ]
    }
}

§Accessibility (WCAG Contrast)

The accessibility module provides WCAG 2.1 contrast ratio calculations:

use gilt::accessibility::{contrast_ratio, meets_aa, meets_aaa};
use gilt::color_triplet::ColorTriplet;

let black = ColorTriplet::new(0, 0, 0);
let white = ColorTriplet::new(255, 255, 255);
assert!((contrast_ratio(&black, &white) - 21.0).abs() < 0.1);
assert!(meets_aa(&black, &white));
assert!(meets_aaa(&black, &white));

§Environment Variables

gilt respects standard terminal environment variables with a 5-tier priority system:

VariableEffect
NO_COLORDisables all color output (no-color.org)
FORCE_COLORForces color output even when not a TTY
CLICOLOR_FORCESame as FORCE_COLOR
CLICOLOR=0Disables color
COLUMNS / LINESOverrides terminal size detection

Programmatic settings (via ConsoleBuilder) always take priority over environment variables.

§Console Export (HTML, SVG, Text)

When recording is enabled, the console can export its output in multiple formats:

let mut c = Console::builder().width(60).record(true).build();
c.print_text("[bold green]Success![/bold green]");

let text = c.export_text(true, false);             // plain text
let html = c.export_html(None, true, true);         // HTML with inline styles
let svg  = c.export_svg("Title", None, true, None, 0.61); // SVG image

Files can be written directly with save_text, save_html, and save_svg.

§Module Index

ModuleDescription
consoleConsole engine: rendering, capture, export
styleText styles: colors, attributes, hyperlinks
textRich text with markup parsing and word wrapping
tableUnicode box-drawing tables
panelBordered content panels
treeHierarchical tree display
ruleHorizontal rules with titles
columnsAuto-fitting multi-column layout
layoutSplit-pane terminal layouts
progressMulti-task progress bars with live display
liveLive-updating terminal display
statusSpinner with status message
gradientTrue-color gradient text
sparklineInline Unicode sparkline charts
canvasBraille dot-matrix graphics
diffColored unified and side-by-side diffs
figletLarge ASCII art text
csv_tableCSV-to-Table conversion
styled_strStylize trait for "text".bold().red() chaining
inspectDebug any value with rich formatting
markupMarkup tag parser
colorColor types and parsing
segmentLow-level rendering segments
themeNamed style collections
accessibilityWCAG 2.1 contrast checking
highlighterRegex-based and repr syntax highlighters
emojiEmoji shortcode replacement
box_chars19 box-drawing character sets
preludeConvenience re-exports

Re-exports§

pub use utils::styled;
pub use utils::styled_str;
pub use color::accessibility;
pub use color::color_env;
pub use color::color_triplet;
pub use color::palette;
pub use color::terminal_theme;
pub use color::theme;
pub use error::traceback;
pub use error::logging_handler;
pub use live::live_render;
pub use live::screen;
pub use status::spinner;
pub use status::spinners;
pub use status::toast;
pub use utils::align_widget;
pub use utils::ansi;
pub use utils::bar;
pub use utils::box_chars;
pub use utils::cells;
pub use utils::constrain;
pub use utils::containers;
pub use utils::control;
pub use utils::default_styles;
pub use utils::diagnose;
pub use utils::emoji;
pub use utils::emoji_codes;
pub use utils::emoji_replace;
pub use utils::filesize;
pub use utils::highlighter;
pub use utils::inspect;
pub use utils::padding;
pub use utils::pretty;
pub use utils::protocol;
pub use utils::ratio;
pub use utils::scope;
pub use widgets::table;
pub use style::clear_style_cache;
pub use style::style_cache_size;
pub use color::clear_color_cache;
pub use color::color_cache_size;

Modules§

accordion
Accordion widget – collapsible content panels for organizing complex output.
badge
Badge/Tag widget for displaying status indicators.
breadcrumbs
Breadcrumbs widget for showing navigation path/location.
canvas
Canvas – Braille dot matrix for high-resolution terminal graphics.
color
Terminal color representation and manipulation.
columns
Columns module – displays renderables in neat auto-fitted columns.
console
Console engine — the central orchestrator of gilt rendering output.
csv_table
CSV to Table — load CSV data directly into a gilt Table.
diff
Colored diff rendering widget.
error
Error types used throughout the gilt library.
export_format
Export format templates for Console HTML and SVG output.
figlet
Large ASCII art text using Unicode block characters.
gradient
True color gradient rendering across text.
group
Group widget – renders a collection of renderables in sequence.
json
Pretty-printed, syntax-highlighted JSON display.
layout
Layout module — a recursive screen-splitting layout system.
live
Live display module – a terminal display that refreshes at regular intervals.
markdown
Markdown rendering module – parses CommonMark and produces styled terminal output.
markup
Rich markup parser — parses [bold red]text[/] syntax into styled Text.
measure
Measurement module for tracking minimum and maximum rendering widths.
pager
Pager module for displaying content through a system pager.
panel
Panel widget – a bordered box around content with optional title/subtitle.
prelude
Convenience re-exports for common gilt types.
progress
Progress tracking system – configurable progress bars with live display.
progress_bar
Progress bar renderable – a styled progress bar with pulse animation.
prompt
Interactive prompt module for styled user input with validation, choices, and defaults.
region
Region type for rectangular screen areas.
rule
Rule widget – a horizontal line with optional title.
segment
Segment - the atomic unit of terminal rendering.
sparkline
Sparkline – inline Unicode sparkline charts.
status
Status indicator with a spinner animation.
style
Style representation and manipulation for terminal text.
syntax
Syntax highlighting module for terminal display.
text
Rich text module - the core text manipulation type.
tree
Tree widget for rendering hierarchical structures with guide characters.
utils
Utility modules for gilt.
widgets
Widget modules for gilt.
wrap
Word wrapping utilities for terminal text.

Macros§

derive_gilt_cast
Macro to derive RichCast implementation (placeholder for future derive macro).
gilt_cast_impl
Macro to implement RichCast using a closure-like syntax.

Functions§

inspect
Inspect a value in the default console.
print
Print a renderable to the default console.
print_json
Pretty-print JSON to the default console.
print_text
Print a text string to the default console, processing markup.
with_console
Access the global default console.