libvt

Pure-Python virtual terminal emulator and streaming VT parser.

class libvt.AnsiColor
class libvt.AnsiColor

Bases: IntEnum

Standard and bright ECMA-48 / aixterm 16-color palette indices.

class libvt.Bell
class libvt.Bell

Bases: object

Emitted when BEL (0x07) executes in GROUND.

class libvt.BlockKind
class libvt.BlockKind

Bases: StrEnum

Reason categories when StatusState.BLOCKED requests user action.

class libvt.CaptureCompleteness
class libvt.CaptureCompleteness

Bases: object

Explicit fidelity report for a decoded tmux capture-pane snapshot.

class libvt.Cell
class libvt.Cell

Bases: object

Immutable view of a single terminal grid cell.

class libvt.ClipboardWrite
class libvt.ClipboardWrite

Bases: object

Emitted when OSC 52 writes base64-decoded text to a selection target.

class libvt.ColorScheme
class libvt.ColorScheme

Bases: IntEnum

CSI ? 997 ; Ps n color-scheme values (DEC ?2031 / DSR ?996n).

class libvt.ColorSchemeQueried
class libvt.ColorSchemeQueried

Bases: object

Emitted when CSI ? 996 n queries the host color scheme.

class libvt.CsiParams
class libvt.CsiParams

Bases: object

Parsed CSI parameter list preserving ; vs : subparameter boundaries.

class libvt.Cursor
class libvt.Cursor

Bases: object

Zero-based cursor state on a Screen.

class libvt.CursorShape
class libvt.CursorShape

Bases: StrEnum

Cursor glyph shape configured via DECSCUSR (CSI Ps SP q).

class libvt.DecrpmValue
class libvt.DecrpmValue

Bases: IntEnum

DECRPM status codes returned in CSI ? Ps ; Pm $ y replies.

class libvt.EraseCause
class libvt.EraseCause

Bases: StrEnum

Reason a screen rectangle was cleared or scrolled.

class libvt.ExplainedSpan
class libvt.ExplainedSpan

Bases: object

Human-readable disassembly of one parsed VT token.

class libvt.FlightRecorder
class libvt.FlightRecorder

Bases: object

Bounded raw-byte ring buffer capturing recent VT traffic for diagnostics.

class libvt.FocusEvent
class libvt.FocusEvent

Bases: object

Terminal window focus-in / focus-out event (?1004).

class libvt.Formatter
class libvt.Formatter

Bases: object

Serialize a Snapshot or Terminal to text, VT, or HTML.

class libvt.GraphicsProtocol
class libvt.GraphicsProtocol

Bases: StrEnum

Terminal graphics protocol family.

class libvt.Hyperlink
class libvt.Hyperlink

Bases: object

OSC 8 hyperlink attached to printed cells independent of SGR 0.

class libvt.ImageMeta
class libvt.ImageMeta

Bases: object

Stored sans-I/O image metadata without buffered pixel bitmaps.

class libvt.ImagePlacement
class libvt.ImagePlacement

Bases: object

Immutable snapshot of a SIXEL or Kitty image placement on a screen.

class libvt.InBandResize
class libvt.InBandResize

Bases: object

Emitted when resize() queues a ?2048 in-band resize report.

class libvt.IndexedColor
class libvt.IndexedColor

Bases: object

256-color palette entry (SGR 38;5;n / SGR 48;5;n).

class libvt.KeyAction
class libvt.KeyAction

Bases: IntEnum

Key press lifecycle event type for Kitty CSI u.

class libvt.KeyEvent
class libvt.KeyEvent

Bases: object

Structured keyboard event for outbound PTY encoding.

class libvt.KeyMod
class libvt.KeyMod

Bases: IntFlag

Keyboard and mouse modifier bitmask matching Kitty CSI u bits.

class libvt.KittyCommand
class libvt.KittyCommand

Bases: object

Zero-dependency APC G Kitty graphics protocol record.

