libvt¶
Headless terminal emulator and VT parser for Python.
-
class libvt.Appearanceclass[source]class[source]class libvt.Appearance
Bases:
objectImmutable terminal theme, dynamic colors, and palette overrides.
-
attributeattribute
Active color-scheme preference (
DARKorLIGHT).
Effective default foreground 8-bit
(r, g, b)color.
Effective default background 8-bit
(r, g, b)color.
Effective cursor 8-bit
(r, g, b)color.
Sorted
(index, (r, g, b))overrides diverging from the base 256-color xterm palette.
-
attributeattribute
Truewhen DEC mode?5(DECSCNM) inverts screen foreground and background colors.
References
ghostty-org/ghostty src/terminal/osc/parsers/color.zig (v1.4.0)
ghostty-org/ghostty src/terminal/modes.zig — DECSCNM ?5 (v1.4.0)
Examples
>>> from libvt.config import ColorScheme >>> from libvt.style import Appearance >>> app = Appearance(scheme=ColorScheme.LIGHT, bg_rgb=(255, 255, 255)) >>> (app.scheme, app.bg_rgb) (<ColorScheme.LIGHT: 2>, (255, 255, 255))
-
__init__(*, scheme=
ColorScheme.DARK, fg_rgb=(229, 229, 229), bg_rgb=(30, 30, 30), cursor_rgb=(229, 229, 229), palette_overrides=(), reverse_video=False)method[source]method[source]__init__(*, scheme=ColorScheme.DARK, fg_rgb=(229, 229, 229), bg_rgb=(30, 30, 30), cursor_rgb=(229, 229, 229), palette_overrides=(), reverse_video=False)
-
resolve_rgb(color, *, default_rgb)method[source]method[source]resolve_rgb(color, *, default_rgb)
Resolve color to 8-bit
(r, g, b)usingpalette_overrides.References
Examples
>>> from libvt.style import AnsiColor, Appearance >>> app = Appearance(palette_overrides=((1, (220, 40, 40)),)) >>> app.resolve_rgb(AnsiColor.RED, default_rgb=(255, 255, 255)) (220, 40, 40) >>> app.resolve_rgb(None, default_rgb=(10, 20, 30)) (10, 20, 30)
-
-
class libvt.Cellclass[source]class[source]class libvt.Cell
Bases:
objectImmutable view of a single terminal grid cell.
-
attributeattribute
Grapheme cluster string (
" "for narrow blanks,""forWidthRole.SPACER_TAILandWidthRole.SPACER_HEAD).
-
width_role: WidthRoleattributeattributewidth_role: WidthRole
Column occupancy role (narrow, wide lead, or spacer).
Active
OSC 8hyperlink, when present.
-
attributeattribute
DECSCAprotection attribute respected byDECSED/DECSEL.
Examples
>>> term = Terminal(rows=1, cols=8) >>> term.feed("\x1b[1;32m日\x1b[0mok".encode()) >>> snap = term.committed >>> snap[0, 0].text, snap[0, 0].width, snap[0, 0].style.bold ('日', 2, True) >>> snap[0, 1].width_role.name, snap[0, 1].width ('SPACER_TAIL', 0)
-
__init__(text=' ', style=Style(fg=None, bg=None, underline_color=None, bold=False, dim=False, italic=False, underline=<UnderlineStyle.NONE: 0>, blink=False, reverse=False, hidden=False, strikethrough=False, overline=False), width_role=WidthRole.NARROW, hyperlink=None, protected=False)method[source]method[source]__init__(text=' ', style=Style(fg=None, bg=None, underline_color=None, bold=False, dim=False, italic=False, underline=<UnderlineStyle.NONE: 0>, blink=False, reverse=False, hidden=False, strikethrough=False, overline=False), width_role=WidthRole.NARROW, hyperlink=None, protected=False)
-
propertyproperty
Return
Truewhen the cell holds an unstyled narrow space.
-
-
class libvt.Eventclass[source]class[source]class libvt.Event
Bases:
objectOpen nominal base class for structured terminal events.
Built-in and integration-defined event records inherit from
Eventwith keyword-only fields so new attributes can be added with defaults without breaking callers ormatchclass patterns. UseKnownEventwhen static exhaustiveness over built-in core events is desired.Examples
>>> from dataclasses import dataclass >>> from libvt.events import Bell, Event >>> isinstance(Bell(), Event) True >>> @dataclass(frozen=True, slots=True, kw_only=True, match_args=False) ... class CustomMuxEvent(Event): ... pane: str >>> issubclass(CustomMuxEvent, Event) True
-
exception libvt.LibVtErrorexception[source]exception[source]exception libvt.LibVtError
Bases:
ExceptionBase exception for all libvt errors.
-
class libvt.Limitsclass[source]class[source]class libvt.Limits
Bases:
objectResource ceilings protecting memory and CPU against hostile byte streams.
-
attributeattribute
Maximum Unicode codepoints stored in a single grid cell (default
32).
-
attributeattribute
Maximum parameter slots retained in a
CSIorDCSheader.
-
attributeattribute
Maximum payload bytes buffered for an
OSCsequence.
-
attributeattribute
Maximum payload bytes buffered for a
DCSsequence (default8_388_608, sized abovemax_apc_bytesso 4 MiB graphics wrapped inDCS tmux;fit without truncation).
-
attributeattribute
Maximum payload bytes buffered for an
APCsequence.
-
attributeattribute
Maximum unread bytes queued in
drain_replies().
-
attributeattribute
Maximum repeat count executed by
REP(CSI Ps b).
-
attributeattribute
Maximum
OSC 133prompt zones retained on a terminal.
-
attributeattribute
Maximum concurrent
OSC 7501task records retained in the store (default256).
-
attributeattribute
Maximum unread
Eventitems retained whenrecord_events=True.
-
attributeattribute
Maximum cumulative payload bytes retained across unread events when
record_events=True(default16_777_216).
-
attributeattribute
Maximum entries per screen in the Kitty
CSI ukeyboard stack.
-
attributeattribute
Maximum raw input bytes retained by
FlightRecorder.
-
attributeattribute
Maximum stored Kitty /
SIXELimage metadata entries per screen (default256).
-
attributeattribute
Maximum active + scrollback image placements retained per screen (default
1_024).
-
attributeattribute
Maximum pixel width or height accepted for
SIXELor Kitty images (default10_000).
-
attributeattribute
Maximum concurrent incomplete Kitty
OSC 99(d=0) chunked notifications retained (default16).
-
attributeattribute
Maximum cumulative UTF-8 text bytes retained per notification payload (default
16_384).
-
__init__(*, max_grapheme_codepoints=32, max_csi_params=32, max_osc_bytes=131072, max_dcs_bytes=8388608, max_apc_bytes=4194304, max_reply_bytes=65536, max_rep_count=4096, max_prompt_zones=1024, max_status_records=256, max_events=4096, max_event_bytes=16777216, max_keyboard_stack=8, max_recorder_bytes=4096, max_images=256, max_placements=1024, max_image_dimension=10000, max_pending_notifications=16, max_notification_bytes=16384)method[source]method[source]__init__(*, max_grapheme_codepoints=32, max_csi_params=32, max_osc_bytes=131072, max_dcs_bytes=8388608, max_apc_bytes=4194304, max_reply_bytes=65536, max_rep_count=4096, max_prompt_zones=1024, max_status_records=256, max_events=4096, max_event_bytes=16777216, max_keyboard_stack=8, max_recorder_bytes=4096, max_images=256, max_placements=1024, max_image_dimension=10000, max_pending_notifications=16, max_notification_bytes=16384)
- Parameters:
max_grapheme_codepoints (
int)max_csi_params (
int)max_osc_bytes (
int)max_dcs_bytes (
int)max_apc_bytes (
int)max_reply_bytes (
int)max_rep_count (
int)max_prompt_zones (
int)max_status_records (
int)max_events (
int)max_event_bytes (
int)max_keyboard_stack (
int)max_recorder_bytes (
int)max_images (
int)max_placements (
int)max_image_dimension (
int)max_pending_notifications (
int)max_notification_bytes (
int)
- Return type:
-
-
class libvt.Policyclass[source]class[source]class libvt.Policy
Bases:
objectDefault-deny host security and strictness policy.
-
attributeattribute
Emit automatic terminal query and notification response bytes into
drain_replies()oron_pty_write(defaultTrue; setFalsefor passive multiplexer/observer taps).
-
attributeattribute
Permit
CSI 21 twindow-title report replies (defaultFalse).
-
attributeattribute
Disposition for
OSC 52 ; <selection> ; ?clipboard read queries (IGNOREdrops silently by default;EMIT_EVENTemitsClipboardReadRequestedwithout fabricating reply bytes).
-
attributeattribute
Emit
ClipboardWriteevents onOSC 52writes (defaultTrue; no host clipboard is ever mutated bylibvt).
-
attributeattribute
Permit
OSC 4 ; c ; ?,OSC 10 ; ?throughOSC 12 ; ?, andCSI ? 996 npalette and color-scheme replies (defaultTrue).
-
attributeattribute
Permit
OSC 7501 ; ?capability replies wheneverprofile.identity.osc_7501_capabilitiesis non-empty (defaultTrue).
-
attributeattribute
Allow schemes outside
http://,https://, andmailto:in HTML<a href>output (defaultFalse).
-
attributeattribute
Replay unwrapped
DCS tmux; ESC ESC ... STinner byte streams through a persistent passthrough parser in addition to emittingPassthrough(defaultFalse, matchingtmux’sallow-passthrough off).
-
attributeattribute
When
True, dispatch an accumulatedOSCstring if interrupted by a non-\ESCbyte (matchingtmux/Ghosttystate-exit behavior). Defaults toFalse(DEC STD 070 abort-and-drop).
Lowercase hostnames in
OSC 7file://<host>/...URIs permitted to updatecwd.None(default) uses{"", "localhost"}onTerminaland automatically adds the local hostname inopen_pty().
-
attributeattribute
Raise
ProtocolErroron unrecognized or overflowing escape sequences instead of ignoring or recordingUnhandledSequence(defaultFalse).
-
attributeattribute
Track
SIXELand KittyAPC Gimage metadata and grid placements (defaultTrue).
-
attributeattribute
Emit
Notificationevents onOSC 9, KittyOSC 99, andOSC 777;notifysequences (defaultTrue).
-
attributeattribute
Answer Kitty
OSC 99p=?capability queries whenemit_repliesandallow_notificationsareTrue(defaultFalse).
-
__init__(*, emit_replies=True, allow_title_report=False, clipboard_read=
ClipboardReadPolicy.IGNORE, allow_clipboard_write=True, allow_color_queries=True, allow_program_status_query=True, allow_unsafe_uris=False, allow_passthrough=False, abort_dispatch_osc=False, osc7_hosts=None, strict=False, track_graphics=True, allow_notifications=True, allow_notification_queries=False)method[source]method[source]__init__(*, emit_replies=True, allow_title_report=False, clipboard_read=ClipboardReadPolicy.IGNORE, allow_clipboard_write=True, allow_color_queries=True, allow_program_status_query=True, allow_unsafe_uris=False, allow_passthrough=False, abort_dispatch_osc=False, osc7_hosts=None, strict=False, track_graphics=True, allow_notifications=True, allow_notification_queries=False) - Parameters:
emit_replies (
bool)allow_title_report (
bool)clipboard_read (
ClipboardReadPolicy)allow_clipboard_write (
bool)allow_color_queries (
bool)allow_program_status_query (
bool)allow_unsafe_uris (
bool)allow_passthrough (
bool)abort_dispatch_osc (
bool)strict (
bool)track_graphics (
bool)allow_notifications (
bool)allow_notification_queries (
bool)
- Return type:
-
-
class libvt.Profileclass[source]class[source]class libvt.Profile
Bases:
objectPeer-neutral terminal capability profile composed of domain groups.
-
attributeattribute
Device attributes,
XTVERSIONbanner, andOSC 7501capabilities.
-
attributeattribute
Status-request switches and default RGB / color-scheme values.
-
attributeattribute
Grid wrapping, margin, reset,
ESC krename, and pixel geometry rules.
-
attributeattribute
Keyboard protocol state switches (Kitty
CSI uandXTMODKEYS).
-
attributeattribute
East Asian Ambiguous cell width and variation-selector rules.
References
Examples
>>> from libvt.config import Profile, ScreenBehavior >>> prof = Profile(screen=ScreenBehavior(cell_width_px=10, cell_height_px=20)) >>> (prof.screen.cell_width_px, prof.screen.cell_height_px) (10, 20)
-
__init__(*, identity=Identity(name='libvt', da1=b'\x1b[?62;22c', da2=b'\x1b[>1;10;0c', xtversion='libvt 0.1', osc_7501_capabilities='?:states=idle, working, done, blocked, error:kinds=permission, question, auth'), queries=QueryBehavior(decrqss_enabled=True, xtgettcap_enabled=True, kitty_keyboard_query_enabled=True, color_scheme=<ColorScheme.DARK: 1>, fg_rgb=(229, 229, 229), bg_rgb=(30, 30, 30), cursor_rgb=(229, 229, 229), xtsmgraphics_enabled=True, xtsmgraphics_geometry_enabled=True, xtsmgraphics_set_enabled=True, sixel_color_registers=256, max_sixel_color_registers=1024), screen=ScreenBehavior(pending_wrap_phantom_col=False, cbt_preserves_pending_wrap=False, reflow_on_resize=True, ed3_clears_scrollback_on_alt=False, ed2_scrolls_primary_to_history=False, erase_severs_history_wrap=True, top_margin_scrolls_to_history=False, hpr_vpr_enabled=True, il_dl_resets_col=True, rep_wraps=True, rep_uses_last_graphic=False, default_g1_charset='B', decstr_enabled=True, declrmm_enabled=True, xtsave_enabled=True, separate_alt_save_cursor=False, alternate_entry_preserves_cursor=False, ris_alt_screen=<RisAltScreenBehavior.EXIT_TO_PRIMARY: 'exit_to_primary'>, allow_esc_k_title=False, cell_width_px=8, cell_height_px=16, sixel_erase_policy='cell_mask', deccolm=<DeccolmBehavior.GATED_BY_MODE_40: 'gated_by_mode_40'>, allow_encoding_switch=False), input=InputBehavior(kitty_keyboard_enabled=True, modify_other_keys_enabled=True, reset_any_mouse_encoding=False), unicode=UnicodeBehavior(ambiguous_width=1, vs15_narrows_wide_emoji=True, vs16_always_wide=False))method[source]method[source]__init__(*, identity=Identity(name='libvt', da1=b'\x1b[?62;22c', da2=b'\x1b[>1;10;0c', xtversion='libvt 0.1', osc_7501_capabilities='?:states=idle, working, done, blocked, error:kinds=permission, question, auth'), queries=QueryBehavior(decrqss_enabled=True, xtgettcap_enabled=True, kitty_keyboard_query_enabled=True, color_scheme=<ColorScheme.DARK: 1>, fg_rgb=(229, 229, 229), bg_rgb=(30, 30, 30), cursor_rgb=(229, 229, 229), xtsmgraphics_enabled=True, xtsmgraphics_geometry_enabled=True, xtsmgraphics_set_enabled=True, sixel_color_registers=256, max_sixel_color_registers=1024), screen=ScreenBehavior(pending_wrap_phantom_col=False, cbt_preserves_pending_wrap=False, reflow_on_resize=True, ed3_clears_scrollback_on_alt=False, ed2_scrolls_primary_to_history=False, erase_severs_history_wrap=True, top_margin_scrolls_to_history=False, hpr_vpr_enabled=True, il_dl_resets_col=True, rep_wraps=True, rep_uses_last_graphic=False, default_g1_charset='B', decstr_enabled=True, declrmm_enabled=True, xtsave_enabled=True, separate_alt_save_cursor=False, alternate_entry_preserves_cursor=False, ris_alt_screen=<RisAltScreenBehavior.EXIT_TO_PRIMARY: 'exit_to_primary'>, allow_esc_k_title=False, cell_width_px=8, cell_height_px=16, sixel_erase_policy='cell_mask', deccolm=<DeccolmBehavior.GATED_BY_MODE_40: 'gated_by_mode_40'>, allow_encoding_switch=False), input=InputBehavior(kitty_keyboard_enabled=True, modify_other_keys_enabled=True, reset_any_mouse_encoding=False), unicode=UnicodeBehavior(ambiguous_width=1, vs15_narrows_wide_emoji=True, vs16_always_wide=False))
- Parameters:
identity (
Identity)queries (
QueryBehavior)screen (
ScreenBehavior)input (
InputBehavior)unicode (
UnicodeBehavior)
- Return type:
-
-
exception libvt.ProtocolErrorexception[source]exception[source]exception libvt.ProtocolError
Bases:
LibVtErrorRaised when
Policy.strictrejects a malformed or unsupported sequence.
-
class libvt.Screenclass[source]class[source]class libvt.Screen
Bases:
objectMutable 2D character grid with
FrozenRowRLE scrollback and reflow.Examples
>>> term = Terminal(rows=2, cols=10) >>> term.feed(b"line 1\r\nline 2\r\nline 3") >>> term.screen.lines, [r.text for r in term.screen.history] (('line 2', 'line 3'), ['line 1'])
-
keyboard_stackattributeattributekeyboard_stack
-
scroll_regionattributeattributescroll_region
-
__init__(*, rows=24, cols=80, scrollback=2000, keyboard_stack_depth=8, cell_height_px=16, max_images=256, max_placements=1024, max_image_dimension=10000, is_alt=False, top_margin_scrolls_to_history=False, profile=
DEFAULT_PROFILE, on_mutate=None)method[source]method[source]__init__(*, rows=24, cols=80, scrollback=2000, keyboard_stack_depth=8, cell_height_px=16, max_images=256, max_placements=1024, max_image_dimension=10000, is_alt=False, top_margin_scrolls_to_history=False, profile=DEFAULT_PROFILE, on_mutate=None)
-
blit(source, *, top=0, left=0, src_top=0, src_left=0, rows=None, cols=None, preserve_wrap=False)method[source]method[source]blit(source, *, top=0, left=0, src_top=0, src_left=0, rows=None, cols=None, preserve_wrap=False)
Copy a rectangular 2D cell region from source onto this screen.
Copies packed 64-bit SGR attributes, grapheme strings,
WidthRole,OSC 8hyperlinks, andDECSCAprotection without re-encoding ANSI sequences. Out-of-bounds source or destination coordinates clip cleanly, split wide glyphs heal to narrow blanks at clip boundaries, and sourceSPACER_HEADsoft-wrap markers convert to narrow blanks. Rows overwritten up tocolsclearwrappedunless preserve_wrap isTrueon a full-width copy.- Parameters:
source (
Snapshot|Screen|RegionView) – Source grid surface to copy cells from.top (
int, default 0) – Destination zero-based top row offset (negative values clip).left (
int, default 0) – Destination zero-based left column offset (negative values clip).src_top (
int, default 0) – Source zero-based starting row offset.src_left (
int, default 0) – Source zero-based starting column offset.rows (
int|None,optional) – Maximum row count to copy;Nonecopiessource.rows - src_top.cols (
int|None,optional) – Maximum column count to copy;Nonecopiessource.cols - src_left.preserve_wrap (
bool, default False) – Preserve sourcewrappedflags when blitting full-width rows (dst_col == 0andwidth == self.cols == source_row.cols).
- Return type:
Examples
>>> from libvt.screen import Screen >>> from libvt.terminal import Terminal >>> pane = Terminal(rows=2, cols=6) >>> pane.feed("日本!\r\nok".encode()) >>> canvas = Screen(rows=3, cols=10) >>> canvas.blit(pane.committed, top=1, left=2) >>> canvas.lines ('', ' 日本!', ' ok')
Return space-padded text of width
colsfor every visible row.
Return
O(1)immutableRowViewsequence over scrollback.
Return stored
SIXEL/ KittyImageMetarecords.
-
propertyproperty
Return
Truewhen this screen is an alternate screen buffer.
Return right-trimmed text for every visible row.
-
propertyproperty
Return
XTMODKEYSmodifyOtherKeyslevel (0,1, or2).
-
propertyproperty
Return active + scrollback
ImagePlacementrecords.
-
propertyproperty
Return
Profilegoverning width and grid behavior.
-
put_text(row, col, text, *, style=DEFAULT_STYLE, hyperlink=None, protected=False, max_cols=None, profile=None)method[source]method[source]put_text(row, col, text, *, style=DEFAULT_STYLE, hyperlink=None, protected=False, max_cols=None, profile=None)
Write display-width-aware text onto row starting at col.
Places narrow, wide, and combining grapheme clusters on a single row without moving
cursoror settingwrapped, clipping negative col offsets and healing split wide cells at start and end boundaries.- Parameters:
row (
int) – Zero-based destination row index (out-of-range values return0).col (
int) – Zero-based starting column index (negative values left-clip).text (
str) – Text to draw; control characters are skipped and wide clusters stop before overflowingmax_colsorcols.style (
Style, default DEFAULT_STYLE) – Cell SGR rendition applied to written clusters.hyperlink (
Hyperlink|None,optional) –OSC 8hyperlink attached to written cells.protected (
bool, default False) –DECSCAcharacter-protection flag respected byDECSEDandDECSEL.max_cols (
int|None,optional) – Maximum display columns to examine from col;Nonewrites up tocols - col.profile (
Profile|None,optional) – Compatibility profile used for grapheme display width; defaults to this screen’s profile.
- Returns:
Number of visible destination columns written on
0..cols.- Return type:
Examples
>>> from libvt.screen import Screen >>> from libvt.style import AnsiColor, Style >>> scr = Screen(rows=1, cols=8) >>> scr.put_text(0, 1, "日本ok", style=Style(fg=AnsiColor.GREEN), max_cols=5) 5 >>> scr.lines, scr[0, 1].style.fg ((' 日本o',), <AnsiColor.GREEN: 2>)
-
scroll_up(count=1, *, top=None, bottom=None, left=0, right=None, save_history=True, bce_word=0, is_line_op=False)method[source]method[source]scroll_up(count=1, *, top=None, bottom=None, left=0, right=None, save_history=True, bce_word=0, is_line_op=False)
Scroll region
[top..bottom, left..right]upward by count lines.
-
propertyproperty
Return cumulative primary rows scrolled off the top margin.
-
snapshot(*, cursor=None, title='', cwd='', cwd_uri='', modes=frozenset(), active_is_alt=False, appearance=None, program_status=None, program_statuses=None, generation=None, profile=None)method[source]method[source]snapshot(*, cursor=None, title='', cwd='', cwd_uri='', modes=frozenset(), active_is_alt=False, appearance=None, program_status=None, program_statuses=None, generation=None, profile=None)
Freeze this screen into an immutable
Snapshot.Clones visible viewport rows and CoW scrollback blocks so subsequent edits on this
Screennever mutate the returned snapshot.- Parameters:
cursor (
Cursor|None,optional) – Explicit cursor state for the snapshot; defaults tocursor.title (
str, default “”) – Window title metadata stored on the snapshot.cwd (
str, default “”) – Working directory path stored on the snapshot.cwd_uri (
str, default “”) – RawOSC 7/OSC 9;9working directory URI.modes (
frozenset[Mode],optional) – Enabled ANSI and DEC private modes stored on the snapshot.active_is_alt (
bool, default False) – Whether the snapshot marks the alternate screen active (omitting primary scrollback whenTrue).appearance (
Appearance|None,optional) – Theme scheme, default RGBs, palette overrides, and reverse-video state; inferred from modes whenNone.program_status (
ProgramStatus|None,optional) – Highest-urgencyOSC 7501/OSC 9;4status record.program_statuses (
Mapping[str,ProgramStatus] |None,optional) – ActiveOSC 7501task records keyed byid.generation (
int|None,optional) – Explicit generation watermark; defaults to the row mutation counter.profile (
Profile|None,optional) – Terminal compatibility profile stored on the snapshot; defaults to this screen’s profile.
- Returns:
Point-in-time immutable screen capture.
- Return type:
Examples
>>> from libvt.screen import Cursor, Screen >>> scr = Screen(rows=2, cols=8) >>> _ = scr.put_text(0, 0, "ready") >>> snap = scr.snapshot(cursor=Cursor(row=0, col=5)) >>> _ = scr.put_text(0, 0, "later") >>> snap.lines, (snap.cursor.row, snap.cursor.col) (('ready', ''), (0, 5))
Return sorted horizontal tabstop columns.
-
propertyproperty
Return visible screen text with trailing blank rows omitted.
-
propertyproperty
Return visible screen text with soft-wrapped rows joined.
Contiguous
row.wrappedrows join without"\n"while hard linebreaks stay"\n"and trailing blank rows are omitted.Examples
>>> term = Terminal(rows=3, cols=8) >>> term.feed(b"hello world\r\nok") >>> term.screen.unwrapped_text 'hello world\nok'
-
-
class libvt.Snapshotclass[source]class[source]class libvt.Snapshot
Bases:
objectImmutable point-in-time capture of terminal screen, history, and metadata.
Obtain instances via
committed(tear-free across?2026synchronized frames) orsnapshot()(immediate working buffer). Once captured, aSnapshotnever mutates when later bytes arrive on theTerminaland can be shared across threads without locking.Index
snap[row]for aRowView,snap[row, col]for an immutableCell, orsnap[r0:r1, c0:c1]for a rectangularRegionView. Render a visual grid box withformat_screen_box()or include header metadata andSGRspans withserialize_vt_snapshot().-
attributeattribute
Zero-based cursor position, shape, visibility, and
pending_wrap.
-
attributeattribute
Truewhen the alternate screen buffer is active.
-
attributeattribute
Recorded primary-screen
OSC 133semantic prompt zones (empty whenactive_is_altisTrue).
-
attributeattribute
Highest-urgency active
OSC 7501/OSC 9;4status record.
-
attributeattribute
Read-only mapping of active
OSC 7501task records keyed byid.
-
attributeattribute
Terminal mutation generation when this snapshot was captured.
-
attributeattribute
Committed theme scheme, default RGBs, palette overrides, and
?5reverse-video state.
-
attributeattribute
Read-only mapping of stored
SIXEL/ KittyImageMetaitems.
-
attributeattribute
Immutable active + scrollback
ImagePlacementrecords.
Examples
>>> from libvt.terminal import Terminal >>> from libvt.testing import serialize_vt_snapshot >>> term = Terminal(rows=2, cols=14) >>> term.feed(b"\x1b[1;32mREADY\x1b[0m api\r\n\x1b[7m> worker\x1b[0m") >>> snap = term.committed >>> print(serialize_vt_snapshot(snap)) size=14x2 cursor=(1,8,vis=True) alt=False modes=[] ┌──────────────┐ │READY api │ │> worker │ └──────────────┘ styles: r0[0..5]: bold fg=green r1[0..8]: reverse >>> snap[0, 0].text, snap[0, 0].style.bold, snap[1, 0].style.reverse ('R', True, True)
-
at_abs(abs_row)method[source]method[source]at_abs(abs_row)
Return
RowViewat abs_row in history or viewport.- Parameters:
abs_row (
int) – Monotonic absolute row coordinate.- Returns:
Immutable view of the row from scrollback or the active viewport.
- Return type:
- Raises:
IndexError– When abs_row has been evicted from history or is out of range.
Examples
>>> term = Terminal(rows=2, cols=8) >>> term.feed(b"hist\r\nvis1\r\nvis2") >>> snap = term.committed >>> snap.at_abs(0).text, snap.at_abs(2).text ('hist', 'vis2')
-
propertyproperty
Return snapshot width in columns.
Examples
>>> Terminal(rows=3, cols=10).committed.cols 10
Return space-padded text of width
colsfor every visible row.Examples
>>> term = Terminal(rows=2, cols=6) >>> term.feed(b"ok") >>> term.committed.display_lines ('ok ', ' ')
-
propertyproperty
Return count of scrollback rows evicted from the active screen.
Examples
>>> term = Terminal(rows=1, cols=8, scrollback=1) >>> term.feed(b"a\r\nb\r\nc") >>> term.committed.evicted_total 1
-
find_cells(text, /)method[source]method[source]find_cells(text, /)
Find exact text matches by cell in the active viewport.
Return zero-based, half-open spans in row and column order, including overlaps. An empty tuple means no match. Search each row separately, including soft-wrapped rows. Matches span complete stored graphemes without normalization. Wide glyphs occupy two columns. Search skips wrap spacers and unwritten trailing padding. Explicit trailing spaces and blanks before later text can match.
Examples
>>> term = Terminal(rows=2, cols=16) >>> term.feed("界界界·Go Go".encode()) >>> snap = term.committed >>> snap.find_cells("Go") (CellSpan(row=0, start=7, stop=9), CellSpan(row=0, start=10, stop=12)) >>> hit = snap.find_cells("Go")[0] >>> snap[hit.row, hit.start:hit.stop].text 'Go'
-
method[source]method[source]
Render this snapshot using
Formatter.Replay
VTinto a freshTerminalof the same size and profile. The stream restores cell protection, scroll margins, and the active SGR, OSC 8, and DECSCA pen. Pending wrap is restored when the stream can redraw the captured edge glyph in place.- Parameters:
output_format (
OutputFormat, default OutputFormat.PLAIN) – Target export representation (PLAIN,VT, orHTML).policy (
Policy,optional) – URI and sequence policy applied when exporting hyperlinks or VT.profile (
Profile|None,optional) – Terminal profile governing export defaults; defaults to the profile captured on this snapshot.unwrap (
bool) – WhenTrue, join soft-wrapped continuation rows onto a single line inPLAINandHTMLoutput.
- Returns:
Formatted plain text, ANSI/DEC VT stream, or
<pre>HTML block.- Return type:
Examples
>>> from libvt.terminal import OutputFormat, Terminal >>> term = Terminal(rows=2, cols=8) >>> term.feed(b"\x1b[1;32mhello world\x1b[0m") >>> snap = term.committed >>> snap.format(OutputFormat.PLAIN, unwrap=True) 'hello world' >>> "<span" in snap.format(OutputFormat.HTML) True
Return
O(1)immutableRowViewsequence over scrollback rows.Examples
>>> term = Terminal(rows=1, cols=10) >>> term.feed(b"first\r\nsecond") >>> [row.text for row in term.committed.history] ['first']
Return visible row text with unwritten trailing blank cells omitted.
Examples
>>> term = Terminal(rows=2, cols=8) >>> term.feed(b"ok") >>> term.committed.lines ('ok', '')
-
propertyproperty
Return the profile captured with this frame.
-
propertyproperty
Return snapshot height in rows.
Examples
>>> Terminal(rows=3, cols=10).committed.rows 3
-
propertyproperty
Return monotonic count of rows scrolled off the active screen’s top.
Examples
>>> term = Terminal(rows=2, cols=8) >>> term.feed(b"a\r\nb\r\nc") >>> term.committed.scrolled_total 1
-
propertyproperty
Return visible snapshot text with trailing blank rows omitted.
Examples
>>> term = Terminal(rows=3, cols=8) >>> term.feed(b"top\r\nnext") >>> term.committed.text 'top\nnext'
-
to_dict()method[source]method[source]to_dict()
Serialize snapshot state into a deterministic JSON-compatible dict.
- Returns:
JSON-serializable dictionary of dimensions,
lines,history_lines,cursor,modes,appearance,program_status, andplacements.- Return type:
Examples
>>> term = Terminal(rows=2, cols=8) >>> term.feed(b"\x1b]2;ci\x07pass") >>> data = term.committed.to_dict() >>> data["title"], data["lines"], data["cursor"]["col"] ('ci', ['pass', ''], 4)
-
propertyproperty
Return visible snapshot text with soft-wrapped rows joined.
Contiguous
row.wrappedrows join without"\n"while hard linebreaks stay"\n"and trailing blank rows are omitted.Examples
>>> term = Terminal(rows=3, cols=8) >>> term.feed(b"hello world\r\nok") >>> term.committed.unwrapped_text 'hello world\nok'
-
viewport(offset=0)method[source]method[source]viewport(offset=0)
Return a
(rows, cols)RegionViewat offset.- Parameters:
offset (
int) – Zero-based upward scroll offset in terminal rows.0returns the captured active viewport; positive values scroll into retained primary history (clamped tolen(history)). Alternate-screen snapshots (active_is_altisTrue) always return their alternate viewport without blending primary scrollback.- Returns:
- Return type:
- Raises:
TypeError– If offset is not anint(or is abool).ValueError– If offset is negative.
Examples
>>> from libvt.testing import serialize_vt_snapshot >>> term = Terminal(rows=2, cols=10) >>> term.feed(b"line 1\r\nline 2\r\nline 3") >>> snap = term.committed >>> print(serialize_vt_snapshot(snap.viewport(offset=1))) size=10x2 region=True ┌──────────┐ │line 1 │ │line 2 │ └──────────┘
-
viewport_row(abs_row)method[source]method[source]viewport_row(abs_row)
Return zero-based viewport row for abs_row, or
None.Examples
>>> term = Terminal(rows=2, cols=8) >>> term.feed(b"r0\r\nr1\r\nr2") >>> snap = term.committed >>> snap.viewport_row(0), snap.viewport_row(1), snap.viewport_row(2) (None, 0, 1)
-
-
class libvt.Styleclass[source]class[source]class libvt.Style
Bases:
objectImmutable SGR graphic rendition attributes for a cell or active pen.
-
fg: Colorattributeattributefg: Color
Foreground color, or
Nonefor terminal default foreground.
-
bg: Colorattributeattributebg: Color
Background color, or
Nonefor terminal default background.
-
underline_color: Colorattributeattributeunderline_color: Color
Underline color (
SGR 58), orNoneto inherit foreground.
-
attributeattribute
Underline style (
SGR 4/SGR 4:x/SGR 21).
-
__init__(fg=None, bg=None, underline_color=None, bold=False, dim=False, italic=False, underline=
UnderlineStyle.NONE, blink=False, reverse=False, hidden=False, strikethrough=False, overline=False)method[source]method[source]__init__(fg=None, bg=None, underline_color=None, bold=False, dim=False, italic=False, underline=UnderlineStyle.NONE, blink=False, reverse=False, hidden=False, strikethrough=False, overline=False)
-
-
class libvt.Terminalclass[source]class[source]class libvt.Terminal
Bases:
objectHeadless terminal emulator over a streaming VT500 parser.
Every method call and attribute read on a
Terminalinstance (including capturing state viasnapshot()orcommitted) belongs to a single owning thread orasyncioevent loop unless externally synchronized. ReturnedSnapshotvalues are immutable and safe to pass across threads without locking.Examples
>>> from libvt.terminal import Terminal >>> from libvt.testing import serialize_vt_snapshot >>> term = Terminal(rows=2, cols=16) >>> term.feed(b"\x1b[1;32mBUILD\x1b[0m ok\r\n2 passed") >>> print(serialize_vt_snapshot(term.committed)) size=16x2 cursor=(1,8,vis=True) alt=False modes=[] ┌────────────────┐ │BUILD ok │ │2 passed │ └────────────────┘ styles: r0[0..5]: bold fg=green
-
__init__(*, rows=24, cols=80, scrollback=2000, profile=
DEFAULT_PROFILE, policy=DEFAULT_POLICY, limits=DEFAULT_LIMITS, on_event=None, on_pty_write=None, record_events=False, recorder=None, encoding='utf-8', newline_mode=False)method[source]method[source]__init__(*, rows=24, cols=80, scrollback=2000, profile=DEFAULT_PROFILE, policy=DEFAULT_POLICY, limits=DEFAULT_LIMITS, on_event=None, on_pty_write=None, record_events=False, recorder=None, encoding='utf-8', newline_mode=False) - Parameters:
- Return type:
-
propertyproperty
Return live
Appearanceof the working buffer.While DEC mode
?2026synchronized output is active, live dynamic color mutations appear onterm.appearanceimmediately whileterm.committed.appearanceretains the pre-hold frame until?2026l.References
Examples
>>> from libvt.terminal import Terminal >>> term = Terminal(rows=2, cols=10) >>> term.feed(b"\x1b[?2026h\x1b]11;#112233\x07") >>> term.appearance.bg_rgb, term.committed.appearance.bg_rgb ((17, 34, 51), (30, 30, 30))
-
propertyproperty
Return
Truewhen the parser is inGROUNDwith no pending UTF-8.References
Examples
>>> from libvt.terminal import Terminal >>> term = Terminal(rows=2, cols=10) >>> term.feed(b"\xe6\x97") >>> term.at_ground_state False >>> term.feed(b"\xa5") >>> term.at_ground_state True
-
changes_since(token=None, *, view='committed')method[source]method[source]changes_since(token=None, *, view='committed')
Compute incremental changes relative to token without mutating state.
- Parameters:
token (
SyncToken|None) – Previous watermark fromsync_token()orScreenDelta.token;Nonerequests an initial full sync.view (
SyncView) –"committed"(default) or"working".
- Returns:
Incremental row/scrollback delta or full resynchronization record.
- Return type:
Examples
>>> term = Terminal(rows=2, cols=12) >>> term.feed(b"row 0\r\nrow 1") >>> tok = term.sync_token() >>> term.feed(b"\x1b[2;1Hupdated") >>> delta = term.changes_since(tok) >>> delta.dirty_rows, delta.snapshot.lines ((1,), ('row 0', 'updated'))
-
propertyproperty
Return tear-free committed
Snapshotrespecting?2026hold.While DEC mode
?2026synchronized output is active (CSI ? 2026 h…CSI ? 2026 l),committedretains the frame captured when?2026opened so observers and renderers never see half-erased screens. Outside?2026blocks,committedreturns the same immutableSnapshotassnapshot().Examples
>>> from libvt.terminal import Terminal >>> from libvt.testing import format_screen_box >>> term = Terminal(rows=2, cols=14) >>> term.feed(b"frame 1\r\nready") >>> term.feed(b"\x1b[?2026h\x1b[2J\x1b[Hredrawing...") >>> print(format_screen_box(term.committed)) ┌──────────────┐ │frame 1 │ │ready │ └──────────────┘ >>> term.feed(b"\r\x1b[2Kframe 2\r\ndone\x1b[?2026l") >>> print(format_screen_box(term.committed)) ┌──────────────┐ │frame 2 │ │done │ └──────────────┘
-
propertyproperty
Return monotonic counter incremented whenever
committedadvances.
-
propertyproperty
Return local working directory path accepted under
Policy.osc7_hosts.
-
propertyproperty
Return raw
OSC 7/OSC 9;9working directory URI.
Return space-padded visible lines of width
colson the active screen.
-
drain_events()method[source]method[source]drain_events()
Return and clear buffered
Eventrecords fromlibvt.events.Buffers events only when the terminal was constructed with
record_events=True.Examples
>>> term = Terminal(rows=2, cols=10, record_events=True) >>> term.feed(b"\x1b]2;editor\x07\x07") >>> [type(ev).__name__ for ev in term.drain_events()] ['TitleChanged', 'Bell'] >>> term.drain_events() ()
-
drain_replies()method[source]method[source]drain_replies()
Return and clear buffered terminal reply bytes.
Automatic query responses (such as
DSRcursor position reports) populate this buffer only whenPolicy(emit_replies=True)is set; explicitenqueue_reply()payloads buffer unconditionally whenon_pty_writeis unset.- Returns:
Concatenated outbound PTY response bytes.
- Return type:
Examples
>>> from libvt.config import Policy >>> term = Terminal(rows=2, cols=10, policy=Policy(emit_replies=True)) >>> term.feed(b"abc\x1b[6n") >>> term.drain_replies() b'\x1b[1;4R' >>> term.drain_replies() b''
-
encode(event, /)method[source]method[source]encode(event, /)
Encode event into outbound PTY bytes using active terminal modes.
Examples
>>> from libvt.input import KeyEvent >>> term = Terminal(rows=2, cols=10) >>> term.feed(b"\x1b[?1h") >>> term.encode(KeyEvent("up")) b'\x1bOA'
- Parameters:
event (
InputEvent)- Return type:
-
property encoding: ParserEncodingpropertypropertyproperty encoding: ParserEncoding
Return active wire character encoding (
"utf-8"or"latin-1").
-
enqueue_reply(data, /)method[source]method[source]enqueue_reply(data, /)
Queue explicit host reply data onto
drain_replies().When
on_pty_writewas passed at construction, data forwards synchronously toon_pty_write(bytes(data))instead of buffering. Otherwise data appends todrain_replies()(waking an attachedlibvt.aiosession writer if present), or is dropped in full if buffering it would exceedmax_reply_bytes. Works regardless ofemit_replies.- Parameters:
data (
collections.abc.Buffer) – Wire-formatted response bytes supplied by the host driver (such as anOSC 52clipboard payload answeringClipboardReadRequested).- Return type:
References
Examples
>>> from libvt.config import Policy >>> from libvt.terminal import Terminal >>> term = Terminal(policy=Policy(emit_replies=False)) >>> term.enqueue_reply(b"\x1b]52;c;aGVsbG8=\x1b\\") >>> term.drain_replies() b'\x1b]52;c;aGVsbG8=\x1b\\'
-
expire_synchronized_output(sync_generation=None)method[source]method[source]expire_synchronized_output(sync_generation=None)
Release a stalled
?2026hold when sync_generation matches.Returns
Trueif an active?2026batch was expired, orFalsewhen?2026was already inactive or belonged to a newer batch.Examples
>>> term = Terminal(rows=1, cols=12) >>> term.feed(b"old\x1b[?2026h\rnew") >>> term.committed.lines ('old',) >>> term.expire_synchronized_output(), term.committed.lines (True, ('new',))
-
feed(data, /)method[source]method[source]feed(data, /)
Consume all bytes in data, updating terminal state in place.
Examples
>>> from libvt.testing import format_screen_box >>> term = Terminal(rows=2, cols=10) >>> term.feed(b"line 1\r\nline 2") >>> print(format_screen_box(term.committed)) ┌──────────┐ │line 1 │ │line 2 │ └──────────┘
-
feed_str(text, /)method[source]method[source]feed_str(text, /)
Encode text as UTF-8 and feed into the terminal.
- Raises:
ValueError– When the parser wire encoding is"latin-1"(either on entry or after an in-streamESC % @switch with trailing characters).- Parameters:
text (
str)- Return type:
-
feed_until(data, *, offset=0, stop=StopOn.EOF | StopOn.SYNC_END)method[source]method[source]feed_until(data, *, offset=0, stop=StopOn.EOF | StopOn.SYNC_END)
Feed bytes starting at offset until a stop boundary occurs.
Examples
>>> from libvt.terminal import StopOn, Terminal >>> term = Terminal(rows=1, cols=12) >>> buf = b"\x1b[?2026hframe 1\x1b[?2026ltrailing" >>> step = term.feed_until(buf, stop=StopOn.SYNC_END) >>> step.stopped_on == StopOn.SYNC_END, term.committed.lines, buf[step.offset:] (True, ('frame 1',), b'trailing')
- Parameters:
- Return type:
-
from_size(size, *, scrollback=2000, profile=
DEFAULT_PROFILE, policy=DEFAULT_POLICY, limits=DEFAULT_LIMITS, encoding='utf-8', record_events=False)classmethod method[source]classmethod method[source]from_size(size, *, scrollback=2000, profile=DEFAULT_PROFILE, policy=DEFAULT_POLICY, limits=DEFAULT_LIMITS, encoding='utf-8', record_events=False) Construct a
Terminalfromos.terminal_size.
Return sealed scrollback
RowViewlines.
-
propertyproperty
Return icon title set by
OSC 0/OSC 1orCSI 23 ; 1 t.- Returns:
Current icon/tab title string (
""initially and afterRIS).- Return type:
References
Examples
>>> from libvt.terminal import Terminal >>> term = Terminal(rows=2, cols=20) >>> term.feed(b"\x1b]1;my-icon\x07\x1b]2;my-win\x07") >>> (term.icon_title, term.title) ('my-icon', 'my-win')
Return active screen’s stored
ImageMetamap.
-
propertyproperty
Return active screen’s
KittyKeyboardFlags.
Return right-trimmed visible lines of the active screen.
-
propertyproperty
Return active screen’s
XTMODKEYSmodifyOtherKeyslevel.
-
propertyproperty
Return current
ParserState.
-
propertyproperty
Return active screen’s
ImagePlacementrecords.
-
propertyproperty
Return highest-urgency active
OSC 7501/OSC 9;4status.
-
propertyproperty
Return all active
OSC 7501task records keyed byid.
-
propertyproperty
Return recorded primary-screen
OSC 133semantic prompt zones.
-
propertyproperty
Return attached
TerminalRecorder, if any.
-
replace_from(other)method[source]method[source]replace_from(other)
Replace emulated screen, mode, parser, and guest state from other.
Preserves host identity and wiring (
_terminal_id, callbacks,recorder, host theme, policy, and limits) while transferring live emulated state from donor other in place and advancing the sync epoch so existingSyncTokenconsumers receiveResyncReason.EPOCH_CHANGED.Ownership of other’s internal screen buffers and parser transfers to
self; do not continue mutating other afterwards.Examples
>>> from libvt.terminal import ResyncReason, Terminal >>> dst = Terminal(rows=2, cols=10) >>> dst.feed(b"\x1b]10;#ff0000\x07old") >>> tok = dst.sync_token() >>> src = Terminal(rows=2, cols=10) >>> src.feed(b"fresh") >>> dst.replace_from(src) >>> dst.lines[0], dst.changes_since(tok).resync_reason ('fresh', <ResyncReason.EPOCH_CHANGED: 'epoch_changed'>)
-
resize(*, rows, cols, reflow=None)method[source]method[source]resize(*, rows, cols, reflow=None)
Resize terminal screens to
(rows, cols).A resize to the active screen’s current dimensions preserves the grapheme in progress.
Examples
>>> from libvt.testing import format_screen_box >>> term = Terminal(rows=2, cols=6) >>> term.feed(b"hello world") >>> term.resize(rows=2, cols=12) >>> print(format_screen_box(term.committed)) ┌────────────┐ │hello world │ │ │ └────────────┘
-
propertyproperty
Return the dual primary/alternate
ScreenSet.
-
set_theme(*, scheme=None, fg_rgb=None, bg_rgb=None, cursor_rgb=None, palette=None)method[source]method[source]set_theme(*, scheme=None, fg_rgb=None, bg_rgb=None, cursor_rgb=None, palette=None)
Update host theme defaults without clobbering active guest overrides.
When DEC mode
?2031(COLOR_SCHEME_UPDATES) is enabled and any host theme attribute changes, queues an unsolicitedCSI ? 997 ; Ps nnotification (subject toemit_replies). Subsequent guest resets (OSC 104,OSC 110-112,RIS) fall back to the updated host values.- Parameters:
scheme (
ColorScheme|None) – Updated host color scheme (DARKorLIGHT).fg_rgb (
tuple[int,int,int] |None) – Updated 8-bit host default foreground(r, g, b).bg_rgb (
tuple[int,int,int] |None) – Updated 8-bit host default background(r, g, b).cursor_rgb (
tuple[int,int,int] |None) – Updated 8-bit host cursor(r, g, b).palette (
collections.abc.Mapping[int,tuple[int,int,int]] |None) – Replacement host 256-color palette overrides keyed by0..255.
- Raises:
TypeError– If scheme is aboolrather than aColorScheme.ValueError– If any RGB channel or palette index falls outside0..255.
- Return type:
References
Contour VT Extensions — Color-Palette Update Notifications (?2031)
ghostty-org/ghostty src/terminal/c/color_scheme.zig (v1.4.0)
Examples
>>> from libvt.config import ColorScheme >>> from libvt.terminal import Terminal >>> term = Terminal(rows=2, cols=10) >>> term.feed(b"\x1b[?2031h") >>> term.set_theme(scheme=ColorScheme.LIGHT, bg_rgb=(250, 250, 250)) >>> term.drain_replies() b'\x1b[?997;2n'
-
snapshot()method[source]method[source]snapshot()
Capture an immutable
Snapshotof the live working buffer.Freezes active viewport rows, RLE scrollback history, cursor state, enabled ANSI/DEC modes,
OSC 133prompt zones,OSC 7501program status, and graphics placements. Repeated calls without intervening mutations return the cachedSnapshotinO(1).Unlike
committed,snapshot()reads the live buffer even while DEC mode?2026synchronized output is open; prefercommittedwhen observing completed frames.Examples
>>> from libvt.terminal import Terminal >>> from libvt.testing import format_screen_box, serialize_vt_snapshot >>> term = Terminal(rows=2, cols=14) >>> term.feed(b"\x1b[1;36mINFO\x1b[0m listening\r\nport=8000") >>> snap = term.snapshot() >>> term.feed(b"\x1b[2J\x1b[Hshutdown") >>> print(serialize_vt_snapshot(snap)) size=14x2 cursor=(1,9,vis=True) alt=False modes=[] ┌──────────────┐ │INFO listening│ │port=8000 │ └──────────────┘ styles: r0[0..4]: bold fg=cyan >>> print(format_screen_box(term.snapshot())) ┌──────────────┐ │shutdown │ │ │ └──────────────┘
-
propertyproperty
Return monotonic
?2026synchronized-update batch counter.
-
sync_token(*, view='committed')method[source]method[source]sync_token(*, view='committed')
Return an immutable watermark token for
changes_since().- Parameters:
view (
SyncView) –"committed"(default, respecting?2026frame holds) or"working"(live in-progress buffer).- Returns:
Opaque watermark capturing current state without mutating the terminal.
- Return type:
Examples
>>> term = Terminal(rows=2, cols=10) >>> tok = term.sync_token() >>> term.changes_since(tok).has_changes False
-
propertyproperty
Return
Truewhile DEC mode?2026synchronized output is active.
-
propertyproperty
Return visible active-screen text with trailing blank rows omitted.
-
propertyproperty
Return visible active-screen text with soft-wrapped rows joined.
Examples
>>> term = Terminal(rows=3, cols=8) >>> term.feed(b"hello world\r\nok") >>> term.unwrapped_text 'hello world\nok'
-
-
libvt.render(data, /, *, rows=24, cols=80, profile=
DEFAULT_PROFILE, newline_mode=False, unwrap=False)function[source]function[source]libvt.render(data, /, *, rows=24, cols=80, profile=DEFAULT_PROFILE, newline_mode=False, unwrap=False) Emulate data on a fresh
(rows, cols)terminal and return screen text.- Parameters:
data (
collections.abc.Buffer|str) – Raw VT byte stream or UTF-8 string to feed.rows (
int) – Screen height in rows.cols (
int) – Screen width in columns.profile (
Profile) – Compatibility profile governing emulation quirks.newline_mode (
bool) – WhenTrue, enable ANSILNM(LFimpliesCR).unwrap (
bool) – WhenTrue, returnTerminal.unwrapped_textwith soft-wrapped rows joined instead ofTerminal.text.
- Returns:
Rendered visible text with trailing blank rows omitted.
- Return type:
Examples
>>> import libvt >>> libvt.render(b"loading 10%\r\x1b[2Kloading 100%", rows=1, cols=20) 'loading 100%' >>> libvt.render(b"hello world", rows=2, cols=8, unwrap=True) 'hello world'
-
libvt.strip(data, /)function[source]function[source]libvt.strip(data, /)
Strip VT escape, CSI, OSC, DCS, and APC sequences, keeping plain text.
Unlike
render(),strip()removes control sequences without applying cursor movements or line erasures.Examples
>>> import libvt >>> libvt.strip("\x1b[1;32mPASS\x1b[0m\n") 'PASS\n'