pub struct Term { /* private fields */ }Expand description
The terminal prompt engine.
Owns the input event loop. Call Term::get_next_event in a loop to
drive it.
Real terminals isolate each blocking crossterm read in a short-lived helper
thread and deliver the result through an internal channel. This lets
shutdown wake the downstream input loop without timeout polling while still
avoiding a persistent stdin reader that could race a foreground program such
as $EDITOR.
Virtual terminals (tests) use the injected channel branch.
Implementations§
Source§impl Term
impl Term
Sourcepub fn new(
left_prompt: impl Into<StyledText>,
terminal_options: TerminalOptions,
) -> Result<(Self, TermHandle)>
pub fn new( left_prompt: impl Into<StyledText>, terminal_options: TerminalOptions, ) -> Result<(Self, TermHandle)>
Creates a new terminal prompt.
Enters raw mode with terminal_options and spawns the redraw thread.
Returns the prompt engine and a cloneable TermHandle.
§Errors
Returns terminal I/O errors from enabling raw mode or terminal input features. If feature setup fails after raw mode was enabled, raw mode is disabled on a best-effort basis before returning the error.
Sourcepub fn new_virtual(
width: usize,
height: usize,
left_prompt: impl Into<StyledText>,
output: Box<dyn Write + Send>,
cursor_shape: CursorShape,
) -> (Self, TermHandle, Sender<RawEvent>)
pub fn new_virtual( width: usize, height: usize, left_prompt: impl Into<StyledText>, output: Box<dyn Write + Send>, cursor_shape: CursorShape, ) -> (Self, TermHandle, Sender<RawEvent>)
Creates a virtual terminal for testing.
No raw mode, no crossterm input reader. Output goes to the
provided writer (e.g. a pipe). Input is injected via the
returned Sender<RawEvent>. Dropping every returned sender closes
virtual input and makes later reads return sticky Event::Eof.
Sourcepub fn handle(&self) -> &TermHandle
pub fn handle(&self) -> &TermHandle
Returns a reference to the embedded TermHandle. Most
callers can simply call handle methods through Term’s
Deref<Target = TermHandle> instead.
Sourcepub fn defer_submitted_input_history_limit(&mut self)
pub fn defer_submitted_input_history_limit(&mut self)
Defers submitted-input retention until the high-level owner has canonicalized or redacted the entry.
Sourcepub fn finalize_submitted_input_history(&mut self)
pub fn finalize_submitted_input_history(&mut self)
Applies the raw input-history limit after a deferred submitted entry has reached its final canonical or redacted representation.
Sourcepub fn get_next_event(&self) -> Result<Event>
pub fn get_next_event(&self) -> Result<Event>
Blocks until the next meaningful input event.
Handles key editing internally (insert, delete, cursor movement) and only surfaces events the downstream cares about. Triggers a redraw before returning so internal state changes are visible.
§Errors
Returns terminal I/O errors from crossterm reading on real terminals. Both real and virtual terminals return the typed retained output failure after their redraw owner fail-stops. Virtual terminals otherwise return EOF when their injected input channel is disconnected.
Sourcepub fn set_completion_source(
&mut self,
source: Option<Box<dyn CompletionSource>>,
)
pub fn set_completion_source( &mut self, source: Option<Box<dyn CompletionSource>>, )
Plugs in (or replaces) the completion source. Pass None to
disable completion entirely. Closes the menu if currently open.
Sourcepub fn set_bindings(
&mut self,
bindings: impl IntoIterator<Item = (String, String)>,
)
pub fn set_bindings( &mut self, bindings: impl IntoIterator<Item = (String, String)>, )
Configures key bindings surfaced as Event::Binding.
Supported key spellings include Tab, BackTab, Shift-Tab, Enter,
Esc, arrow/navigation/editing keys, C-Enter, C-Up, C-Down, and
C-<letter>, and canonical M-<ascii-character> for exact Alt-only
character events. Control letters are case-sensitive:
C-b and shifted C-B may have different actions when the terminal
reports Shift.
Sourcepub fn seed_input_history(&mut self, history: impl IntoIterator<Item = String>)
pub fn seed_input_history(&mut self, history: impl IntoIterator<Item = String>)
Appends previously submitted prompts to the input history.
Intended for startup seeding from persistent history. Empty prompts are ignored, and the active edit buffer is left intact.
Sourcepub fn replace_last_submitted_input(&mut self, text: String)
pub fn replace_last_submitted_input(&mut self, text: String)
Replaces the most recently submitted input-history entry and any recalled source entry that the submission edited.
Higher layers use this after canonicalizing prompt syntax that the raw editor intentionally does not interpret.
Sourcepub fn pause_for_external(&self) -> Result<()>
pub fn pause_for_external(&self) -> Result<()>
Releases the terminal for an external program (e.g. $EDITOR):
disables raw mode + bracketed paste, restores the user-configured
cursor shape, and clears the screen so the editor starts on a clean
canvas.
No reader-thread coordination is needed: the one-shot crossterm reader
is joined logically by get_next_event returning before callers can
launch the external program, so no persistent stdin reader remains
active while the program owns the terminal.
§Errors
Returns terminal I/O errors from releasing raw-mode features or clearing
the screen. On failure, Tau attempts to roll terminal ownership back via
Self::resume_after_external, which also unmutes redraws and
invalidates the next frame.
Sourcepub fn resume_after_external(&self) -> Result<()>
pub fn resume_after_external(&self) -> Result<()>
Re-acquires raw mode + bracketed paste after an external
program. Marks the redraw thread’s Screen cache stale so the
next render repaints from scratch; without this, the cache
would diff against what we thought was on screen and skip
drawing anything since the editor exited.
§Errors
Returns terminal I/O errors from re-enabling raw-mode features or clearing the screen. Even on failure, the redraw pause is cleared, the tracked terminal size is refreshed, and the next frame is invalidated.
Sourcepub fn record_prompt_undo(&self)
pub fn record_prompt_undo(&self)
Records the current prompt as an undo snapshot without changing the visible buffer.
External pickers call this before releasing the terminal so that a later undo restores the draft that was on screen when the picker opened.
Sourcepub fn trigger_insert_newline(&self) -> Event
pub fn trigger_insert_newline(&self) -> Event
Programmatically inserts a newline into the prompt.
This is the same editing operation as unbound Enter,
Shift-Enter, or Alt-Enter.
Sourcepub fn trigger_submit_or_accept_completion(&self) -> Event
pub fn trigger_submit_or_accept_completion(&self) -> Event
Programmatically submits the prompt or accepts a completion preview.
This is the same operation as unbound Ctrl-Enter: if a
completion candidate is previewed, it is accepted without
submitting; otherwise the current prompt is submitted.
Programmatically closes any open completion menu.
Returns true when a menu was open and got dismissed. If the
selected completion had previewed text in the input buffer, the
buffer is restored to the text that opened the menu.
Sourcepub fn trigger_history_step(&self, delta: isize)
pub fn trigger_history_step(&self, delta: isize)
Programmatically triggers a history step (the same operation
Up/Down and Ctrl-K/Ctrl-J perform). Closes any open
completion menu first so callers don’t have to coordinate with
the input loop.
Sourcepub fn trigger_undo(&self) -> bool
pub fn trigger_undo(&self) -> bool
Programmatically triggers prompt undo.
Sourcepub fn trigger_redo(&self) -> bool
pub fn trigger_redo(&self) -> bool
Programmatically triggers prompt redo.
Sourcepub fn is_named_action(action: &str) -> bool
pub fn is_named_action(action: &str) -> bool
Returns true when action is handled by Self::trigger_named_action.
Sourcepub fn trigger_named_action(&self, action: &str) -> Option<Event>
pub fn trigger_named_action(&self, action: &str) -> Option<Event>
Runs one named raw prompt action, returning the event it produced.
These action names make built-in editing and prompt UI behaviors available to the configurable binding layer.
Methods from Deref<Target = TermHandle>§
Sourcepub fn request_input_shutdown(&self)
pub fn request_input_shutdown(&self)
Requests that the prompt input loop stop and return EOF.
The input loop waits on an internal channel rather than polling, so a shutdown message is sent after the shared flag is set to wake any blocked receiver immediately. Blocking crossterm reads that are already in flight may finish later; their events are ignored after this flag is set.
Sourcepub fn request_completion_refresh(&self)
pub fn request_completion_refresh(&self)
Requests a completion-source refresh without changing the prompt buffer.
The input owner recomputes the menu and redraws it, so background state updates never run completion code on their own threads.
Sourcepub fn completion_refresh_generation(&self) -> u64
pub fn completion_refresh_generation(&self) -> u64
Returns the generation that a background completion owner must preserve before requesting a guarded menu refresh.
Sourcepub fn request_completion_refresh_if_generation(&self, generation: u64)
pub fn request_completion_refresh_if_generation(&self, generation: u64)
Requests a completion refresh only if the input interaction still
matches generation and no candidate is currently previewed.
Sourcepub fn with_redraw_suppressed<R>(&self, f: impl FnOnce() -> R) -> R
pub fn with_redraw_suppressed<R>(&self, f: impl FnOnce() -> R) -> R
Run f while redraw notifications from this handle are suppressed.
Mutations remain visible in shared state, but redraw requests are marked dirty and coalesced into one notification after the outermost nested suppression scope exits. Use this to publish related visible-state changes as one coherent rendered frame.
Sourcepub fn suppress_redraws(&self) -> RedrawSuppressionGuard
pub fn suppress_redraws(&self) -> RedrawSuppressionGuard
Suppress redraw notifications until the returned owned guard is dropped.
Prefer Self::with_redraw_suppressed for one lexical operation. This
owned form exists for bounded multi-message publication such as initial
attachment catch-up.
Sourcepub fn with_output_transaction<R>(&self, f: impl FnOnce() -> R) -> R
pub fn with_output_transaction<R>(&self, f: impl FnOnce() -> R) -> R
Run f while terminal output snapshot mutations from other threads are
blocked.
This transaction is intentionally narrower than the shared
terminal-state mutex: callers can perform a multi-step snapshot swap
using ordinary TermHandle methods without exposing the temporary
snapshot to local output producers that own only a cloned handle.
Sourcepub fn redraw(&self)
pub fn redraw(&self)
Triggers a redraw of the terminal.
Call this after updating one or more blocks/zones. Multiple calls coalesce into a single repaint.
This goes through the differential update path — only the
visible viewport is repainted. Use it for any mutation
guaranteed to be inside the viewport (input, status chip,
streaming live blocks, newly-printed blocks). For mutations
to past blocks that may have scrolled into scrollback, use
invalidate_screen instead. See
README.md § “When mutations need a full redraw” for the
full rule.
Sourcepub fn observe_presentation_mutation(
&self,
delivery_id: RendererDeliveryId,
fact: OpaquePresentationFact,
) -> bool
pub fn observe_presentation_mutation( &self, delivery_id: RendererDeliveryId, fact: OpaquePresentationFact, ) -> bool
Registers one completed selected-transcript mutation for flush correlation.
The caller must establish raw frontend-progress TRACE interest before
calling. The delivery identity and caller-owned opaque label remain
process-local and content-free. A caller whose typed opaque fact
invalidates a visible predecessor must suppress redraw
capture across both its presentation mutation and this registration.
Returns true exactly when redraw capture was suppressed while the
registration held shared terminal state; false means capture was not
suppressed. The return value does not report notification delivery or
eventual writer success.
Sourcepub fn clear_output(&self)
pub fn clear_output(&self)
Drops every rendered block from every output zone and forces a full repaint. The prompt, current input buffer, and input-line history are left intact.
Sourcepub fn output_snapshot(&self) -> OutputSnapshot
pub fn output_snapshot(&self) -> OutputSnapshot
Returns a clone of all output blocks/zones, excluding prompt input and prompt-history state.
Sourcepub fn output_snapshot_count(&self) -> u64
pub fn output_snapshot_count(&self) -> u64
Returns how many full terminal output snapshots this handle has cloned.
This content-free counter supports frontend progress diagnostics and guards hidden-agent rendering against transcript-sized clone regressions.
Sourcepub fn take_output_snapshot(&self) -> OutputSnapshot
pub fn take_output_snapshot(&self) -> OutputSnapshot
Transfers all output blocks and zones out of the visible terminal.
The returned snapshot owns the exact map and zone allocations formerly installed in the terminal. Prompt input and prompt history remain in the terminal. Callers must install another snapshot before allowing visible output mutations.
Sourcepub fn output_snapshot_take_count(&self) -> u64
pub fn output_snapshot_take_count(&self) -> u64
Returns how many output snapshots this handle has transferred by ownership rather than cloned.
This content-free counter distinguishes selection handoffs from transcript-sized clone requests in frontend progress diagnostics.
Sourcepub fn replace_output_snapshot(&self, snapshot: OutputSnapshot)
pub fn replace_output_snapshot(&self, snapshot: OutputSnapshot)
Replaces all output blocks/zones, preserving prompt input and history.
Sourcepub fn replace_output_snapshot_quiet(&self, snapshot: OutputSnapshot)
pub fn replace_output_snapshot_quiet(&self, snapshot: OutputSnapshot)
Replaces all output blocks/zones without invalidating or redrawing. The caller must ensure the visible terminal still corresponds to the restored snapshot.
Sourcepub fn invalidate_screen(&self)
pub fn invalidate_screen(&self)
Forces the next redraw to take the full-render path: clear
the visible screen + scrollback (\x1b[2J\x1b[H\x1b[3J)
and re-emit the configured suffix of rendered history/log rows plus the
fixed tail. Overflow naturally rebuilds recent terminal scrollback, but
full-redraw plans intentionally omit rubber.
Use this when a mutation affects rows that may already be in
terminal scrollback — e.g. toggling visibility of a block from
a past turn (:set show-diff, :set show-thinking). The
differential renderer only repaints the visible window, so
without invalidation those scrolled-out rows would remain as
stale fossils that disagree with current state. See
README.md § “When mutations need a full redraw”.
Sourcepub fn full_render_count(&self) -> u64
pub fn full_render_count(&self) -> u64
Number of full renders performed by the redraw thread since terminal creation. Temporary debugging aid for scrollback bugs.
Sourcepub fn redraw_history_size(&self) -> usize
pub fn redraw_history_size(&self) -> usize
Maximum number of rendered history/log rows replayed during a full
redraw. usize::MAX preserves the historical unbounded behavior.
Sourcepub fn set_redraw_history_size(&self, redraw_history_size: usize)
pub fn set_redraw_history_size(&self, redraw_history_size: usize)
Updates the maximum number of rendered history/log rows replayed during full redraw. This method only stores the value; callers decide whether to invalidate the screen immediately.
Sourcepub fn redraw_sync(&self)
pub fn redraw_sync(&self)
Triggers a redraw and blocks until the redraw thread has
processed it. Uses a generation counter: the caller bumps
sync_requested, the redraw thread sets sync_completed
atomically with going idle (right before blocking on recv).
After terminal output fail-stop, this returns immediately without requesting or retrying a redraw. The failed attachment can no longer promise that any terminal frame was delivered.
Sourcepub fn new_block(
&self,
debug_id: impl Into<String>,
block: impl Into<StyledBlock>,
) -> BlockId
pub fn new_block( &self, debug_id: impl Into<String>, block: impl Into<StyledBlock>, ) -> BlockId
Allocates a new BlockId and stores the block.
Sourcepub fn set_block(&self, id: BlockId, block: impl Into<StyledBlock>)
pub fn set_block(&self, id: BlockId, block: impl Into<StyledBlock>)
Updates the content of an existing block (or inserts it at the given id).
Sourcepub fn set_block_with_presentation_delta(
&self,
id: BlockId,
block: impl Into<StyledBlock>,
) -> bool
pub fn set_block_with_presentation_delta( &self, id: BlockId, block: impl Into<StyledBlock>, ) -> bool
Updates a block and reports whether an already-rendered reference changed.
Sourcepub fn remove_block(&self, id: BlockId)
pub fn remove_block(&self, id: BlockId)
Removes a block from the central store and every zone that references it.
Sourcepub fn remove_block_with_presentation_delta(&self, id: BlockId) -> bool
pub fn remove_block_with_presentation_delta(&self, id: BlockId) -> bool
Removes a block and reports whether any rendered zone referenced it.
Sourcepub fn push_history(&self, id: BlockId)
pub fn push_history(&self, id: BlockId)
Appends a block id to the history (persistent output).
Sourcepub fn push_above_active(&self, id: BlockId)
pub fn push_above_active(&self, id: BlockId)
Appends a block id to the above-active zone (if not already present).
Sourcepub fn push_above_active_with_presentation_delta(&self, id: BlockId) -> bool
pub fn push_above_active_with_presentation_delta(&self, id: BlockId) -> bool
Adds an active block and reports whether its rendered zone changed.
Sourcepub fn push_above_active_before_any<I>(&self, id: BlockId, anchors: I)where
I: IntoIterator<Item = BlockId>,
pub fn push_above_active_before_any<I>(&self, id: BlockId, anchors: I)where
I: IntoIterator<Item = BlockId>,
Inserts a block id into the above-active zone before the first matching anchor block, or appends it when none of the anchors are active.
Existing references to id are moved rather than duplicated. This keeps
callers from rebuilding the whole output snapshot when they need a
stable sub-order inside the bottom-anchored live block area.
Sourcepub fn push_above_active_before_any_with_presentation_delta<I>(
&self,
id: BlockId,
anchors: I,
) -> boolwhere
I: IntoIterator<Item = BlockId>,
pub fn push_above_active_before_any_with_presentation_delta<I>(
&self,
id: BlockId,
anchors: I,
) -> boolwhere
I: IntoIterator<Item = BlockId>,
Reorders an active block and reports whether the rendered order changed.
Sourcepub fn remove_above_active(&self, id: BlockId)
pub fn remove_above_active(&self, id: BlockId)
Removes a block id from the above-active zone.
Sourcepub fn push_above_sticky(&self, id: BlockId)
pub fn push_above_sticky(&self, id: BlockId)
Appends a block id to the above-sticky zone (if not already present).
Sourcepub fn remove_above_sticky(&self, id: BlockId)
pub fn remove_above_sticky(&self, id: BlockId)
Removes a block id from the above-sticky zone.
Sourcepub fn push_suggestions(&self, id: BlockId)
pub fn push_suggestions(&self, id: BlockId)
Appends a block id to the suggestions zone (if not already present). Rendered between the prompt and below blocks.
Sourcepub fn remove_suggestions(&self, id: BlockId)
pub fn remove_suggestions(&self, id: BlockId)
Removes a block id from the suggestions zone.
Sourcepub fn push_below(&self, id: BlockId)
pub fn push_below(&self, id: BlockId)
Appends a block id to the below zone (if not already present).
Sourcepub fn push_below_with_presentation_delta(&self, id: BlockId) -> bool
pub fn push_below_with_presentation_delta(&self, id: BlockId) -> bool
Adds a below-prompt block and reports whether its rendered zone changed.
Sourcepub fn remove_below(&self, id: BlockId)
pub fn remove_below(&self, id: BlockId)
Removes a block id from the below zone.
Sourcepub fn print_output(
&self,
debug_id: impl Into<String>,
block: impl Into<StyledBlock>,
) -> BlockId
pub fn print_output( &self, debug_id: impl Into<String>, block: impl Into<StyledBlock>, ) -> BlockId
Creates a new block and appends it to the history. Triggers a redraw automatically.
Sourcepub fn set_left_prompt(&self, text: impl Into<StyledText>)
pub fn set_left_prompt(&self, text: impl Into<StyledText>)
Updates the left prompt prefix.
Sourcepub fn get_buffer(&self) -> String
pub fn get_buffer(&self) -> String
Returns a clone of the current input buffer.
Sourcepub fn enable_paste_uploads(&self, threshold: usize)
pub fn enable_paste_uploads(&self, threshold: usize)
Enables large-paste interception for an application that handles uploads.
Sourcepub fn finish_paste_upload(&self, id: u64, result: Result<String, String>)
pub fn finish_paste_upload(&self, id: u64, result: Result<String, String>)
Delivers a content-free upload outcome to the sole editor input owner.
Success contains only the reference to insert, never original bytes. Late outcomes after cancellation or a later retry are ignored.
Sourcepub fn get_cursor(&self) -> usize
pub fn get_cursor(&self) -> usize
Returns the current cursor position in bytes.
Sourcepub fn get_buffer_revision(&self) -> u64
pub fn get_buffer_revision(&self) -> u64
Returns the current monotonic editor revision.
Sourcepub fn last_submitted_buffer_revision(&self) -> Option<u64>
pub fn last_submitted_buffer_revision(&self) -> Option<u64>
Returns the exact editor revision captured after the most recent raw line submission cleared the prompt.
Sourcepub fn set_buffer(&self, text: String, cursor: usize)
pub fn set_buffer(&self, text: String, cursor: usize)
Replaces the input buffer and cursor position. Also clears any active history-navigation, completion menu, and prompt undo state — an external buffer set is treated as a fresh starting point.
Sourcepub fn set_buffer_if_revision(
&self,
expected_revision: u64,
text: String,
cursor: usize,
) -> bool
pub fn set_buffer_if_revision( &self, expected_revision: u64, text: String, cursor: usize, ) -> bool
Replaces the input buffer only if no raw or external editor mutation has
occurred since expected_revision.
Sourcepub fn recall_prompt_before_current(&self, text: String)
pub fn recall_prompt_before_current(&self, text: String)
Recalls a queued prompt before the current draft, matching prompt-history navigation so pressing Down restores the draft that was present at recall time.
Sourcepub fn set_buffer_preserving_undo(&self, text: String, cursor: usize)
pub fn set_buffer_preserving_undo(&self, text: String, cursor: usize)
Replaces the input buffer and cursor position without clearing prompt undo history.
Use this after the caller has explicitly recorded the current prompt as an undo snapshot before launching an external picker. Active history navigation and completion are still closed because the replacement becomes the new editable draft.
Sourcepub fn completion_state(&self) -> Option<CompletionView>
pub fn completion_state(&self) -> Option<CompletionView>
Snapshot of the open completion menu, if any. Returns None
when no menu is showing.
Sourcepub fn set_right_prompt(&self, text: impl Into<StyledText>)
pub fn set_right_prompt(&self, text: impl Into<StyledText>)
Updates the right prompt.
Sourcepub fn set_input_placeholder(&self, text: impl Into<StyledText>)
pub fn set_input_placeholder(&self, text: impl Into<StyledText>)
Updates the placeholder shown when the input buffer is empty.
Sourcepub fn set_prompt_scroll_indicator(&self, enabled: bool)
pub fn set_prompt_scroll_indicator(&self, enabled: bool)
Enables or disables the compact hidden-row indicator for capped prompt input.
Sourcepub fn print_terminal_bell(&self)
pub fn print_terminal_bell(&self)
Queues a terminal bell to be written by the redraw thread on its next pass. Goes through the redraw loop so the byte never interleaves with an in-flight frame.
Sourcepub fn print_osc1337_set_user_var(&self, name: &str, value: &str, in_tmux: bool)
pub fn print_osc1337_set_user_var(&self, name: &str, value: &str, in_tmux: bool)
Queues an iTerm2 OSC 1337 SetUserVar side effect.
name must be non-empty printable ASCII, must not contain =, and must
be at most 128 bytes. Invalid names are skipped and logged without
echoing the invalid bytes. When in_tmux is true, the OSC is wrapped in
a tmux passthrough DCS sequence so the outer terminal receives it.
value is base64-encoded before being written. Invalid name values
are rejected and logged rather than emitted because OSC names are
structural escape-sequence fields.