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