class libvt.KittyGraphic
class libvt.KittyGraphic

Bases: object

Emitted when an APC G Kitty graphics sequence completes.

class libvt.KittyKeyboardFlags
class libvt.KittyKeyboardFlags

Bases: IntFlag

Progressive-enhancement flags for the Kitty Keyboard Protocol (CSI u).

exception libvt.LibVtError
exception[source]
exception[source]
exception libvt.LibVtError

Bases: Exception

Base exception for all libvt errors.

class libvt.Limits
class libvt.Limits

Bases: object

Resource ceilings protecting memory and CPU against hostile byte streams.

class libvt.Mode
class libvt.Mode

Bases: IntEnum

ANSI standard modes and DEC private modes (0x8000 | code).

class libvt.ModeState
class libvt.ModeState

Bases: object

Mutable set of active ANSI and DEC private modes.

class libvt.MouseAction
class libvt.MouseAction

Bases: StrEnum

Mouse pointer action.

class libvt.MouseButton
class libvt.MouseButton

Bases: IntEnum

Mouse buttons and scroll wheel directions.

class libvt.MouseEvent
class libvt.MouseEvent

Bases: object

Zero-based (row, col) mouse event for outbound SGR / X10 encoding.

class libvt.OutputFormat
class libvt.OutputFormat

Bases: StrEnum

Export target formats supported by Formatter.

class libvt.Parser
class libvt.Parser

Bases: object

Streaming VT500 / ANSI escape-sequence byte parser.

class libvt.ParserState
class libvt.ParserState

Bases: IntEnum

States of the DEC ANSI / VT500 byte state machine.

class libvt.Passthrough
class libvt.Passthrough

Bases: object

Emitted when a DCS tmux; ESC ESC ... ST passthrough envelope arrives.

class libvt.PasteEvent
class libvt.PasteEvent

Bases: object

Clipboard paste payload encoded with ?2004 bracketing and safety checks.

class libvt.Policy
class libvt.Policy

Bases: object

Default-deny host security and strictness policy.

class libvt.Profile
class libvt.Profile

Bases: object

Terminal identity responses and compatibility switches.

class libvt.ProgramStatus
class libvt.ProgramStatus

Bases: object

Validated OSC 7501 (or OSC 9;4 fallback) task status record.

class libvt.ProgramStatusChanged
class libvt.ProgramStatusChanged

Bases: object

Emitted when OSC 7501 or OSC 9;4 mutates task status.

class libvt.ProgramStatusStore
class libvt.ProgramStatusStore

Bases: object

Bounded store managing hierarchical OSC 7501 and OSC 9;4 status.

class libvt.PromptKind
class libvt.PromptKind

Bases: StrEnum

OSC 133 FinalTerm / semantic-shell prompt zone markers.

class libvt.PromptMark
class libvt.PromptMark

Bases: object

Emitted when OSC 133 records a semantic prompt zone.

class libvt.PromptZone
class libvt.PromptZone

Bases: object

Semantic shell prompt boundary emitted via OSC 133.

exception libvt.ProtocolError
exception[source]
exception[source]
exception libvt.ProtocolError

Bases: LibVtError

Raised when Policy.strict rejects a malformed or unsupported sequence.

class libvt.Rect
class libvt.Rect

Bases: object

Zero-based rectangular cell region.

class libvt.RegionView
class libvt.RegionView

Bases: Sequence[RowView]

Read-only 2D rectangular slice view over (rows, cols).

class libvt.RenderHoldChanged
class libvt.RenderHoldChanged

Bases: object

Emitted when DEC mode ?2026 synchronized output starts or ends.

class libvt.ResyncReason
class libvt.ResyncReason

Bases: StrEnum

Reason Terminal.changes_since() emitted a full resynchronization.

class libvt.RgbColor
class libvt.RgbColor

Bases: object

24-bit direct RGB color (SGR 38;2;r;g;b / SGR 38:2::r:g:b).

