termosaic 0.3.0

Semantic, structured output for human, machine-text, and opaque-byte destinations
Documentation

Termosaic

Termosaic provides structured CLI presentation. It keeps human output, machine-readable text, and opaque bytes as distinct capabilities; renders semantic tokens through application-owned themes; lays out documents and tables without splitting Unicode graphemes; and coordinates human diagnostics with stderr progress.

The library owns no process-global stdout, stderr, color, theme, or progress state. Each Console instance receives explicit destination capabilities and output classes, so mixed human and machine streams cannot silently contaminate each other.

Features

Feature Default Capability
serde via json Validated serialization for names and tokens
json yes Semantic pretty JSON and compact/pretty machine JSON
progress yes Coordinated stderr progress handles
adaptive-tables no Width-aware borderless tables
background-probe no Opt-in OSC 11 terminal background detection

The core library, including human and machine-text writers, opaque bytes, semantic tokens, themes, document layout, and fixed tables, builds with default features disabled. Termosaic 0.3 supports Rust 1.88 and newer.

Laidout layout engine

Termosaic re-exports the complete Laidout crate as termosaic::laidout. Applications can use Termosaic's semantic Doc and prepared rendering APIs, drop to Laidout's generic annotation and allocation-control surfaces, or use both without declaring Laidout separately:

use std::num::NonZeroU32;

use termosaic::laidout::{Doc, RenderOptions, render};

let doc = Doc::<()>::group(Doc::concat([
    Doc::text("release"),
    Doc::line(),
    Doc::text("ready"),
]));
let options = RenderOptions::new(NonZeroU32::new(80).unwrap());
let output = render(&doc, options)?;
assert_eq!(output.text(), "release ready");
# Ok::<(), Box<dyn std::error::Error>>(())

Enable Termosaic's laidout-research feature to expose Laidout's optional research module through the same namespace.

Example

use termosaic::{
    Console, Span, StdioOptions, Stream, themes, tokens,
};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let console = Console::stdio(StdioOptions::human(themes::default()))?;

    console
        .human(Stream::Stdout)?
        .line(&[Span::new(tokens::STATUS_SUCCESS, "composed")])?;
    Ok(())
}

See examples/basic.rs for a compilable example. For injected files, buffers, or test sinks, ConsoleOptions::non_terminal(stdout_class, stderr_class, theme) supplies explicit non-terminal policy without repeating capability fields. Widget and cell-grid consumers that own their renderer can call TerminalColorPolicy::detect_stdout(ColorChoice::Auto) to reuse the same NO_COLOR, TERM, COLORTERM, TTY, and color-depth decision as Console::stdio.

Formatters

Termosaic provides human document constructors for wrapped prose, fixed-width text, lines, words, lists, key/value pairs, diagnostics, and tables. They return ordinary semantic Doc values and remain fully themeable:

use std::num::NonZeroU8;
use termosaic::formatters;

let prose = formatters::word_wrapped("A long explanation that wraps by width.");
let fixed = formatters::fixed_width_with_tab_width(
    "name\tstatus",
    NonZeroU8::new(4).unwrap(),
);

With the json feature, human JSON is adaptive and semantically tokenized, while NDJSON remains validated machine text:

# fn example() -> Result<(), termosaic::JsonFormatError> {
let value = serde_json::json!({"status": "ready", "count": 2});
let human: termosaic::Doc = termosaic::formatters::json::pretty(&value)?;
let machine: termosaic::MachineText = termosaic::formatters::json::ndjson(&value)?;
assert!(machine.as_str().ends_with('\n'));
# Ok(()) }

MachineTextWriter::write_ndjson writes one compact record and one line feed. Machine JsonStyle::Pretty is fixed serialized JSON; it never uses terminal width, themes, or ANSI styling.

formatters::ByteSize keeps an exact u64 byte count while rendering a human-scale binary unit:

use termosaic::formatters::ByteSize;

assert_eq!(ByteSize::bytes(36_828_222_525).to_string(), "34.30 GB");
assert_eq!(ByteSize::bytes(36_828_222_525).as_u64(), 36_828_222_525);

