Skip to main content

Term

Struct Term 

Source
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

Source

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.

Source

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.

Source

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.

Source

pub fn defer_submitted_input_history_limit(&mut self)

Defers submitted-input retention until the high-level owner has canonicalized or redacted the entry.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn dismiss_completion_menu(&self) -> bool

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.

Source

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.

Source

pub fn trigger_undo(&self) -> bool

Programmatically triggers prompt undo.

Source

pub fn trigger_redo(&self) -> bool

Programmatically triggers prompt redo.

Source

pub fn is_named_action(action: &str) -> bool

Returns true when action is handled by Self::trigger_named_action.

Source

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>§

Source

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.

Source

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.

Source

pub fn completion_refresh_generation(&self) -> u64

Returns the generation that a background completion owner must preserve before requesting a guarded menu refresh.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn output_snapshot(&self) -> OutputSnapshot

Returns a clone of all output blocks/zones, excluding prompt input and prompt-history state.

Source

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.

Source

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.

Source

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.

Source

pub fn replace_output_snapshot(&self, snapshot: OutputSnapshot)

Replaces all output blocks/zones, preserving prompt input and history.

Source

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.

Source

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”.

Source

pub fn size(&self) -> (usize, usize)

Current terminal size tracked by the renderer.

Source

pub fn height(&self) -> usize

Current terminal height tracked by the renderer.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn new_block( &self, debug_id: impl Into<String>, block: impl Into<StyledBlock>, ) -> BlockId

Allocates a new BlockId and stores the block.

Source

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).

Source

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.

Source

pub fn remove_block(&self, id: BlockId)

Removes a block from the central store and every zone that references it.

Source

pub fn remove_block_with_presentation_delta(&self, id: BlockId) -> bool

Removes a block and reports whether any rendered zone referenced it.

Source

pub fn push_history(&self, id: BlockId)

Appends a block id to the history (persistent output).

Source

pub fn push_above_active(&self, id: BlockId)

Appends a block id to the above-active zone (if not already present).

Source

pub fn push_above_active_with_presentation_delta(&self, id: BlockId) -> bool

Adds an active block and reports whether its rendered zone changed.

Source

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.

Source

pub fn push_above_active_before_any_with_presentation_delta<I>( &self, id: BlockId, anchors: I, ) -> bool
where I: IntoIterator<Item = BlockId>,

Reorders an active block and reports whether the rendered order changed.

Source

pub fn remove_above_active(&self, id: BlockId)

Removes a block id from the above-active zone.

Source

pub fn push_above_sticky(&self, id: BlockId)

Appends a block id to the above-sticky zone (if not already present).

Source

pub fn remove_above_sticky(&self, id: BlockId)

Removes a block id from the above-sticky zone.

Source

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.

Source

pub fn remove_suggestions(&self, id: BlockId)

Removes a block id from the suggestions zone.

Source

pub fn push_below(&self, id: BlockId)

Appends a block id to the below zone (if not already present).

Source

pub fn push_below_with_presentation_delta(&self, id: BlockId) -> bool

Adds a below-prompt block and reports whether its rendered zone changed.

Source

pub fn remove_below(&self, id: BlockId)

Removes a block id from the below zone.

Source

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.

Source

pub fn set_left_prompt(&self, text: impl Into<StyledText>)

Updates the left prompt prefix.

Source

pub fn get_buffer(&self) -> String

Returns a clone of the current input buffer.

Source

pub fn enable_paste_uploads(&self, threshold: usize)

Enables large-paste interception for an application that handles uploads.

Source

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.

Source

pub fn get_cursor(&self) -> usize

Returns the current cursor position in bytes.

Source

pub fn get_buffer_revision(&self) -> u64

Returns the current monotonic editor revision.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn completion_state(&self) -> Option<CompletionView>

Snapshot of the open completion menu, if any. Returns None when no menu is showing.

Source

pub fn set_right_prompt(&self, text: impl Into<StyledText>)

Updates the right prompt.

Source

pub fn set_input_placeholder(&self, text: impl Into<StyledText>)

Updates the placeholder shown when the input buffer is empty.

Source

pub fn set_prompt_scroll_indicator(&self, enabled: bool)

Enables or disables the compact hidden-row indicator for capped prompt input.

Source

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.

Source

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.

Trait Implementations§

Source§

impl Deref for Term

Source§

type Target = TermHandle

The resulting type after dereferencing.
Source§

fn deref(&self) -> &TermHandle

Dereferences the value.
Source§

impl Drop for Term

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Term

§

impl !Sync for Term

§

impl !UnwindSafe for Term

§

impl Freeze for Term

§

impl Send for Term

§

impl Unpin for Term

§

impl UnsafeUnpin for Term

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more