class libvt.RowRun
class libvt.RowRun

Bases: object

Contiguous run of identically styled cells within a RowView.

class libvt.RowView
class libvt.RowView

Bases: Sequence[Cell]

Read-only sequence view over one live viewport or scrollback row.

class libvt.Screen
class libvt.Screen

Bases: object

Mutable 2D character grid with FrozenRow RLE scrollback and reflow.

exception libvt.ScreenAssertionError
exception[source]
exception[source]
exception libvt.ScreenAssertionError

Bases: LibVtError, AssertionError

Raised when assert_screen() detects a screen mismatch.

class libvt.ScreenDelta
class libvt.ScreenDelta

Bases: object

Multi-consumer incremental screen update from Terminal.changes_since().

class libvt.ScreenErased
class libvt.ScreenErased

Bases: object

Emitted when cells clear or scroll on the active screen.

class libvt.ScreenSet
class libvt.ScreenSet

Bases: object

Dual primary and alternate (?1049) screen pair.

class libvt.ScrollRegion
class libvt.ScrollRegion

Bases: object

Inclusive zero-based scroll margin bounds (DECSTBM / DECSLRM).

class libvt.SixelData
class libvt.SixelData

Bases: object

Zero-dependency DCS ... q SIXEL payload record.

class libvt.SixelGraphic
class libvt.SixelGraphic

Bases: object

Emitted when a DCS ... q SIXEL graphic sequence completes.

class libvt.Snapshot
class libvt.Snapshot

Bases: object

Immutable point-in-time capture of terminal screen, history, and metadata.

class libvt.StatusState
class libvt.StatusState

Bases: StrEnum

Foreground task lifecycle states defined by OSC 7501.

class libvt.StepResult
class libvt.StepResult

Bases: object

Return value from Terminal.feed_until().

class libvt.StopOn
class libvt.StopOn

Bases: IntFlag

Boundary conditions for Terminal.feed_until().

class libvt.Style
class libvt.Style

Bases: object

Immutable SGR graphic rendition attributes for a cell or active pen.

class libvt.SyncToken
class libvt.SyncToken

Bases: object

Opaque monotonic watermark passed to Terminal.changes_since().

class libvt.Terminal
class libvt.Terminal

Bases: object

Sans-I/O virtual terminal emulator over a streaming VT500 parser.

exception libvt.TerminalTimeoutError
exception[source]
exception[source]
exception libvt.TerminalTimeoutError

Bases: LibVtError, TimeoutError

Raised when an async terminal stream or PTY wait exceeds its deadline.

Parameters:
  • message (str | None) – Concise single-line error summary; omitted when None.

  • parser_state (ParserState | None) – Parser state at timeout or premature EOF.

  • screen_text (str) – Visible screen text at failure time.

  • recent_bytes (collections.abc.Buffer) – Trailing raw bytes from FlightRecorder.

  • eof (bool) – True when the stream closed before the predicate matched.

  • diagnostics (str) – Pre-rendered viewport box and flight-recorder diagnostic block.

  • attach_note (bool) – When True (default), attach formatted diagnostics via PEP 678 BaseException.add_note() while keeping str(exc) single-line.

class libvt.TitleChanged
class libvt.TitleChanged

Bases: object

Emitted when OSC 0 or OSC 2 updates the window title.

class libvt.TmuxCaptureResult
class libvt.TmuxCaptureResult

Bases: object

Decoded tmux capture bundle ready for inspection or live streaming.

class libvt.TmuxLineFlags
class libvt.TmuxLineFlags

Bases: IntFlag

Per-line flags emitted by tmux capture-pane -F (tmux >= 3.8).

class libvt.TmuxPaneMetadata
class libvt.TmuxPaneMetadata

Bases: object

Out-of-band tmux pane state queried via TMUX_METADATA_FORMAT.

class libvt.UnderlineStyle
class libvt.UnderlineStyle

