Skip to content

API Reference

Terminal

evp.Terminal

Terminal(
    columns: int,
    rows: int,
    *,
    max_scrollback_bytes: int = 0,
    on_write_pty: Callable[[bytes], object] | None = None,
    on_bell: Callable[[], object] | None = None,
    on_title_changed: Callable[[str], object] | None = None,
    on_pwd_changed: Callable[[str], object] | None = None,
    on_clipboard_write: Callable[
        [ClipboardLocation, list[tuple[str, str]]], object
    ]
    | None = None,
    on_size: Callable[[], tuple[int, int] | None]
    | None = None,
    on_color_scheme: Callable[[], ColorScheme | None]
    | None = None,
    on_device_attributes: Callable[
        [], DeviceAttributes | None
    ]
    | None = None,
)

A terminal emulator, fed the bytes a program writes.

max_scrollback_bytes bounds the scrollback, the rows that scrolled off the top of the screen, in bytes rather than rows, and is fixed when the terminal is made. libghostty frees the scrollback a page, a few hundred KB, at a time, so any limit above zero keeps at least a page or two of rows. Plain text takes about 10 bytes a cell; styles and grapheme clusters take more. The default, 0, keeps no scrollback.

The callbacks run while the terminal reads what the program wrote, so they can't call the terminal's methods; each is passed what it needs instead. Whatever one raises, the call that fed the terminal raises once it's done (the first exception, if several do). A callback left unset ignores what it would have been called for, except that device attributes get Ghostty's.

  • on_write_pty receives the bytes the terminal answers the program's queries with (cursor position and size reports, device attributes), which belong on the program's input.
  • on_bell is called for each BEL.
  • on_title_changed receives the title the program set (with OSC 0 or 2).
  • on_pwd_changed receives the working directory the program reported (with OSC 7).
  • on_clipboard_write receives a clipboard the program wrote to (with OSC 52) and what it wrote, as (mime_type, data) pairs: none means clear it. Data that isn't UTF-8 arrives as an empty string.
  • on_size returns a cell's (width, height) in pixels, for the size reports XTWINOPS asks for (ESC [ 14 t, 16 t and 18 t), or None to send none.
  • on_color_scheme returns the color scheme to report when the program asks (ESC [ ? 996 n), or None to send none.
  • on_device_attributes returns the device attributes to report when the program asks (ESC [ c), or None for Ghostty's own, which DeviceAttributes() also gives.

The terminal answers XTVERSION (ESC [ > q) with libghostty, sends nothing for ENQ, and ignores sequences it doesn't recognize, with no callback for any of them.

is_rendered property

is_rendered: bool

Whether a RenderState reads this terminal now.

feed

feed(data: bytes) -> None

Feed the terminal what the program wrote, raising whatever on_write_pty raised.

resize

resize(
    columns: int,
    rows: int,
    *,
    cell_width: int = 0,
    cell_height: int = 0,
) -> None

Resize the terminal, rewrapping its screen and scrollback, as resizing a window does. A cell's size in pixels is for the in-band size report (mode 2048) and images.

reset

reset() -> None

Reset the terminal, as a program's ESC c does, keeping its size.

scroll_viewport

scroll_viewport(delta: int) -> None

Scroll the viewport, what a RenderState frame shows, by delta rows: up into the scrollback for negative.

scroll_viewport_to_top

scroll_viewport_to_top() -> None

Scroll the viewport to the oldest row of the scrollback.

scroll_viewport_to_bottom

scroll_viewport_to_bottom() -> None

Scroll the viewport back to the screen the program draws on.

size

size() -> tuple[int, int]

The terminal's (columns, rows).

mode

mode(number: int, *, ansi: bool = False) -> bool

Whether a DEC private mode (ESC [ ? n h) is set, or with ansi, an ANSI one.

set_mode

set_mode(
    number: int, value: bool, *, ansi: bool = False
) -> None

Set or reset a DEC private mode, as the program's ESC [ ? n h or l does, or with ansi, an ANSI one.

title

title() -> str

The title the program set (with OSC 0 or 2), or an empty one.

pwd

pwd() -> str

The working directory the program reported (with OSC 7), or an empty one.

set_default_colors

set_default_colors(
    foreground: RGB, background: RGB
) -> None

Set the colors the program's default foreground and background stand for, as a user choosing their terminal's theme does. A color the program set (with OSC 10 or 11) stays.

set_default_palette

set_default_palette(palette: bytes) -> None

Set the 256-color palette, as 768 bytes of RGB, one triple per color. An entry the program changed (with OSC 4) stays.

evp.DeviceAttributes

DeviceAttributes(
    *,
    conformance_level: int = 62,
    features: Sequence[int] = (22,),
    device_type: int = 1,
    firmware_version: int = 0,
    unit_id: int = 0,
)

What a terminal answers a program's device attributes queries with: the primary attributes (ESC [ c), the secondary (ESC [ > c) and the tertiary (ESC [ = c).

The defaults answer as Ghostty does: a VT220-level terminal with ANSI color.

conformance_level property

conformance_level: int

The primary attributes' conformance level: 62 for a VT220, up to 65 for a VT525.

features property

features: list[int]

The primary attributes' features, at most 64, as DEC numbers them: 22 for ANSI color, 52 for the clipboard.

device_type property

device_type: int

The secondary attributes' terminal type: 1 for a VT220.

firmware_version property

firmware_version: int

The secondary attributes' firmware version.

unit_id property

unit_id: int

The tertiary attributes' unit id, which the reply writes as 8 hexadecimal digits.

evp.ClipboardLocation

Bases: IntEnum

Which clipboard a program wrote to.

evp.ColorScheme

Bases: IntEnum

Whether the terminal's colors are light or dark.

Reading the screen

evp.RenderState

RenderState(terminal: Terminal)

Reads what a terminal shows, a frame at a time, and what scrolls off it.

A terminal has at most one render state at a time, since a second would take the first's record of which rows changed: making a second raises RuntimeError until the first is gone.

frame, scrolled_off and history share one table of styles. Each delivers the styles first used since any of them last delivered, so a style always arrives no later than the first row that uses it.

frame

frame() -> Frame

Bring the render state up to date with the terminal and read what it shows.

scrolled_off

scrolled_off() -> ScrolledOff

Read the rows that scrolled off the top of the screen since the last call, or since the render state was made.

Each row is returned once, as the scrollback holds it at the call. A program drawing on the alternate screen scrolls nothing off. Call it often enough that the scrollback can't free rows before it returns them.

history

history() -> History

Read every row the scrollback holds now, oldest first, rewrapped by every resize since it scrolled off. It reads every row each call, so it's for now and then, not every frame.

evp.Frame

What a terminal shows at one moment, as RenderState.frame reads it.

size property

size: tuple[int, int]

The terminal's (columns, rows).

rows property

rows: tuple[Row, ...]

Every row, top to bottom.

A row that shows what a row of the last frame showed is the same Row object, including a row a scroll moved, so derived data kept by row can be reused by identity.

new_styles property

new_styles: tuple[Style, ...]

The styles first used since the render state last delivered any, in index order.

cursor property

cursor: tuple[int, int, bool] | None

The cursor's (x, y, at_wide_tail), or None when it's hidden or off the screen. at_wide_tail is whether it's on the second column of a wide character.

foreground property

foreground: RGB

What the program's default foreground stands for.

background property

background: RGB

What the program's default background stands for.

palette property

palette: bytes

The 256-color palette as the program left it, as 768 bytes of RGB.

evp.ScrolledOff

The rows that scrolled off the screen since the last RenderState.scrolled_off.

rows property

rows: tuple[Row, ...]

The rows, oldest first, as the scrollback holds them now.

new_styles property

new_styles: tuple[Style, ...]

The styles first used since the render state last delivered any, in index order.

has_gap property

has_gap: bool

Whether rows may have been lost since the last call: more scrolled off than the scrollback holds, the program erased the scrollback (ESC [ 3 J), or a resize rewrapped it.

An erase is missed when the last call found the scrollback empty.

evp.History

Every row the scrollback holds, as RenderState.history reads it.

rows property

rows: tuple[Row, ...]

The rows, oldest first.

new_styles property

new_styles: tuple[Style, ...]

The styles first used since the render state last delivered any, in index order.

evp.Row

One row of cells, as parallel sequences with one entry per column.

A wide character's grapheme takes its first column, with width 2, and its second column holds an empty grapheme with width 0. Ghostty can leave a wide character without its second column, and evp reads it as Ghostty keeps it: narrowing the alternate screen, which Ghostty truncates rather than rewraps, leaves a wide character it cuts in half in the last column, still with width 2, and widening the screen again puts a blank with width 1 after it.

graphemes property

graphemes: tuple[str, ...]

Each column's grapheme cluster, a space where the column is blank.

widths property

widths: bytes

How many columns each grapheme cluster takes: 1, 2 if wide, or 0 after a wide one.

styles property

styles: tuple[int, ...]

Each column's style, as an index into the styles the render state has delivered.

evp.Style

How a cell is drawn: its colors and attributes, as libghostty-vt's GhosttyStyle.

Styles compare and hash by value. A render state delivers each distinct style once, and rows name styles by their index among those delivered, so convert each style once, by index.

foreground property

foreground: Color

The text's color.

background property

background: Color

The cell's background color.

underline_color property

underline_color: Color

The underline's color, None for the text's color.

inverse property

inverse: bool

Whether the cell swaps its foreground and background colors.

invisible property

invisible: bool

Whether the cell's text is drawn in its background color.

underline property

underline: int

The SGR underline kind: 0 for none, then single, double, curly, dotted and dashed.

Input to the program

evp.KeyEncoder

KeyEncoder(
    terminal: Terminal,
    *,
    macos_option_as_alt: OptionAsAlt = FALSE,
)

Encodes key events as the bytes a program reads from its terminal, as the terminal's modes say: cursor and keypad application modes, modifyOtherKeys, and the kitty keyboard protocol's flags, read again for each event.

encode

encode(
    key: Key,
    *,
    action: KeyAction = PRESS,
    mods: Mods = Mods(0),
    consumed_mods: Mods = Mods(0),
    text: str | None = None,
    unshifted_codepoint: str | None = None,
    composing: bool = False,
) -> bytes

The bytes a key event sends the program, which are empty for an event that sends none, like a modifier's press.

text is what the key types in the keyboard's layout, before control or alt change it, and is what a printable key sends: Key.A with no text sends nothing. Leave it None for a key that types no text, such as an arrow. consumed_mods are the modifiers that went into text, like shift for an uppercase letter. unshifted_codepoint is the character the key types with no modifiers, which the kitty protocol reports. composing is whether the key is part of an input method's composition, which sends nothing, but for a modifier key's own event under the kitty keyboard protocol.

evp.Key

Bases: IntEnum

A physical key, independent of the keyboard layout, as the W3C UI Events KeyboardEvent.code names it.

evp.KeyAction

Bases: IntEnum

What a key did: pressed, released, or repeated while held.

evp.Mods

Bases: IntFlag

Modifier keys held during a key or mouse event. A _SIDE flag means the right-hand key of its modifier.

evp.OptionAsAlt

Bases: IntEnum

Which of macOS's option keys a key encoder treats as alt.

evp.MouseEncoder

MouseEncoder(
    terminal: Terminal,
    *,
    cell_width: int = 1,
    cell_height: int = 1,
    track_last_cell: bool = False,
)

Encodes mouse events as the bytes a program reads from its terminal, as the terminal's mouse modes say: which events it reports (modes 9, 1000, 1002 and 1003), and in which format (modes 1005, 1006, 1015 and 1016).

Positions are in pixels from the screen's top left corner, and a cell is cell_width by cell_height pixels. The defaults, 1 by 1, make positions cells: (3, 1) is the fourth column of the second row. With track_last_cell, motion within the cell the last motion was reported in isn't reported again.

encode

encode(
    action: MouseAction,
    x: float,
    y: float,
    *,
    button: MouseButton | None = None,
    mods: Mods = Mods(0),
    any_button_pressed: bool = False,
) -> bytes

The bytes a mouse event sends the program, which are empty when its modes don't report it.

button is the button pressed or released, or for motion, the one held, if any. any_button_pressed is whether any button is held, which decides whether motion is reported when the program asked for motion only while a button is held (mode 1002). A position may be off the screen, as when dragging outside it, but raises ValueError unless it's at least -231 pixels and less than both 231 pixels and 65,536 cells.

reset

reset() -> None

Forget the cell the last motion was reported in, so the next motion is reported even in the same cell.

evp.MouseAction

Bases: IntEnum

What the mouse did: pressed a button, released one, or moved.

evp.MouseButton

Bases: IntEnum

A mouse button. Buttons four and five are the scroll wheel's up and down, six and seven its left and right.

evp.encode_focus builtin

encode_focus(event: FocusEvent) -> bytes

The bytes that report a focus change to a program that asked for focus reports (mode 1004).

evp.FocusEvent

Bases: IntEnum

Whether the terminal gained or lost focus.

evp.encode_paste builtin

encode_paste(text: str, *, bracketed: bool) -> bytes

Text as a paste writes it to the program: control characters that could act on the terminal replaced by spaces, and wrapped in bracketed paste's markers when bracketed, or with newlines as carriage returns.

evp.is_paste_safe builtin

is_paste_safe(text: str) -> bool

Whether text is safe to paste without asking: it has no newline, which could run a command, and no bracketed paste end marker, which could end the paste early.

evp.encode_color_scheme builtin

encode_color_scheme(scheme: ColorScheme) -> bytes

The bytes that report the terminal's color scheme, as the reply to ESC [ ? 996 n does. Send them unasked only while the program has mode 2031 set.

evp.encode_size_report builtin

encode_size_report(
    style: SizeReportStyle,
    *,
    columns: int,
    rows: int,
    cell_width: int,
    cell_height: int,
) -> bytes

The bytes of a size report, in the given style.

evp.SizeReportStyle

Bases: IntEnum

Which size report to encode: an in-band report (mode 2048), or the reply to XTWINOPS 14, 16 or 18 (the text area in pixels, a cell in pixels, the text area in cells).

Text out

evp.Formatter

Formatter(
    terminal: Terminal,
    *,
    format: FormatterFormat = PLAIN,
    unwrap: bool = False,
    trim: bool = False,
    palette: bool = False,
    modes: bool = False,
    scrolling_region: bool = False,
    tabstops: bool = False,
    pwd: bool = False,
    keyboard: bool = False,
    cursor: bool = False,
    style: bool = False,
    hyperlink: bool = False,
    protection: bool = False,
    kitty_keyboard: bool = False,
    charsets: bool = False,
)

Writes what a terminal's active screen shows: as plain text, as VT sequences that draw it again, or as HTML.

unwrap joins rows the terminal wrapped, and trim drops the spaces ending rows of plain text. The rest add the terminal's state to VT output, as the sequences that set it: the palette, modes, scrolling region, tab stops, working directory and keyboard modes, and the cursor's position, style, hyperlink, protection, kitty keyboard flags and character sets.

format

format() -> str

Format what the terminal shows now.

evp.FormatterFormat

Bases: IntEnum

What a formatter writes: plain text, VT sequences that redraw the screen, or HTML.

Widths

evp.codepoint_width builtin

codepoint_width(codepoint: str) -> int

How many columns a codepoint takes, as the terminal lays it out: 0, 1, or 2 if it's wide. Summing these over a string is right only while grapheme clustering (mode 2027) is off.

evp.grapheme_width builtin

grapheme_width(text: str) -> tuple[int, int]

The first grapheme cluster of text, as the terminal lays it out with grapheme clustering (mode 2027) on: how many codepoints it takes, and how many columns. (0, 0) only for empty text.

Errors

evp.GhosttyError

Bases: Exception

An error libghostty-vt returned.