Skip to main content

Terminal

Struct Terminal 

Source
pub struct Terminal<'alloc: 'cb, 'cb> { /* private fields */ }
Expand description

Complete terminal emulator state and rendering.

A terminal instance manages the full emulator state including the screen, scrollback, cursor, styles, modes, and VT stream processing.

Once a terminal session is up and running, you can configure a key encoder to write keyboard input via key::Encoder::set_options_from_terminal.

§Example: VT stream processing

use libghostty_vt::{Terminal, TerminalOptions};

// Create a terminal
let mut terminal = Terminal::new(TerminalOptions {
    cols: 80,
    rows: 24,
    max_scrollback: 0,
}).unwrap();

// 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");

§Effects

By default, the terminal sequence processing with Terminal::vt_write only process sequences that directly affect terminal state and ignores sequences that have side effect behavior or require responses. These sequences include things like bell characters, title changes, device attributes queries, and more. To handle these sequences, the user must configure “effects.”

Effects are callbacks that the terminal invokes in response to VT sequences processed during Terminal::vt_write. They let the embedding application react to terminal-initiated events such as bell characters, title changes, device status report responses, and more.

Each effect is registered with its corresponding Terminal::on_<effect> function, which accepts a closure with access to the terminal state and possibly other parameters. Some examples include Terminal::on_bell and Terminal::on_pty_write.

All callbacks are invoked synchronously during Terminal::vt_write. Callbacks must be very careful to not block for too long or perform expensive operations, since they are blocking further IO processing.

§Shared state

Unlike the C API, you cannot specify arbitrary user data that’s shared between all callbacks, mainly because a safe, idiomatic Rust equivalent of this pattern is very difficult to implement and use due to Rust’s much stricter safety guarantees. In turn, we use the user data internally for callback dispatch purposes.

You should instead use types that allow safe interior mutability (e.g. Cell or RefCell) and pass a shared reference into each effect handler that needs to mutate the shared state. Note that reference counting mechanisms like Rc and Arc are optional.

§Example: Registering effects and processing VT data

use std::cell::Cell;
use libghostty_vt::{Terminal, TerminalOptions};

// Set up a simple bell counter.
//
// `usize` is a simple, `Copy`able type, which means `Cell`s are
// perfectly suitable here. More complex, non-`Copy` types should
// use `RefCell`s instead.
//
// This has to be done before the terminal is created, since
// its effect handlers will continue to refer to the bell counter
// during the lifetime of the terminal.
let bell_count = Cell::new(0usize);

let mut terminal = Terminal::new(TerminalOptions {
    cols: 80,
    rows: 24,
    max_scrollback: 0,
})?;

terminal
    .on_pty_write(|_term, data| {
        println!("Replying {} bytes to the PTY", data.len());
    })?
   .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())
       }
    })?
   .on_title_changed(|term| {
       // Query the cursor position to confirm the terminal processed the
       // title change (the title itself is tracked by the embedder via the
       // OSC parser or its own state).
       let col = term.cursor_x().unwrap();
       println!("Title changed! (cursor at col {col})");
   })?;

// Feed VT data that triggers effects:
// 1. Bell (BEL = 0x07)
terminal.vt_write(b"\x07");
// 2. Title change (OSC 2 ; <title> ST)
terminal.vt_write(b"\x1b]2;Hello Effects\x1b\\");
// 3. Device status report (DECRQM for wraparound mode ?7)
//    triggers write_pty with the response
terminal.vt_write(b"\x1B[?7$p");
// 4. Another bell to show the counter increments
terminal.vt_write(b"\x07");

assert_eq!(bell_count.get(), 2);

§Color theme

The terminal maintains a set of colors used for rendering: a foreground color, a background color, a cursor color, and a 256-color palette. Each of these has two layers: a default value set by the embedder, and an override value that programs running in the terminal can set via OSC escape sequences (e.g. OSC 10/11/12 for foreground/background/cursor, OSC 4 for individual palette entries).

§Default colors

Use Terminal::set_default_fg_color, Terminal::set_default_bg_color, Terminal::set_default_cursor_color and Terminal::set_default_color_palette to configure the default colors. These represent the theme or configuration chosen by the embedder. Passing None clears the default, leaving the color unset.