Bases: IntEnum

ITU T.416 / Kitty extended underline styles (SGR 4:x).

class libvt.UnhandledSequence
class libvt.UnhandledSequence

Bases: object

Recorded when an unrecognized control sequence arrives and strict=False.

exception libvt.UnsafePasteError
exception[source]
exception[source]
exception libvt.UnsafePasteError

Bases: LibVtError

Raised when pasted text contains control or bracket-escape bytes.

class libvt.WidthRole
class libvt.WidthRole

Bases: IntEnum

Column occupancy role of a terminal grid cell.

class libvt.WindowRenamed
class libvt.WindowRenamed

Bases: object

Emitted when ESC k <name> ESC \ updates the tmux window name.

class libvt.WorkingDirectoryChanged
class libvt.WorkingDirectoryChanged

Bases: object

Emitted when OSC 7 or OSC 9;9 updates the working directory.

class libvt.ZLayer
class libvt.ZLayer

Bases: StrEnum

Kitty graphics z-ordering plane relative to cell background and text.

libvt.decode_tmux_capture(captured, *, metadata=None, rows=24, cols=80, scrollback=None, flagged=False, joined_capture=None, saved_primary_capture=None, saved_primary_flagged=None, post_metadata=None, profile=TMUX_PROFILE, policy=TMUX_CAPTURE_POLICY, limits=DEFAULT_LIMITS)
function[source]
function[source]
libvt.decode_tmux_capture(captured, *, metadata=None, rows=24, cols=80, scrollback=None, flagged=False, joined_capture=None, saved_primary_capture=None, saved_primary_flagged=None, post_metadata=None, profile=TMUX_PROFILE, policy=TMUX_CAPTURE_POLICY, limits=DEFAULT_LIMITS)

Reconstruct a Terminal from tmux capture-pane.

Handles bare SO/SI (0x0e/0x0f) ACS box-drawing runs without polluting the reconstructed terminal’s live G1 charset, expands GRID_FLAG_TAB \t cells against #{pane_tabs} while preserving active SGR background/attributes, carries SGR across rows just like tmux’s grid_string_cells(&gc), reconstructs pending_wrap from cursor_x >= pane_width, and optionally populates backgrounded primary history when alternate_on is active.

Parameters:
  • captured (CaptureInput) – Output of tmux capture-pane -S - -E - -e -p -N [-F] as str, bytes, or a line sequence (e.g. libtmux Pane.capture_pane).

  • metadata (TmuxPaneMetadata | str | None) – Parsed TmuxPaneMetadata or raw format line emitted by display-message -p TMUX_METADATA_FORMAT; when None, rows, cols, and scrollback defaults are used.

  • rows (int) – Fallback pane height when metadata is None.

  • cols (int) – Fallback pane width when metadata is None.

  • scrollback (int | None) – Explicit scrollback line cap; when None, defaults to metadata.history_limit if metadata is provided, else 2000.

  • flagged (bool) – True when captured includes capture-pane -F line prefixes.

  • joined_capture (CaptureInput | None) – Optional capture-pane -S - -E - -e -p -J output used to infer soft wraps on tmux < 3.8 when flagged=False.

  • saved_primary_capture (CaptureInput | None) – Optional capture-pane -a -q -S - -E - -e -p -N [-F] output restoring the backgrounded primary screen and scrollback when alternate_on is True.

  • saved_primary_flagged (bool | None) – Whether saved_primary_capture carries -F prefixes (defaults to flagged).

  • post_metadata (TmuxPaneMetadata | str | None) – Optional second metadata sample taken immediately after capture-pane to verify pane_output_generation stability.

  • profile (Profile) – Compatibility profile for the reconstructed terminal.

  • policy (Policy) – Security policy for the reconstructed terminal.

  • limits (Limits) – Resource ceilings for the reconstructed terminal.

Returns:

Reconstructed terminal, immutable snapshot, completeness report, and parsed per-line flags.

