Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Search

A Search finds a string in a terminal. It covers the active area and scrollback of both the primary and alternate screens.

Terminal search is harder than searching a string, because the text won’t hold still. Scrollback can be huge, and a program can keep writing while you search. We handle that part. Results stay in sync with the live screens. They survive primary and alternate screen switches, so opening and closing a fullscreen app such as vim doesn’t restart a scrollback search. And they recover from resize, reflow, resets and scrollback pruning.

What’s left to you is deciding when the work happens. If you want a one-shot search, Search::run() does all of it, and you can go straight to the example. If you’re building a find bar for a terminal with a lot of scrollback, read the first section.

Driving a search

A search starts idle. Setting a needle with Search::set_needle() starts it, changing the needle restarts it from scratch, and clearing it returns the search to idle. Setting the needle it already has keeps the results, so a find bar can resubmit freely.

Matching is byte-exact, except for ASCII letters, which compare case-insensitively.

Searching a large scrollback takes time, so the work is split into small steps you drive yourself. That gives you direct control over the performance:

FunctionWhat it doesNeeds the terminal
Search::tick()Makes a bounded amount of progress on data the search has already copied.No
Search::feed()Reads the terminal to copy in more data and pick up changes, and returns a snapshot of the matched items.Yes
Search::run()Blocks, feeding and ticking until the search is caught up. Interactive programs should use the other two instead.Yes

Tick while the status is search::Status::Running, and feed when it becomes search::Status::FeedRequired. That’s also the status right after a needle is set, because the search hasn’t seen the terminal yet.

Feeding is the only way a search learns that the terminal changed. So keep feeding periodically while the search is in use, even after it reports complete.

search::Status::Complete means the search is caught up with the terminal as of the last feed. It never means finished forever, because later writes need another feed to be seen.

Matches are selections

Every match is a Selection snapshot with rectangle set to false. So everything in Selection works on matches:

Matches follow the usual snapshot rule. They’re only valid until the next operation that changes the terminal, including Terminal::vt_write(), resize, reset and free. Read matches after a feed, use them before the terminal changes again, and read them again rather than caching them.

Lifetime

A search borrows the terminal it was created with and never owns it. Any number of searches can share one terminal, alongside other readers such as formatters and render states.

You can drop the search and its terminal in either order. Dropping the search first releases the tracked state it holds in the terminal. If the terminal goes first, the search detects that:

  • Calls that need the terminal, and Search::tick(), return Error::InvalidValue.
  • Reads return whatever the search last saw.
  • The Drop implementation releases only the search’s own memory.

A search can’t be rebound. To search another terminal, create a new search.

Threads

The library creates no threads. Calls on one Search aren’t safe to make concurrently with each other, so you have to serialize them.

The functions that touch the terminal also have to be serialized with all other access to that terminal:

Everything else, meaning Search::tick() and its various getters, only touches memory the search owns. Those are safe to call while another thread changes the terminal.

That split is how Ghostty runs search on a background thread: tick freely, and take the terminal lock only to feed.

Reading a returned match value is always safe. Passing one to a function that takes the terminal follows the terminal’s serialization rule above.

Example

This creates a search, runs it, steps through the matches like a find bar, and reads the viewport matches to draw highlights.

use libghostty_vt::{
    Terminal,
    error::Error,
    point::Space,
    search::{MatchBuffer, Search},
};

fn main() -> Result<(), Error> {
    // Create a terminal and fill it with some content to search.
    let mut terminal = Terminal::new(80, 24)?;
    terminal.vt_write(b"$ make test\r\n");
    terminal.vt_write(b"compiling module A... ok\r\n");
    terminal.vt_write(b"compiling module B... error: missing semicolon\r\n");
    terminal.vt_write(b"linking... error: undefined symbol\r\n");
    terminal.vt_write(b"$ grep -n ERROR build.log\r\n");

    // The user opened the find bar, so create a search bound to the
    // terminal. It starts idle until it has a needle.
    let mut search = Search::new(&terminal)?;

    // The user typed a query. Matching is byte-exact except ASCII
    // letters, which compare case-insensitively, so "error" also finds
    // "ERROR". Retyping just sets the needle again: a changed needle
    // restarts the search and an unchanged one keeps its results.
    search.set_needle(&mut terminal, b"error")?;

    // Drive the search. Interactive embedders interleave
    // `Search::tick` and `Search::feed` with their event
    // loop, but for a one-shot search we can just run it to completion.
    search.run(&terminal)?;

    // The total match count, for find bar text like "1 of 3".
    let total = search.total_matches()?;
    println!(r#"{total} matches for "error""#);

    // The user pressed Enter, so select the next match. Selection starts
    // at the newest match, moves toward older content, and wraps around.
    // This scrolls the viewport to the match if it isn't visible, per
    // the `Search::scroll` policy.
    while let Some(s) = search.select_next(&terminal)? {
        // Read the selection state. Index 0 is the newest
        // match, so a "k of n" find bar renders index + 1.
        let selected_index = s.index()?;
        println!("selected {} of {}", selected_index + 1, total);

        // Wrapped back around to the first match: stop.
        if selected_index + 1 == total {
            break;
        }
    }

    // Each frame while the find bar is open, feed to catch up with any
    // terminal changes and then read the viewport matches to draw
    // highlights. The list can include matches just past the viewport
    // when they share a page with it, so convert each endpoint to
    // viewport coordinates and skip matches outside the visible rows.
    search.feed(&terminal)?;

    let mut match_buffer = MatchBuffer::new();
    for m in search.viewport_matches(&terminal, &mut match_buffer)? {
        let Ok(Some(start)) = terminal.point_from_grid_ref(m.start(), Space::Viewport) else {
            continue;
        };
        let Ok(Some(end)) = terminal.point_from_grid_ref(m.end(), Space::Viewport) else {
            continue;
        };

        if start.y >= 24 || end.y >= 24 {
            continue;
        }

        // A real embedder draws a highlight rect from start to end here.
        println!(
            "highlight rows {}-{}, cols {}-{}",
            start.y, end.y, start.x, end.x
        );
    }

    Ok(())
}

Full program: rust-vt-search/src/main.rs