Backgrounds and backend-owned attributes

TokenStyle carries the four attributes every terminal backend understands, plus a background. Cell-grid hosts signal selection with a fill rather than a text color:

use termosaic::{AnsiColor, Color, TokenStyle};

const SLATE: Color = Color::Rgb { red: 47, green: 53, blue: 73, fallback: AnsiColor::Blue };
let selected = TokenStyle::on(Color::Ansi(AnsiColor::White), SLATE);
assert_eq!(selected.background, Some(SLATE));

Backends need more than Termosaic can enumerate — fill characters, hyperlinks, modifiers with no Termosaic equivalent. Style attributes are the seam. The vocabulary is open, exactly like TokenId; the value domain is closed, so styles remain comparable and use compact shared storage:

use termosaic::{AttrValue, StyleAttr, TokenStyle};

const REVERSED: StyleAttr = StyleAttr::from_static("ratatui.reversed");

let style = TokenStyle::default().with_attr(REVERSED, AttrValue::Flag(true));
assert_eq!(style.attrs.get(REVERSED), Some(AttrValue::Flag(true)));

Termosaic's own writers ignore every attribute. An attribute means whatever the backend that minted it decides, and no other backend is affected by it. Themes resolve attributes alongside colors, so a rule inherits an ancestor's attributes and overlays its own. ThemeRule::clear_attr removes an inherited attribute.

Background-aware themes

Background discovery is application-controlled. background::from_env checks COLORFGBG without terminal I/O. The background-probe feature exposes an explicit bounded OSC 11 query. Unknown is the result when the terminal does not answer. themes::for_background selects the theme:

use termosaic::{Background, themes};

let theme = themes::for_background(Background::Light);
assert_eq!(theme.name().as_str(), "light");

Neither path installs process-global policy, and Console construction never performs a terminal round-trip.

Prepared documents and strict rendering

Human documents use Laidout internally, but every public document, option, capacity, and error type is owned by Termosaic. Laidout remains usable on its own and never depends on or names Termosaic.

For repeated output, retain one HumanWriter, prepare the document once, and warm the width/strategy before entering a latency-sensitive path:

use termosaic::{Doc, HumanLayoutOptions, Stream};
# fn example(console: &termosaic::Console) -> Result<(), Box<dyn std::error::Error>> {
let doc = Doc::group(Doc::concat([
    Doc::text("status"), Doc::line(), Doc::text("ready"),
]));
let prepared = doc.prepare()?;
let mut human = console.human(Stream::Stdout)?;
let capacity = human.warm_rendering(&prepared, HumanLayoutOptions::fast())?;
human.reserve_rendering(capacity)?;
human.doc_strict(&prepared, HumanLayoutOptions::fast())?;
# Ok(()) }

Preparation and warming allocate as needed. Once adequately reserved, doc_strict performs layout, ANSI generation, terminal-newline handling, and the complete no-progress write through a preinitialized nonallocating sink with zero allocator calls. Insufficient storage is a typed error and writes no document bytes. doc_prepared is the Growable alternative; release_rendering_capacity drops a retained high-water mark.

Cell-grid hosts retain the same storage without exposing Laidout:

use std::num::NonZeroU16;
use termosaic::{Doc, HumanLayoutOptions, StyledRenderWorkspace, themes};

# fn example() -> Result<(), Box<dyn std::error::Error>> {
let prepared = Doc::text("ready").prepare()?;
let mut workspace = StyledRenderWorkspace::new();
let lines = prepared.render_styled_into(
    NonZeroU16::new(80).unwrap(),
    &themes::default(),
    HumanLayoutOptions::fast(),
    &mut workspace,
)?;
assert_eq!(lines[0].text(), "ready");
# Ok(()) }

The returned lines borrow the workspace. After warming at the required high-water mark, compatible render_styled_into calls reuse layout, line, run, and text allocations. release_capacity drops the retained storage.

See the 0.2 migration guide for constructor, error, Fast-layout, and dependency changes.

Verification

./scripts/verify.sh

This checks formatting, every feature lane, core/default/all-feature tests, the example, and Clippy with warnings denied.

License

MIT