Skip to main content

Crate ansi

Crate ansi 

Source
Expand description

ansi: ANSI/VT terminal output as data, on the Rust standard library alone. Zero dependencies.

Three tightly-related capabilities, all pure bytes in / bytes out:

  • Build styled output: Style + Color render to SGR escape sequences, absolutely (Style::sgr) or as a minimal transition from a previous style (Style::transition_to).
  • Parse a terminal byte stream incrementally: Parser::feed accepts chunks split at any byte boundary (mid-escape, mid-UTF-8) and yields Tokens (text runs, C0 controls, CSI/ESC/OSC sequences).
  • Render by diff: Screen is a grid of styled Cells; Screen::diff emits the minimal cursor-move/SGR/text bytes that turn one screen into another, and Screen::render_full repaints from scratch.
use ansi::{Color, Style};

let style = Style { bold: true, fg: Color::Indexed(2), ..Style::default() };
assert_eq!(style.sgr(), "\x1b[0;1;32m");

let mut p = ansi::Parser::new();
let tokens = p.feed(b"hi\x1b[1;31mred");
assert_eq!(tokens.len(), 3); // Text("hi"), Csi(SGR 1;31), Text("red")

There is no I/O here: no raw mode, no stdin/stdout, no PTY. Those are the rawterm and pty crates’ concerns; this crate turns bytes into meaning and meaning into bytes.

Structs§

Cell
One character cell: a char, its Style, and its CellWidth. The default cell is a single-width space in the default style.
Cursor
A 0-based cursor position on a Screen. Named fields, so a row and a column cannot be transposed the way a bare (usize, usize) can.
Parser
The incremental parser. Create one per stream and call feed with each chunk as it arrives.
Screen
A rows x cols grid of Cells plus a Cursor, both 0-based.
Style
A complete character style: foreground, background, and attributes.

Enums§

CellWidth
How many terminal columns a Cell covers, modeling East Asian double-width glyphs and emoji, which occupy two columns.
Color
A terminal color: the terminal’s default, one of the 256 indexed colors (0–7 normal, 8–15 bright, 16–255 the extended cube/grays), or 24-bit RGB.
Token
One parsed unit of terminal output.