Querying the terminal
A terminal query writes a request. Its reply arrives as an ordinary Event,
beside keyboard and mouse input. Your application owns the wait and its deadline.
The samples on this page target the current checkout.
Select and write a batch
- Create
Probe::new(program.env())before you borrow the screen. - Select each query that your application needs.
- Write the probes through the same screen writer.
- Set
terminatortotruefor the final probe to append Primary Device Attributes (DA1). - Flush the screen once.
- End the screen borrow before you read events.
Probe::new(env) captures relevant environment values by value and selects common session queries.
It selects synchronized output, Unicode core, in-band resize, Kitty keyboard, terminal name,
and modifyOtherKeys.
It selects the RGB and Tc termcap names when environment detection reports a profile below truecolor.
The probe uses environment evidence independently of the program’s forced color profile.
Select cursor measurements and color-value queries explicitly.
Clear mode lists or set query flags to false to omit requests.
The query method writes bytes and returns a record. The caller flushes the writer.
For general discovery, select modes, Kitty keyboard, terminal name, and termcap names.
termcap: None selects automatic RGB and Tc discovery.
Some(vec![]) skips all termcap queries.
Some(names) requests exactly those names, without automatic additions.
For example, probe.termcap = Some(vec!["RGB".into(), "Tc".into()]) selects two XTGETTCAP requests.
Each explicit name produces one request, including when environment detection reports truecolor.
terminal_name selects XTVERSION.
Apple Terminal safety rules skip mode, terminal-name, modifyOtherKeys, and termcap queries.
The Probe reference defines the exact query order.
This complete example preserves keys that arrive during startup:
use std::io::Write;
use std::time::{Duration, Instant};
use uncurses::ansi::mode::Mode;
use uncurses::event::Event;
use uncurses::program::{Probe, Program};
fn main() -> std::io::Result<()> {
let mut program = Program::stdio()?;
let result = (|| {
program.init()?;
let mut probe = Probe::new(program.env());
probe.modes = vec![
Mode::SYNCHRONIZED_OUTPUT,
Mode::UNICODE_CORE,
Mode::IN_BAND_RESIZE,
];
probe.kitty_keyboard = true;
probe.terminal_name = true;
probe.termcap = Some(vec!["RGB".into(), "Tc".into()]);
let mut caps = {
let screen = program.screen_mut();
let caps = probe.query_capabilities(screen, true)?;
screen.flush()?;
caps
};
let mut keys = Vec::new();
let deadline = Instant::now() + Duration::from_millis(300);
'startup: while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
if !program.poll_event(Some(remaining))? {
break;
}
while let Some(event) = program.try_read_event()? {
caps.record(&event);
match event {
Event::PrimaryDeviceAttributes(_) => break 'startup,
Event::KeyPress(_) | Event::KeyRelease(_) => keys.push(event),
_ => {}
}
}
}
for event in keys.into_iter().rev() {
program.unread_event(event);
}
program.apply_defaults(&caps)?;
Ok(())
})();
let finish = program.finish();
result.and(finish)
}An application can also retain keys in its own queue. Handle resize, paste, and other application events during collection, or retain them for the normal loop. Replay queued events after collection so the startup reader does not read them again.
Collect and apply replies
caps.record(&event) updates the record and returns ().
Your loop detects DA1, records it, then ends startup.
For multiple probes, broadcast DA1 to every record before you end collection.
DA1 closes pending measurements in each record.
Use a deadline even when you request DA1. Some terminals leave queries unanswered. A DA1 reply is a useful startup boundary, but multiplexers can forward replies in a different order. Keep identified late replies recordable after startup. A timeout ends your wait; the terminal can still send the answer. Unknown values stay unknown. Boolean helpers mean confirmed support.
Call program.apply_defaults(&caps)? after collection.
It adopts confirmed features according to ProgramOptions:
prefer_grapheme_clusters, prefer_in_band_resize, and prefer_synchronized_output.
These preferences default to true with ProgramOptions::default().
ProgramOptions::new() sets them to false.
They take effect through apply_defaults after support replies arrive.
Initialization applies the immediate settings, such as bracketed paste and mouse tracking.
Explicit program mode choices keep their selected values. The options remain unchanged.
The method also applies measured ambiguous width, Backarrow state, and color evidence.
Rewrite existing text after a width policy change.
Domain managers use their own capability records.
For Glyph Protocol discovery, select uncurses_glyph::Probe::support and collect its record
beside the core record. See Custom probes for the batch pattern.
Measure width with cursor replies
Probe::new(env) sets eaw_width to false.
Select it explicitly because the measurement changes terminal content and the cursor position.
The core eaw_width query measures the ellipsis character.
It writes a carriage return, the ellipsis, a cursor request, another carriage return, and an erase of two cells.
The cursor ends at column zero. Use a blank row before the first frame.
Check that the terminal has at least three columns before you select this query.
A plain writer has byte access; the application supplies geometry and screen bookkeeping.
Invalidate erased content and the tracked cursor after direct cursor changes.
On a blank row, replace the probe setup and write block in the complete startup example with this fragment:
let mut probe = Probe::new(program.env());
probe.eaw_width = program.screen().size().width >= 3;
let mut caps = {
let screen = program.screen_mut();
let caps = probe.query_capabilities(screen, true)?;
if probe.eaw_width {
screen.invalidate();
screen.invalidate_tracked_cursor();
}
screen.flush()?;
caps
};Use the startup loop above to collect replies with caps.record(&event).
For this measurement, suppress ambiguous F3 events until the cursor reply arrives, as explained below.
Read the result with caps.eaw_width(): Some(1) or Some(2) reports the measured width.
None means the measurement is unknown, including when the terminal is too narrow or sends no reply.
Call program.apply_defaults(&caps)? before the first frame to adopt the measured width.
The width example
contains a complete application.
Run cargo run -p examples --example eaw_width on a blank terminal row to print the result.
Cursor reports carry coordinates and a page number. They identify their request through application-controlled order. Read earlier cursor replies before the batch. Keep later cursor requests outside the collection phase. When several selected probes request the cursor, use an application counter based on their documented order. The custom probe example routes two requests this way.
A missing, late, or stray cursor report can break that ordering assumption. Its coordinates alone cannot establish its owner. Treat the measurement as unknown when ownership is uncertain. The deadline does not cancel pending reports.
A standard report on row 1 can also spell modified F3.
The decoder emits the F3 key first, then Event::CursorPosition.
During a known standard cursor request, suppress that ambiguous F3.
A real modified F3 can have the same bytes and can also be suppressed during this interval.
The examples preserve other keys.
Ask one question
The Program::request_* methods write a request and flush.
Match the reply in your normal event loop.
For example, request_background_color() produces Event::BackgroundColor.
request_extended_cursor_position() requests DECXCPR, whose reply has a distinct wire form.
See the Program API for each request and reply.
This complete example collects one background-color reply and preserves keys:
use std::time::{Duration, Instant};
use uncurses::event::Event;
use uncurses::program::Program;
fn main() -> std::io::Result<()> {
let mut program = Program::stdio()?;
let mut background = None;
let result = (|| {
program.init()?;
program.request_background_color()?;
let mut keys = Vec::new();
let deadline = Instant::now() + Duration::from_millis(300);
'wait: while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
if !program.poll_event(Some(remaining))? {
break;
}
while let Some(event) = program.try_read_event()? {
match event {
Event::BackgroundColor(color) => {
background = Some(color);
break 'wait;
}
Event::KeyPress(_) | Event::KeyRelease(_) => keys.push(event),
_ => {}
}
}
}
for event in keys.into_iter().rev() {
program.unread_event(event);
}
Ok(())
})();
let finish = program.finish();
result.and(finish)?;
println!("Background: {background:?}");
Ok(())
}In an application, retain the result and continue the normal loop before cleanup. Process other application events during collection, or retain them for that loop.
Cursor replies arrive as Event::CursorPosition { position, page }.
The coordinates are zero-based. The page number is one-based, or zero when absent.
request_cursor_position() requests standard CPR.
Run cargo run --example query -- --extended to try DECXCPR.
Use set_origin for a report that answers your request_origin call.
The mouse guide
shows the origin-request counter and the F3 ambiguity.
Store current dimensions in application state.
WindowCellSize reports columns and rows.
WindowPixelSize reports the text area in pixels.
CellPixelSize reports one cell’s pixel dimensions.
Resize supplies changed dimensions; zero pixel dimensions mean unknown.
Use program.get_window_size()? for the operating system’s current size.
See Mouse input for pixel conversion.
Run cargo run --example query to see the size replies your terminal supports.
Keep domain and runtime state
Set probe.program_status = true for OSC 7501 discovery.
Core Capabilities records that support. See Program status.
caps.clipboard_write() reports confirmed clipboard-write support from DA1.
The raw DA1 attributes also remain available for application interpretation.
Ask for a current setting
DECRQSS reports current settings through Event::SettingReport.
Use uncurses::ansi::status::write_decrqss to write the request through your chosen writer.
SettingReport::Sgr(report).style() converts text attributes into a Style.
SettingReport::CursorStyle reports the cursor style.
Keep current settings in application state.
Send one DECRQSS at a time when you need to identify an unrecognized-setting reply.
Run cargo run --example sgr_report for an output-only conversion example.
This complete example requests the current text attributes with DECRQSS:
use std::io::Write;
use std::time::{Duration, Instant};
use uncurses::ansi::status::write_decrqss;
use uncurses::event::{Event, SettingReport};
use uncurses::program::Program;
fn main() -> std::io::Result<()> {
let mut program = Program::stdio()?;
let mut sgr = None;
let result = (|| {
program.init()?;
write_decrqss(program.screen_mut(), "m")?;
program.screen_mut().flush()?;
let mut keys = Vec::new();
let deadline = Instant::now() + Duration::from_millis(300);
'wait: while let Some(remaining) = deadline.checked_duration_since(Instant::now()) {
if !program.poll_event(Some(remaining))? {
break;
}
while let Some(event) = program.try_read_event()? {
match event {
Event::SettingReport(SettingReport::Sgr(report)) => {
sgr = Some(report.style());
break 'wait;
}
Event::SettingReport(SettingReport::Unrecognized) => break 'wait,
Event::KeyPress(_) | Event::KeyRelease(_) => keys.push(event),
_ => {}
}
}
}
for event in keys.into_iter().rev() {
program.unread_event(event);
}
Ok(())
})();
let finish = program.finish();
result.and(finish)?;
println!("Text attributes: {sgr:?}");
Ok(())
}SettingReport::Sgr holds an ansi::sgr::Sgr value.
Its params field contains semicolon-separated groups of colon-separated u16 values.
Omitted values become zero.
The style() helper applies these parameters to the default Style.
Unknown parameters remain in params and leave the style unchanged.
Other settings arrive as SettingReport::Raw, with the complete CSI body.
A refusal arrives as SettingReport::Unrecognized and identifies no setting.
Send one DECRQSS at a time, or track request order to identify refusals.
Keep current settings in application state alongside the capability record.
Read a clipboard reply
Call program.request_system_clipboard()? or
program.request_primary_clipboard()?.
The terminal decides whether its access policy permits a reply.
Use a caller deadline if your application must stop the wait.
The reply arrives through ClipboardStart, zero or more ClipboardChunk
events, and ClipboardEnd.
Keep the selection from the start event when your application needs it.
Process each chunk as it arrives to keep memory use independent of the total
payload size.
Chunks contain raw wire bytes, normally base64.
Chunk boundaries can split a base64 group, so retain partial groups if you
decode the payload incrementally.
This current-source fragment counts bytes without retaining clipboard contents:
use uncurses::event::Event;
fn observe_clipboard(event: Event, bytes: &mut usize) {
match event {
Event::ClipboardStart { .. } => *bytes = 0,
Event::ClipboardChunk(chunk) => *bytes += chunk.len(),
Event::ClipboardEnd { complete } => {
println!("Clipboard: {bytes} wire bytes; complete: {complete}");
}
_ => {}
}
}Treat complete: false as an interrupted transfer.
The source ends an active reply after two seconds without new input.
It delivers retained bytes before the incomplete end event.
Use EventSource::with_clipboard_idle_timeout to choose another idle timeout.
Use set_clipboard_idle_timeout on an existing source.
Pass None to preserve framing through long pauses.
The setter restarts the idle wait during a reply and refreshes active async waits.
Call EventSource::end_clipboard() for explicit recovery.
It delivers retained bytes before an incomplete end and wakes active async readers.
Later bytes count as ordinary input.
Idle recovery is a heuristic: keys before expiry can become payload, and delayed
payload after expiry can become keys.
Caller timeouts and wakes preserve a reply, subject to its independent idle timeout.
A fatal input or readiness error can end your read loop.
Discard any unfinished transfer when your application stops that loop.
See the ClipboardEnd contract
for framing and input-error details.
Run cargo run --example clipboard for a complete example with a caller
deadline and terminal cleanup.
It reports the byte and chunk counts, rather than clipboard contents.
Add -- --no-idle-timeout to disable idle recovery in that example.
Compose application probes
A local probe owns query selection and returns its own record.
Write it beside core and domain probes, then flush once.
Use typed core events and ANSI helpers to implement the protocol.
The Custom probes guide contains a complete local module.
Run cargo run --example probe_batch for the executable counterpart.
Add -- --replay to use deterministic replies with an in-memory writer.
Query through a writer
Core, Glyph, and application probes accept any std::io::Write.
Use an EventSource to decode replies when your application owns terminal setup.
The ansi module supplies named request constants and protocol writers.
Append DA1 after the selected queries when you want that collection boundary.
Flush the writer and use an application deadline.
The query example shows direct requests and typed replies.
The gradient example applies color evidence through Program.
The async_screen example collects replies in a tokio::select! loop.