Return type:

TmuxCaptureResult

libvt.display_width(text, *, mode_2027=True, profile=None)
function[source]
function[source]
libvt.display_width(text, *, mode_2027=True, profile=None)

Return rendered terminal column width of text.

Parameters:
Return type:

int

libvt.encode_input(event, *, modes, kitty_flags=KittyKeyboardFlags.NONE)
function[source]
function[source]
libvt.encode_input(event, *, modes, kitty_flags=KittyKeyboardFlags.NONE)

Encode event into outbound PTY bytes respecting active terminal modes.

Parameters:
Return type:

bytes

libvt.encode_paste(text, *, bracketed, sanitize=False, allow_unbracketed_newlines=False)
function[source]
function[source]
libvt.encode_paste(text, *, bracketed, sanitize=False, allow_unbracketed_newlines=False)

Encode text for pasting, failing closed on escape/control injection.

Parameters:
  • text (str)

  • bracketed (bool)

  • sanitize (bool)

  • allow_unbracketed_newlines (bool)

Return type:

bytes

libvt.explain(data)
function[source]
function[source]
libvt.explain(data)

Disassemble data into sanitized ExplainedSpan records.

Parameters:

data (Buffer | str)

Return type:

tuple[ExplainedSpan, ...]

libvt.format_explain(data)
function[source]
function[source]
libvt.format_explain(data)

Format explain() spans as aligned one-line records.

Parameters:

data (Buffer | str)

Return type:

str

libvt.is_safe_paste(text, *, bracketed=True)
function[source]
function[source]
libvt.is_safe_paste(text, *, bracketed=True)

Return True when text contains no escape or injection control bytes.

Parameters:
Return type:

bool

libvt.parse_flagged_line(line)
function[source]
function[source]
libvt.parse_flagged_line(line)

Split a tmux capture-pane -F line into (flags, body).

Parameters:

line (str) – Single line emitted by tmux capture-pane -F (without trailing \n).

Returns:

Parsed TmuxLineFlags and remaining SGR/text payload.

Return type:

tuple[TmuxLineFlags, str]

Raises:

ValueError – If line does not start with a valid <flags> space-delimited prefix.

libvt.parse_sgr(params, current=DEFAULT_STYLE, *, memo=None)
function[source]
function[source]
libvt.parse_sgr(params, current=DEFAULT_STYLE, *, memo=None)

Apply CSI ... m parameters to current and return a new Style.

Parameters:
Return type:

Style

libvt.render(data, /, *, rows=24, cols=80, profile=DEFAULT_PROFILE, newline_mode=False)
function[source]
function[source]
libvt.render(data, /, *, rows=24, cols=80, profile=DEFAULT_PROFILE, newline_mode=False)

Emulate data on a fresh (rows, cols) terminal and return text.

Parameters:
Return type:

str

libvt.sanitize_terminal_text(text)
function[source]
function[source]
libvt.sanitize_terminal_text(text)

Escape C0, C1, DEL, and BiDi override codepoints for safe display.

Parameters:

text (str)

Return type:

str

libvt.strip(data, /)
function[source]
function[source]
libvt.strip(data, /)

Strip VT escape, CSI, OSC, DCS, and APC sequences, keeping plain text.

Parameters:

data (Buffer | str)

Return type:

str

libvt.unescape_tmux_control_output(data)
function[source]
function[source]
libvt.unescape_tmux_control_output(data)

Decode tmux -CC %output octal escapes into raw PTY bytes.

tmux control mode escapes bytes < 0x20 and backslash (0x5c -> \134) as three-digit octal sequences \ooo while passing printable ASCII and UTF-8 bytes verbatim (including split multi-byte UTF-8 sequences).

Parameters:

data (collections.abc.Buffer | str) – Escaped payload following %output %<pane_id>.

Returns:

Unescaped raw VT byte stream ready for feed().

Return type:

bytes