About libghostty-vt
Important
This book is an adaptation of the original C language libghostty-vt documentation, using the officially supported Rust bindings and slightly altered to reflect how it should idiomatically be used in Rust.
While the two sources should be largely consistent, the C documentation should be seen as the more authoritative source in case of conflicting information.
libghostty-vt is a portable, high-performance C library for terminal emulation, with officially supported bindings for Rust and more. It is open source and MIT licensed.
- It is highly generic: you give it the bytes a program writes, and it processes and exposes the state of the terminal such as the screen, the cursor, the scrollback, etc.
- It is highly portable: we build and test libghostty-vt for Linux, macOS, iOS, Android, FreeBSD, Windows, WebAssembly, and bare-metal RISC-V and ARM. It works on 32-bit and 64-bit systems.
- It is high-performance: the IO throughput is best-in-class and faster than any other known terminal emulator. Memory usage is highly optimized, one libghostty-vt consumer was able to run 10,000 active (input/output) terminals with a running shell on a 4 core 8 GB Linux machine.
- It has no dependencies: For the highest performance, the library only needs libc, but you can optionally build it without that requirement and it can be fully freestanding on its own and run directly on hardware.
You can use libghostty-vt to build:
- Terminal emulators and multiplexers
- Web terminals and remote sessions
- Session recording and playback
- Test harnesses for TUI apps
- Agents and automation that read what a TUI is showing
- Etc.
libghostty-vt was originally extracted from Ghostty, but since then is in use by hundreds of projects both free and commercial. We don’t have any tracking of course but by our best estimates libghostty-vt is used by tens of millions of people daily across every major desktop and mobile platform.
Where to Next?
- Getting the library? See Installing.
- Building a terminal? Read Your First Terminal.
- Only need one piece? The parsers and encoders work without a terminal. See Building Blocks and Input.
- Read API Conventions for general library-wide conventions.
Example
Here is a complete program. It creates a terminal, writes some text with a color sequence in it, and prints what ended up on the screen.
use libghostty_vt::{Terminal, error::Error, fmt::Formatter};
fn main() -> Result<(), Error> {
// Create an 80x24 terminal with the default allocator.
let mut terminal = Terminal::new(80, 24)?;
// Write the bytes a program would send. They can come from anywhere: a pty,
// a network connection, a recording. The escape sequences make "world" bold
// and green.
terminal.vt_write(b"Hello, \x1b[1;32mworld\x1b[0m!\r\n");
// Read the screen back. A new formatter emits plain text, so the styles
// don't appear in the output, but you can set options to enable that.
let mut formatter = Formatter::new(&terminal)?;
let buf = formatter.format_alloc(None)?;
println!("{}", buf.escape_ascii());
Ok(())
}
Full program: rust-vt-hello/src/main.rs
It prints Hello, world! in plain text. The color is in the terminal’s state
but the way we configured the formatter doesn’t show it. This has no GUI window
and doesn’t use a real PTY, but it is hopefully demonstrative of libghostty-vt
and how you could hook it up to both.
Getting Started
These two pages take you from nothing to a working terminal, in the order you’ll need them. If you only want a parser or an encoder, read the first page and then go straight to Building Blocks or Input.
- Installing - Get the library and link it into your program.
- Your First Terminal - Create a terminal, write bytes into it, read the screen back, and draw it.
Installing
The Rust bindings for libghostty-vt are available on
crates.io as libghostty_vt.
However, since it’s a C library implemented in Zig, installing it is not
as easy as just adding the crate to your project.
pkg-config
For general use cases we recommend using libghostty-vt as a system library,
usually built by your distribution or package manager. The crate discovers
the C library with pkg-config, so any package manager should work.
The Rust crate defaults to static linking, but dynamic linking is available
via the link-dynamic feature flag. Other than that, the opportunity for
configuring libghostty-vt as a system library is rather limited, as it is
usually compiled with general-purpose settings. For more fine-grained control,
you might want to vendor libghostty-vt instead.
Vendoring
When you have more specific requirements, such as finetuning the list of included
Optional Features in order to minimize binary size, using
libghostty-vt in particular hardware environments (embedded SoCs, retro hardware,
etc.), and so on, you might want to build libghostty-vt from source as a vendored
library. Opting into vendoring is done with the vendored Cargo feature.
You then need to have Zig installed and available
in your PATH (see Building from Source in the C documentation). The
crate’s build script would then download
libghostty-vt’s source tarball, build with the appropriate flags, and then
link your project to the built library. Zig features great support for
cross-compilation out of the box, so feel free to compile against any
architecture you like.
Static linking is the default, but dynamic linking is supported on most platforms. One notable exception is on iOS where everything has to be statically linked, and the build host must be macOS with both Xcode and iOS SDKs installed. This is a restriction from Apple that we cannot easily lift.
Your First Terminal
Let’s create a simple terminal that processes real bytes and produces a rendered screen. There’s no GUI or real pty attached to it, to keep the example simple and focused on libghostty-vt.
Every feature in libghostty-vt builds on the basics shown here: the function call style, error handling, and option setting. If you go through this page, then you’ll be able to easily adopt the remainder of the library.
We’ll walk through rust-vt-stream.
Installing shows how to build it, and in the repo it’s one
cargo run.
Create a Terminal
let mut terminal = Terminal::new(80, 24)?;
Full code: rust-vt-stream/src/main.rs.
Terminal::new() takes the size in columns and rows. If you want to use a
custom allocator, use Terminal::new_with_alloc(). See Memory.
libghostty-vt functions never crash your program by design, given valid use of
the API. All failure scenarios including allocation failures are handled and
returned, and libghostty-vt never puts itself into a corrupt state. Always check
the Result of every function.
Write Bytes
// Feed VT data into the terminal
terminal.vt_write(b"Hello, World!\r\n");
// ANSI color codes: ESC[1;32m = bold green, ESC[0m = reset
terminal.vt_write(b"\x1b[1;32mGreen Text\x1b[0m\r\n");
// Cursor positioning: ESC[1;1H = move to row 1, column 1
terminal.vt_write(b"\x1b[1;1HTop-left corner\r\n");
// Cursor movement: ESC[5B = move down 5 lines
terminal.vt_write(b"\x1b[5B");
terminal.vt_write(b"Moved down!\r\n");
// Erase line: ESC[2K = clear entire line
terminal.vt_write(b"\x1b[2K");
terminal.vt_write(b"New content\r\n");
// Multiple lines
terminal.vt_write(b"Line A\r\nLine B\r\nLine C\r\n");
Full code: rust-vt-stream/src/main.rs.
Terminal::vt_write() takes the raw bytes a program wrote (e.g. from a
pty, session recording, network, etc.). libghostty-vt parses all escape
sequences and applies their logic appropriately to the terminal state. Above,
\x1b[1;32m turns on bold green. \x1b[5B moves the cursor down five rows.
This call never fails, which is why there’s no result to check. You also don’t need to line your writes up with anything. A sequence or a UTF-8 character can be split across two calls and the parser picks up where it left off.
It is safe to pass untrusted data to this function. Bad input gets skipped. By default, without any effects, untrusted data can’t cause any damage. Memory usage is bounded and no side effects are possible. libghostty-vt is fuzzed 24/7 with multiple dedicated machines to keep this function safe against all forms of data input.
Your program can widen this. Be careful with effects, such as clipboard reads, and with the options that let Kitty images load from files or shared memory. Anything you read back, such as the title, also came from untrusted data, so treat it that way.
Note the end of each line is \r\n, not just \n. In terminal emulators, a
\n alone just moves the cursor down. It doesn’t move it back to the first
column.
You rarely see this because a pty normally turns a program’s \n into \r\n in
the kernel line discipline logic. But if you feed in bytes that didn’t come
through a pty, such as a text file, that’s now your job. Beware!
Read the Screen
Warning
The formatter is only for simple snapshots of the screen, such as saving it to a file or printing it once. Don’t use it for a real, live render. Use a render state instead. See Draw the Screen.
// Get the final terminal state as a plain string using the formatter
let mut formatter = fmt::Formatter::new(&terminal)?;
formatter.set_format(fmt::Format::Plain)?.set_trim(true)?;
let buf = formatter.format_alloc(None)?;
println!("{}", buf.escape_ascii());
Full code: rust-vt-stream/src/main.rs.
A terminal screen is a grid of cells with styles, wide characters, wrapped rows, etc. The formatter processes this grid state and produces the screen state into a format requested: plain text, HTML, VT sequences.
A new formatter by default emits plain text with trailing whitespace trimmed, so
the two Formatter::set_* calls here only show you where those options
are.
The program prints this:
Top-left corner
Green Text
Moved down!
New content
Line A
Line B
Line C
Notice what’s missing. We wrote Hello, World! first, but Top-left corner
went on top of it after the cursor moved to row 1. This shows that the
formatter is processing a real terminal screen.
Draw the Screen
The RenderState API exists to build a high-performance, low-latency, frame-by-frame renderer. It can be used as the foundation for CPU or GPU rendering. It does dirty tracking, viewport handling, smooth scroll handling, and more.
// Create these once and reuse them for every frame.
let mut render_state = RenderState::new()?;
let mut rows = RowIterator::new()?;
let mut cells = CellIterator::new()?;
// Capture the frame. This is the only step that reads the terminal.
let snapshot = render_state.update(&terminal)?;
// Visit only the rows that changed. In the first frame, that's all of them.
let mut row_iter = rows.update(&snapshot)?;
while let Some((_y, row)) = row_iter.next_dirty() {
let mut cell_iter = cells.update(row)?;
while let Some(cell) = cell_iter.next() {
let style = cell.style()?;
let mut graphemes = String::new();
cell.graphemes_utf8(&mut graphemes)?;
// A real renderer draws the cell here. We print it, with its bold
// style, which the plain text from the formatter didn't have.
if graphemes.is_empty() {
print!(" ");
continue;
}
if style.bold {
print!("\x1b[1m");
}
print!("{graphemes}");
if style.bold {
print!("\x1b[0m");
}
}
println!();
}
// The frame is drawn, so the next one only reports new changes.
snapshot.clean()?;
Full code: rust-vt-stream/src/main.rs.
A real renderer repeats three steps for every frame: update, draw, clean. Create the handles once, outside of that loop.
RenderState::update() is the only step that touches the terminal, which
creates a Snapshot of the render state. After that, you draw from the
snapshot alone, so your renderer doesn’t get in the way of the program writing
to the terminal. The update only redoes what changed. Because only update needs
access to the terminal, this is the only critical area that requires a lock for
multi-threaded terminal and renderers.
Note
Unlike the C API, in Rust we make a clear distinction between a
RowIteratorand aRowIteration. While the iterator can be reused over and over again, the iteration only reflects its current state, after being fed up-to-date data. This is to prevent users from accessing stale or invalid state when iterators aren’t yet ready.This design is symmetrical across all handles of the render state API:
Handle created on startup State on each frame RenderStateSnapshotRowIteratorRowIterationCellIteratorCellIterationImageIteratorImageIteration
RowIteration::next_dirty() skips the rows that didn’t change, which is most of
them in most frames. Once you’ve drawn a complete frame, Snapshot::clean()
marks it as done. An update never clears the dirty state, so without this call
every row stays dirty.
This program draws by printing, so you see the same screen as the formatter
printed, except that Green Text is now bold. It’s still not green, because we
didn’t read the colors. See Rendering for the colors, the cursor, and
how to share a terminal with a renderer thread.
Drop Everything
libghostty-vt does allocate at times, and they need to be dropped. Fortunately, the Rust bindings use Rust’s lifetime and RAII rules as much as possible to drop them in the correct order.
The buffer from Formatter::format_alloc() is yours. You can drop it whenever
you want, as long as the buffer does not outlive the allocator it that gave
its memory. See Allocating and Dropping Buffers.
The formatter borrows the terminal, so the terminal has to outlive it. Drop the formatter first.
The render state and its iterators are yours too. The borrow checker should be able to ensure they are dropped in order.
The terminal should be dropped last.
The rules for handles are the same across the whole library. See Handles.
What to Read Next
- Effects - Answer the things a program asks of the terminal.
- Examples - Complete programs for everything else.
Guides
A guide is a page you read top to bottom to learn how to do one thing. The API Reference is where you look something up. If you know what you want to do but not which functions do it, start here.
- Effects - Answer the things a program asks of the terminal, such as the bell, title changes and queries.
- Rendering - Draw a terminal: copy a frame out from under the lock, redraw only what changed, and respect render holds.
- Input - Encode keys, mouse events, focus changes and pastes, and keep the encoders in step with the terminal’s modes.
- Colors - Set a theme, read colors back, parse color strings, and report light or dark mode.
- Grid - Name a position in the grid, read its cells, and hold onto a cell as the terminal changes.
- Selection - Select text, turn pointer gestures into selections, and copy them out.
- Scrollback - Limit history, scroll through it, draw a scrollbar, and keep its memory down.
- Search - Find a string in the screen and scrollback, and drive the search from your event loop or a thread.
- Images - Accept the images programs send, decode PNGs, draw them, and play animations.
- Snapshots - Save a terminal’s full state, and restore it in one call or a piece at a time.
- Custom Sequences - Handle sequences we don’t implement, and stop a write at a string boundary.
Effects
An effect is a callback the terminal calls when a program asks for something the terminal can’t do by itself. That means things like ringing the bell, changing the window title, writing to the clipboard, or answering a query.
Why callbacks? libghostty-vt has no window, no clipboard and no pty. Those are yours. When a program writes a BEL we know what it means, but we can’t make a sound. So we tell you, and you decide what a bell is.
By default, the VT write functions only process sequences that directly change terminal state. Anything with a side effect or a reply is ignored until you register a callback for it. That includes queries, so a program that asks a question gets no answer.
If you’re only feeding bytes into a terminal to read the result back, you can skip this page. You need effects as soon as a real program runs in the terminal.
Registering an effect
Each effect can be registered by passing a callback into a corresponding function on
Terminal, prefixed with on_:
terminal.on_bell(|_term| println!("Ring-a-ding-a-ding!"));
The callbacks always receive a shared reference to the Terminal as their
first parameter, as well as other parameters depending on the exact callback.
The rules for callbacks
Callbacks run synchronously, in the middle of Terminal::vt_write() or
Terminal::vt_write_until(). All of these rules come from that.
You can’t write to the same terminal from a callback. The terminal is still
working through the first write, and it isn’t reentrant. This applies to both
vt_write() and vt_write_until(). For this reason, callbacks only
receive a shared reference to the terminal, which cannot call
mutating functions like vt_write().
Don’t block, and don’t do anything expensive. Further IO processing waits until your callback returns, so a slow callback is a slow terminal.
Copy what you want to keep. Strings and buffers passed to a callback are borrowed, and they’re only valid until it returns.
The effects
There are 19 effects:
| Function | Callback type | Trigger |
|---|---|---|
on_pty_write | PtyWriteFn | VT query and mode reports written back to the pty |
on_bell | BellFn | BEL character (0x07) |
on_title_changed | TitleChangedFn | Title change via OSC 0 / OSC 2 |
on_pwd_changed | PwdChangedFn | Pwd change via OSC 7 / OSC 9 / OSC 1337 |
on_enquiry | EnquiryFn | ENQ character (0x05) |
on_xtversion | XtversionFn | XTVERSION query (CSI > q) |
on_size | SizeFn | XTWINOPS query (CSI 14/16/18/19 t) or mode 2048 enable |
on_color_scheme | ColorSchemeFn | Color scheme query (CSI ? 996 n) |
on_device_attributes | DeviceAttributesFn | Device attributes query (CSI c, CSI > c, CSI = c) |
on_clipboard_write | ClipboardWriteFn | Clipboard write via OSC 52 / OSC 1337 / OSC 5522 |
on_clipboard_read | ClipboardReadFn | Clipboard read via OSC 52 ? / OSC 5522 |
on_desktop_notification | DesktopNotificationFn | Desktop notification via OSC 9 / OSC 777 |
on_progress_report | ProgressReportFn | Progress report via OSC 9;4 |
on_program_status | ProgramStatusFn | Program status report via OSC 7501 |
on_unknown_sequence | UnknownSequenceFn | APC or OSC sequence we don’t implement. See Custom Sequences |
on_render_hold | RenderHoldFn | Synchronized output (mode 2026) begins or ends |
on_semantic_prompt | SemanticPromptFn | Shell reports a prompt or command step via OSC 133 |
on_reset | ResetFn | Full reset (RIS, ESC c) |
on_resize_window | ResizeWindowFn | Window resize request (CSI 8 t) |
Common callbacks
These are the callbacks most terminals start with. Each one is from the same example program, which prints what it receives.
Replying to the program
Start with this one. Every reply the terminal generates comes through it, such as the answer to a device status report or a mode query. Write the bytes to your pty. The data is only valid during the call, so copy it if you can’t write it right away.
terminal.on_pty_write(|_term, data| {
println!(
" pty_write ({} bytes): {}",
data.len(),
data.escape_ascii()
);
})?;
Full program: rust-vt-effects/src/main.rs
The bell
The bell has no data at all. This one counts bells with a state variable
placed within a Cell, which allows for
interior mutability.
// Specific to the Rust bindings: any state borrowed by the callbacks
// mutably is held mutably for the entire lifetime of the terminal,
// which means that it cannot be accessed by other parties, including
// other callbacks. They must therefore also outlive the terminal.
//
// To prevent this, use a type with _interior mutability_ which allows
// the value inside to be safely mutated by an immutable, shared reference.
// In this case, `usize` is a simple `Copy` type, so we can use `Cell`s
// here. Non-copy types need to use `RefCell`s instead.
let bell_count = Cell::new(0usize);
// ...
terminal.on_bell({
// Explicitly borrow the bell count, or otherwise `move`
// will attempt to capture the entire `Cell` and cause a
// compiler error
let bell_count = &bell_count;
move |_term| {
bell_count.update(|v| v + 1);
println!(" bell! (count={})", bell_count.get());
}
})?;
Full program: rust-vt-effects/src/main.rs
Title changes
The callback tells you the title changed, but not what it changed to. You can
read the new title with Terminal::title inside the callback.
terminal.on_title_changed(|term| {
// The new title is already set, so you can read it here with
// `Terminal::title`. This example reads the cursor position
// to show that the terminal can be queried from a callback.
let col = term.cursor_x().unwrap();
println!(" title changed (cursor at col {col})");
})?;
Full program: rust-vt-effects/src/main.rs
Clipboard writes
A write is a request, not a command. You should ask the person using your
terminal unless granted is set, and the stream waits until your callback
returns while you do.
Answer by calling reply before you return. If you return without replying, the
write is denied. Every entry in contents is a representation of the same
value, so commit them together. A contents_len of zero asks you to clear the
clipboard.
terminal.on_clipboard_write(|_term, write| {
// The write is synchronous: a real embedder would ask the user for
// permission here (unless `write.granted()`) and the VT stream waits until
// this callback returns. The replied result is sent to the program
// (OSC 5522) through the on_pty_write callback.
let contents = write.contents();
println!(
" clipboard write (location={:?}, contents={})",
write.location(),
contents.len()
);
if contents.len() == 0 {
println!(" clear");
}
for content in contents {
print!(" ");
if !content.mime.is_empty() {
print!("{}", content.mime.escape_ascii());
}
print!(" ({} bytes): ", content.data.len());
if !content.data.is_empty() {
print!("{}", content.data.escape_ascii());
}
println!();
}
write.reply(Ok(()), false);
})?;
Full program: rust-vt-effects/src/main.rs
Clipboard reads
Reads work the same way. Ask first unless granted is set, and call reply
before you return. If you return without replying, the program gets an empty
clipboard for OSC 52 and EPERM for OSC 5522.
terminal.on_clipboard_read(|_term, read| {
// The read is synchronous: a real embedder would ask the user for
// permission here (unless read->granted) and the VT stream waits until
// this callback returns. The reply is sent to the program through the
// on_pty_write callback.
let mimes = read.mimes();
println!(
" clipboard read (location={:?}, mimes={})",
read.location(),
mimes.len()
);
for mime in mimes {
println!(" {}", mime.escape_ascii());
}
// Reply with every requested representation we have.
// This example only has text.
read.reply(
Ok(&[ClipboardReplyContent::new(
b"text/plain",
b"Hello from the clipboard",
)]),
&[],
false,
);
})?;
Full program: rust-vt-effects/src/main.rs
Sequences we don’t implement
The callback for unknown sequences has more to it than the others, so it has its own guide. See Custom Sequences.
Putting it together
This registers the callbacks above, along with the unknown sequence callback, and then writes a sequence for each one so you can watch them fire.
// Feed VT data that triggers effects:
// 1. Bell (BEL = 0x07)
println!("Sending BEL:");
terminal.vt_write(b"\x07");
// 2. Title change (OSC 2 ; <title> ST)
println!("Sending title change:");
terminal.vt_write(b"\x1B]2;Hello Effects\x1B\\");
// 3. Device status report (DECRQM for wraparound mode ?7)
// triggers write_pty with the response
println!("Sending DECRQM query:");
terminal.vt_write(b"\x1B[?7$p");
// 4. Clipboard write (OSC 52 ; c ; <base64 data> ST)
println!("Sending clipboard write:");
terminal.vt_write(b"\x1B]52;c;SGVsbG8gY2xpcGJvYXJk\x1B\\");
// 5. Clipboard read (OSC 52 ; c ; ? ST)
println!("Sending clipboard read:");
terminal.vt_write(b"\x1B]52;c;?\x1B\\");
// 6. Unsupported APC sequence
println!("Sending unknown APC:");
terminal.vt_write(b"\x1B_private-command;payload\x1B\\");
println!("Sending unknown OSC:");
terminal.vt_write(b"\x1B]7400;status=busy\x07");
// 7. Another bell to show the counter increments
println!("Sending another BEL:");
terminal.vt_write(b"\x07");
println!("Total bells: {}", bell_count.get());
Full program: rust-vt-effects/src/main.rs
Rendering
A render state is a copy of everything you need to draw one frame: the rows, the cells, the cursor, and the colors.
Why a copy? Your renderer and your IO are usually on different threads. The terminal changes every time the program writes a byte, and you can’t draw from something that is changing underneath you. You could hold a lock for the whole frame, but then the program stalls while you draw.
With a render state you take the lock, update, and let go. Everything after that reads only from the render state.
It’s also built for being updated over and over from the same terminal. An update only redoes what changed, and it tells you what changed so you can redraw only that.
If you only want the screen as text, you don’t need this page. Use the Formatter instead. Images have their own guide, Images.
Drawing a frame
There are three steps:
- Create an empty render state.
- Update it from a terminal whenever you need a new frame. This returns a snapshot of the render state.
- Read from the snapshot to draw.
// Create a terminal and render state, then update the render state
// from the terminal. The render state captures a snapshot of everything
// needed to draw a frame.
let mut terminal = Terminal::new(40, 5)?;
let mut render_state = RenderState::new()?;
// Feed some styled content into the terminal.
terminal.vt_write(b"Hello, \x1b[1;32mworld\x1b[0m!\r\n"); // bold green "world"
terminal.vt_write(b"\x1b[4munderlined\x1b[0m text\r\n"); // underlined text
terminal.vt_write(b"\x1b[38;2;255;128;0morange\x1b[0m\r\n"); // 24-bit orange fg
// Select "underlined" on the second row. Render state exposes this
// later as a row-local selected cell range.
let selection_start = terminal.grid_ref(Point::Active(Coordinate { x: 0, y: 1 }))?;
let selection_end = terminal.grid_ref(Point::Active(Coordinate { x: 9, y: 1 }))?;
let selection = terminal.select(selection_start, selection_end, false);
terminal.set_selection(Some(selection))?;
let snapshot = render_state.update(&terminal)?;
Full program: rust-vt-render/src/main.rs
Now read what you need. The colors come as one struct:
// Retrieve colors (background, foreground, palette) from the render
// state. These are needed to resolve palette-indexed cell colors.
let colors = snapshot.colors()?;
println!(
"Background: #{:02x}{:02x}{:02x}",
colors.background.r, colors.background.g, colors.background.b
);
println!(
"Foreground: #{:02x}{:02x}{:02x}",
colors.foreground.r, colors.foreground.g, colors.foreground.b
);
Full program: rust-vt-render/src/main.rs
So does the cursor:
// Read all cursor state in one call.
let cursor = snapshot.cursor()?;
if cursor.visible
&& let Some(viewport) = cursor.viewport
{
let style_name = match cursor.visual_style {
CursorVisualStyle::Bar => "bar",
CursorVisualStyle::Block => "block",
CursorVisualStyle::Underline => "underline",
CursorVisualStyle::BlockHollow => "hollow",
_ => "unknown",
};
println!(
"Cursor at ({}, {}), style: {}",
viewport.x, viewport.y, style_name
);
}
Full program: rust-vt-render/src/main.rs
Rows and cells have their own iterators. Row and cell data is only valid until the next update.
// Iterate rows via the row iterator. For each dirty row, iterate its
// cells, read codepoints/graphemes and styles, and emit ANSI-colored
// output as a simple "renderer".
let mut rows = RowIterator::new()?;
let mut cells = CellIterator::new()?;
let mut row_it = rows.update(&snapshot)?;
while let Some((y, row)) = row_it.next_dirty() {
print!("Row {y} [dirty]: ");
// Query the row-local selection range. Rows without a selection return
// `None`; selected rows return inclusive start/end columns.
if let Some(selection) = row.selection()? {
print!("selection={}..{}", selection.start_x, selection.end_x);
}
// Get cells for this row (reuses the same cells handle).
let mut cell_it = cells.update(row)?;
while let Some(cell) = cell_it.next() {
// Get the graphemes of this cell.
let graphemes = cell.graphemes()?;
if graphemes.is_empty() {
print!(" ");
continue;
}
// Read the style for this cell. Returns the default style for
// cells that have no explicit styling.
let style = cell.style()?;
// Resolve foreground color for this cell.
let fg = cell.fg_color()?.unwrap_or(colors.foreground);
// Emit ANSI true-color escape for the foreground.
print!("\x1b[38;2;{};{};{}m", fg.r, fg.g, fg.b);
if style.bold {
print!("\x1b[1m");
}
if style.underline != Underline::None {
print!("\x1b[4m");
}
// Print the read grapheme codepoints.
// In a real renderer you would reuse a grapheme buffer for this step.
print!("{}", String::from_iter(graphemes));
print!("\x1b[0m"); // Reset style after each cell.
}
println!();
}
Full program: rust-vt-render/src/main.rs
Two-phase updates
RenderState::update() needs exclusive access to the terminal for the
whole call. If a renderer thread shares a lock with an IO thread, you can hold
that lock for less time by splitting the update in two.
RenderState::begin_update() needs the terminal and returns a render::Update
object. render::Update::end() finishes any work that was deferred, and it
only touches memory the render state owns. So lock, begin, unlock, and then end
while the IO thread goes back to modifying the terminal:
let update = {
let terminal = terminal_mutex.lock().unwrap();
render_state.begin_update(&terminal)
};
let snapshot = update.end();
Every begin needs an end before you read the render state, because it’s
incomplete until then. RenderState::update() is the same as calling the two
back to back.
Dirty tracking
Most frames change very little, so the render state tracks what changed and you redraw only that.
There are two independent layers. A global state says if the frame is clean, partially dirty or fully dirty. A flag on each row says which rows changed in a partially dirty frame.
// Check the global dirty state to decide how much work the renderer
// needs to do. After rendering, reset it to false.
match snapshot.dirty()? {
Dirty::Clean => println!("Frame is clean, nothing to draw."),
Dirty::Partial => println!("Partial redraw needed."),
Dirty::Full => println!("Full redraw needed."),
}
Full program: rust-vt-render/src/main.rs
An update only ever sets dirty state, it never clears it. That’s your job. Once
you’ve drawn a complete frame, Snapshot::clean clears both layers in one
call:
// After successfully rendering the complete frame, clear both the global
// and per-row dirty state in one call.
snapshot.clean()?;
Full program: rust-vt-render/src/main.rs
If you only use part of a frame, clear what you used with
Snapshot::set_dirty() and RowIteration::set_dirty() instead.
Be careful here, because clearing one layer doesn’t clear the other. Setting the
global state to false leaves every row flag as it was, so you have to manage
both.
Render holds
A render hold is the time between a program asking the terminal to stop updating the screen and letting it update again.
Programs use holds to avoid flicker. A full-screen program usually redraws in several steps: clear, draw the text, move the cursor. If you draw halfway through, the person using your terminal sees a broken frame. So the program starts a hold, draws everything, and releases it. The screen should keep showing the last finished frame the whole time and then switch to the new one all at once.
Today the only way to start a hold is synchronized output (DEC private mode
2026, Mode::SYNC_OUTPUT). The callback is named for what you should do
rather than for that mode, so that other sources of holds can be added later.
RenderState::update() doesn’t check for any of this. It always captures
the terminal as it is right now, so a renderer that updates on every draw shows
half-drawn frames. To avoid that:
- Set a
Terminal::on_render_hold()callback on the terminal. - When a hold begins, update the render state from inside the callback. At that
moment the terminal holds exactly the frame the program wants left on screen.
Nothing after the start of the hold has been processed yet, even if more
bytes follow in the same
Terminal::vt_write(). - Don’t update the render state again until the hold ends. You can keep drawing it in the meantime, and it won’t change.
- End the hold yourself if it lasts too long.
You need the timeout. The terminal has no clock, so it never ends a hold on its own, and a program that crashes or forgets to release its hold would freeze your screen forever. One second is a common limit. When it expires, reset the mode yourself and go back to updating normally. Setting the mode again during a hold does nothing, so a program can’t keep pushing your deadline back.
Why a callback? You could check Mode::SYNC_OUTPUT before each draw and
skip the update when it’s set. That’s simpler, but it has two problems. First,
the frame left on screen is whatever you happened to draw last, which can be
older than what the program intended or even half-drawn. Second, if the program
releases a hold and starts the next one between two of your draws, you never see
the mode turn off, and the finished frame in between is lost. A program that
draws continuously can then look frozen. Capturing the frame when each hold
begins avoids both.
You’re free to ignore a hold whenever live content matters more, such as when someone scrolls or starts a selection.
Like every callback, this one runs on the thread that called
Terminal::vt_write(). If another thread draws the render state, protect
the update in the callback the same way you protect any other access to it.
Overscan
By default, a render state captures exactly the rows visible in the viewport. That’s all you need if you draw whole rows, so most programs can skip this section.
Some renderers draw the grid shifted by a fraction of a row, usually to scroll smoothly. While the grid is shifted, part of a row just outside the viewport shows at one edge, and you need that row’s content to draw it. Overscan captures extra rows above and below the viewport for this.
Request it with RenderState::set_overscan(). The request applies to every
update after you set it, and you should expect a full redraw on the update after
a change. The row iterator then visits the extra rows along with the viewport,
from top to bottom. RowIteration::viewport_y() tells you where
each row belongs: rows above the viewport are negative, viewport rows are 0
through snapshot.rows() - 1, and rows below the viewport start at snapshot.rows().
Extra rows are only captured when they exist. There’s nothing above the first
line of scrollback, and there’s nothing below the viewport while it’s scrolled
to the bottom, which is the usual case. After an update, Snapshot::overscan()
reports how many rows were actually captured on each side. Don’t shift the grid
toward a side where nothing was captured.
Extra rows carry the same data as viewport rows, including cells, styles, dirty flags and selection. The cursor is only reported when it’s inside the viewport.
The render state doesn’t store the scroll position. If you need it, read
Terminal::scrollbar() or Terminal::viewport_active() at the same time as you
call RenderState::begin_update(), while you have exclusive access to the
terminal. The values then describe the same moment as the render state.
This draws one frame of a smooth scroll. offset_px comes from your own scroll
animation. It’s how far the grid is shifted up, from zero up to but not
including one row height.
// Once, when setting up the render state. One row below the viewport
// is enough to draw the partially visible row at the bottom edge.
render_state.set_overscan(Overscan { above: 0, below: 1 })?;
// Each frame.
let snapshot = render_state.update(&terminal)?;
let captured = snapshot.overscan()?;
// With no row below the viewport, there is nothing to scroll into.
if captured.below == 0 { offset_px = 0; }
let mut row_iter = rows.update(&snapshot)?;
while let Some(row) = row_iter.next() {
let y = row.viewport_y()?;
draw_row(row, y * cell_height - offset_px);
}
Row identity
Every row has an id, RowIteration::id(), that stays with the row
as it moves. When the viewport scrolls by one row, each row shows up one
position higher or lower in the next update but keeps its id. Ids work with or
without overscan.
Ids let you keep expensive per-row work, such as shaped text or a prepared texture, in your own cache keyed by id. You can reuse a cached entry when both of these are true:
- A row with the same id is in the new update.
- That row’s dirty flag isn’t set.
The dirty flag is conservative. A row can be marked dirty even though its content didn’t change. For example, every row is currently marked dirty after the viewport scrolls. Rebuilding a dirty row is always correct.
An id disappears when its row is no longer captured, is removed from scrollback, or is changed in place by the terminal, for example when a program scrolls only part of the screen. Ids are never reused, so an old id can never match a different row. You can throw away cache entries for ids that no longer appear.
while let Some(row) = row_iter.next() {
let id = row.id()?;
// `cache` is your own map from row id to prepared row.
let prepared = if row.dirty()? { None } else { cache.find(id) };
let prepared = prepared.or_else(|| cache.prepare(id, row));
draw_prepared_row(prepared);
}
Input
Input is everything a person does that a program needs to hear about: keys, mouse events, focus changes and pastes. All of it reaches the program the same way, as bytes on the pty. These functions produce those bytes.
The catch is that the right bytes keep changing. The up arrow is ESC [ A until
a program turns on cursor key application mode, and then it’s ESC O A. A
program can turn on the Kitty keyboard protocol and get a different encoding for
its keys. A click is nothing at all until a program turns on mouse tracking, and
then it’s one of five formats. A paste is framed differently under bracketed
paste.
So an encoder has to follow the terminal’s modes, or it writes the wrong bytes.
If you have a Terminal, following its modes takes one call per encoder.
That’s the first section, and it’s the one thing on this page you have to get
right. If you only feed a terminal output and read the result, you can skip this
page. You need it as soon as a person can type into your terminal.
Following the terminal’s modes
Each kind of input follows the terminal in its own way:
| Input | How it follows the terminal |
|---|---|
| Keys | key::Encoder::set_options_from_terminal copies the modes into the encoder. |
| Mouse | mouse::Encoder::set_options_from_terminal copies the tracking mode and format into the encoder. |
| Focus | There’s no encoder. You check the mode yourself. |
| Paste | Terminal::paste reads the modes itself. |
The two set_options_from_terminal calls read the terminal’s state when you make them.
They don’t stay attached to it, and a program can change its modes in any write.
So sync the encoder after you write to the terminal, or right before you encode.
// Create a terminal and feed it some VT data that changes modes.
let mut terminal = Terminal::new(80, 24)?;
// The program might enable the Kitty keyboard protocol here.
terminal.vt_write(data);
// Create an encoder and sync its options from the terminal.
let encoder = key::Encoder::new()?;
encoder.set_options_from_terminal(&terminal);
// Encode a key event using the terminal's modes.
let mut buf = [0u8; 128];
let written = encoder.encode(event, &mut buf)?;
The mouse works the same way with mouse::Encoder::new,
mouse::Encoder::set_options_from_terminal and mouse::Encoder::encode.
Each sync leaves some options to you:
- The key sync replaces all of the encoder’s options. That covers cursor key
application mode, keypad mode, ignoring the keypad with numlock, the alt
escape prefix, backarrow key mode, modifyOtherKeys state and the Kitty
keyboard flags. It can’t know your macOS option key setting, so it resets
key::Encoder::set_macos_option_as_alttokey::OptionAsAlt::False. If you use that option, set it again after every sync. - The mouse sync sets the tracking mode and output format. It doesn’t touch the size or whether a button is held. Those are yours. See Mouse.
Without a terminal, there’s nothing to follow. Set the options yourself with
the various setters on key::Encoder and mouse::Encoder, as the examples
below do.
Keys
We encode keys with the legacy encoding or the Kitty keyboard protocol, depending on the encoder’s options.
- Create an encoder with
key::Encoder::new. - Configure it with
key::Encoder::set_options_from_terminal, or with other setters if you don’t have a terminal. - For each key event, create an event with
key::Event::new, set its action, key, modifiers and so on, and encode it withkey::Encoder::encode. Then drop it, or change its properties and use it again.
This one has no terminal, so it turns on the Kitty keyboard protocol by hand:
use libghostty_vt::{error::Error, key};
fn main() -> Result<(), Error> {
// Create encoder
let mut encoder = key::Encoder::new()?;
// Enable Kitty keyboard protocol with all features
encoder.set_kitty_flags(key::KittyKeyFlags::ALL);
// Create and configure key event for Ctrl+C press
let mut event = key::Event::new()?;
event
.set_action(key::Action::Press)
.set_key(key::Key::C)
.set_mods(key::Mods::CTRL)
.set_unshifted_codepoint('c');
// Encode the key event
let mut buf = [0u8; 128];
let len = encoder.encode(&event, &mut buf)?;
// Use the encoded sequence (e.g., write to terminal)
println!("{}", buf[0..len].escape_ascii());
Ok(())
}
Full program: rust-vt-encode-key/src/main.rs
Not every key event produces output. An unmodified modifier key usually doesn’t,
for example. Those events return Ok(0), so check the count before you write to
the pty.
Most sequences are short, so a fixed buffer of 128 bytes usually does. If it’s
too small, you get Error::OutOfSpace with the size you need. Discard what’s
in the buffer and encode again with a bigger one.
Mouse
We encode mouse events in the X10, UTF-8, SGR, URxvt and SGR-Pixels formats. The steps are the same as for keys:
- Create an encoder with
mouse::Encoder::new. - Configure it with
mouse::Encoder::set_options_from_terminal, or with other setters if you don’t have a terminal. - For each mouse event, create an event with
mouse::Event::new, set its action, button, modifiers and position, and encode it withmouse::Encoder::encode. Then drop it or reuse it.
Event positions are in surface-space pixels, so the encoder has to know your
geometry to turn them into cells. Set it with mouse::Encoder::set_size.
The default is a 1x1 pixel screen with 1x1 pixel cells, which is never what you have.
Call mouse::Encoder::set_any_button_pressed as well, to say whether a button
is held. Neither one comes from the terminal.
use libghostty_vt::{error::Error, mouse};
fn main() -> Result<(), Error> {
// Create encoder
let mut encoder = mouse::Encoder::new()?;
// Configure SGR format with normal tracking
encoder
.set_tracking_mode(mouse::TrackingMode::Normal)
.set_format(mouse::Format::Sgr);
// Set terminal geometry for coordinate mapping
encoder.set_size(mouse::EncoderSize {
screen_width: 800,
screen_height: 600,
cell_width: 10,
cell_height: 20,
..mouse::EncoderSize::default()
})?;
// Create and configure a left button press event
let mut event = mouse::Event::new()?;
event
.set_action(mouse::Action::Press)
.set_button(Some(mouse::Button::Left))
.set_position(mouse::Position { x: 50.0, y: 40.0 });
// Encode the mouse event
let mut buf = [0u8; 128];
let len = encoder.encode(&event, &mut buf)?;
// Use the encoded sequence (e.g., write to terminal)
println!("{}", buf[0..len].escape_ascii());
Ok(())
}
Full program: rust-vt-encode-mouse/src/main.rs
As with keys, not every event produces output, so check the count. And as with keys, a 128-byte buffer is enough for typical events.
If you call mouse::Encoder::set_track_last_cell with true, the encoder
deduplicates motion by the last cell. mouse::Encoder::reset clears that
state.
Focus
A program that turns on focus reporting (mode 1004) wants to know when your
terminal gains or loses focus. focus::Event::encode encodes that as CSI I
or CSI O. There’s no encoder to create and no options to set.
It also doesn’t look at the terminal, so it’s up to you to check the mode first:
if terminal.mode(Mode::FOCUS_EVENT).ok_or(false) {
// Encode the event and write it to the pty.
}
If the buffer is too small, you get Error::OutOfSpace and the size you need.
use libghostty_vt::focus;
fn main() {
let mut buf = [0u8; 8];
if let Ok(len) = focus::Event::Gained.encode(&mut buf) {
println!("Encoded {} bytes: {}", len, buf[0..len].escape_ascii());
}
}
Full program: rust-vt-encode-focus/src/main.rs
Paste
What a paste writes to the pty depends on the terminal’s state, so the way to
paste is Terminal::paste. You give it the MIME types the clipboard
holds (just text/plain for an ordinary paste), a MIME reader callback that
produces the data of any one of them, and where the paste came from. The
terminal decides how its current modes apply.
The bytes come out of the Terminal::on_pty_write callback, so you need
one installed. See Effects.
What gets written
The terminal sends the program a paste event instead of the data if all three of these are true:
- Kitty clipboard protocol paste events (mode 5522,
Mode::PASTE_EVENTS) are on. - The person pasted from a clipboard (
paste::Source::Clipboard). - You’ve installed a clipboard read callback.
A paste event lists the clipboard’s MIME types with a one-time password. No data
is read for it. The program then reads what it wants through your clipboard read
callback, which arrives with granted set, so you don’t need to ask for
permission.
Otherwise the terminal writes the first text representation. Unsafe control
bytes are replaced with spaces. If mode 2004 (Mode::BRACKETED_PASTE) is
on, the text is wrapped in bracketed paste sequences. If it’s off, newlines are
converted to carriage returns.
We only pull data through the MIME reader when a representation is actually pasted, so a clipboard holding a large image next to some text costs nothing. The encoded bytes stream to your callback in chunks as they’re produced, never in one piece. It may run several times for one paste, and you have to write the pieces to the pty in order.
Unsafe pastes
Some text could inject commands: a newline or carriage return when the paste
isn’t bracketed, or the bracketed paste terminator when it is. We refuse that
text with Error::Rejected and write nothing, unless GhosttyPaste::allow_unsafe
is set.
The usual flow is to call once, confirm with the person on Error::Rejected,
and call again with allow_unsafe set. Each call reads the text at most once
and buffers it whole while the rule is applied. So your source doesn’t have to
stay the same between reads. The confirmed retry just pastes whatever the source
holds by then, and a refused or failed paste writes nothing at all.
/// What the clipboard holds. A real embedder would keep a handle to the
/// pasteboard or its items here; the data is only produced on demand.
struct Clipboard {
text: &'static str,
}
impl Clipboard {
/// Produces the data of one representation when the terminal needs it.
/// Only the text is ever read: the image is listed on a paste event
/// but never requested, so a large image costs nothing to paste.
/// Nothing written to the writer is retained, so the data can be
/// streamed from anywhere in pieces of any size.
fn read(&self, mime: &[u8], writer: &mut dyn Write) -> io::Result<()> {
match mime {
b"text/plain" => {
// Stream the text in small pieces just to show that it works.
for chunk in self.text.as_bytes().chunks(4) {
writer.write_all(chunk)?;
}
Ok(())
}
_ => Err(io::Error::other(
"image read requested, which never happens",
)),
}
}
}
// Paste whatever the clipboard holds. The terminal applies its own
// state: bracketed paste framing (mode 2004) or a Kitty paste event
// (mode 5522) instead of the text.
fn paste_clipboard(terminal: &mut Terminal<'_, '_>, text: &'static str) {
let clipboard = Clipboard { text };
let options = paste::Options::new()
.with_location(effect::ClipboardLocation::Standard)
.with_source(paste::Source::Clipboard);
let mimes = &[
// The first text representation is what a text paste writes.
effect::ClipboardMime::new(b"text/plain"),
// Listed on a paste event, never read.
effect::ClipboardMime::new(b"image/png"),
];
let mut result = terminal.paste(options, mimes, |mime, writer| clipboard.read(mime, writer));
if let Err(Error::Rejected) = result {
// The text could inject commands (e.g. a newline outside of a
// bracketed paste). Nothing was written; ask, then retry.
if !confirm_with_user() {
return;
}
result = terminal.paste(options.with_allow_unsafe(true), mimes, |mime, writer| {
clipboard.read(mime, writer)
});
}
match result {
// Whether the pty got the text or a paste event depends on the
// terminal's modes; either way it went through write_pty above, in
// chunks as the text was read.
Ok(true) => println!(" written"),
Ok(false) => println!(" nothing to paste"),
Err(e) => eprintln!("paste failed: {e}"),
}
}
Full program: rust-vt-paste/src/main.rs
Without a terminal
If you encode without a terminal, there are two building blocks.
paste::is_safe checks whether paste data contains potentially dangerous
sequences. It’s conservative, and it ignores terminal state.
fn safety_example() {
if paste::is_safe(b"hello world") {
println!("Safe to paste");
}
if paste::is_safe(b"rm -rf /\n") {
println!("Unsafe! Contains newline");
}
}
Full program: rust-vt-paste/src/main.rs
paste::encode encodes paste data for the pty, including bracketed paste
wrapping and unsafe byte stripping. It modifies your input buffer in place.
fn encode_example() {
let mut buf = [0u8; 64];
// The input buffer is modified in place (unsafe bytes are stripped).
let mut data = *b"hello\nworld";
if let Ok(len) = paste::encode(&mut data, true, &mut buf) {
println!("Encoded {len} bytes: {}", buf[0..len].escape_ascii());
}
}
Full program: rust-vt-paste/src/main.rs
Colors
A terminal has a foreground color, a background color, a cursor color and a 256-color palette. You set them to your theme, and the programs running in the terminal can change them.
That’s the problem this page is about. A program can change the background with an OSC sequence, but that shouldn’t erase the theme you configured. So each color has two layers: a default that you set, and an override that programs set with OSC sequences, such as OSC 10, 11 and 12 for the foreground, background and cursor, and OSC 4 for a palette entry.
If you only need to set a theme, read the first two sections. The rest is for reading colors out of config files, generating palettes, and telling programs whether you’re in light or dark mode.
Setting your theme
Use the various Terminal::set_default_* methods to set the default colors.
Passing None clears a default and leaves that color unset.
| Option | Input type | Description |
|---|---|---|
Terminal::set_default_fg_color | Option<Rgb> | Default foreground color |
Terminal::set_default_bg_color | Option<Rgb> | Default background color |
Terminal::set_default_cursor_color | Option<Rgb> | Default cursor color |
Terminal::set_default_color_palette | Option<Palette> | Default 256-color palette |
The palette is a little different. Passing None resets it to the built-in
default palette, and setting it keeps any per-index overrides that programs have
applied. Only the unmodified indices are updated.
/// Set up a dark color theme with custom palette entries.
fn set_color_theme(terminal: &mut Terminal<'_, '_>) -> Result<(), Error> {
// Set default foreground (light gray) and background (dark)
terminal
.set_default_fg_color(Some(Rgb { r: 0xDD, g: 0xDD, b: 0xDD }))?
.set_default_bg_color(Some(Rgb { r: 0x1E, g: 0x1E, b: 0x2E }))?
.set_default_cursor_color(Some(Rgb { r: 0xF5, g: 0xE0, b: 0xDC }))?;
// Set a custom palette — start from the built-in default and override
// the first 8 entries with a custom dark theme.
let mut palette = terminal.color_palette()?;
palette.set(PaletteIndex::BLACK, Rgb { r: 0x45, g: 0x47, b: 0x5A });
palette.set(PaletteIndex::RED, Rgb { r: 0xF3, g: 0x8B, b: 0xA8 });
palette.set(PaletteIndex::GREEN, Rgb { r: 0xA6, g: 0xE3, b: 0xA1 });
palette.set(PaletteIndex::YELLOW, Rgb { r: 0xF9, g: 0xE2, b: 0xAF });
palette.set(PaletteIndex::BLUE, Rgb { r: 0x89, g: 0xB4, b: 0xFA });
palette.set(PaletteIndex::MAGENTA, Rgb { r: 0xF5, g: 0xC2, b: 0xE7 });
palette.set(PaletteIndex::CYAN, Rgb { r: 0x94, g: 0xE2, b: 0xD5 });
palette.set(PaletteIndex::WHITE, Rgb { r: 0xBA, g: 0xC2, b: 0xDE });
terminal.set_default_color_palette(Some(palette))?;
Ok(())
}
Full program: rust-vt-colors/src/main.rs
Reading colors
Use the various getters to read colors. Each color has two keys. The effective value is what you should draw with: the override if a program set one, and the default if not. The default value ignores overrides.
| Data | Output type | Description |
|---|---|---|
Terminal::fg_color | Option<Rgb> | Effective foreground (override or default) |
Terminal::bg_color | Option<Rgb> | Effective background (override or default) |
Terminal::cursor_color | Option<Rgb> | Effective cursor (override or default) |
Terminal::color_palette | Palette | Current palette (with any OSC overrides) |
Terminal::default_fg_color | Option<Rgb> | Default foreground only (ignores OSC override) |
Terminal::default_bg_color | Option<Rgb> | Default background only (ignores OSC override) |
Terminal::default_cursor_color | Option<Rgb> | Default cursor only (ignores OSC override) |
Terminal::default_color_palette | Palette | Default palette only (ignores OSC overrides) |
The foreground, background and cursor getters return None if
there’s neither a default nor an override. So handle that case, because a new
terminal starts with these unset. The palette getters always succeed, since the
palette always has a value. If nothing else is set, it’s the built-in default.
/// Print the effective and default values for a color, showing how
/// OSC overrides layer on top of defaults.
fn print_color(name: &str, effective: Option<Rgb>, default: Option<Rgb>) {
match effective {
Some(v) => print!(" {name:>12} effective: #{:02X}{:02X}{:02X}", v.r, v.g, v.b),
None => print!(" {name:>12} effective: (not set)"),
}
match default {
Some(v) => println!(" default: #{:02X}{:02X}{:02X}", v.r, v.g, v.b),
None => println!(" default: (not set)"),
}
}
fn print_all_colors(terminal: &Terminal<'_, '_>, label: &str) -> Result<(), Error> {
println!("{label}:");
print_color(
"foreground",
terminal.fg_color()?,
terminal.default_fg_color()?,
);
print_color(
"background",
terminal.bg_color()?,
terminal.default_bg_color()?,
);
print_color(
"cursor",
terminal.cursor_color()?,
terminal.default_cursor_color()?,
);
// Show palette index 0 (black) as an example
let palette = terminal.color_palette()?;
let first = palette.get(PaletteIndex(0));
print!(
" {:>12} effective: #{:02X}{:02X}{:02X}",
"palette[0]", first.r, first.g, first.b
);
let palette = terminal.default_color_palette()?;
let first = palette.get(PaletteIndex(0));
println!(" default: #{:02X}{:02X}{:02X}", first.r, first.g, first.b);
Ok(())
}
Full program: rust-vt-colors/src/main.rs
Here are the two layers working together. A program overrides the foreground with OSC 10, and then clearing the default leaves the override in place.
fn main() -> Result<(), Error> {
// Create a terminal
let mut terminal = Terminal::new(80, 24)?;
// Before setting any colors, everything is unset
print_all_colors(&terminal, "Before setting defaults")?;
// Set our color theme defaults
set_color_theme(&mut terminal)?;
print_all_colors(&terminal, "\nAfter setting defaults")?;
// Simulate an OSC override (e.g. a program running inside the
// terminal changes the foreground via OSC 10)
terminal.vt_write(b"\x1B]10;rgb:FF/00/00\x1B\\");
print_all_colors(&terminal, "\nAfter OSC foreground override")?;
// Clear the foreground default — the OSC override is still active
terminal.set_default_fg_color(None)?;
print_all_colors(&terminal, "\nAfter clearing foreground default")?;
Ok(())
}
Full program: rust-vt-colors/src/main.rs
Parsing colors
Your theme probably starts out as text. These functions parse the same color strings as Ghostty’s config and theme files, and none of them need a terminal.
Rgb::parse accepts:
- X11 color names, matched ASCII case-insensitively.
- 3- or 6-digit hex colors, with or without a leading
#. - 9- or 12-digit hex colors, with a leading
#. - XParseColor-style
rgb:<red>/<green>/<blue>values. - XParseColor-style
rgbi:<red>/<green>/<blue>values.
Leading and trailing spaces and tabs are ignored. Use Rgb::parse_x11_color
when you only want to accept X11 names.
The FromStr implementation on Rgb is identical to
Rgb::parse, so you may use it instead if you have a color string.
let color = match Rgb::parse("ForestGreen") {
Ok(color) => color,
Err(e) => { /* Handle invalid color input. */ },
};
// ASCII byte strings are also accepted
let color = Rgb::parse(b"#abc").unwrap();
// Using `str::parse` / `FromStr::from_str` with XParseColor-style colors
let color = "rgb:12/34/56".parse::<Rgb>().unwrap();
X11ColorNames::new() returns the table of X11 names, if you want to offer
them to someone. The table is static memory that lives as long as the program.
Entries are in rgb.txt order. X11ColorNames::len() returns the number of entries.
// X11ColorNames implements IntoIterator, so you can directly use a for-loop
for name in X11ColorNames::new() {
println!("{:?} = {:?}", name.name, name.color);
}
Palettes
Palette::default() gives you the same 256-color palette the
terminal uses by default. Palette::parse_palette_entry() parses one Ghostty
palette override in INDEX=COLOR form. The index can be decimal or use a 0x,
0o or 0b prefix, and the color side accepts anything Rgb::parse()
does.
let mut palette = Palette::default();
if let Some((index, rgb)) = Palette::parse_palette_entry("0x10=#282c34") {
palette.set(index, rgb);
}
Palette::generate() derives the 216-color cube and the grayscale
ramp from a base palette, a background and a foreground, so they match the
theme. Set bits in a PaletteMask to keep specific indices from the
base palette.
let palette = Palette::default();
let mut skip = PaletteMask::default();
skip.set(PaletteIndex(16));
let background = Rgb { r: 40, g: 44, b: 52 };
let foreground = Rgb { r: 220, g: 223, b: 228 };
let new_palette = Palette::generate(
Some(&palette),
Some(&skip),
background,
foreground,
true, // harmonious
);
If your UI needs to make decisions from a color, Rgb::luminance(),
Rgb::perceived_luminance() and Rgb::contrast() give you the
luminance and contrast values.
Light and dark reports
Programs want to know if your terminal is light or dark, so they can pick colors that fit. There are two ways they find out.
A program can ask with CSI ? 996 n. Register a callback with
Terminal::on_color_scheme() and fill in the current scheme, or
return false to ignore the query. See Effects.
Or a program can set mode 2031 and expect you to tell it when the scheme changes.
For this one, encode the report yourself with report::ColorScheme::encode()
and write it to the pty. Only send it if Mode::COLOR_SCHEME_REPORT is set,
which you read with Terminal::mode(). Dark schemes encode as ESC [ ? 997 ; 1 n
and light schemes as ESC [ ? 997 ; 2 n, which are the same bytes as the terminal’s
reply to the query.
If your buffer is too small, the function returns Error::OutOfSpace and
sets the output parameter to the size it needs.
fn main() {
let mut buf = [0u8; 16];
if let Ok(len) = ColorScheme::Dark.encode(&mut buf) {
println!("Encoded {len} bytes: {}", buf[0..len].escape_ascii());
}
}
Full program: rust-vt-color-scheme/src/main.rs
The Grid
The grid is what’s on the terminal: rows of cells, each holding text and a style. This page is how you read it.
The hard part isn’t reading a cell. It’s naming one. “Row 3” means one thing to a program moving its cursor, another to someone scrolled back through history, and another to a tool walking the whole scrollback. And the grid moves under you. A write can scroll a row into history, a resize can reflow it, and pruning can throw it away.
So there are two ideas here. A point names a position in one of four coordinate systems. A grid reference is what a point resolves to: one actual cell. An untracked reference is a snapshot that dies on the next change to the terminal. A tracked reference follows its cell, and the terminal pays a little for that on every change.
This isn’t how you draw. Grid references aren’t built to sustain the framerates needed to render a large screen. Use Render State for that. If you only want the text out, use Formatter. This page is for reading particular cells, and for anything that has to keep pointing at one.
Coordinates
A GhosttyPoint is a coordinate plus a tag that says which coordinate system it’s in:
| Tag | Top-left is | What it covers |
|---|---|---|
point::Space::Active | The top of the active area | The area where the cursor can move, at the terminal’s full height. |
point::Space::Viewport | The top of what you’re showing | The visible viewport. This changes when it’s scrolled. |
point::Space::Screen | The oldest row of scrollback | The full screen including scrollback, through the last written row. |
point::Space::History | The oldest row of scrollback | Scrollback only. It ends at the row just before the active area. |
Here’s how they line up on a 24-row terminal with 100 rows of scrollback:
screen y history y active y
+----------------+
| scrollback | 0 0
| | ... ...
| | 99 99
+----------------+
| active area | 100 0
| | ... ...
| | 123 23
+----------------+
The viewport is a 24-row window onto all of that. Scrolled to the bottom, it’s the same rows as the active area. See Scrollback for moving it.
x is the column and y is the row, and both start at zero. y is 32 bits
wide because a row in scrollback can be a long way from the top.
Terminal::grid_ref() resolves a point to a grid reference:
use libghostty_vt::point::{Point, Coordinate};
let point = Point::Active(Coordinate { x: 4, y: 0 });
if let Ok(grid_ref) = terminal.grid_ref(point) {
let cell = grid_ref.cell().unwrap();
}
A point that’s out of bounds returns Error::InvalidValue. Lookups with the
active and viewport tags are fast. The screen and history tags may have to walk
the full scrollback page list to find the row, so they can be expensive with a
large scrollback.
Terminal::point_from_grid_ref() goes the other way. Not every cell exists
in every coordinate system, though. A cell in scrollback has no active
coordinates, and a cell that has scrolled out of view has no viewport
coordinates. In those cases you get None. This is the only way to
get a cell’s position.
Cells, rows and styles
A grid reference gets you everything about its cell:
| Function | What you get |
|---|---|
GridRef::cell() | The Cell. |
GridRef::row() | The Row it’s on. |
GridRef::graphemes() | The full grapheme cluster, as codepoints. |
GridRef::hyperlink_uri() | The hyperlink URI, if it has one. |
GridRef::style() | The Style. |
A Style describes how a cell looks: its foreground, background and
underline colors, plus flags for bold, italic, underline and other decorations.
A cell only holds a style id, Cell::style_id(). Use GridRef::style()
to get the full style.
This walks the whole grid, reading each cell’s text, each row’s wrap state, and a style:
fn main() -> Result<(), Error> {
// Create a small terminal
let mut terminal = Terminal::new(10, 3)?;
// Write some content so the grid has interesting data
terminal.vt_write(b"Hello!\r\n"); // Row 0: H e l l o !
terminal.vt_write(b"World\r\n"); // Row 1: W o r l d
terminal.vt_write(b"\x1b[1mBold"); // Row 2: B o l d (bold style)
// Get terminal dimensions
let cols = terminal.cols()?;
let rows = u32::from(terminal.rows()?);
// Traverse the entire grid using grid refs
for row in 0..rows {
print!("Row {row}: ");
for col in 0..cols {
// Resolve the point to a grid reference
let point = Point::Active(Coordinate { x: col, y: row });
let grid_ref = terminal.grid_ref(point)?;
// Read the cell from the grid ref
let cell = grid_ref.cell()?;
// Check if the cell has text
if cell.has_text()? {
let codepoint = cell.codepoint()?;
print!("{codepoint}");
} else {
print!(".");
}
}
// Also inspect the row for wrap state
let point = Point::Active(Coordinate { x: 0, y: row });
let grid_ref = terminal.grid_ref(point)?;
let row = grid_ref.row()?;
print!(" (wrap={}", row.is_wrapped()?);
// Check the style of the first cell with text
let style = grid_ref.style()?;
print!(", bold={}", style.bold);
}
Ok(())
}
Full program: rust-vt-grid-traverse/src/main.rs
Untracked references
A GridRef is untracked. It’s a value that snapshots one cell, and you
don’t free it.
It’s only valid until the next call that changes the terminal. That includes
Terminal::vt_write() and Terminal::resize(). There’s no guarantee it
survives any change, even one to a part of the grid that looks unrelated.
So get one, read what you need, and cache the values. Don’t keep the reference.
An untracked reference costs you the initial lookup and nothing after that. It’s a one-time snapshot, so it has no effect on the terminal’s ongoing performance.
Tracked references
A TrackedGridRef follows its cell. Scrolling, scrollback pruning, resize
and reflow, and other terminal changes all update it automatically. Create one
with Terminal::track_grid_ref().
Each tracked reference adds bookkeeping to every terminal change, so use them sparingly. They’re for long-lived anchors such as selections, search state, marks and bookmarks in your application.
To read cell data, snapshot it first with TrackedGridRef::snapshot().
What you get back is an untracked reference with the same short life as any
other. TrackedGridRef::point() gets you the position without that step.
fn codepoint_at_tracked_ref(
terminal: &Terminal<'_, '_>,
tracked: &TrackedGridRef,
) -> Result<char, Error> {
let snapshot = tracked
.snapshot(terminal)?
.expect("tracked grid ref should be active");
let cell = snapshot.cell()?;
assert!(cell.has_text()?);
cell.codepoint()
}
fn main() -> Result<(), Error> {
let mut terminal = Terminal::new(8, 3)?;
terminal.vt_write(b"alpha\r\nbravo\r\ncharlie");
let alpha = Point::Active(Coordinate { x: 0, y: 0 });
let mut tracked = terminal.track_grid_ref(alpha)?;
// Writing another line scrolls the original "alpha" row into scrollback.
// The tracked ref still follows the same cell.
terminal.vt_write(b"\r\ndelta");
assert!(tracked.has_value());
println!(
"tracked codepoint after scroll: {}",
codepoint_at_tracked_ref(&terminal, &tracked)?
);
let screen = tracked
.point(Space::Screen)?
.expect("tracked point should be on screen");
println!("tracked screen point: {},{}", screen.x, screen.y);
// Resetting the terminal discards the old grid contents. The tracked
// handle remains valid, but no longer has a meaningful location.
terminal.reset();
assert!(!tracked.has_value());
assert!(tracked.snapshot(&terminal)?.is_none());
// The same handle can be moved to a new point after it loses its value.
terminal.vt_write(b"echo");
let echo = Point::Active(Coordinate { x: 0, y: 0 });
tracked.set(&mut terminal, echo)?;
assert!(tracked.has_value());
println!(
"tracked codepoint after reset/set: {}",
codepoint_at_tracked_ref(&terminal, &tracked)?
);
Ok(())
}
Full program: rust-vt-grid-ref-tracked/src/main.rs
When a tracked reference loses its cell
A tracked reference can still lose its place. That happens when the grid under
it is reset, pruned, or otherwise discarded in a way that can’t be mapped to a
meaningful new cell. TrackedGridRef::has_value() then returns false, and
TrackedGridRef::snapshot() and TrackedGridRef::point() return None.
The handle is still valid. Move it to a new point with TrackedGridRef::set().
Primary and alternate screens
A tracked reference belongs to the screen that was active when you created it or
last set it. Converting it to a point uses that screen, even if the terminal has
since switched between primary and alternate. TrackedGridRef::set()
resolves the new point against the screen that’s active now, so it can move the
reference from one screen to the other.
Dropping
Tracked references are yours, and you can drop them after the terminal is gone. If the terminal is dropped first, the handle stays valid for the tracked reference functions only: it reports no value, and it can still be freed.
When a reference dies
| Untracked | Tracked | |
|---|---|---|
| Terminal changes | Invalid. Don’t touch it again. | Follows the cell. |
| Its cell is discarded | Invalid. | Valid, but has no value until you set it again. |
| Terminal is freed | Invalid. | Valid, but has no value. You still have to free it. |
| Cost | One lookup. | Bookkeeping on every terminal change for as long as it exists. |
Selection
A selection is a range of terminal content: a word someone double-clicked, a line, a command’s output, or a block dragged out with the mouse. You make one to highlight text and to copy it.
Selecting text in a terminal takes more than two cells. What counts as a word, where a line really starts, which rows are a command’s output, and what a double-click-and-drag should do when the pointer is between words are all questions we’ve already answered in Ghostty. These functions give you the same answers.
If you don’t let anyone select text, you can skip this page. If you do, the gesture section is the one you want. It turns raw pointer events into selections so you don’t have to write that logic.
What a selection is
A Selection is two cells, start and end, and both are included. By
default it’s linear: it runs from start to end the way text flows, wrapping
from the end of one row to the start of the next. Set rectangle to true for a
rectangular block instead, with start and end at opposite corners.
The ends keep the direction of the selection. If someone drags up or to the
left, start comes after end in the terminal, so don’t assume start is the
top-left end. Selection::to_ordered() gives you the ends in the
order you ask for.
Both ends are GridRef values, so a selection is an untracked snapshot and
follows the same rule as any untracked reference. It’s only valid until the next
call that changes the terminal, including freeing it.
See When a reference dies.
To keep a selection across changes, you have two choices. Install it as the
terminal’s selection, or keep tracked references for the ends and build a new
Selection from fresh snapshots when you need one.
The terminal’s selection
The active screen has a selection, and the terminal owns it. Passing a selection
to Terminal::set_selection() copies it right away and converts it to tracked
state, so what you passed doesn’t need to outlive the call. Passing None clears
it.
Read it back with Terminal::selection(), which returns None if there’s no
active selection. The struct you get is yours to keep, but the references in it
are untracked again. They’re only valid until the next call that changes the
terminal.
Nothing in this guide installs a selection for you. Every function below returns a snapshot, and you decide what to do with it.
Making a selection
You can fill in a selection by hand with Terminal::select (or equivalently,
Selection::new). This selects the first ten cells of the second row and
makes that the terminal’s selection:
use libghostty_vt::{
point::{Coordinate, Point},
selection::Selection,
Terminal,
};
let start = terminal.grid_ref(Point::Active(Coordinate { x: 0, y: 1 }))?;
let end = terminal.grid_ref(Point::Active(Coordinate { x: 9, y: 1 }))?;
let selection = terminal.select(start, end, false);
terminal.set_selection(Some(selection))?;
Usually you want the terminal’s rules instead:
| Function | What it selects |
|---|---|
Terminal::select_word() | The word under a grid reference. |
Terminal::select_word_between() | The nearest word between two grid references, searching from start toward end. |
Terminal::select_line() | The line under a grid reference. |
Terminal::select_output() | The command output under a grid reference. This needs OSC 133 prompt markers. |
Terminal::select_all() | All selectable content. |
Each returns None when there’s nothing to select there.
The word functions use Ghostty’s default word boundaries unless you pass your
own codepoints. The line function trims Ghostty’s default whitespace unless you
pass your own. Set semantic_prompt_boundary and the line stops at semantic
prompt changes, so a line at a shell prompt selects the input and leaves out the
$ .
fn ref_at<'t>(terminal: &'t Terminal<'_, '_>, x: u16, y: u32) -> GridRef<'t> {
terminal
.grid_ref(Point::Active(Coordinate { x, y }))
.expect("ref should exist")
}
fn print_selection<'t>(
terminal: &'t Terminal<'_, '_>,
label: &str,
selection: Selection<'t>,
) -> Result<(), Error> {
let mut formatter = Formatter::new(terminal)?;
formatter
.set_format(Format::Plain)?
.set_trim(true)?
.set_selection(Some(selection))?;
let buf = formatter.format_alloc(None)?;
let mut stdout = std::io::stdout();
_ = write!(stdout, "{label}: ");
_ = stdout.write_all(&buf);
_ = writeln!(stdout);
Ok(())
}
fn main() -> Result<(), Error> {
let mut terminal = Terminal::new(80, 8)?;
// A realistic shell transcript with OSC 133 semantic prompt markers.
// Ghostty uses these markers to distinguish prompt/input from command
// output for semantic line and output selections.
terminal.vt_write(b"\x1B]133;A\x07$ "); // Prompt starts: "$ "
terminal.vt_write(b"\x1B]133;B\x07git status"); // Input starts: "git status"
terminal.vt_write(b"\x1B]133;C\x07\r\n"); // Output starts after Enter
terminal.vt_write(b"On branch main\r\n");
terminal.vt_write(b"nothing to commit, working tree clean");
// Double-click style word selection under the cursor.
let grid_ref = ref_at(&terminal, 6, 0); // the "status" in "git status"
let selection = terminal
.select_word(grid_ref)
.finish()?
.expect("word should be selected");
print_selection(&terminal, "word", selection)?;
// Double-click-and-drag style selection. Suppose the user double-clicks
// "git" and drags to "status". The pointer may pass over whitespace, so
// select the nearest word between the original click and current drag point
// in both directions, then combine the outer word bounds.
let click_ref = ref_at(&terminal, 2, 0); // the "git" in "git status"
let drag_ref = ref_at(&terminal, 6, 0); // the "status" in "git status"
let start_word = terminal
.select_word_between(click_ref, drag_ref)
.finish()?
.expect("word should be selected");
let end_word = terminal
.select_word_between(drag_ref, click_ref)
.finish()?
.expect("word should be selected");
let selection = terminal.select(start_word.start(), end_word.end(), false);
print_selection(&terminal, "double-click drag", selection)?;
// Triple-click style line selection. With semantic prompt boundaries enabled,
// this selects only the input area rather than the leading "$ " prompt.
let grid_ref = ref_at(&terminal, 2, 0); // the "git status" input area.
let selection = terminal
.select_line(grid_ref)
.with_semantic_prompt_boundary(true)
.finish()?
.expect("line should be selected");
print_selection(&terminal, "line", selection)?;
// Select exactly the command output for the command under the cursor.
let output_ref = ref_at(&terminal, 0, 1);
let selection = terminal
.select_output(output_ref)?
.expect("output should be selected");
print_selection(&terminal, "output", selection)?;
// Select all visible content.
let selection = terminal.select_all()?.expect("all should be selected");
print_selection(&terminal, "all", selection)?;
Ok(())
}
Full program: rust-vt-selection/src/main.rs
Double-click and drag
Word-granular dragging needs Terminal::select_word_between(). If someone
double-clicks a word and drags across spaces or punctuation toward another word,
selecting only the word under the pointer flickers or collapses whenever the
pointer is between words. So ask for the nearest word between the click and the
drag point, ask again in the other direction, and combine the two. The gesture
API below does this for you.
// Double-click-and-drag style selection. Suppose the user double-clicks
// "git" and drags to "status". The pointer may pass over whitespace, so
// select the nearest word between the original click and current drag point
// in both directions, then combine the outer word bounds.
let click_ref = ref_at(&terminal, 2, 0); // the "git" in "git status"
let drag_ref = ref_at(&terminal, 6, 0); // the "status" in "git status"
let start_word = terminal
.select_word_between(click_ref, drag_ref)
.finish()?
.expect("word should be selected");
let end_word = terminal
.select_word_between(drag_ref, click_ref)
.finish()?
.expect("word should be selected");
let selection = terminal.select(start_word.start(), end_word.end(), false);
print_selection(&terminal, "double-click drag", selection)?;
Full program: rust-vt-selection/src/main.rs
Working with a selection
These all take a selection whose references are valid for the terminal’s active screen. They have to come from that terminal and that screen, with no change to the terminal since. We don’t check, so a stale reference is on you.
| Function | What it does |
|---|---|
Selection::adjust() | Moves the selection’s logical end, as keyboard selection does. The result is a snapshot. |
Selection::order() | Tells you which way the ends are ordered. |
Selection::to_ordered() | Returns a new snapshot with the ends in the order you ask for. |
Selection::contains() | Tests whether a point is inside, for rectangular selections too. |
Selection::equals() | Tests whether two selections have the same ends and shape. |
Mouse gestures
A selection gesture is a state machine that turns pointer events into selections. It handles click counts, dragging, and what each click count selects. You feed it events and it hands back snapshots.
Create one Gesture per stream of pointer events with
Gesture::new(). It isn’t bound to a terminal, so the functions
that need one take it as an argument. Then create a gesture event
for each event type you use with its corresponding new function,
(e.g. PressEvent::new()). The type is fixed, but the
object is reusable: change its options with the various setters
and apply it with the corresponding apply() method (e.g.
PressEvent::apply()).
| Event type | apply arguments | Optional |
|---|---|---|
PressEvent | Ref | The rest use their defaults. |
DragEvent | Ref, geometry | Position, rectangle, word boundaries. |
ReleaseEvent | None | Ref. Unset means it wasn’t over a cell. |
AutoscrollTickEvent | Viewport, geometry | Position, rectangle, word boundaries. |
DeepPressEvent | None | Word boundaries. |
A press only gets repeat clicks if you call PressEvent::set_time().
Without a time, only single-click behavior is available. By default a single
click selects by cell, a double click by word and a triple click by line.
Change that with PressEvent::set_behaviors(), which can also
select command output.
Getting Ok(None) from apply() isn’t an error. It means this event doesn’t
produce a selection right now, as with a normal single press. A release never
produces one, and in fact always returns a Ok(()) when successful. When you
do get a selection, it isn’t installed anywhere. You decide whether to draw it,
copy it, or install it as the terminal’s selection.
fn ref_at<'t>(terminal: &'t Terminal<'_, '_>, x: u16, y: u32) -> GridRef<'t> {
terminal
.grid_ref(Point::Active(Coordinate { x, y }))
.expect("ref should exist")
}
fn print_selection<'t>(
terminal: &'t Terminal<'_, '_>,
label: &str,
selection: Selection<'t>,
) -> Result<(), Error> {
let mut formatter = Formatter::new(terminal)?;
formatter
.set_format(Format::Plain)?
.set_trim(true)?
.set_selection(Some(selection))?;
let buf = formatter.format_alloc(None)?;
let mut stdout = std::io::stdout();
_ = write!(stdout, "{label}: ");
_ = stdout.write_all(&buf);
_ = writeln!(stdout);
Ok(())
}
fn main() -> Result<(), Error> {
let mut terminal = Terminal::new(20, 4)?;
terminal.vt_write(b"hello world\r\nsecond line");
let mut gesture = Gesture::new()?;
let mut press = gesture::PressEvent::new()?;
let mut drag = gesture::DragEvent::new()?;
let mut release = gesture::ReleaseEvent::new()?;
let mut deep_press = gesture::DeepPressEvent::new()?;
let geometry = gesture::Geometry {
columns: 20,
cell_width: 10,
padding_left: 0,
screen_height: 40,
};
// Press in the first cell. A normal single press records the click anchor but
// doesn't produce a selection yet, so we discard the optional output.
let press_ref = ref_at(&terminal, 0, 0);
let selection = press
.set_position(2.0, 8.0)?
.apply(&mut gesture, &terminal, press_ref)?;
assert!(selection.is_none());
// Drag across "hello". The drag event returns a selection snapshot that the
// embedder can apply to its UI, copy, or format immediately.
let drag_ref = ref_at(&terminal, 4, 0);
let selection = drag
.set_position(46.0, 8.0)?
.apply(&mut gesture, &terminal, drag_ref, geometry)?
.expect("'hello' should be selected");
print_selection(&terminal, "drag", selection)?;
// Release updates gesture state but never produces a selection.
release.apply(&mut gesture, &terminal, None)?;
println!("dragged: {}", gesture.dragged(&terminal)?);
// Deep press uses the active click anchor to select the surrounding word.
gesture.reset(&terminal);
let world_ref = ref_at(&terminal, 6, 0);
let selection = press.apply(&mut gesture, &terminal, world_ref)?;
assert!(selection.is_none());
let selection = deep_press
.apply(&mut gesture, &terminal)?
.expect("'world' should be selected");
print_selection(&terminal, "deep press", selection)?;
Ok(())
}
Full program: rust-vt-selection-gesture/src/main.rs
Dragging past the edge
When a drag reaches the top or bottom of the surface, the gesture wants the
viewport to scroll. Read Gesture::autoscroll() after each drag. While it’s
up or down, run a timer of your own that sends AutoscrollTickEvent
events. Each tick scrolls the viewport one row and continues the drag.
The interval is up to you, and about 15 milliseconds is a reasonable default.
Scroll faster by ticking faster. If a tick returns Autoscroll::None,
the gesture has cancelled itself, so stop the timer.
Rules for gestures
Calls that use a gesture aren’t safe to run concurrently, and they have to be serialized with changes to the terminal.
Gesture::reset() cancels the current click sequence and
releases the gesture’s tracked state without freeing it.
Copying it out
A selection names cells. To get the text, use a formatter with
Formatter::set_selection. For the same text Ghostty puts on the
clipboard, use plain output with Formatter::set_unwrap and
Formatter::set_trim both true:
use libghostty_vt::{fmt::{Format, Formatter}};
let Some(selection) = terminal.selection()? else {
return;
};
let mut formatter = Formatter::new(&terminal)?;
formatter
.set_format(Format::Plain)?
.set_unwrap(true)?
.set_trim(true)?
.set_selection(Some(selection))?;
let buf = formatter.format_alloc(None);
// Put buf on the clipboard.
The formatter keeps its own copy of the selection, but that copy is still only valid until the next change to the terminal. After a change, set the selection again before you format, or clear it.
Scrollback
Scrollback is the history that has scrolled off the top of the screen, kept so you can scroll back and read it.
It’s also where a terminal’s memory goes. Most of what a terminal holds is its screen contents and scrollback, and a program can write forever. So you need to decide how much history to keep, and if you’re running a lot of terminals, what to do about the memory it takes.
The default limit is small, so nearly every terminal wants to set its own. The scrollbar and the compression sections are only for those who need them. Most programs never need compression.
Limits
Scrollback has two limits, and both are set with their corresponding setter. If you set both, the first one reached is used.
| Option | Default | usize::MAX | None |
|---|---|---|---|
Terminal::set_scrollback_max_bytes() | 10,000 bytes | No limit | Restores the default |
Terminal::set_scrollback_max_lines() | No limit | No limit | No limit |
// Keep up to 10 MB of history.
terminal.set_scrollback_max_bytes(Some(10 * 1024 * 1024))?;
They’re useful together, because each one depends on things you don’t control. The byte limit is reached with fewer lines if the program uses more styles, and the line limit is reached sooner with a narrower terminal.
Both limits are estimates. History lives in pages, the smallest unit of grid space we allocate, and we only prune whole pages. A page is about 400 KB at the time of writing, so the byte limit is accurate to about that much, and the default of 10,000 bytes is one page in practice. The line limit almost always keeps more lines than you asked for, usually somewhere from dozens to a hundred or so.
Lowering a limit removes eligible complete pages right away. A byte limit of zero disables scrollback and erases the history you have.
Read the limits back with Terminal::scrollback_max_bytes() and
Terminal::scrollback_max_lines(). They return None when the limit is
unlimited, and they always report the primary screen’s value, even while the
alternate screen is active.
Scrolling the viewport
The viewport is the part of the terminal you’re showing. Move it with
Terminal::scroll_viewport(), which takes a tagged union:
| Tag | What it does |
|---|---|
ScrollViewport::Top | Scroll to the top of the scrollback |
ScrollViewport::Bottom | Scroll to the bottom (the active area) |
ScrollViewport::Delta | Scroll by a number of rows, negative for up |
ScrollViewport::Row | Scroll so that this row is the first one visible |
ScrollViewport::DeltaPrompt | Scroll by a number of prompts, negative for backward |
terminal.scroll_viewport(ScrollViewport::Delta(-5))?; // up 5 rows
Row 0 is the top of the scrollback. The row is clamped so the viewport never scrolls past the top of the active area. With no scrollback, such as on the alternate screen, the viewport stays on the active area.
Scrolling by prompts needs semantic prompt markers from the shell. Without a matching prompt it does nothing.
Terminal::viewport_active() tells you if the viewport is following
the active area, or if someone has scrolled up into history.
The scrollbar
Read Terminal::scrollbar() to get a terminal::Scrollbar, which
has the three numbers you need to draw one: total rows in the scrollable area,
the offset of the viewport into them, and the len of the visible area.
There’s no notification when these change, and that’s on purpose. Poll once per frame or once per write batch and compare the result with the last one. This is what Ghostty’s own renderer does. It’s cheap, because we keep the total up to date as the terminal changes and cache the offset. The one exception is the first read after the viewport moves somewhere that isn’t an absolute row, which can cost O(pages).
The offset is the same row space as ScrollViewport::Row, so
when someone drags your scrollbar you can scroll straight to the position you
drew.
let bar = terminal.scrollbar()?;
// Someone dragged the scrollbar halfway down.
let row = (bar.total - bar.len) / 2;
terminal.scroll_viewport(ScrollViewport::Row(row as usize));
If you only want counts, Terminal::total_rows() is the rows in the
active screen including scrollback, and Terminal::scrollback_rows()
is the rows in scrollback.
Resizing
By default, a resize can pull rows out of scrollback and back into the active area. Growing the rows reveals scrollback if the cursor is on the bottom row, and a column reflow that needs fewer rows reveals it too.
Most programs want this and can skip this section. But if your pty keeps its own
screen buffer without scrollback, it can’t pull rows back, and it will disagree
with the terminal about the screen after a resize. Windows ConPTY is the case
that needs this. Call Terminal::set_resize_pull_scrollback() with false:
terminal.set_resize_pull_scrollback(false)?;
Now growing the rows always appends blank rows at the bottom, and a column reflow keeps the top of the active area on the same content. A line that’s fully in scrollback stays there, but a soft-wrapped line with at least one row still in the active area can still unwrap back into view. The setting survives a full reset (RIS).
Memory use
Read Terminal::memory_usage() to see how much memory a terminal
holds. This is for applications that host many terminals and have to stay inside
a budget, for example by compressing or closing whichever ones hold the most.
The read never decompresses scrollback, but it does look at every page,
so don’t do it after every write.
Budget against the resident bytes. That’s the physical memory the pages use right now. Virtual bytes are the address space reserved for pages.
Each screen has its own fields, with a primary_ or alternate_ prefix, so add
them together for the terminal’s total. The primary screen holds shell output
and all of the scrollback. The alternate screen is used by full-screen programs
such as text editors, and its fields are zero until a program first switches to
it.
Colors, styles and hyperlinks are stored in pages, so they’re already in the page figures. Images are stored separately and have their own fields. Small things outside of pages, such as the window title and internal bookkeeping, aren’t counted. They’re small next to the pages once a terminal has any scrollback.
On macOS, the system takes back memory freed by compression lazily, when something else needs it. Until then, the memory the system reports for your process (its RSS) can be higher than the resident figures here.
/// Return the bytes of memory a terminal currently holds. A server hosting
/// many terminals can compare this figure across terminals to decide which
/// one to compress or shut down first.
fn terminal_resident_bytes(terminal: &Terminal<'_, '_>) -> Result<u64, Error> {
let usage = terminal.memory_usage()?;
// Count both screens and any images. The alternate screen reports zero
// until a program such as a full-screen editor first switches to it.
Ok(usage.primary_resident_bytes
+ usage.primary_image_bytes
+ usage.alternate_resident_bytes
+ usage.alternate_image_bytes)
}
Full program: rust-vt-compression/src/main.rs
Compression
Old scrollback is mostly sitting there, so we can compress it. This changes how the history is stored and nothing else. The contents and the scrollback limit stay the same, and reading compressed history restores it transparently.
You drive it. libghostty-vt doesn’t create a timer or a background thread, so nothing is compressed until you ask. The shape is an idle timer: restart it when the terminal changes, and when it fires, compress a step at a time until there’s nothing left to do.
Terminal::compression_activity() returns an opaque token. Only compare it
for equality, because it can wrap, and a change in either direction means the
same thing. It changes only when compression-relevant state changes, so restart
your idle timer when it does.
let mut activity = terminal.compression_activity()?;
// Terminal mutations may change the token. When it changes, restart the
// application's idle timer rather than compressing on the output path.
for _ in 0..4000 {
terminal.vt_write(b"repeated and compressible terminal history\r\n");
}
let new_activity = terminal.compression_activity()?;
if activity != new_activity {
activity = new_activity;
// Restart the application's compression idle timer here.
}
Full program: rust-vt-compression/src/main.rs
When the timer fires, call Terminal::compress with
CompressionMode::Incremental, which does a bounded amount of
work. There are three results:
CompressionResult::Pendingmeans there’s more to do. Schedule another step while the terminal stays idle.CompressionResult::Completemeans you’re done until the activity token changes.CompressionResult::Unsupportedmeans this platform can’t free memory this way. Thecompression_supportedfield ofMemoryUsagetells you the same thing, and to lower memory there you have to do something else, such as closing a terminal.
/// Perform one step after the application's idle timer fires. Returning true
/// asks the application to schedule another step while the terminal is idle.
fn compression_idle_step(terminal: &mut Terminal<'_, '_>) -> Result<bool, Error> {
match terminal.compress(CompressionMode::Incremental)? {
CompressionResult::Pending => Ok(true),
CompressionResult::Unsupported | CompressionResult::Complete => Ok(false),
_ => unreachable!(),
}
}
Full program: rust-vt-compression/src/main.rs
Complete means the pass finished, not that every page was compressed. Compression is opportunistic. A page can be unprofitable to compress, or hit an allocation or reclamation failure.
CompressionMode::Full does one synchronous scan of every
eligible page instead. It can stall on large scrollback.
Terminal::compress isn’t thread-safe with anything else on the same
terminal, so serialize it with your writes, rendering, searches and other
terminal access.
Compression lowers the resident figure but not the virtual one, because each page’s space stays reserved for decompression.
Search
A Search finds a string in a terminal. It covers the active area and
scrollback of both the primary and alternate screens.
Terminal search is harder than searching a string, because the text won’t hold still. Scrollback can be huge, and a program can keep writing while you search. We handle that part. Results stay in sync with the live screens. They survive primary and alternate screen switches, so opening and closing a fullscreen app such as vim doesn’t restart a scrollback search. And they recover from resize, reflow, resets and scrollback pruning.
What’s left to you is deciding when the work happens. If you want a one-shot
search, Search::run() does all of it, and you can go straight to the
example. If you’re building a find bar for a terminal with a lot of scrollback,
read the first section.
Driving a search
A search starts idle. Setting a needle with Search::set_needle() starts
it, changing the needle restarts it from scratch, and clearing it returns the
search to idle. Setting the needle it already has keeps the results, so a find
bar can resubmit freely.
Matching is byte-exact, except for ASCII letters, which compare case-insensitively.
Searching a large scrollback takes time, so the work is split into small steps you drive yourself. That gives you direct control over the performance:
| Function | What it does | Needs the terminal |
|---|---|---|
Search::tick() | Makes a bounded amount of progress on data the search has already copied. | No |
Search::feed() | Reads the terminal to copy in more data and pick up changes, and returns a snapshot of the matched items. | Yes |
Search::run() | Blocks, feeding and ticking until the search is caught up. Interactive programs should use the other two instead. | Yes |
Tick while the status is search::Status::Running, and feed when it
becomes search::Status::FeedRequired. That’s also the status right after
a needle is set, because the search hasn’t seen the terminal yet.
Feeding is the only way a search learns that the terminal changed. So keep feeding periodically while the search is in use, even after it reports complete.
search::Status::Complete means the search is caught up with the terminal
as of the last feed. It never means finished forever, because later writes need
another feed to be seen.
Matches are selections
Every match is a Selection snapshot with rectangle set to false. So
everything in Selection works on matches:
- To copy the matched text, use a
FormatterwithFormatter::set_selection(). - To position highlight rectangles, use
Terminal::point_from_grid_ref()withpoint::Space::Viewport. - To hit test, use
Selection::contains(). - To make a match the terminal’s selection, use
Terminal::set_selection().
Matches follow the usual snapshot rule. They’re only valid until the next
operation that changes the terminal, including Terminal::vt_write(),
resize, reset and free. Read matches after a feed, use them before the terminal
changes again, and read them again rather than caching them.
Lifetime
A search borrows the terminal it was created with and never owns it. Any number of searches can share one terminal, alongside other readers such as formatters and render states.
You can drop the search and its terminal in either order. Dropping the search first releases the tracked state it holds in the terminal. If the terminal goes first, the search detects that:
- Calls that need the terminal, and
Search::tick(), returnError::InvalidValue. - Reads return whatever the search last saw.
- The
Dropimplementation releases only the search’s own memory.
A search can’t be rebound. To search another terminal, create a new search.
Threads
The library creates no threads. Calls on one Search aren’t safe to make
concurrently with each other, so you have to serialize them.
The functions that touch the terminal also have to be serialized with all other access to that terminal:
Search::new()and theDropimplementationSearch::feed()andSearch::run()Search::select_next()andSearch::select_prev()Search::set_needle()
Everything else, meaning Search::tick() and its various getters, only
touches memory the search owns. Those are safe to call while another thread
changes the terminal.
That split is how Ghostty runs search on a background thread: tick freely, and take the terminal lock only to feed.
Reading a returned match value is always safe. Passing one to a function that takes the terminal follows the terminal’s serialization rule above.
Example
This creates a search, runs it, steps through the matches like a find bar, and reads the viewport matches to draw highlights.
use libghostty_vt::{
Terminal,
error::Error,
point::Space,
search::{MatchBuffer, Search},
};
fn main() -> Result<(), Error> {
// Create a terminal and fill it with some content to search.
let mut terminal = Terminal::new(80, 24)?;
terminal.vt_write(b"$ make test\r\n");
terminal.vt_write(b"compiling module A... ok\r\n");
terminal.vt_write(b"compiling module B... error: missing semicolon\r\n");
terminal.vt_write(b"linking... error: undefined symbol\r\n");
terminal.vt_write(b"$ grep -n ERROR build.log\r\n");
// The user opened the find bar, so create a search bound to the
// terminal. It starts idle until it has a needle.
let mut search = Search::new(&terminal)?;
// The user typed a query. Matching is byte-exact except ASCII
// letters, which compare case-insensitively, so "error" also finds
// "ERROR". Retyping just sets the needle again: a changed needle
// restarts the search and an unchanged one keeps its results.
search.set_needle(&mut terminal, b"error")?;
// Drive the search. Interactive embedders interleave
// `Search::tick` and `Search::feed` with their event
// loop, but for a one-shot search we can just run it to completion.
search.run(&terminal)?;
// The total match count, for find bar text like "1 of 3".
let total = search.total_matches()?;
println!(r#"{total} matches for "error""#);
// The user pressed Enter, so select the next match. Selection starts
// at the newest match, moves toward older content, and wraps around.
// This scrolls the viewport to the match if it isn't visible, per
// the `Search::scroll` policy.
while let Some(s) = search.select_next(&terminal)? {
// Read the selection state. Index 0 is the newest
// match, so a "k of n" find bar renders index + 1.
let selected_index = s.index()?;
println!("selected {} of {}", selected_index + 1, total);
// Wrapped back around to the first match: stop.
if selected_index + 1 == total {
break;
}
}
// Each frame while the find bar is open, feed to catch up with any
// terminal changes and then read the viewport matches to draw
// highlights. The list can include matches just past the viewport
// when they share a page with it, so convert each endpoint to
// viewport coordinates and skip matches outside the visible rows.
search.feed(&terminal)?;
let mut match_buffer = MatchBuffer::new();
for m in search.viewport_matches(&terminal, &mut match_buffer)? {
let Ok(Some(start)) = terminal.point_from_grid_ref(m.start(), Space::Viewport) else {
continue;
};
let Ok(Some(end)) = terminal.point_from_grid_ref(m.end(), Space::Viewport) else {
continue;
};
if start.y >= 24 || end.y >= 24 {
continue;
}
// A real embedder draws a highlight rect from start to end here.
println!(
"highlight rows {}-{}, cols {}-{}",
start.y, end.y, start.x, end.x
);
}
Ok(())
}
Full program: rust-vt-search/src/main.rs
Images
A program running in your terminal can send images and ask you to draw them. Today that means the Kitty graphics protocol.
Images don’t fit in cells, so the render state’s rows can’t carry them. There are two parts instead. The terminal keeps every image a program sends in an image storage, and that’s where the pixels are. The render state works out what to draw, where, how big and in what order. You read the list from the render state and the pixels from the storage, and you never have to track a cell yourself.
If you don’t draw images, you can skip this page. Just know that the protocol is on by default, so programs can fill the storage even if you never read it. Set the limit below to zero to turn it off.
Setting up
Kitty graphics are on by default with a 10 MB storage limit. Change the limit
with Terminal::set_kitty_image_storage_limit(). A limit of zero disables
the protocol and deletes every stored image and placement. If Kitty graphics
were disabled at build time, this option returns Error::Unsupported.
terminal.set_kitty_image_storage_limit(Some(64 * 1024 * 1024))?; // 64 MiB
The terminal also needs a cell size. Image sizes depend on the size of a cell in
pixels, which you set with Terminal::resize(). Without it there’s nothing
to draw and the image list is empty.
Programs can send image data directly in the sequence. Loading it from a file, a
temporary file or shared memory is off by default. Turn those on with
Terminal::set_kitty_image_from_file_allowed(),
Terminal::set_kitty_image_temp_file_dir() and
Terminal::set_kitty_image_from_shared_mem_allowed().
Each screen, main and alternate, has its own storage. Get a handle to the active
one with Terminal::kitty_graphics(). The handle is borrowed, so see
Lifetime before you keep one.
Decoding PNGs
We don’t ship a PNG decoder. You bring your own, so use whatever library you already have. Without one, PNG images are rejected.
Install it with kitty::graphics::set_png_decoder(). This is a process-global
setting, not a terminal one. Set it at startup, before you use anything that
depends on it. This isn’t thread-safe, so call it before any other thread uses
the library, and never while one does. Passing None clears the decoder and
turns PNG support off again.
The callback gets the PNG bytes and fills in a kitty::graphics::DecodedImage.
Pixels are 8-bit RGBA, row by row from the top-left, with no padding, so a complete
image is width * height * 4 bytes. Allocate them with Bytes::new_zeroed_with_alloc()
and the allocator we pass you, and return it. We own the buffer after that.
That allocator limits how much memory one image can use, so Bytes::new_zeroed_with_alloc()
can return None for a very large image. Treat that as a failure: free anything you
allocated and return None, and the image is rejected. kitty::graphics::DecodePng
has the rest of the contract.
This example shows the shape of a decoder, but it doesn’t actually decode anything. It hardcodes one red pixel.
/// Minimal PNG decoder callback for the sys interface.
///
/// A real implementation would use a PNG library (libpng, stb_image, etc.)
/// to decode the PNG data. This example uses a hardcoded 1x1 red pixel
/// since we know exactly what image we're sending.
///
/// WARNING: This is only an example for providing a callback, it DOES NOT
/// actually decode the PNG it is passed. It hardcodes a response.
struct StubPngDecoder {
decode_count: Arc<AtomicUsize>,
}
impl graphics::DecodePng for StubPngDecoder {
fn decode_png<'alloc>(
&mut self,
alloc: &'alloc Allocator<'_>,
data: &[u8],
) -> Option<graphics::DecodedImage<'alloc>> {
_ = self.decode_count.fetch_add(1, Ordering::SeqCst);
let count = self.decode_count.load(Ordering::SeqCst);
println!(" decode_png called (size={}, call #{count})", data.len());
// Allocate RGBA pixel data through the provided allocator.
let mut data = Bytes::new_zeroed_with_alloc(alloc, 4).ok()?;
// Fill with red (R=255, G=0, B=0, A=255).
data.copy_from_slice(&[255, 0, 0, 255]);
Some(graphics::DecodedImage {
width: 1,
height: 1,
data,
})
}
}
Full program: rust-vt-kitty-graphics/src/main.rs
Drawing images
The render state gives you the images to draw as a list of placements, which you
read with a ImageIterator. Each placement is one rectangle of one image:
- What to draw: the image’s protocol and ID, plus a source rectangle that selects part of the image in image pixels.
- Where to draw it: the top-left cell, relative to the viewport, plus a pixel offset within that cell.
- How big to draw it: a destination size in pixels. The image is already scaled to fit its cells.
- In what order to draw it: a layer (below cell backgrounds, below text, or above text) and a z-index within the layer.
These values mean the same thing for every protocol, so one drawing routine handles all of them. The only part that depends on the protocol is getting the pixels. Use the placement’s protocol to pick the right storage and its image ID to look the image up.
Later versions may add more protocols and more kinds of placements. Skip any placement whose protocol you don’t support, and your renderer keeps working when that happens.
// Create the iterator once and reuse it for every frame.
let mut images = ImageIterator::new()?;
// Each frame, after `RenderState::update`.
let snapshot = render_state.update(&terminal)?;
let mut image_it = images.update(&snapshot)?;
while let Some(image) = image_it.next() {
let protocol = image.protocol()?,
let id = image.image_id()?;
let gen = image.image_generation()?;
// Your renderer: find the texture for this image. Only read the
// pixels when you don't have a texture for this protocol, ID and
// generation yet.
let texture = match texture_cache_find(protocol, id, gen) {
Some(texture) => texture,
None => match protocol {
// Look up image_id with ghostty_kitty_graphics_image(), read its
// pixels with ghostty_kitty_graphics_image_get(), and upload.
ImageProtocol::Kitty => upload_kitty_image(id, gen),
// A protocol this renderer doesn't support yet.
else => continue,
}
};
// The destination rectangle in pixels, relative to the top-left
// corner of the viewport. It can start above or left of the
// viewport, so clip it when drawing.
let x = image.viewport_col()? * cell_width + image.cell_offset_x()? as i32;
let y = image.viewport_row()? * cell_height + image.cell_offset_y()? as i32;
// Queue the image. Sort the queue by layer and then z before
// drawing, since iteration order is not drawing order.
queue_image(texture, image.layer()?, image.z()?, x, y,
image.pixel_width()?, image.pixel_height(),
image.source_x()?, image.source_y()?,
image.source_width()?, image.source_height()?);
}
Like rows, they belong to the render state and can be read without access to the terminal. After each update, fill the iterator again before you read it.
The pixels are different, because the render state doesn’t copy them. It only knows where to draw. Read pixels from the terminal while you still have access to it, for example right after the update while you hold your terminal lock.
Each entry has an image ID. Look it up with Graphics::image(), then
read the image’s size, pixel format and pixels with various getters on Image.
The pixels are always decoded and uncompressed, so you can upload them as they are.
This example reads a list and prints what it would draw, including the pixels:
/// Read the render state's image list, the way a renderer builds its list
/// of images to draw. Returns the number of images, or -1 on error.
///
/// The list holds every Kitty image on screen, however the program placed
/// it, with its position, size and draw order worked out. The Kitty
/// graphics storage is only used to read pixels.
///
/// A real renderer would find or upload a texture for each image and
/// queue it for drawing, sorted by layer and then z. This example prints
/// what it would draw instead.
fn draw_images<'alloc>(
snapshot: &Snapshot<'alloc, '_>,
images: &mut ImageIterator<'alloc>,
terminal: &Terminal<'alloc, '_>,
) -> Result<usize, Error> {
// Fill the iterator from the last update.
let mut image_it = images.update(snapshot)?;
// The storage is only needed to read pixels.
let graphics = terminal.kitty_graphics()?;
let mut count = 0usize;
while let Some(image) = image_it.next() {
// Skip protocols this renderer doesn't support.
let Ok(ImageProtocol::Kitty) = image.protocol() else {
continue;
};
count += 1;
println!(
" image {count}: kind={:?} image_id={} placement_id={:?}",
image.kitty_kind()?,
image.image_id()?,
image.kitty_placement_id()?
);
println!(
" layer={:?} z={} cell=({},{}) cells={}x{} offset=({},{})",
image.layer()?,
image.z()?,
image.viewport_col()?,
image.viewport_row()?,
image.grid_cols()?,
image.grid_rows()?,
image.cell_offset_x()?,
image.cell_offset_y()?,
);
println!(
" size={}x{} source=({},{} {}x{})",
image.pixel_width()?,
image.pixel_height()?,
image.source_x()?,
image.source_y()?,
image.source_width()?,
image.source_height()?,
);
// Read the pixels to upload them as a texture. A real renderer keys
// its textures by protocol, image ID and image generation, and only
// gets here when it has no texture for that key yet. The generation
// changes whenever the pixels do, so most frames skip this.
let Some(image) = graphics.image(image.image_id()?) else {
continue;
};
println!(
" pixels: {}x{} format={:?} data_len={} generation={}",
image.width()?,
image.height()?,
image.format()?,
image.data_len()?,
image.generation()?,
);
}
Ok(count)
}
Full program: rust-vt-kitty-graphics/src/main.rs
The list holds every Kitty image on screen, however the program placed it. Earlier versions left some images out, so renderers had to draw them from the storage’s placement iterator. That’s no longer needed. If your renderer still draws from that iterator, stop, or those images are drawn twice. See Inspecting the storage for what it’s for.
Images partly outside the captured rows
An image is in the list when any part of it is in the captured rows, which are the viewport plus any overscan rows. See Overscan.
Images shown with placeholder cells are split into one placement per row of cells, so each of those placements is always inside the captured rows.
Every other placement is reported at its full size, even when only part of it
can be seen. Its ImageIteration::viewport_col() can be negative,
and its ImageIteration::viewport_row() can be above the first
overscan row. It can also extend past the right or bottom edge. So clip what you
draw to the viewport, or to the captured rows if you draw overscan rows. Most
graphics APIs can do this for you with a scissor or clip rectangle.
For example, with no overscan, an image 4 rows tall whose top row scrolled 2 rows above the viewport has a row of -2 and covers 4 rows. Draw it at its full size starting 2 rows above the viewport, clipped to the viewport. Its bottom 2 rows show at the top of the viewport.
Knowing what changed
Most frames don’t change any image. A program prints text or moves the cursor, and every image stays where it was. So a renderer can skip most of its image work. Two values tell you what to redo.
Snapshot::image_placements_generation() belongs to the render
state’s whole list. It tells you when to read the list again. After each update,
compare it with the value from the last time you read the list. If they match,
the list is the same as before, and you can keep drawing what you built last
time:
// Kept by your renderer between frames. The flag makes sure the first
// frame always reads the list.
let mut last_generation = 0u64;
let mut have_draw_list = false;
// Each frame, after `RenderState::update`:
let snapshot = render_state.update(&terminal)?;
let generation = snapshot.image_placements_generation()?;
if !have_draw_list || generation != last_generation {
last_generation = generation;
have_draw_list = true;
// Your renderer: read the iterator as in the example above and
// build a new queue of images to draw.
rebuild_image_queue(&snapshot, images);
}
draw_image_queue();
The value changes when an update adds or removes an image, moves one, changes which part of one is shown, or changes the pixels of one. It stays the same when only text changes, as long as the changed rows had no placeholder cells before or after the change.
A new value means “read the list again”. It doesn’t promise that anything on screen moved. The value can change even when every image ends up exactly where it was, for example:
- When a program rewrites a row that has placeholder cells.
- When a program changes any image or placement while images shown with placeholder cells are on screen.
Only compare the value for equality, and only with the last value you read from the same render state. It wraps around, so a larger value doesn’t mean a newer one. It’s always 0 when Kitty graphics are disabled.
Image::generation() belongs to a single image. It tells you when to upload
that image’s pixels again. It changes when a program sends the image again and
on every animation frame. The render state reports the same value for each
entry as ImageIteration::image_generation(), so you can check your texture
cache without touching the storage, and most frames don’t touch the terminal
at all.
Use the image generation as part of your texture cache key. Don’t rely on the image’s size or data length instead. A program can send new pixels with the same size under the same ID.
Here’s a frame loop that reads the list only when it changed:
/// Draw three frames, reading the image list only when it changed.
///
/// Each frame updates the render state and compares the placements
/// generation with the one from the last time the list was read. The
/// first frame always reads the list. The second frame changes nothing,
/// so it keeps the list it has. Before the third frame, new output
/// scrolls the screen by two rows, which moves both images, so the third
/// frame reads the list again.
fn run_frames(terminal: &mut Terminal<'_, '_>) -> Result<(), Error> {
// Create the render state and the image iterator once, and reuse them.
let mut state = RenderState::new()?;
let mut images = ImageIterator::new()?;
// The flag makes sure the first frame always reads the list.
let mut last_generation = 0u64;
let mut have_draw_list = false;
for frame in 1..=3 {
if frame == 3 {
// Move to the bottom row and print two newlines to scroll.
terminal.vt_write(b"\x1b[24;1H\r\n\r\n");
}
let snapshot = state.update(terminal)?;
let generation = snapshot.image_placements_generation()?;
if have_draw_list && generation == last_generation {
println!("\nFrame {frame}: no image changed, keep drawing the last list");
continue;
}
last_generation = generation;
have_draw_list = true;
println!("\nFrame {frame}: images changed, reading the list:");
let count = draw_images(&snapshot, &mut images, terminal)?;
println!("Total images: {count}");
}
Ok(())
}
Full program: rust-vt-kitty-graphics/src/main.rs
The storage also has a generation of its own, Graphics::generation().
It changes whenever a program sends, places or deletes an image, but not when
images only move on screen. So it can’t tell you when to read the render state’s
list again. It’s useful for work that only depends on what the storage holds,
such as freeing the textures of deleted images.
The two storage generations are never reused, not even across the main and alternate screens, terminal resets, or different terminals. That makes either one safe to use as a cache key on its own.
Placements at a cell
You draw every placement the same way, so you can skip the next three sections
unless you’re curious how a list entry got there, or you’re reading
ImageIteration::kitty_kind().
A program can place an image at a cell on the screen. The image is attached to that cell, so it moves when the text moves: when new output scrolls the screen, when a program scrolls part of the screen, and when the viewport scrolls through the scrollback.
The render state finds the position of these images during each update, so you don’t need to track the cells yourself. This costs very little on a typical frame, including frames where the viewport scrolls.
Placeholders
A program can also place an image with text. It creates a virtual placement, which has no position of its own, and prints placeholder characters (U+10EEEE) wherever the image should appear. Each placeholder cell says which image it shows and which piece of that image belongs in the cell. Programs such as tmux use this so that images scroll, move and disappear along with the text around them.
Only the cells know where these images are, so the storage can’t tell you where to draw them. The render state works it out during each update. It finds the placeholder cells, groups neighboring cells that show the same image into runs, and calculates which part of the image each run shows. It only looks at rows that changed, so this costs very little on a typical frame.
A virtual placement usually turns into several entries in the list, one for each row of placeholder cells. For example, an image shown in a block of 10 columns by 4 rows of placeholders gives 4 entries, each 10 cells wide and 1 cell tall, and each drawing a quarter of the image. Drawn together, they form the whole image.
Relative placements
A program can place an image relative to another placement, its parent. The image is drawn a number of cells to the right of and below its parent. Negative numbers move it left or up. The parent can be relative to another placement too, so placements can form a chain.
The render state follows the chain to the placement at its start and positions the image from there:
- If the chain starts at an image placed at a cell, the image is drawn from that cell, and moves whenever that cell moves.
- If the chain starts at a virtual placement, the image is drawn from the top-left corner of that placement’s placeholder cells. If none of those cells are in the captured rows, the image isn’t in the list.
For example, an image placed 3 columns right of and 2 rows below a parent at column 2, row 1 is drawn at column 5, row 3. Like other placements, it’s in the list when any part of it is in the captured rows, even if its parent isn’t.
Animation
Programs can send images with several frames and ask the terminal to play them,
much like an animated GIF. The terminal stores every frame, but it has no timer
of its own. You drive playback by calling Graphics::tick_animation().
Each call shows whichever frame is due at the time you pass in. When an image
moves to a new frame, Image::data() returns the pixels of the new frame and
Image::generation() returns a new value. If you already cache textures by
image generation, new frames appear without any extra work.
The tick also tells you when the next frame is due. Use that time to schedule a single redraw instead of calling the tick in a loop:
- Call the tick each time you prepare a frame to draw, as long as the storage holds at least one image.
- If it returns
Ok(time), schedule one redraw at the returned time. Don’t schedule it sooner than your shortest frame interval, for example 8 ms for a 120 Hz display. - If it returns
None, nothing is playing. Don’t schedule anything.
You never need to watch for animations starting. A program starts or resumes playback by writing a command to the terminal, and that write already gives you a reason to redraw. The tick on that redraw picks up the animation. A terminal with no playing animations costs nothing extra.
Here’s a helper that follows these steps. A renderer calls it once per frame and uses the result to schedule the next redraw:
/// Advance any playing animations while preparing a frame to draw.
///
/// Call this once per frame, before drawing images. It returns how many
/// milliseconds to wait before the next redraw, or -1 if no animation is
/// playing. In that case, don't schedule a redraw for animations at all.
/// A program that starts an animation does so by writing to the
/// terminal, which already causes a redraw.
///
/// `now_ms` comes from a clock you choose, such as milliseconds since
/// your app started. Always use the same clock with the same starting
/// point.
fn tick_animations(graphics: &mut Graphics<'_>, now_ms: u64) -> Option<u64> {
/// The shortest time between two redraws. About 8 ms suits a 120 Hz display.
pub const MIN_FRAME_INTERVAL_MS: u64 = 8;
let Ok(Some(next_ms)) = graphics.tick_animation(now_ms) else {
return None;
};
// next_ms is an absolute time. Turn it into a delay from now.
Some(next_ms.saturating_sub(now_ms).min(MIN_FRAME_INTERVAL_MS))
}
Full program: rust-vt-kitty-graphics/src/main.rs
This plays a two-frame animation with that helper. It uses a pretend clock so that it runs instantly:
/// Print the first pixel and the generation of an image.
fn print_image(graphics: &Graphics<'_>, image_id: u32) {
let Some(image) = graphics.image(image_id) else {
return;
};
// The image may be gone, and the first pixel below needs three bytes.
let Ok(Some([p0, p1, p2, ..])) = image.data() else {
print!("no pixels");
return;
};
let generation = image.generation().unwrap_or(0);
print!("pixel=({p0},{p1},{p2}) generation={generation}");
}
/// Play a two-frame animation using tick_animations().
///
/// A real app waits for the delay that tick_animations() returns. To keep
/// this example quick, a pretend clock jumps ahead by that delay instead.
fn run_animation(terminal: &mut Terminal<'_, '_>) -> Result<(), Error> {
// These commands set up the animation:
//
// a=T Send a red 1x1 RGBA image with ID 2 and display it.
// a=f Add a blue second frame that shows for 40 ms.
// a=a Make the first frame show for 30 ms. It starts at 0 ms,
// which would mean the frame is skipped.
// a=a Start playing on a loop (s=3).
//
// q=2 tells the terminal not to send replies.
terminal.vt_write(b"\x1b_Ga=T,f=32,i=2,s=1,v=1,q=2;/wAA/w==\x1b\\");
terminal.vt_write(b"\x1b_Ga=f,f=32,i=2,s=1,v=1,z=40,q=2;AAD//w==\x1b\\");
terminal.vt_write(b"\x1b_Ga=a,i=2,r=1,z=30,q=2\x1b\\");
terminal.vt_write(b"\x1b_Ga=a,i=2,s=3,q=2\x1b\\");
// Draw three frames, following each delay.
let mut graphics = terminal.kitty_graphics()?;
let mut now_ms = 0u64;
for _ in 0..3 {
let delay_ms = tick_animations(&mut graphics, now_ms).expect("tick should succeed");
// The tick invalidates image handles, so print_image() looks the
// image up again. The generation changes whenever the frame does.
print!(" t={now_ms} ms: ");
print_image(&graphics, 2);
println!(", next redraw in {delay_ms} ms");
now_ms += delay_ms;
}
// Stop playback (s=1). Once stopped, the tick asks for no redraws.
terminal.vt_write(b"\x1b_Ga=a,i=2,s=1,q=2\x1b\\");
// Writing to the terminal invalidates the storage handle. Get it again.
let mut graphics = terminal.kitty_graphics()?;
if tick_animations(&mut graphics, now_ms).is_none() {
println!(" t={now_ms} ms: stopped, no redraw needed");
}
Ok(())
}
Full program: rust-vt-kitty-graphics/src/main.rs
Inspecting the storage
A renderer doesn’t need this section. A kitty::graphics::PlacementIterator
lists every placement in the storage, including placements that are off screen
and virtual placements. It’s for tools such as debuggers or tests that need to
see what the storage holds.
- Create an iterator with
PlacementIterator::new(). - Fill it from the storage with
PlacementIterator::updateand obtain aPlacementIteration. - Optionally limit it to one layer with
PlacementIteration::set_layer(). - Move to each placement with
PlacementIteration::next()and read its values with the various getters.
These functions work out the geometry of the iterator’s current placement from the storage:
PlacementIteration::pixel_size(): the size to draw the image at, in pixels.PlacementIteration::grid_size(): the number of columns and rows of cells it covers.PlacementIteration::viewport_pos(): the top-left cell, relative to the viewport.PlacementIteration::source_rect(): the part of the image to draw, in image pixels.PlacementIteration::rect(): the cells it covers, as a GhosttySelection.PlacementIteration::render_info(): all of the above except the selection, in one call.
They only know about placements at a cell and placements relative to one. They can’t find virtual placements, or placements relative to a virtual placement, because those depend on the cells. The render state gives the same values for every entry in its list, so prefer it whenever you’re drawing.
Lifetime
Everything borrowed from the terminal is short-lived. Graphics and Image
handles stay valid until the next call that changes the terminal, such as
Terminal::vt_write() or Terminal::reset(). So get them again after
each of those.
Graphics::tick_animation() changes the storage too. It invalidates
image handles and image data slices, so look images up again afterward.
The placement iterator belongs to you, but the values it returns are only valid until the terminal changes.
Putting it together
This creates a terminal, places one image at a cell and another with placeholder cells, lists both from the render state, and reads each image’s pixels from the storage.
fn main() -> Result<(), Error> {
// Install the PNG decoder.
let decode_count = Arc::new(AtomicUsize::new(0));
unsafe {
graphics::set_png_decoder(Some(Box::new(StubPngDecoder {
decode_count: Arc::clone(&decode_count),
})))?;
}
// Create a terminal with Kitty graphics enabled.
let mut terminal = Terminal::new(80, 24)?;
// Set the cell size in pixels. Image sizes depend on it.
terminal.resize(80, 24, 8, 16)?;
// Set a storage limit to enable Kitty graphics.
terminal.set_kitty_image_storage_limit(Some(64 * 1024 * 1024))?; // 64 MiB
// Install write_pty to see the protocol response.
// The Kitty graphics protocol sends an APC response back to the pty
// when an image is loaded (unless suppressed with q=2).
terminal.on_pty_write(|_term, data| {
println!(" response ({} bytes): {}", data.len(), data.escape_ascii());
})?;
// Move the cursor to row 10 so the images have room to scroll up.
terminal.vt_write(b"\x1b[10;1H");
// Send a 1x1 PNG image and place it at the cursor. The image is
// attached to that cell, so it moves when the text moves.
//
// The escape sequence is:
// ESC _G a=T,f=100,q=1; <base64 PNG data> ESC \
//
// Where:
// a=T transmit the image and place it
// f=100 the data is a PNG
// q=1 only reply on errors (q=0 would also reply on success)
println!("Sending Kitty graphics PNG image:");
terminal.vt_write(b"\x1b_Ga=T,f=100,q=1;");
terminal.vt_write(b"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAA");
terminal.vt_write(b"DUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==");
terminal.vt_write(b"\x1b\\");
println!("PNG decode calls: {}", decode_count.load(Ordering::SeqCst));
// Show a second image with placeholder cells. First send a green 1x1
// image with ID 3 and give it a virtual placement 2 columns wide and
// 1 row tall (U=1). Then, on the next row, print two placeholder
// characters (U+10EEEE) where the image should appear:
//
// ESC[38;5;3m the foreground color says which image: ID 3
// U+0305 U+0305 the first cell shows row 0, column 0 of the image
// U+0305 U+030D the second cell shows row 0, column 1
//
// The image moves with those cells, like text.
terminal.vt_write(b"\x1b_Ga=T,U=1,f=32,i=3,s=1,v=1,c=2,r=1,q=2;AP8A/w==\x1b\\");
terminal.vt_write(b"\r\n\x1b[38;5;3m");
terminal.vt_write(b"\xf4\x8e\xbb\xae\xcc\x85\xcc\x85");
terminal.vt_write(b"\xf4\x8e\xbb\xae\xcc\x85\xcc\x8d");
terminal.vt_write(b"\x1b[39m");
// The storage has a generation of its own. It changes when a program
// sends, places or deletes an image, but not when images only move on
// screen. That is why the frames below use the render state's
// placements generation to know when to read the list again.
let graphics = terminal.kitty_graphics()?;
let storage_generation = graphics.generation()?;
println!("\nStorage generation: {storage_generation}");
// Find what to draw from the render state, over three frames.
run_frames(&mut terminal)?;
// Animate a second image by driving the animation tick.
println!("\nPlaying an animation:");
run_animation(&mut terminal)?;
Ok(())
}
Full program: rust-vt-kitty-graphics/src/main.rs
Snapshots
A snapshot is the complete state of a terminal as bytes. Encode one, keep it or send it somewhere, and restore a terminal from it later.
The problem with a big terminal is scrollback. A complete snapshot can be large, and you don’t want someone staring at nothing while old history loads. So a snapshot is ordered: first comes enough state to render and resume the terminal, including any unfinished VT parser input, and then the older scrollback. You can show a restored terminal and feed it live input while the history is still arriving.
Most programs never need this. If you do, you can restore a snapshot in one call, or in pieces if you want the terminal on screen first.
The format isn’t stable yet. Snapshot format version 1 is a work in progress and doesn’t carry a binary-compatibility guarantee.
Encoding
There are three ways to encode, and they differ only in where the bytes go:
| Function | Where the bytes go |
|---|---|
Terminal::encode_snapshot() | A writer. |
Terminal::encode_snapshot_buf() | A buffer you provide. Pass an empty slice to ask for the size. |
Terminal::encode_snapshot_alloc() | A new, allocated buffer. |
A snapshot includes unfinished input, such as half of an escape sequence. To
capture it, the terminal has to have been keeping track of that input, which you
turn on by calling Terminal::set_continuation_max_bytes(). Turn it on before the
input is written. If tracking is off and the VT parser and UTF-8 decoder are
both at ground, encoding still works. If either one is unfinished, encoding
returns Error::InvalidValue.
// A wide, shallow screen fills backing pages quickly enough to leave older
// PAGE records after READY for the incremental decoder to demonstrate.
let mut source = Terminal::new(215, 2)?;
// Snapshot encoding requires continuation tracking if the input can stop
// partway through a sequence, and it has to be enabled before feeding
// input. The limit bounds unfinished VT sequence retention.
source.set_continuation_max_bytes(1024)?;
// Keep enough scrollback to demonstrate incremental history restoration.
source.set_scrollback_max_bytes(Some(usize::MAX))?;
for _ in 0..1000 {
source.vt_write(b"snapshot history line\r\n");
}
// Leave an SGR sequence unfinished so its continuation is snapshotted too.
source.vt_write(b"\x1b[31");
let snapshot = source
.encode_snapshot_alloc(None)?
.expect("snapshot should succeed");
println!("encoded {} snapshot bytes", snapshot.len());
Full program: rust-vt-snapshot/src/main.rs
Terminal::encode_snapshot() needs the terminal to hold still. Don’t write to it or
change it for the duration of the call, and don’t call terminal functions on the
same terminal from your writer. Encoding begins at the writer’s current
position, and calls to the writer are synchronous. We don’t flush, or make your
destination durable. If an error occurs, the writer may hold a partial snapshot
with no valid FINISH marker.
Restoring in one call
Create a decoder over your bytes with snapshot::Decoder::new_buf(), then
call snapshot::Decoder::decode(). You get back a terminal that you own,
with its VT stream restored. It’s safe to free the decoder right away.
The bytes aren’t copied. They have to stay valid and unchanged until FINISH is
reached or the decoder is freed. Bytes after FINISH aren’t consumed, and
snapshot::Decoder::source_offset() tells you where they start.
let full_decoder = Decoder::new_buf(&snapshot)?;
let full_terminal = full_decoder.decode()?;
Full program: rust-vt-snapshot/src/main.rs
Options
Set options with the various setters before decoding starts. After that it
returns Error::InvalidValue. A None value restores an option’s default.
| Option | What it does |
|---|---|
snapshot::Decoder::set_max_continuation_bytes() | The largest unfinished input the decoder accepts. Zero accepts only snapshots at ground. |
snapshot::Decoder::set_retain_continuation() | Keep tracking unfinished input on the restored terminal. Tracking is off by default. |
snapshot::Decoder::set_compress_history_enabled() | Compress each history page right after restoring it. |
snapshot::Decoder::set_kitty_image_storage_limit() | The image storage limit for each restored screen. The snapshot doesn’t carry the original’s limit. |
If you retain the continuation and don’t need tracking after you’ve exported it,
call Terminal::set_continuation_max_bytes() with zero before you write any
new input. Exporting an empty continuation doesn’t turn tracking off.
Without snapshot::Decoder::set_compress_history_enabled(), restored
scrollback is uncompressed, even if the original terminal had compressed it.
That can be many times more memory than the terminal needed before, and it
stays that way until you call Terminal::compress(). With the option on,
the decode never holds more than one uncompressed history page at a time.
The snapshot format doesn’t change, so this works with any snapshot.
let mut compressed_decoder = Decoder::new_buf(&snapshot)?;
// Options must be set before decoding starts. With this set, each history
// page is compressed as soon as it is restored, so the full scrollback is
// never held uncompressed in memory.
compressed_decoder.set_compress_history_enabled(true)?;
let compressed_terminal = compressed_decoder.decode()?;
Full program: rust-vt-snapshot/src/main.rs
Errors
End-of-file before a required READY or FINISH marker means the snapshot is
truncated, and you get Error::InvalidValue. Error::IoError is reserved for
a reader callback that returns false.
A decoding, I/O or allocation error after the decoder has started consuming input poisons it, and all you can do is drop it. An invalid argument or lifecycle error caught before any input is consumed doesn’t.
Restoring in pieces
This is the path that gets a terminal on screen first:
snapshot::Decoder::ready()decodes through READY and gives you ansnapshot::IncrementalDecoder.snapshot::IncrementalDecoder::terminal()gives you a reference to the underlying terminal, usable right away for rendering and live input.snapshot::IncrementalDecoder::next()decodes one record per call: a history page with the Kitty graphics placements pinned to it, or the pixels of one image or animation frame. The current progress is returned as asnapshot::Progressstruct.Ok(None)fromsnapshot::IncrementalDecoder::next()means FINISH was validated. Calling it again returns the same thing.
History pages arrive newest to oldest, so each one is prepended to the scrollback.
The source can be a reader instead of a buffer. Create that decoder
with Decoder::new(). It stores a reference to your reader,
and the callback and its context have to stay valid until FINISH is reached or the
decoder is freed. Reads are synchronous and only happen during ready, next and
decode calls.
A successful read of zero bytes is permanent end-of-file, not temporary starvation. If your source is nonblocking, wait outside the decoder or block in your reader implementation.
struct BufferReader<'a> {
data: &'a [u8],
offset: usize,
}
impl Read for BufferReader<'_> {
// GhosttyReader callbacks are synchronous. A successful zero-byte read is
// permanent EOF; returning false would report an I/O error.
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let remaining = self.data.len() - self.offset;
let count = remaining.min(buf.len());
// Deliberately return short reads to demonstrate that the decoder retries.
let count = count.min(64);
buf[0..count].copy_from_slice(&self.data[self.offset..][0..count]);
self.offset += count;
Ok(count)
}
}
Full program: rust-vt-snapshot/src/main.rs
let mut reader = BufferReader {
data: &snapshot,
offset: 0,
};
let incremental_decoder = Decoder::new(&mut reader)?;
// READY returns a validated, renderable terminal before old history.
let mut incremental_decoder = incremental_decoder.ready()?;
let incremental_terminal = incremental_decoder.terminal();
println!(
"snapshot advertises {} primary history rows",
incremental_decoder.decoder().history_rows_primary()?,
);
let mut page_count = 0usize;
while let Some(progress) = incremental_decoder.next()? {
// Each call decodes either a history page or the pixels of one Kitty
// graphics image. This terminal has no images, but a real client should
// check the kind before reading the page values.
match progress.kind()? {
ProgressKind::Image { id, .. } => {
println!("restored the pixels of image {id}");
}
ProgressKind::Page { rows, remaining } => {
println!(
"restored {} rows to screen {:?} ({} pages remain)",
rows,
progress.screen()?,
remaining
);
}
_ => {}
}
page_count += 1;
}
// None means FINISH validated successfully and is idempotent.
assert!(page_count > 0);
assert!(incremental_decoder.next()?.is_none());
Full program: rust-vt-snapshot/src/main.rs
Between calls
You can render, resize and feed live pty input to the terminal between calls. The decoder borrows your terminal while it restores history, so keep the terminal alive until FINISH validates or the decoder is freed.
If a history page can’t be applied safely anymore, it’s still consumed and validated, and progress reports zero rows. Image pixels work the same way, and report zero bytes. That happens if live input deleted the image or sent a new image with the same id, if the image didn’t fit the storage limit, or if its screen was removed or replaced.
The remaining field on snapshot::ProgressKind::Page counts the page records
left in the same screen’s history, not in the whole snapshot.
You can stop early. Freeing the decoder leaves you a usable terminal with whatever history was already restored. After a decoding error the terminal is also still yours and usable, but the only thing you can do with the decoder is free it.
Images
Images are restored at READY with their pixels pending. A pending image can be placed
and queried, but Image::data() returns Ok(None) for it
until its pixels arrive through IncrementalDecoder::next().
When they arrive, the image keeps its Image::generation(), but Graphics::generation()
changes. A renderer that watches that value picks up the new pixels on its next frame.
Pixels can arrive between history pages, so they’re only known to be done when
next returns None. To show progress, compare
snapshot::IncrementalDecoder::kitty_pending_bytes_primary with what arrives.
snapshot::IncrementalDecoder::next has an example.
The format
You only need this if you’re writing your own tools for snapshots. The Zig codec documentation has the rest.
A snapshot is an ordered, CRC-protected record stream. Every integer is unsigned and little-endian. The stream begins with this fixed ten-byte envelope:
byte 0 8 10
+---------------+--------+
| "GHOSTSNP" | version|
| 8-byte magic | u16 |
+---------------+--------+
After that come independently checksummed records. A record’s CRC32C covers its encoded tag and payload length, followed by its payload. It doesn’t cover the CRC field itself.
byte 0 2 6 10 10 + payload_len
+-------+-------------+-----------+----------------+
| tag | payload_len | CRC32C | payload |
| u16 | u32 | u32 | payload_len B |
+-------+-------------+-----------+----------------+
\____________________/ \______________/
CRC prefix CRC suffix
Record groups occur in this strict order. SCREEN and HISTORY groups contain one entry for each screen declared by TERMINAL. Each manifest is followed by the number of PAGE records it declares. Active SCREEN pages make the terminal renderable. HISTORY pages are older scrollback, ordered newest to oldest so an incremental decoder can prepend them as they arrive.
+---------------- TERMINAL ----------------+
| terminal-wide state and screen count |
+----------------- SCREEN -----------------+ repeated per screen
| active-screen manifest |
+------------------ PAGE ------------------+ repeated per manifest
| active screen rows |
+---------- KITTY_IMAGE_STORAGE -----------+ optional, per screen
| images, placements, in-progress load |
+------------- CONTINUATION ---------------+
| unfinished VT/UTF-8 input, or ground |
+------------------ READY -----------------+
| empty renderable-state marker | ready() returns here
+---------- KITTY_IMAGE_PAYLOAD -----------+ optional, anywhere until FINISH,
| one image's or frame's pixels | next() consumes one
+----------------- HISTORY ----------------+ repeated per screen
| scrollback manifest |
+------------------ PAGE ------------------+ next() consumes one page
| older screen rows |
+------ KITTY_IMAGE_PAGE_PLACEMENTS -------+ optional, after a PAGE
| placements pinned to that page |
+------------------ FINISH ----------------+
| empty end-of-snapshot marker | next() returns NO_VALUE
+------------------------------------------+
| trailing transport bytes (not consumed) |
+------------------------------------------+
READY separates the renderable prefix through CONTINUATION from history. FINISH terminates the record sequence. Both are empty records protected by CRC32C, like every other record. Declared record counts, tags and strict decoding enforce the stream’s ordering and completeness.
A decoder skips any record whose tag it doesn’t know, wherever it appears. That lets a newer library add optional kinds of records that older libraries ignore, without changing the snapshot version. Skipped records are still checked, so a damaged record fails decoding even when its tag is unknown.
The Kitty graphics records are optional in this way. A library built without Kitty graphics skips them and restores the same terminal without its images, and a terminal without images writes none of them.
Custom Sequences
libghostty-vt gives you two ways to get at escape sequences yourself: a callback for the sequences we don’t implement, and a write function that stops at the start or end of a control string.
Programs sometimes send sequences we don’t implement, such as a newer protocol or one specific to your application. The terminal discards these by default. And some applications sit between a shell and a terminal, and need to see exactly where each string starts and ends in the bytes going past.
Most programs never need this page. If you don’t have your own sequences to handle and you aren’t in the middle of someone else’s stream, you can skip it.
Handling sequences we don’t implement
You can ask the terminal to hand these sequences to you, so your application can implement the protocol itself. Two options work together, and you have to set both:
Terminal::on_unknown_sequence()installs the callback.Terminal::set_unknown_max_bytes()sets how many bytes of each sequence to keep. It defaults to zero, which turns the feature off.
The callback receives a effect::UnknownSequence. Its tag says which kind
of sequence arrived. APC and OSC sequences are reported today, and more kinds
may be added later, so ignore any tag you don’t handle.
For OSC, the content is everything between ESC ] and the terminator, including
the number that identifies the sequence. As an example, suppose your application
invents its own OSC 7400 so that programs can report their status. If a program
writes ESC ] 7400;status=busy BEL, the callback receives the content
7400;status=busy and the terminator osc::Terminator::Bel. Match on the
number followed by ;, so that 7400; doesn’t also match an unrelated 74000;
sequence.
We only report numbers we don’t recognize. A sequence that uses a number we do implement, such as OSC 2 for the window title, is never reported, even when its contents are malformed. We also don’t report sequences cut short before their terminator, or supported protocols that you turned off.
The callback runs while the terminal is processing input, so it can answer a query by writing straight to the pty. The reply stays in order with the terminal’s own replies. Use the terminator from the request in your reply, since that’s what the program expects. The rules from The rules for callbacks all apply here.
terminal
// Keep up to 4 KiB of each unknown sequence and report them.
.set_unknown_max_bytes(4096)?
.on_unknown_sequence(|_term, seq| {
let UnknownSequence::Osc { content, truncated, .. } = seq else {
return;
};
// This protocol needs the whole sequence, so skip cut-off ones.
if truncated {
return;
}
// Only handle OSC 7400. Everything else is ignored.
if let Some(status) = content.strip_prefix(b"7400;") {
// The content is only valid during this call. Copy it if you need it
// later. my_app_handle_status is your own function.
my_app.handle_status(status);
}
})?;
Pick a limit that fits the largest sequence you expect. A longer sequence is
still reported, with the first bytes up to the limit in its content and
truncated set to true. Unknown OSC sequences up to 2048 bytes fit in a buffer
the terminal already owns, so limits up to 2048 add no allocations for OSC.
Larger limits allocate memory for each unknown OSC sequence, and unknown APC
sequences are always kept in allocated memory.
This callback handles both kinds and prints what it gets:
terminal
.on_unknown_sequence(|_term, seq| match seq {
UnknownSequence::Apc {
content, truncated, ..
} => {
println!(
" unknown APC (truncated={}, content={} bytes): {}",
if truncated { "yes" } else { "no" },
content.len(),
content.escape_ascii(),
);
}
UnknownSequence::Osc {
content,
truncated,
terminator,
..
} => {
// The content starts with the OSC number, for example
// "7400;status=busy". A real application would check for the
// numbers it implements and ignore the rest. If it replies, it should
// end the reply with the same terminator the program used.
println!(
" unknown OSC (truncated={}, terminator={}, content={} bytes): {}",
if truncated { "yes" } else { "no" },
match terminator {
Terminator::Bel => "BEL",
Terminator::St => "ST",
_ => "unknown",
},
content.len(),
content.escape_ascii(),
);
}
_ => {}
})?
// Unknown sequence capture is independently bounded and disabled by
// default. This limit will apply to every supported unknown sequence type.
.set_unknown_max_bytes(256)?;
Full program: rust-vt-effects/src/main.rs
Stopping a write at a string boundary
Terminal::vt_write_until() works like Terminal::vt_write(), but it
can pause at points you care about. It tells you exactly where a control string
starts or ends, using the same parse that updates the terminal. A program that
sits between a shell and a terminal can use it to:
- Find the exact bytes of each APC, DCS or OSC string, such as a Kitty graphics command, a tmux control mode message or a clipboard write, so it can forward, rewrite or drop that string.
- Wait until the stream is at ground before inserting its own sequences, so it never splits a sequence from the program.
Finding string content
After a START stop, the string’s content begins at the first byte that wasn’t
consumed. For a Kitty graphics command that byte is G. For an OSC it’s the
first digit of the command number. An END stop consumes the byte that ended the
string, which isn’t part of the content. A string can start in one call and end
several calls later.
This loop handles one chunk of output and finds the content of the APC strings in it. DCS and OSC strings work the same way with their own flags:
let want = Boundary::APC_START | Boundary::APC_END;
let mut off = 0usize;
while off < data.len() {
let Some(stop) = terminal.vt_write_until(&data[off..], want) else {
// No boundary in the rest of the chunk. Everything was consumed.
break;
};
off += stop.consumed;
if stop.reached.contains(Boundary::APC_START) {
// The content starts at data[off..].
}
if stop.reached.contains(Boundary::APC_END) {
// The ending byte is at data[off - 1].
// The content stops just before it.
}
}
Strings that end with ESC
The usual string terminator is the two bytes ESC \. The call stops after the
ESC with StringEnd::StEsc and doesn’t consume the \. The loop above needs
no special case for this. The \ is simply the first byte of the next call,
where it completes the terminator and brings the stream back to ground.
DCS strings
A DCS_START stop lands on the introducer, before the header. The bytes after it
are the parameters, intermediates and final byte of the header, then the
payload. For ESC P 1 ; 2 | data ESC \ the stop lands on P, and 1;2| is the
header that follows.
The string can end in its header. CAN, SUB, 0x9C, ESC or another 8-bit control
byte there gives a DCS_END stop for a DCS that never had a payload. Past the
header, only ESC, CAN and SUB end the string, and every other byte is payload,
8-bit bytes included. A 0x90 in the header restarts the header without ending
the string, so it doesn’t stop.
One byte that ends a string and starts another
An 8-bit introducer of a different kind inside an APC, or inside a DCS header,
ends that string and starts the new one on the same byte. The stop has both an
END flag and a START flag in reached, end is ABORTED and introducer is C1.
The content of the new string begins right after the stop.
For example, in ESC _ a 0x9D 2 ; t BEL the 0x9D ends the APC and starts an
OSC. Asking for APC_END and OSC_START gives one stop on the 0x9D with both flags
set, kind APC and byte 0x9D. The OSC content 2;t begins right after it,
and the BEL then gives an OSC_END stop. WriteStop::reached lists
which bytes do this.
Waiting for ground
Boundary::GROUND is a state, not an event. If the stream is already at
ground, the call returns Ok right away with WriteStop::consumed
set to 0. So if you keep asking for ground with the same input, you never make
progress. After a ground stop, write the next bytes without the GROUND flag, or
with Terminal::vt_write.
API Conventions
The libghostty-vt API follows the same few rules everywhere. Learn them once and every bit of functionality in the library behaves in a predictable, regular way.
Four of the rules are short and they’re on this page. The others have pages of their own:
Results
Functions that can fail return an error::Result. The error
can be of the following:
| Result | What it means |
|---|---|
Error::OutOfMemory | An allocation failed. |
Error::InvalidValue | An argument is wrong, such as a NULL pointer where a value is required or an enum value that is out of range. |
Error::OutOfSpace | The buffer you gave us is too small. See Output Buffers. |
Error::IoError | Reading from or writing to external I/O failed. |
Error::LimitExceeded | Encoded input went past a configured limit. |
Error::Rejected | A safety check refused the operation, such as pasted text that could inject commands. Nothing was done. |
Error::Unsupported | This library can’t do what you asked. The key is newer than the library, or the feature was left out of this build. |
Error::Unsupported is how a program handles a library that isn’t the one it was
built for. See Newer Headers, Older Libraries and
Optional Features.
Handles
Much of the libghostty-vt API is handle-based. A handle is an opaque pointer
to something the library manages; the structure of the thing is not public
API for you to dig into. For example: Terminal.
A handle you create is yours. Most come from a new function, such as
Terminal::new(). If you need to, you can also explicitly pass an allocator
when allocating memory for the object with the new_with_alloc functions,
such as Terminal::new_with_alloc(). See Memory.
A borrowed handle belongs to something else, so you don’t free it. It also
doesn’t last. The kitty::Graphics handle you get from
Terminal::kitty_graphics() is only valid until the next call that changes the
terminal, such as Terminal::vt_write(). Each borrowed handle documents
how long it lasts.
Some handles you create still point at a terminal, and it matters which one you drop first:
- A
Formatterborrows its terminal. The terminal must outlive the formatter. - A
Searchor aTrackedGridRefcan outlive its terminal. If the terminal is dropped first, a search fails cleanly on any call that needs the terminal, a tracked reference reports no value, and you can still drop both.
Memory works the same way as handles. Bytes represents a buffer
the library allocates for you, such as the output of fmt::Formatter::format_alloc()
which is owned by the caller. See Allocating and Freeing Buffers.
Threads
The library creates no threads on its own. In general, calls on one handle
are never thread-safe. In the Rust bindings, this is represented by making
handle types !Send + !Sync. But calls across multiple handles are. It is
possible to build a multi-threaded terminal on libghostty-vt and is how many
terminals are built.
Every callback runs on the thread whose call triggered it. libghostty-vt has no concept at all of main threads or routing calls to different threads; you must solve this yourself as the caller.
Calls on one handle, and on any handle borrowed from it, must not run at the same time unless a function’s documentation says otherwise. Handles that share nothing can be used on different threads.
A common example: render state can run on a separate thread from terminal IO, so that IO can continue while rendering happens. There is only one function in render state that uses the terminal and requires a lock.
Output Buffers
Functions that write bytes for you take a mutable slice. You usually don’t know how much space the output needs, so you can ask. Pass an empty slice and the call tells you the size.
When there’s nothing to write, the call returns Ok(0), even for a size query.
When the buffer is too small, the call returns an Error::OutOfSpace, which
contains the size needed. The contents of the buffer are then unspecified unless
the function says otherwise. Throw them away and retry with a larger buffer.
Getting and Setting Values
libghostty-vt has hundreds of values you may want to read or change. Unlike the C API, however, the Rust API provides separate methods for getting or setting each value, since there are no concerns about ABI compatibility, and type safety is much more significant instead.
Newer Headers, Older Libraries
We add new configurable values over time. A program built with a newer header can end up running against an older copy of the library, for example when the library is installed separately as a shared library.
If you pass a key that the loaded library doesn’t know, the call returns
Error::Unsupported and doesn’t touch your output. This works the same way in
debug and release builds of the library.
That lets you use a newer key when it’s there and fall back when it isn’t. In
this example, imagine that render::Snapshot::cursor_blinking was added
in a later release than the library your program loads:
let blinking = match snapshot.cursor_blinking() {
Ok(v) => v,
// This library predates the key. Use a sensible default instead.
Err(Error::Unsupported) => true,
// A real error. Handle it as usual.
Err(err) => return err,
};
Note that for functions that return Result<Option<T>>, the Ok(None) case
and the Err(Error::Unsupported) case mean different things. Error::Unsupported
means the library doesn’t know the value at all. None means the library
knows the value, but something you passed with it is wrong.
The same check applies to enum values you pass as plain arguments or inside
option values, such as a key::Action or the variant of a Point.
A value the library doesn’t recognize returns Error::InvalidValue and leaves
the object unchanged.
Memory
libghostty-vt may allocate memory and fully supports custom allocators.
Most programs never need to think about this. Any function that allocates
either has variants with or without allocators (e.g. new vs new_with_alloc),
or takes an Option<alloc::Allocator<'a>> (None selects the default allocator).
Pass your own when you want memory to come from a specific place, such as an
arena, a pool, a tracking allocator, or a platform without a C library.
The library handles allocation failure. When an allocator returns NULL, the
function that needed the memory returns an error such as Error::OutOfMemory.
It doesn’t crash.
The Default Allocator
The default allocator uses:
- libc
mallocandfreewhen the library is linked against libc. - A built-in allocator when it isn’t. This is currently Zig’s SMP allocator, or Zig’s WebAssembly allocator on WebAssembly.
- An allocator that always fails on native freestanding targets, which have no heap. On these targets you must pass your own allocator to any function that allocates.
Writing a Custom Allocator
Rust users have two ways to obtain a custom libghostty Allocator:
Allocator::GLOBAL, which uses Rust’s own global allocator;- Adapting a custom allocator via the soon-to-be stable (at the time of writing)
Allocator API. We offer a
Fromimplementation that converts an Allocator API-compliant allocator into a libghostty allocator.
Note
You may notice that libghostty’s
Allocatortype comes with a lifetime parameter'ctx. This is because we might need to take a reference to the Rust-side allocator state when converting an existing allocator. If you use the default allocator orAllocator::GLOBAL, feel free to set'ctxto'static.
The library may call an allocator’s functions from any thread that uses a handle
created with it. If handles that share one allocator are used on different
threads, its functions must be thread-safe. In other words, the allocator must
be Sync. The default allocator is.
Alignment
Every vtable function receives an alignment argument. It’s an exponent, not a
byte count. The address you return must be a multiple of 1 << alignment bytes.
alignment | Address must be a multiple of |
|---|---|
| 0 | 1 byte |
| 3 | 8 bytes |
| 4 | 16 bytes |
| 12 | 4096 bytes |
Warning
You must translate the alignment value into bytes when creating a Rust
std::alloc::Layout. It’s different from Zig’sstd.mem.Alignmentin this regard, and failing to do so can render your allocator completely unusable. Other APIs likealigned_allocorposix_memalignmay use different conventions.
Allocating and Freeing Buffers
Bytes is the primary type for buffers allocated by or for libghostty.
Use them when:
- You need a buffer to hand to a libghostty-vt function, such as returning a image decoded by the installed Kitty graphics PNG decoder.
- You want libghostty to handle allocation for you while still having ownership
over the returned data, such as in the case of
Formatter::format_alloc().
Memory must only be freed by the same allocator that created it. On some
platforms the library and your program use different heaps. On Windows, for
example, Zig’s libc and MSVC’s C runtime each keep their own, so freeing memory
from one with the other is undefined behavior. The Rust bindings make sure
this will never happen normally through our Drop implementations.
Allocators Passed to Callbacks
Some callbacks receive an allocator from the library, such as the PNG decoder
set with kitty::graphics::set_png_decoder. Use that allocator only through
allocating functions, such as Bytes::new_zeroed_with_alloc().
Its inner workings are implementation details that may silently change in future
releases.
Optional Features
Warning
This is not yet implemented for the Rust bindings. We are hard at work implementing it and it will be available in the near future.
Some parts of libghostty-vt are optional. A program that only draws a terminal doesn’t need search or snapshots, for example, so the library can be built without them to make it smaller. You choose features when you build the library with default features disabled and with vendoring enabled. We translate the Cargo features you selected into Zig build flags when vendoring the library.
Rust binding symbols are gated behind Cargo feature flags, as is usual for Rust
libraries. If at runtime however the linked libghostty-vt does not support a
given feature, then the function does nothing and returns Error::Unsupported.
| Feature | Types, functions, traits |
|---|---|
color | All types and functions within color |
formatter | All types and functions within fmt |
glyph-protocol | None. It lets applications register custom glyphs with Ghostty’s glyph protocol. |
grid-introspection | All types and functions within grid_ref, as well as screen::Cell, screen::Row, Terminal::track_grid_ref |
input-encode | All types and functions within key, mouse, focus and paste, as well as Terminal::paste |
kitty-graphics | All types and functions within kitty::graphics, and the Kitty setters and getters on Terminal |
render-state | All types and functions within render |
search | All types and functions within search |
selection | All types and functions within selection, and all select_* methods on Terminal |
snapshot | All types and functions within snapshot |
A few functions depend on two features:
Terminal::grid_ref()andTerminal::point_from_grid_ref()need eithergrid-introspectionorselection.TrackedGridRef::snapshot()needs bothgrid-introspectionandsnapshot.
Kitty graphics need a clock, so builds for targets without an operating system,
such as wasm32-freestanding, never include kitty-graphics.
Checking for a Feature
To find out up front, for example to hide a menu item, call the corresponding
supports_* function in build_info.
let has_search = build_info::supports_search().unwrap_or(false);
if !has_search {
// Hide the find bar.
}
You can also just call the function and check its result.
let search = match Search::new(&terminal) {
Ok(search) => search,
Err(Error::Unsupported) => {
// This library was built without search.
}
Err(e) => { /* Some other issue, such as allocation failure */ }
};
Functions Without a Result
A function that doesn’t return a Result can’t report Error::Unsupported.
When its feature is left out, it returns a fixed value instead:
- Functions that return
bool, such as iterator_nextmethods, return false. - Functions that return a number, an enum or a struct return zero or a zeroed
struct.
key::Event::utf8returns an empty string. color::Palette::default()andcolor::Palette::generate()fill their outputs with zeros.color::X11ColorNamesis empty.kitty::Graphics::image()returns NULL.
In practice these values rarely matter. Most of these functions take a handle
that could only come from a _new function of the same feature, and that
function returned Error::Unsupported.
Stability
libghostty-vt is extremely stable and production proven software.
It has been used by millions of users for years and is shipped in a diverse set of free and commercial software across every major operating system and mobile device. It is covered by a significant set of unit tests. It is fuzzed via an AFL++ harness on multiple dedicated machines 24/7, and we’re continuously expanding our fuzz coverage.
ABI
The C ABI is stable. A program built against one 1.x release keeps working with every later 1.x release. CI checks every change against these rules.
Note
As Rust itself does not have a stable ABI, we believe that ABI stability is not as important for the Rust bindings as the C ABI. Similarly, we only guarantee that the Rust API will compile against the C library of the same version. Compiling against older versions of the library may not work.
The ABI stability guarantee however does hold when a compiled Rust program dynamically links against a different version of libghostty-vt.
A minor release may only add:
- New functions.
- New types.
- New enum values.
Nothing is removed, resized, reordered or re-typed. A behavior change ships as a
new function with a new descriptive name, and the old function is marked
#[deprecated] until the next major version.
The snapshot byte format is versioned separately from the library and isn’t covered by the ABI promise. The snapshot functions are part of the C ABI, but the bytes they produce and accept may change in any release. See the Snapshots guide.
Checking the Version
Like any C library, libghostty-vt has two versions: the version you compile against and the version that is loaded at runtime. They’re the same when statically linking, but can differ when dynamically linking and programs should be resilient to this.
To read the library’s version when your program runs, use build_info::version_string
for the string and build_info::{major,minor,patch,pre}_version for the numbers:
fn print_library_version() -> Result<(), Error> {
// The full version, which is the easiest form to log or display. A
// development build has a suffix, such as "1.1.0-dev+abc1234".
println!("Library version: {:?}", build_info::version_string());
// The same version as numbers, which is the easiest form to compare.
let major = build_info::major_version()?;
let minor = build_info::minor_version()?;
let patch = build_info::patch_version()?;
println!("Library version numbers: {major}.{minor}.{patch}");
Ok(())
}
Full program: rust-vt-build-info/src/main.rs
Examples
Every example is a complete program you can build and run. Each one lives in its
own directory under example/, with a README that says how to run it. Most of
them are one zig build run. CI compiles all Rust examples, so they can’t fall
behind the API.
If you want to see everything working together, start with ghostling-rs. It’s a minimal but complete terminal built on libghostty-vt, written in Rust.
If you only want to read a terminal’s screen, start with rust-vt-stream.
Start Here
| Example | What it does |
|---|---|
| rust-vt-hello | The smallest complete program: create a terminal, write text with a color sequence in it, and print the screen. This is the program on the main page. |
| rust-vt-stream | Feed VT sequences into a terminal, read the final screen back as plain text, and draw it with a render state. Start here for read-only tools like replay viewers and CI log viewers. |
| rust-vt-formatter | Write text and cursor movement into a terminal, then stream the screen to stdout as plain text through a GhosttyWriter. |
Terminal
| Example | What it does | Guide |
|---|---|---|
| rust-vt-colors | Set the default colors and palette, then read effective and default values as an OSC 10 override layers on top. | Colors |
| rust-vt-effects | Register callbacks for what a program asks of the terminal: pty replies, the bell, title changes, OSC 52 clipboard reads and writes, and unknown sequences. You need these as soon as a real program runs in the terminal. | Effects |
| rust-vt-compression | Compress scrollback while the terminal is idle. | Scrollback |
| rust-vt-snapshot | Encode a terminal’s full state and restore it three ways: in one shot, with scrollback kept compressed, and page by page. The page by page path gives you a terminal you can draw before the old history arrives. | Snapshots |
| rust-vt-grid-traverse | Walk the whole grid cell by cell with grid refs, reading codepoints, row wrap state and styles. | The Grid |
| rust-vt-grid-ref-tracked | Keep a reference to one cell while the terminal scrolls under it. | The Grid |
| rust-vt-render | Draw a frame from a render state: check what’s dirty, walk the rows and cells, and read styles, colors, the cursor and the selection. Use this when you render the terminal yourself. | Rendering |
| rust-vt-search | Search the terminal for a string, step through the matches like a find bar, and read the viewport matches to draw highlights. | Search |
| rust-vt-selection | Select a word, a line, a command’s output or the whole screen, then format each selection as text. The line and output selections use OSC 133 prompt markers. | Selection |
| rust-vt-selection-gesture | Feed press, drag, release and deep press events to ghostty_selection_gesture_event() and get back selections you can show or copy. | Selection |
| rust-vt-kitty-graphics | Accept images sent with the Kitty Graphics Protocol and find out what to draw. It installs a stand-in PNG decoder, reads placements from the render state, and plays an animation. | Images |
Input
| Example | What it does | Guide |
|---|---|---|
| rust-vt-encode-key | Encode Ctrl+C as an escape sequence with the Kitty keyboard protocol. | Input |
| rust-vt-encode-mouse | Encode a left button press at a pixel position as an SGR mouse sequence. | Input |
| rust-vt-encode-focus | Encode a focus gained event as CSI I, for programs that turn on focus reporting (mode 1004). | Input |
| rust-vt-paste | Paste into a terminal with ghostty_terminal_paste(): plain text, bracketed paste (mode 2004), the unsafe-paste confirmation, and Kitty paste events (mode 5522). It also checks paste safety and encodes paste data without a terminal. | Input |
Building Blocks
| Example | What it does | Guide |
|---|---|---|
| rust-vt-osc | Parse an OSC sequence and read the window title out of it. | |
| rust-vt-sgr | Parse SGR sequences into text attributes, including a real one from Kakoune with a curly underline and RGB colors. | |
| rust-vt-modes | Pack DEC and ANSI mode numbers into a GhosttyMode and encode a DECRPM report. | |
| rust-vt-color-scheme | Encode a color scheme report, the reply to a CSI ? 996 n query. | Colors |
| rust-vt-size-report | Encode an in-band size report (mode 2048) from the grid and cell size. | |
| rust-vt-allocator | Run a terminal on your own allocator, built on malloc and free. It counts live bytes to check that the terminal frees everything. | |
| rust-vt-build-info | Query build options like SIMD and Kitty graphics, then check that the loaded library matches the headers you compiled against. |
Other Languages
C language examples can be found in the original documentation. Examples written in other languages can be found there as well, under the “Other Languages” section.