For the palette, passing None resets to the built-in default palette. The palette set operation preserves any per-index OSC overrides that programs have applied; only unmodified indices are updated.

§Reading colors

Use functions like Terminal::default_cursor_color, Terminal::bg_color, Terminal::default_color_palette, etc. to read colors. There are two variants for each color: the effective value (which returns the OSC override if one is active, otherwise the default) and the default value (which ignores any OSC overrides).

For foreground, background, and cursor colors, the getters return Ok(None) if no color is configured (neither a default nor an OSC override). The palette getters always succeed since the palette always has a value (the built-in default if nothing else is set).

§Setting a color theme

use libghostty_vt::{
    style::{RgbColor, PaletteIndex},
    Error,
    Terminal,
};

fn set_color_theme(terminal: &mut Terminal<'_, '_>) -> Result<(), Error> {
    // Set default foreground (light gray) and background (dark)
    terminal
        .set_default_fg_color(Some(
            RgbColor { r: 0xDD, g: 0xDD, b: 0xDD }
        ))?
        .set_default_bg_color(Some(
            RgbColor { r: 0x1E, g: 0x1E, b: 0x2E }
        ))?
        .set_default_cursor_color(Some(
            RgbColor { 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.default_color_palette()?;
    palette[PaletteIndex::BLACK.0 as usize]   = RgbColor { r: 0x45, g: 0x47, b: 0x5A };
    palette[PaletteIndex::RED.0 as usize]     = RgbColor { r: 0xF3, g: 0x8B, b: 0xA8 };
    palette[PaletteIndex::GREEN.0 as usize]   = RgbColor { r: 0xA6, g: 0xE3, b: 0xA1 };
    palette[PaletteIndex::YELLOW.0 as usize]  = RgbColor { r: 0xF9, g: 0xE2, b: 0xAF };
    palette[PaletteIndex::BLUE.0 as usize]    = RgbColor { r: 0x89, g: 0xB4, b: 0xFA };
    palette[PaletteIndex::MAGENTA.0 as usize] = RgbColor { r: 0xF5, g: 0xC2, b: 0xE7 };
    palette[PaletteIndex::CYAN.0 as usize]    = RgbColor { r: 0x94, g: 0xE2, b: 0xD5 };
    palette[PaletteIndex::WHITE.0 as usize]   = RgbColor { r: 0xBA, g: 0xC2, b: 0xDE };
     
    terminal.set_default_color_palette(Some(palette))?;
    Ok(())
}

Implementations§

Source§

impl<'alloc: 'cb, 'cb> Terminal<'alloc, 'cb>

Source

pub fn new(opts: Options) -> Result<Self>

Create a new terminal instance.

Source

pub fn new_with_alloc<'ctx: 'alloc>( alloc: &'alloc Allocator<'ctx>, opts: Options, ) -> Result<Self>

Create a new terminal instance with a custom allocator.

See the crate-level documentation regarding custom memory management and lifetimes.

Source

pub fn vt_write(&mut self, data: &[u8])

Write VT-encoded data to the terminal for processing.

Feeds raw bytes through the terminal’s VT stream parser, updating terminal state accordingly. By default, sequences that require output (queries, device status reports) are silently ignored. Use Terminal::on_pty_write to install a callback that receives response data.

This never fails. Any erroneous input or errors in processing the input are logged internally but do not cause this function to fail because this input is assumed to be untrusted and from an external source; so the primary goal is to keep the terminal state consistent and not allow malformed input to corrupt or crash.

Source

pub fn resize( &mut self, cols: u16, rows: u16, cell_width_px: u32, cell_height_px: u32, ) -> Result<()>

Resize the terminal to the given dimensions.

Changes the number of columns and rows in the terminal. The primary screen will reflow content if wraparound mode is enabled; the alternate screen does not reflow. If the dimensions are unchanged, this is a no-op.

This also updates the terminal’s pixel dimensions (used for image protocols and size reports), disables synchronized output mode (allowed by the spec so that resize results are shown immediately), and sends an in-band size report if mode 2048 is enabled.

Source

pub fn reset(&mut self)

Perform a full reset of the terminal (RIS).

Resets all terminal state back to its initial configuration, including modes, scrollback, scrolling region, and screen contents. The terminal dimensions are preserved.

Source

pub fn scroll_viewport(&mut self, scroll: ScrollViewport)

Scroll the terminal viewport.

Source

pub fn grid_ref(&self, point: Point) -> Result<GridRef<'_>>

Resolve a point in the terminal grid to a grid reference.

Resolves the given point (which can be in active, viewport, screen, or history coordinates) to a grid reference for that location. Use GridRef::cell and GridRef::row to extract the cell and row.

Lookups in the active region and viewport are fast. Lookups in the screen and history may require traversing the full scrollback page list to resolve the y coordinate, so they can be expensive for large scrollback buffers.

This function isn’t meant to be used as the core of render loop. It isn’t built to sustain the framerates needed for rendering large screens. Use the render state API for that. This API is instead meant for less strictly performance-sensitive use cases.

Source

pub fn track_grid_ref(&self, point: Point) -> Result<TrackedGridRef>

Create an owned tracked grid reference for a terminal point.

This is the tracked variant of Terminal::grid_ref. The returned handle follows the referenced cell as the terminal’s page list is modified: scrolling, pruning, resize/reflow, and other page-list operations update the tracked reference automatically.

The reference is attached to the terminal screen/page-list that is active at creation time.

If the point is outside the requested coordinate space, this returns Err(Error::InvalidValue).

If the tracked grid reference outlives this terminal, the handle remains valid, but it will always return false or Ok(None).

Source

pub fn point_from_grid_ref( &self, grid_ref: &GridRef<'_>, space: PointSpace, ) -> Result<Option<PointCoordinate>>

Convert a grid reference back to a point in the given coordinate system.

This is the inverse of Terminal::grid_ref: given a grid reference, it returns the x/y coordinates in the requested coordinate system (active, viewport, screen, or history).

The grid reference must have been obtained from the same terminal instance. Like all grid references, it is only valid until the next mutating terminal call.

Not every grid reference is representable in every coordinate system. For example, a cell in scrollback history cannot be expressed in active coordinates, and a cell that has scrolled off the visible area cannot be expressed in viewport coordinates. In these cases, the function returns Ok(None).

Source

pub fn mode(&self, mode: Mode) -> Result<bool>

Get the current value of a terminal mode.

Source

pub fn set_mode(&mut self, mode: Mode, value: bool) -> Result<&mut Self>

Set the value of a terminal mode.

Source

pub fn cols(&self) -> Result<u16>

Get the terminal width in cells.

Source

pub fn rows(&self) -> Result<u16>

Get the terminal height in cells.

Source

pub fn cursor_x(&self) -> Result<u16>

Get the cursor column position (inner-indexed).

Source

pub fn cursor_y(&self) -> Result<u16>

Get the cursor row position within the active area (inner-indexed).

Source

pub fn is_cursor_pending_wrap(&self) -> Result<bool>

Get whether the cursor has a pending wrap (next print will soft-wrap).

Source

pub fn is_cursor_visible(&self) -> Result<bool>

Get whether the cursor is visible (DEC mode 25).

Source

pub fn cursor_style(&self) -> Result<Style>

Get the current SGR style of the cursor.

This is the style that will be applied to newly printed characters.

Source

pub fn kitty_keyboard_flags(&self) -> Result<KittyKeyFlags>

Get the current Kitty keyboard protocol flags.

Source

pub fn scrollbar(&self) -> Result<Scrollbar>

Get the scrollbar state for the terminal viewport.

This may be expensive to calculate depending on where the viewport is (arbitrary pins are expensive). The caller should take care to only call this as needed and not too frequently.

Source

pub fn active_screen(&self) -> Result<Screen>

Get the currently active screen.

Source

pub fn is_mouse_tracking(&self) -> Result<bool>

Get whether any mouse tracking mode is active.

Returns true if any of the mouse tracking modes (X1inner, normal, button, or any-event) are enabled.

Source

pub fn title(&self) -> Result<&str>

Get the terminal title as set by escape sequences (e.g. OSC inner/2).

Returns a borrowed string, valid until the next call to Terminal::vt_write or Terminal::reset. An empty string is returned when no title has been set.

Source

pub fn pwd(&self) -> Result<&str>

Get the current working directory as set by escape sequences (e.g. OSC 7).

Returns a borrowed string, valid until the next call to Terminal::vt_write or Terminal::reset. An empty string is returned when no title has been set.

Source

pub fn total_rows(&self) -> Result<usize>

The total number of rows in the active screen including scrollback.

Source

pub fn scrollback_rows(&self) -> Result<usize>

The number of scrollback rows (total rows minus viewport rows).

Source

pub fn fg_color(&self) -> Result<Option<RgbColor>>

The effective foreground color (override or default).

Source

pub fn default_fg_color(&self) -> Result<Option<RgbColor>>

The default foreground color (ignoring any OSC override).

Source

pub fn set_default_fg_color(&mut self, v: Option<RgbColor>) -> Result<&mut Self>

Set the default foreground color.

Source

pub fn bg_color(&self) -> Result<Option<RgbColor>>

The effective background color (override or default).

Source

pub fn default_bg_color(&self) -> Result<Option<RgbColor>>

The default background color (ignoring any OSC override).

Source

pub fn set_default_bg_color(&mut self, v: Option<RgbColor>) -> Result<&mut Self>

Set the default background color.

Source

pub fn cursor_color(&self) -> Result<Option<RgbColor>>

The effective cursor color (override or default).

Source

pub fn default_cursor_color(&self) -> Result<Option<RgbColor>>

The default cursor color (ignoring any OSC override).

Source

pub fn set_default_cursor_color( &mut self, v: Option<RgbColor>, ) -> Result<&mut Self>

Set the default cursor color.

Source

pub fn set_default_cursor_style( &mut self, v: Option<CursorStyle>, ) -> Result<&mut Self>

Set the default cursor style used by DECSCUSR reset (CSI 0 q).

Passing None resets to libghostty’s built-in block cursor default.

Set whether the default cursor blinks when reset by DECSCUSR (CSI 0 q).

Passing None resets to libghostty’s built-in non-blinking default.

Source

pub fn color_palette(&self) -> Result<[RgbColor; 256]>

The current 256-color palette.

Source

pub fn default_color_palette(&self) -> Result<[RgbColor; 256]>

The default 256-color palette (ignoring any OSC overrides).

Source

pub fn set_default_color_palette( &mut self, v: Option<[RgbColor; 256]>, ) -> Result<&mut Self>

Set the default 256-color palette.

Source

pub fn set_apc_max_bytes(&mut self, max: Option<usize>) -> Result<&mut Self>

Set the maximum bytes the APC handler will buffer for all protocols.

This prevents malicious input from causing unbounded memory allocation. A None value removes all overrides, reverting to the built-in defaults.

Source

pub fn set_glyph_protocol_enabled(&mut self, enabled: bool) -> Result<&mut Self>

Enable or disable Glyph Protocol APC handling.

Disabling the protocol makes the terminal ignore Glyph Protocol APC sequences and clears the session’s glyph glossary.

Source§

impl<'alloc, 'cb> Terminal<'alloc, 'cb>

Methods for registering effect handlers.

Source

pub fn on_pty_write( &mut self, f: impl PtyWriteFn<'alloc, 'cb>, ) -> Result<&mut Self>

Call the given function when the terminal needs to write data back to the pty (e.g. in response to a DECRQM query or device status report).

See #Effects for more details.

Source

pub fn on_bell(&mut self, f: impl BellFn<'alloc, 'cb>) -> Result<&mut Self>

Call the given function when the terminal receives a BEL character (0x07).

See #Effects for more details.

Source

pub fn on_enquiry( &mut self, f: impl EnquiryFn<'alloc, 'cb>, ) -> Result<&mut Self>

Call the given function when the terminal receives an ENQ character (0x05).

See #Effects for more details.

Source

pub fn on_xtversion( &mut self, f: impl XtversionFn<'alloc, 'cb>, ) -> Result<&mut Self>

Call the given function when the terminal receives an XTVERSION query (CSI > q), and respond with the resulting version string (e.g. “myterm 1.0”).

See #Effects for more details.

Source

pub fn on_title_changed( &mut self, f: impl TitleChangedFn<'alloc, 'cb>, ) -> Result<&mut Self>

Call the given function when the terminal title changes via escape sequences (e.g. OSC 0 or OSC 2).

The new title can be queried from the terminal after the callback returns.

See #Effects for more details.

Source

pub fn on_pwd_changed( &mut self, f: impl PwdChangedFn<'alloc, 'cb>, ) -> Result<&mut Self>

Call the given function when the terminal current working directory changes via escape sequences (e.g. OSC 7, OSC 9, or OSC 1337).

The new working directory can be queried from the terminal after the callback returns.

See #Effects for more details.

Source

pub fn on_size(&mut self, f: impl SizeFn<'alloc, 'cb>) -> Result<&mut Self>

Call the given function in response to XTWINOPS size queries (CSI 14/16/18 t).

See #Effects for more details.

Source

pub fn on_color_scheme( &mut self, f: impl ColorSchemeFn<'alloc, 'cb>, ) -> Result<&mut Self>

Call the given function in response to a color scheme device status report query (CSI ? 996 n).

Return Some to report the current color scheme, or return None to silently ignore.

See #Effects for more details.

Source

pub fn on_device_attributes( &mut self, f: impl DeviceAttributesFn<'alloc, 'cb>, ) -> Result<&mut Self>

Call the given function in response to a device attributes query (CSI c, CSI > c, or CSI = c).

Return Some with the response data, or return None to silently ignore.

See #Effects for more details.

Source§

impl Terminal<'_, '_>

Methods related to the Kitty graphics protocol.

Source

pub fn kitty_graphics(&self) -> Result<Graphics<'_>>

Available on crate feature kitty-graphics only.

The Kitty graphics image storage for the active screen.

Returns a borrowed reference to the image storage. The pointer is valid until the next mutating terminal call (e.g. Terminal::vt_write or Terminal::reset).

Source

pub fn kitty_image_storage_limit(&self) -> Result<u64>

Available on crate feature kitty-graphics only.

The Kitty image storage limit in bytes for the active screen.

A value of zero means the Kitty graphics protocol is disabled.

Source

pub fn is_kitty_image_from_file_allowed(&self) -> Result<bool>

Available on crate feature kitty-graphics only.

Whether the file medium is enabled for Kitty image loading on the active screen.

Source

pub fn is_kitty_image_from_temp_file_allowed(&self) -> Result<bool>

Available on crate feature kitty-graphics only.

Whether the temporary file medium is enabled for Kitty image loading on the active screen.

Source

pub fn is_kitty_image_from_shared_mem_allowed(&self) -> Result<bool>

Available on crate feature kitty-graphics only.

Whether the shared memory medium is enabled for Kitty image loading on the active screen.

Source

pub fn set_kitty_image_storage_limit(&mut self, limit: u64) -> Result<&mut Self>

Available on crate feature kitty-graphics only.

Set the Kitty image storage limit in bytes.

Applied to all initialized screens (primary and alternate). A value of zero disables the Kitty graphics protocol entirely, deleting all stored images and placements.

Source

pub fn set_kitty_image_from_file_allowed( &mut self, allowed: bool, ) -> Result<&mut Self>

Available on crate feature kitty-graphics only.

Enable or disable Kitty image loading via the file medium.

Has no effect when Kitty graphics are disabled at build time.

Source

pub fn set_kitty_image_from_temp_file_allowed( &mut self, allowed: bool, ) -> Result<&mut Self>

Available on crate feature kitty-graphics only.

Enable or disable Kitty image loading via the temporary file medium.

Has no effect when Kitty graphics are disabled at build time.

Source

pub fn set_kitty_image_from_shared_mem_allowed( &mut self, allowed: bool, ) -> Result<&mut Self>

Available on crate feature kitty-graphics only.

Enable or disable Kitty image loading via the shared memory medium.

Has no effect when Kitty graphics are disabled at build time.

Source

pub fn set_apc_max_bytes_kitty( &mut self, max: Option<usize>, ) -> Result<&mut Self>

Available on crate feature kitty-graphics only.

Set the maximum bytes the APC handler will buffer for Kitty graphics protocol data.

This prevents malicious input from causing unbounded memory allocation. A None value removes all overrides, reverting to the built-in defaults.

Source§

impl Terminal<'_, '_>

Methods related to selections.

Source

pub fn set_selection(&self, selection: Option<&Selection<'_>>) -> Result<&Self>

Set the active screen selection.

The selection’s grid references must be valid for this terminal’s active screen at the time of the call.

Passing None clears the active screen selection.

This function does not take &mut self since it does not invalidate any state that relies on the terminal.

Source

pub fn select_all(&self) -> Result<Option<Selection<'_>>>

Derive a selection snapshot covering all selectable terminal content.

The returned selection is not installed as the terminal’s current selection.

Source

pub fn select_line( &self, options: SelectLineOptions<'_, '_>, ) -> Result<Option<Selection<'_>>>

Derive a selection snapshot covering all selectable terminal content.

The returned selection is not installed as the terminal’s current selection.

Source

pub fn select_output( &self, grid_ref: GridRef<'_>, ) -> Result<Option<Selection<'_>>>

Derive a command-output selection snapshot from a terminal grid reference.

The returned selection is not installed as the terminal’s current selection.

Source

pub fn select_word( &self, options: SelectWordOptions<'_, '_>, ) -> Result<Option<Selection<'_>>>

Derive a word selection snapshot from a terminal grid reference.

The returned selection is not installed as the terminal’s current selection.

Source

pub fn select_word_between( &self, options: SelectWordBetweenOptions<'_, '_>, ) -> Result<Option<Selection<'_>>>

Derive the nearest word selection snapshot between two terminal grid refs.

Starting at options.start, this searches toward options.end (inclusive) and returns the first selectable word found using Ghostty’s word-selection rules.

This is useful for implementing double-click-and-drag selection in a UI. If a user double-clicks one word and drags across spaces or punctuation toward another word, selecting only the word directly under the current pointer can flicker or collapse when the pointer is between words. Instead, ask for the nearest word between the original click and the drag point, ask again in the reverse direction, and combine the two word bounds into the drag selection.

The returned selection is not installed as the terminal’s current selection.

§Example
use libghostty_vt::{
    Error,
    terminal::{Terminal, Point, PointCoordinate},
    screen::GridRef,
    selection::{Selection, SelectWordBetweenOptions},
};

// 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.
fn ref_at<'t>(terminal: &'t Terminal<'_, '_>, x: u16, y: u32) -> Result<GridRef<'t>, Error> {
    terminal.grid_ref(Point::Active(PointCoordinate { x, y }))
}

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(
    SelectWordBetweenOptions::new(click_ref.clone(), drag_ref.clone())
)?;

let end_word = terminal.select_word_between(
    SelectWordBetweenOptions::new(drag_ref, click_ref)
)?;

let drag_selection = Selection::new(
    start_word.unwrap().start(),
    end_word.unwrap().end(),
    false,
);
Source

pub fn format_selection_alloc<'a, 'ctx: 'a>( &self, alloc: Option<&'a Allocator<'ctx>>, options: FormatOptions<'_, '_>, ) -> Result<Option<Bytes<'a>>>

Format a terminal selection into an allocated buffer.

This is a one-shot convenience API for formatting either the terminal’s active selection or a caller-provided Selection without explicitly creating a Formatter.

The returned buffer is allocated using allocator, or the default allocator if None is passed. The returned bytes are not NUL-terminated. This supports plain text, VT, and HTML uniformly as byte output.

If options.selection is None and the terminal has no active selection, the function returns None.

Source

pub fn format_selection_buf( &self, options: FormatOptions<'_, '_>, buf: &mut [u8], ) -> Result<Option<usize>>

Format a terminal selection into a caller-provided buffer.

This is a one-shot convenience API for formatting either the terminal’s active selection or a caller-provided Selection without explicitly creating a Formatter.

If buf is too small, this returns Err(Error::OutOfSpace { required }) where required is the required size. The caller can then retry with a larger buffer.

If options.selection is None and the terminal has no active selection, the function returns None.

Trait Implementations§

Source§

impl<'alloc: 'cb, 'cb> Debug for Terminal<'alloc, 'cb>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Terminal<'_, '_>

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<'alloc, 'cb> !RefUnwindSafe for Terminal<'alloc, 'cb>

§

impl<'alloc, 'cb> !Send for Terminal<'alloc, 'cb>

§

impl<'alloc, 'cb> !Sync for Terminal<'alloc, 'cb>

§

impl<'alloc, 'cb> !UnwindSafe for Terminal<'alloc, 'cb>

§

impl<'alloc, 'cb> Freeze for Terminal<'alloc, 'cb>

§

impl<'alloc, 'cb> Unpin for Terminal<'alloc, 'cb>

§

impl<'alloc, 'cb> UnsafeUnpin for Terminal<'alloc, 'cb>

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, 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<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.