termosaic 0.2.2

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.2 supports Rust 1.88 and newer.

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.

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);

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