Portable terminal text and input, Kitty graphics, and Silkie extensions for pen, touch, typography, and display control. A pure Python library for building terminal applications.
❯ python hello.py Hello from Hamingjur. Text. Color. Input. A place to begin.
Illustrative browser preview · actual rendering happens in your terminal
from hamingjur import Terminal
term = Terminal()
print(term.bold_green("Hello from Hamingjur."))
with term.cbreak():
key = term.inkey(timeout=1)
if key:
print(f"You pressed {key!r}")
Start with readable text and ordinary input. Add graphics, richer devices, or precise display feedback through the same Terminal object. Discover capabilities before depending on them.
01 — PORTABLE FOUNDATIONS
Text is still first class.
Colors, cursor movement, Unicode width, full-screen contexts, keyboard input, mouse events, and a headless line editor.
02 — RICHER PROTOCOLS
Pixels, paths, and pens.
Kitty image transport and Silkie vector scenes, shaped text, tablet pressure, multitouch, gestures, and terminal-local ink.
03 — EXPLICIT CONTROL
Ask, then act.
Read capability replies and granted modes. Scope reporting with context managers and release the resources your application owns.
Your Python applicationstate · content · event loop
→
HamingjurTerminal · encoders · clients
→
The terminalrendering · shaping · hardware
The terminal performs vector rasterization, text shaping, font loading, and hardware access. Hamingjur encodes requests and reads replies.
Hamingjur is maintained by Adam DePrince. It is an independent MIT-licensed fork, with inherited work and notices from Jeff Quast, Erik Rose, Avram Lubkin, and other Blessed contributors. Its hamingjur namespace can coexist with upstream blessed.
02 / GET STARTED
Installation & a first program.
Install from PyPI, or work from a source checkout. The core APIs need only Python, wcwidth, and jinxed. Add Pillow when you want adaptive image drawing.
Install from PyPI
SHELL
python -m pip install hamingjur
# Optional Pillow image support
python -m pip install 'hamingjur[images]'
# Or, from a source checkout
python -m pip install -e .
The optional images extra adds Pillow. The editable command is for development from the repository root.
Run in a terminal
PYTHON · hello.py
from hamingjur import Terminal
term = Terminal()
with term.fullscreen(), term.cbreak(), term.hidden_cursor():
print(term.home + term.clear, end="")
print(term.bold_green("Hello from Hamingjur."))
print("Press q to exit.")
while True:
key = term.inkey(timeout=0.1)
if key == "q" or key.name == "KEY_ESCAPE":
break
Rendering follows the output stream. Terminal writers respect term.does_styling. Redirected output can stay escape-free, and NO_COLOR disables styling. Run visual demos interactively with terminal input and output.
03 / FEATURE MAP
Features & terminal support.
The APIs cover both familiar terminal behavior and newer extensions. Encoding a request establishes what your application sent; the terminal’s reply establishes what it supports.
KITTY / SILKIE Applications own transfer state and policy. Silkie adds notification return routes.
Remote commands & SSH-agent packets
term.remote_control.call(), term.ssh_agent
Explicit terminal permission. Remote control and SSH-agent transport are separate APIs.
04 / WORKING EXAMPLES
From a request to a result.
Each example makes support and ownership explicit. Use the reference below for every argument, return type, and source docstring.
01 — Discover and read tablet events
Aggregate discovery identifies understood selectors. Query the channel for device-related capabilities, then use the reporting mode that the terminal actually grants.
PYTHON · tablet input
from hamingjur import Terminal
from hamingjur.silkie import TabletMode
term = Terminal()
with term.cbreak():
caps = term.silkie.capabilities(timeout=0.5)
if caps and caps.supports("tablet-pointer"):
mode = TabletMode.TOOLS | TabletMode.TOUCH
with term.tablet.enabled(mode) as granted:
while granted:
key = term.inkey(timeout=0.1)
if key == "q":
break
if key.tablet is not None:
event = key.tablet
print(event.position, event.pressure, event.tilt)
else:
print("Tablet reporting: not supported")
Touchpad coordinates are available through touchpad_position; they are normalized values, rather than physical screen pixels. Reporting contexts restore the previous mode on exit.
02 — Draw an image and release it
The adaptive image API fits your source, negotiates formats and transfer media, and waits for an acknowledgement. Keep the source image if you plan to redraw after a resize.
PYTHON · requires .[images] and a local photo.png
from PIL import Image
from hamingjur import Terminal
term = Terminal()
result = None
with Image.open("photo.png") as source, term.cbreak():
try:
result = term.graphics.draw(
source, x=0, y=0, columns=40, rows=12
)
term.inkey()
finally:
if result is not None:
term.graphics.send(
term.graphics.delete(result.image_id)
)
Use pixel width/height or cell columns/rows, never both. Source formats include packed grayscale, RGB565, RGB/RGBA, PNG, and HDR half-float RGBA where supported. GPU surfaces require an application-owned descriptor.
03 — Send a retained vector scene
Vector records describe paths, groups, gradients, clips, pressure strokes, and shaped text. Use patch() to replace or append records in an existing scene.
PYTHON · Silkie vector images
from hamingjur import Terminal, graphics
term = Terminal()
with term.cbreak():
if term.graphics.supports(200):
records = [
graphics.vector_record(
"p", id=1, d="M0,0H240V100H0Z", fill="#183e35"
),
graphics.text_record(2, {
"text": "Hello, vectors.", "x": 16, "y": 58,
"size": 26, "fill": "#c4e6a8"
}),
]
try:
term.graphics.send(graphics.scene(
records, image_id=7, width=240, height=100, q=1
))
term.inkey()
finally:
term.graphics.send(graphics.delete(7, q=2))
else:
print("Vector graphics: not supported")
04 — Keep input and application state separate
LineEditor handles editing, history, suggestions, grapheme movement, and optional password masking. Your application decides where and when to render.
PYTHON · a headless editor in an event loop
from hamingjur import Terminal, LineEditor, LineHistory
term = Terminal()
editor = LineEditor(history=LineHistory(), max_width=term.width)
with term.cbreak():
while True:
print(editor.render(term, row=0, width=term.width),
end="", flush=True)
result = editor.feed_key(term.inkey())
if result.line is not None:
break
if result.interrupt or result.eof:
break
Feed bracketed-paste contents through insert_text(). For asynchronous applications, use await term.async_inkey() in your own async event loop.
05 / API CONTRACTS
Read the reply you received.
Query APIs return different objects. This distinction matters when decoding responses or handling unsupported features.
The full matched response string, or None. It is not a regular-expression match object. Parse the returned string with the appropriate decoder.
Channel.query(timeout)ProtocolEvent | None
A structured Silkie capability report. Inspect fields, integer(), or number(). A selector’s support does not imply attached hardware.
Graphics.query(data, ...)ProtocolEvent | None
A graphics reply. A successful probe has event.payload == "OK". supports() turns a format probe into a boolean.
Terminal.inkey() / async_inkey()Keystroke
A string-compatible key with name and structured protocol_event or tablet properties. Empty input can indicate a timeout.
Graphics.draw(source, ...)DrawnImage | None
An acknowledged image placement; disabled styling returns None. Upload errors raise, and missing acknowledgements raise TimeoutError.
RemoteControl.call(name, payload, ...)decoded response data
Returns the terminal’s JSON data. Refusal raises RemoteControlError; a missing complete reply raises TimeoutError. Terminal permission is required.
Restore modes.enabled() reads the existing mode, checks granted bits, and restores the previous value in finally. Leave contexts before suspending and re-enter after resuming.
Own resource lifetimes. Release images and uploaded font handles. GPU surface allocation stays with your application. File, shared-memory, and direct transports have different lifecycles.
Serialize shared terminal I/O. Complete a chunked transmission before starting another command on that protocol. Queries preserve unrelated keyboard input.
Interpret payloads by protocol.event.data decodes base64 only where the protocol defines it. Graphics errors and notification activations may carry plain text.
Preserve complete data. Image transmissions, event reports, and retained editing state do not have arbitrary total-size caps. Actual wire ranges and packet sizes still apply; allocation failures propagate.
06 / INTERACTIVE EXAMPLES
Test your terminal.
The interactive showcase probes the current terminal and puts visual samples, live input counters, and capability status together. Unavailable features are marked not supported.
Run the Silkie showcase
From the checkout, with its dependencies installed:
SHELL
PYTHONPATH=. .venv/bin/python bin/silkie_showcase.py
# Keep complete events in a JSONL file
PYTHONPATH=. .venv/bin/python bin/silkie_showcase.py \
--events events.jsonl
qExitTabInspect detailshHaptic tapcClear inkj / kScroll on small screens
A 120 × 30 terminal leaves room for the visual areas. The script adapts to smaller windows and preserves ink on resize. Use --font or --gpu-surface to provide resources for those optional demonstrations.
For a dedicated drawing application, try python bin/tablet_canvas.py --mode tiles, --mode vectors, or --mode ink after installation. Visual results depend on terminal support, attached hardware, user permissions, and display settings.
07 / SOURCE-DERIVED REFERENCE
The API, in detail.
21 modules · 422 declarations · v0.1.0
Search public functions, methods, properties, and classes. Expand an entry for its exact source signature, complete docstring, fields, and source location.
⌕
422 declarations across 21 modules
No matching APIs. Try another search or reset the module filter.
hamingjur.terminal142 entries
Module containing :class:`Terminal`, the primary API entry point.
terminal.TerminalclassAn abstraction for color, style, positioning, and input in the terminal.
An abstraction for color, style, positioning, and input in the terminal.
This keeps the endless calls to ``tigetstr()`` and ``tparm()`` out of your code, acts
intelligently when somebody pipes your output to a non-terminal, and abstracts over the
complexity of unbuffered keyboard input. It uses the terminfo database to remain portable across
terminal types.
Constructor
-----------
Initialize the terminal.
:arg str kind: A terminal string used for capability database, defaults to the value of the
``TERM`` environment variable when undefined. If the terminal supports XTGETTCAP
extension, the 'TN' capability name reported has precedence over 'kind'.
:arg file stream: A file-like object representing the Terminal output.
Defaults to the original value of :obj:`sys.__stdout__`, like
:func:`curses.initscr` does.
If ``stream`` is not a tty, empty Unicode strings are returned for
all capability values, so things like piping your program output to
a pipe or file does not emit terminal sequences.
:arg bool force_styling: Whether to force the emission of capabilities
even if :obj:`sys.__stdout__` does not seem to be connected to a
terminal. If you want to force styling to not happen, use
``force_styling=None``.
This comes in handy if users are trying to pipe your output through
something like ``less -r`` or build systems which support decoding
of terminal sequences.
When the OS Environment variable FORCE_COLOR_ or CLICOLOR_FORCE_ is
*non-empty*, styling is used no matter the value specified by
``force_styling``.
Conversely, When OS Environment variable NO_COLOR_ is *non-empty*,
styling is **not** used no matter the value specified by
``force_styling``, FORCE_COLOR_, or CLICOLOR_FORCE_.
.. _FORCE_COLOR: https://force-color.org/
.. _CLICOLOR_FORCE: https://bixense.com/clicolors/
.. _NO_COLOR: https://no-color.org/
:arg str kind_fallback: Terminal kind to use as fallback when the requested ``kind`` is not
found in jinxed_ virtual terminfo database. Defaults to ``'xterm-256color'`` which is
well supported for all capabilities used by hamingjur on all modern terminals.
.. _jinxed: https://github.com/rockhopper-Technologies/jinxed
Context manager for temporarily moving the cursor.
:arg int x: horizontal position, from left, *0*, to right edge of screen, *self.width - 1*.
:arg int y: vertical position, from top, *0*, to bottom of screen, *self.height - 1*.
:return: a context manager.
:rtype: Iterator
Move the cursor to a certain position on entry, do any kind of I/O, and upon exit
let you print stuff there, then return the cursor to its original position:
.. code-block:: python
term = Terminal()
with term.location(y=0, x=0):
for row_num in range(term.height-1):
print('Row #{row_num}')
print(term.clear_eol + 'Back to original location.')
Specify ``x`` to move to a certain column, ``y`` to move to a certain
row, both, or neither. If you specify neither, only the saving and
restoration of cursor position will happen. This can be useful if you
simply want to restore your place after doing some manual cursor
movement.
Calls cannot be nested: only one should be entered at a time.
.. note:: The argument order *(x, y)* differs from the return value order *(y, x)*
of :meth:`get_location`, or argument order *(y, x)* of :meth:`move`. This is
for API Compatibility with the blessings library, sorry for the trouble!
terminal.Terminal.get_locationmethodReturn tuple (row, column) of cursor position.
Return tuple (row, column) of cursor position.
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and the value ``(-1, -1)`` is returned without inquiry.
:arg float timeout: Return after time elapsed in seconds with value ``(-1, -1)`` indicating
that the remote end did not respond.
:rtype: tuple
:returns: cursor position as tuple in form of ``(y, x)``. Always ensure the return value is
checked for ``(-1, -1)``.
The location of the cursor is determined by emitting the ``u7`` terminal capability for the
VT100 `Query Cursor Position
<https://www2.ccs.neu.edu/research/gpc/VonaUtils/vona/terminal/vtansi.htm#status>`_.
This elicits a response from a reply string described by capability ``u6`` for the VT100
response.
The ``(y, x)`` return value matches the parameter order of the :meth:`move_yx` capability.
The following sequence should cause the cursor to not move at all::
>>> term = Terminal()
>>> term.move_yx(*term.get_location())
And the following should assert True with a terminal:
>>> term = Terminal()
>>> given_y, given_x = 10, 20
>>> with term.location(y=given_y, x=given_x):
... result_y, result_x = term.get_location()
...
>>> assert given_x == result_x, (given_x, result_x)
>>> assert given_y == result_y, (given_y, result_y)
terminal.Terminal.get_fgcolormethodReturn tuple (r, g, b) of default foreground color.
Return tuple (r, g, b) of default foreground color.
This returns the terminal's default color for uncolored text, not any
currently active color set by escape sequences.
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and the value ``(-1, -1, -1)`` is returned without inquiry.
:arg float timeout: Return after time elapsed in seconds with value ``(-1, -1, -1)``
indicating that the remote end did not respond.
:arg int bits: Bits per channel: 16 (default, 0-65535, 48-bit total) or
8 (0-255, 24-bit total).
:rtype: tuple
:returns: foreground color as tuple in form of ``(r, g, b)``. When a timeout is specified,
always ensure the return value is checked for ``(-1, -1, -1)``.
:raises ValueError: When bits is not 8 or 16.
The foreground color is determined by emitting an `OSC 10 color query
<https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands>`_.
See also :meth:`~.Terminal.get_bgcolor` for querying the background color.
.. note::
The default return value is 16-bit, matching the XParseColor specification of the
underlying protocol. For most uses, 8-bit values are preferred::
rgb = term.get_fgcolor(bits=8)
term.color_rgb(*rgb) # reset foreground to default
terminal.Terminal.get_bgcolormethodReturn tuple (r, g, b) of default background color.
Return tuple (r, g, b) of default background color.
This returns the terminal's default background color, not any currently
active color set by escape sequences.
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and the value ``(-1, -1, -1)`` is returned without inquiry.
:arg float timeout: Return after time elapsed in seconds with value ``(-1, -1, -1)``
indicating that the remote end did not respond.
:arg int bits: Bits per channel: 16 (default, 0-65535, 48-bit total) or
8 (0-255, 24-bit total).
:rtype: tuple
:returns: background color as tuple in form of ``(r, g, b)``. When a timeout is specified,
always ensure the return value is checked for ``(-1, -1, -1)``.
:raises ValueError: If bits is not 8 or 16.
The background color is determined by emitting an `OSC 11 color query
<https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands>`_.
See also :meth:`~.Terminal.get_fgcolor` for querying the foreground color.
.. note::
The default return value is 16-bit, matching the XParseColor specification of the
underlying protocol. For most uses, 8-bit values are preferred::
rgb = term.get_bgcolor(bits=8)
term.on_color_rgb(*rgb) # reset background to default
terminal.Terminal.get_fgcolor_hexmethodReturn default foreground color as hex string.
Return default foreground color as hex string.
:arg float timeout: Return after time elapsed in seconds with empty string
if the remote end did not respond.
:arg bool maybe_short: If True, return ``#RGB`` when possible.
:returns: Hex color string (``#RRGGBB`` or ``#RGB``), or empty string on
timeout or when :attr:`is_a_tty` is False.
Convenience wrapper combining :meth:`get_fgcolor` and
:func:`~hamingjur.colorspace.rgb_to_hex`.
terminal.Terminal.get_bgcolor_hexmethodReturn default background color as hex string.
Return default background color as hex string.
:arg float timeout: Return after time elapsed in seconds with empty string
if the remote end did not respond.
:arg bool maybe_short: If True, return ``#RGB`` when possible.
:returns: Hex color string (``#RRGGBB`` or ``#RGB``), or empty string on
timeout or when :attr:`is_a_tty` is False.
Convenience wrapper combining :meth:`get_bgcolor` and
:func:`~hamingjur.colorspace.rgb_to_hex`.
terminal.Terminal.get_device_attributesmethodQuery the terminal's Device Attributes (DA1).
Query the terminal's Device Attributes (DA1).
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``None`` is returned without inquiry.
If a Device Attributes query fails to respond within the ``timeout``
specified, ``None`` is returned. If this was the first query for device
attributes, all subsequent queries return ``None`` unless ``force=True``
is set (sticky failure).
**Responses are cached indefinitely** unless ``force=True`` is
specified.
.. note:: A ``timeout`` value should be set to avoid blocking when the
terminal does not respond to DA1 queries, which may happen with some
kinds of "dumb" terminals.
:arg float timeout: Timeout in seconds to await terminal response
:arg bool force: Force active terminal inquiry even if cached result exists
or previous query failed
:rtype: DeviceAttribute or None
:returns: DeviceAttribute instance with terminal capabilities, or None
if unsupported/timeout
.. code-block:: python
term = Terminal()
# Query device attributes
da = term.get_device_attributes(timeout=TERMINAL_QUERY_TIMEOUT_SECONDS)
if da is not None:
print(f"Service class: {da.service_class}")
print(f"Supports sixel: {da.supports_sixel}")
print(f"Extensions: {sorted(da.extensions)}")
terminal.Terminal.get_software_versionmethodReturn the terminal's software name and version.
Return the terminal's software name and version.
A non-empty ``TERM_PROGRAM`` value takes precedence and no inquiry is made,
otherwise an XTVERSION query is sent to the terminal and the response is
returned as a :class:`SoftwareVersion` instance. Returns ``None`` only if both
methods fail.
**Only Successful responses are cached indefinitely** unless ``force=True`` is specified.
Unlike other query methods, there is no "sticky failure", failed queries are not cached and
are retried.
.. note:: A ``timeout`` value should be set to avoid blocking when the
terminal does not respond to XTVERSION queries, which may happen with
some kinds of "dumb" terminals.
:arg float timeout: Timeout in seconds to await terminal response
:arg bool force: Force active terminal inquiry even if cached result exists
:rtype: SoftwareVersion or None
:returns: SoftwareVersion instance with terminal name and version, or None
if unsupported/timeout
.. code-block:: python
term = Terminal()
# Query software version
sv = term.get_software_version(timeout=TERMINAL_QUERY_TIMEOUT_SECONDS)
if sv is not None:
print(f"Terminal: {sv.name} {sv.version}")
terminal.Terminal.does_sixelmethodQuery whether the terminal supports sixel graphics.
Query whether the terminal supports sixel graphics.
Sixel is a bitmap graphics format supported by some modern terminal
emulators, allowing applications to display inline images.
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``False`` is returned without inquiry.
This method calls :meth:`get_device_attributes` to query the terminal's
capabilities and checks for sixel support (extension 4 in the DA1 response).
Results are cached, so subsequent calls are fast.
:arg float timeout: Timeout in seconds to await terminal response. When
``None`` (default), the query may block indefinitely.
:arg bool force: Bypass cache and re-query the terminal
:rtype: bool
:returns: ``True`` if terminal supports sixel graphics, ``False`` otherwise
terminal.Terminal.detect_ambiguous_widthmethodDetect whether the terminal renders ambiguous width characters as width 1 or 2.
hamingjur.terminal.Terminal.detect_ambiguous_width(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS, fallback: int=1, force: bool=False) -> int
Detect whether the terminal renders ambiguous width characters as width 1 or 2.
:arg float timeout: Timeout in seconds for any single cursor position response.
:arg int fallback: Value to return on timeout, invalid measurement, or not a tty.
:arg bool force: Measure again, bypassing the cache and the ``AMBIGUOUS_WIDE`` override.
:rtype: int
:returns: 1 for "Ambiguous width as narrow", 2 is "Ambiguous width as wide"
East Asian ambiguous width characters render as either single (1) or double width (2)
depending on terminal settings. This measures the rendered width of U+00A7 (SECTION SIGN),
an early Unicode character with East Asian Width property "Ambiguous", by drawing and
erasing it at the current cursor position. Ambiguous width is used in "legacy" contexts,
like with BIG5, gbk, or shift-jis encoding, and most especially in mathematics or artwork,
like on terminal bulletin board systems, https://bbs.modem.xyz/encodings.html#big5, and
sometimes simply as a user preference, for neat and tidy vertical alignment. `configuration
<https://wezterm.org/config/lua/config/treat_east_asian_ambiguous_width_as_wide.html>`_ is
usually required to enable "ambiguous width as wide".
The result is cached, assigned to :attr:`ambiguous_width`, and returned, and used
automatically by subsequent alignment methods, :meth:`length`, :meth:`wrap`, :meth:`ljust`,
:meth:`rjust`, and :meth:`center`.
Example usage::
>>> term = Terminal()
>>> term.length('\u00a7')
1
>>> term.detect_ambiguous_width()
2
>>> term.length('\u00a7')
2
When :attr:`is_a_tty` is False, no sequences are transmitted or response awaited, and
``fallback`` is returned without inquiry.
terminal.Terminal.detect_term_programmethodDetect the terminal software name applied to python wcwidth correction tables.
Detect the terminal software name applied to python wcwidth correction tables.
:arg float timeout: Timeout in seconds to await an XTVERSION response.
:arg bool force: Detect again, bypassing the cache.
:rtype: str
:returns: Terminal name, wcwidth alias, or an empty string when unknown.
A non-empty ``TERM_PROGRAM`` environment value or a unique ``TERM`` that matches wcwidth
other than 'xterm' returns that value. Otherwise, an in-band XTVERSION query is made and its
software name is returned if responded.
The result is cached, assigned to :attr:`term_program`, and used automatically by width or
alignment methods, :meth:`length`, :meth:`wrap`, :meth:`ljust`, :meth:`rjust`, and
:meth:`center`.
When :attr:`is_a_tty` or :attr:`does_styling` is False, or no keyboard is available,
XTVERSION inquiries are not made and timeout does not apply, and the result is not cached.
terminal.Terminal.get_dec_modemethodQuery the state of a DEC Private Mode (DECRQM).
Query the state of a DEC Private Mode (DECRQM).
Sends a DECRQM query to the terminal and returns a
:class:`DecModeResponse` instance. Use the helper methods like
:meth:`DecModeResponse.is_supported` or
:meth:`DecModeResponse.is_enabled` and others to interpret the result.
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and the :class:`DecModeResponse` value returned is always
:attr:`DecModeResponse.NOT_QUERIED`.
In some cases a ``timeout`` value should be set, as it is possible for a
terminal that succeeds :attr:`is_a_tty` to fail to respond to DEC Private
Modes, such as in a CI Build Service or other "dumb" terminal, even a few
popular modern ones such as Konsole. The first query may also make an XTVERSION
query, :meth:`get_software_version`, to avoid a DECRQM query to terminals with
leaky output (Terminal.app), so the total elapsed time may exceed *timeout*.
If a DEC Private mode query fails to respond within the ``timeout``
specified, the :class:`DecModeResponse` value returned is
:attr:`DecModeResponse.NO_RESPONSE`. If this was the first DEC Private
mode query, all subsequent queries return a :class:`DecModeResponse`
value of :attr:`DecModeResponse.NOT_QUERIED` unless ``force=True`` is
set.
**Repeat queries return the (cached) known state immediately** without
re-inquiry unless ``force=True``. Although there are special cases
where a user may re-configure their terminal settings after the state
was requested by an application, the application is generally restarted
to recognize the new settings rather than to repeatedly re-inquire about
their latest value!
:arg mode: DEC Private Mode to query
:type mode: DecPrivateMode | int
:arg float timeout: Timeout in seconds to await terminal response
:arg bool force: Force active terminal inquery in all cases
:rtype: DecModeResponse
:returns: DecModeResponse instance
:raises TypeError: If mode is not DecPrivateMode or int
.. code-block:: python
term = Terminal()
# Query synchronized output support
response = term.get_dec_mode(DecPrivateMode.SYNCHRONIZED_OUTPUT)
if response.supported:
print("Synchronized output is available")
terminal.Terminal.dec_modes_enabledcontext managerContext manager for temporarily enabling DEC Private Modes.
Context manager for temporarily enabling DEC Private Modes.
On entry, queries each mode's current state using get_dec_mode().
For modes that are supported but currently disabled, enables them
and tracks them for restoration. On exit, disables all modes that
were enabled by this context manager, restoring original state.
Unsupported modes are silently ignored.
:arg modes: One or more DEC Private Mode numbers or enum members
:arg float timeout: Timeout in seconds for get_dec_mode calls
:raises TypeError: If mode is not DecPrivateMode or int
.. code-block:: python
term = Terminal()
# Enable synchronized output temporarily
with term.dec_modes_enabled(DecPrivateMode.SYNCHRONIZED_OUTPUT):
# All output will be atomic
print("Frame 1")
print("Frame 2")
terminal.Terminal.dec_modes_disabledcontext managerContext manager for temporarily disabling DEC Private Modes.
Context manager for temporarily disabling DEC Private Modes.
Uses the same logic as dec_modes_enabled but inverted: disables
supported modes that are currently enabled on entry, then restores
them on exit.
:arg modes: One or more DEC Private Mode numbers or enum members
:arg float timeout: Timeout in seconds for get_dec_mode calls
:raises TypeError: If mode is not DecPrivateMode or int
terminal.Terminal.does_mousemethodCheck if the terminal supports the specified mouse tracking features.
Check if the terminal supports the specified mouse tracking features.
This method queries terminal support for the same DEC modes that
:meth:`mouse_enabled` would enable with the given parameters.
:arg bool clicks: Check for basic click reporting (default True)
:arg bool report_pixels: Check for pixel coordinate reporting
:arg bool report_drag: Check for drag reporting
:arg bool report_motion: Check for motion reporting
:arg float timeout: Timeout for mode queries (default 1.0s)
:returns: True if all required modes are supported
:rtype: bool
Example::
if term.does_mouse(report_drag=True, report_pixels=True):
with term.mouse_enabled(report_drag=True, report_pixels=True):
# Use mouse tracking with drag and pixel support
pass
terminal.Terminal.does_inband_resizemethodCheck if the terminal supports in-band window resize notifications.
Check if the terminal supports in-band window resize notifications.
This method queries whether the terminal supports DEC mode 2048
(IN_BAND_WINDOW_RESIZE), which allows receiving resize events as
in-band sequences through :meth:`inkey` instead of relying on
SIGWINCH signals.
:arg float timeout: Timeout for mode query (default 1.0s)
:returns: True if in-band resize notifications are supported
:rtype: bool
Example::
if term.does_inband_resize():
with term.notify_on_resize():
# Use in-band resize events
pass
else:
# Fall back to SIGWINCH or other methods
pass
terminal.Terminal.does_bracketed_pastemethodCheck if the terminal supports bracketed paste mode.
Check if the terminal supports bracketed paste mode.
Bracketed paste mode (DEC mode 2004) wraps pasted text in special
sequences so applications can distinguish pasted text from typed input.
.. seealso:: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Bracketed-Paste-Mode
:arg float timeout: Timeout for mode query (default 1.0s).
:returns: True if bracketed paste mode is supported.
:rtype: bool
terminal.Terminal.does_synchronized_outputmethodCheck if the terminal supports synchronized output.
Query terminal capabilities via XTGETTCAP (DCS +q).
When *caps* is specified, only those capabilities are returned. When unspecified, all known
XTGETTCAP capabilities are queried and returned. All results from XTGETTCAP are memoized
permanently, unlike DECRQSS :meth:`get_decrqss` which may change. Using ``force=True`` to
re-retrieve any request.
:arg float timeout: Timeout in seconds.
:arg bool force: Always re-query for latest values.
:arg caps: Capability names to query. When specified, only these additional capabilities
may queried (incremental on cache). when unspecified, it as though `all=True` was used.
:rtype: TermcapResponse
terminal.Terminal.does_xtgettcapmethodWhether the terminal supports XTGETTCAP (DCS +q) queries.
Whether the terminal supports XTGETTCAP (DCS +q) queries.
Support is determined at class initialization and so this call is always non-blocking unless
the *force* argument is used.
:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.get_font_coveragemethodQuery which codepoints of *text* the terminal font has a glyph for.
Query which codepoints of *text* the terminal font has a glyph for.
:arg str text: Text whose codepoints to query. Each distinct codepoint is asked
about once, in batches, however long *text* is and however often it repeats.
:arg float timeout: Seconds to wait for each round-trip. A long *text* takes
several, so this bounds a single exchange and not the call.
:arg bool force: Discard the cached protocol probe and every cached codepoint
result, and query the terminal again.
:rtype: FontCoverage
:returns: Per-codepoint coverage. When *text* is empty, or when neither
protocol answers, an empty result whose :attr:`~.FontCoverage.supported`
is False, which is falsey. A codepoint the terminal declined to answer
for is reported through :attr:`~.FontCoverage.unknown` and is not asked
about again until ``force``.
Two protocols are tried, mintty's *Font Glyph Coverage Enquiry* (``OSC 7771``)
first, then the *Glyph Protocol* ``'q'`` verb (``APC 25a1``) of rio. The
protocol that answers is remembered, as is the result for every codepoint
queried, so repeated calls over overlapping text cost no further round-trips.
>>> coverage = term.get_font_coverage('─│')
>>> if not coverage:
... print('terminal cannot say')
... elif not coverage.covers('─│'):
... print('falling back to ASCII box drawing')
.. warning:: This reports *coverage of codepoints by a font*, and nothing more.
Neither protocol can be asked about a grapheme cluster, and neither reports
on the shaping that turns codepoints into drawn glyphs: ligatures, mark
positioning, ``ZWJ`` joining, ``VS-15``/``VS-16`` presentation, contextual
forms, or fallback to another font. A cluster whose codepoints are all
covered may still fail to draw, and one with uncovered codepoints may draw
perfectly. The text presentation watch, ``'⌚︎'``, renders correctly
on terminals whose font has no glyph for ``U+FE0E``, as no font does.
Deciding what will render is a heuristic built on this answer, and hamingjur
does not make it for you: see :ref:`detect-tofus.py` for one such heuristic.
.. seealso::
https://github.com/mintty/mintty/wiki/CtrlSeqs#font-glyph-coverage-enquiry
and https://rapha.land/introducing-glyph-protocol-for-terminals/
terminal.Terminal.does_kitty_graphicsmethodCheck if the terminal supports the Kitty graphics protocol.
Check if the terminal supports the Kitty graphics protocol.
Sends a minimal Kitty graphics query and checks for an ``OK``
response. Supported by kitty and WezTerm.
.. seealso:: https://sw.kovidgoyal.net/kitty/graphics-protocol/
:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.get_iterm2_capabilitiesmethodQuery iTerm2 capabilities via OSC 1337;Capabilities.
Query iTerm2 capabilities via OSC 1337;Capabilities.
When :attr:`is_a_tty` is False, returns ``None``.
Responses are cached unless *force* is True.
.. seealso:: https://iterm2.com/documentation-escape-codes.html
:arg float timeout: Timeout in seconds for each sub-query. On the
first call, an additional CPR probe may be performed to enable
fast negative detection, so total elapsed time may exceed
*timeout* for terminals that do not respond.
:arg bool force: Bypass cached result.
:rtype: ITerm2Capabilities or None
terminal.Terminal.does_iterm2methodCheck if the terminal answers the ``OSC 1337`` capabilities report.
Check if the terminal supports the iTerm2 inline image protocol.
Draws a transparent image using iTerm2 protocol and detects for expected cursor position
advance. Uses two CPR requests, before and after, for fast negative detection.
.. seealso:: https://iterm2.com/documentation-images.html
:arg float timeout: Timeout in seconds for each cursor position query.
:arg bool force: Bypass cached result.
:rtype: bool
:returns: True when the cursor advanced a single column, False when the terminal is
1-column width or did not answer a cursor position report within timeout.
terminal.Terminal.does_kitty_notificationsmethodCheck if the terminal supports Kitty desktop notifications (OSC 99).
Check if the terminal supports Kitty desktop notifications (OSC 99).
Sends an OSC 99 query with a CPR boundary guard for fast negative
detection. Currently supported only by kitty.
.. seealso:: https://sw.kovidgoyal.net/kitty/desktop-notifications/
:arg float timeout: Timeout in seconds for each sub-query. On the
first call, an additional CPR probe may be performed to enable
fast negative detection, so total elapsed time may exceed
*timeout* for terminals that do not respond.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.does_kitty_clipboardmethodCheck if the terminal supports the Kitty clipboard protocol (mode 5522).
Query Kitty mouse pointer shape support (OSC 22).
Returns the current pointer shape name if supported, or ``None``
if the terminal does not respond. Uses a CPR boundary guard for
fast negative detection.
.. seealso:: https://sw.kovidgoyal.net/kitty/pointer-shapes/
:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: str or None
terminal.Terminal.does_osc52_clipboardmethodDetect OSC 52 clipboard support without reading the clipboard.
Detect OSC 52 clipboard support without reading the clipboard.
This method uses non-intrusive detection to avoid triggering user-facing clipboard
permission prompts, **DA1 extension 52** and **XTGETTCAP ``Ms``** fields. These methods are
preferred over sending an actual OSC 52 read request (``\x1b]52;c;?\a``), which may trigger
a clipboard permission dialog in many modern terminals.
:arg float timeout: Timeout in seconds for each sub-query.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.clipboard_copymethodCopy text to the system clipboard via OSC 52.
Copy text to the system clipboard via OSC 52.
Writes an OSC 52 set sequence to the terminal output stream.
Most modern terminals accept clipboard writes without any user
prompt.
The sequence is written unconditionally when :attr:`does_styling` is ``True``. If the
terminal does not support OSC 52, the sequence should be ignored by the terminal.
:arg str text: The text to copy to the clipboard.
:arg str selection: The X11 selection target -- ``'c'`` for
clipboard (default), ``'p'`` for primary selection, or
``'s'`` for secondary. Most terminals only honor ``'c'``.
terminal.Terminal.clipboard_pastemethodRead the system clipboard via OSC 52.
Read the system clipboard via OSC 52.
Sends an OSC 52 query (``\x1b]52;c;?\a``) and waits for the terminal to respond with the
clipboard contents.
.. warning::
Many modern terminals display a permission dialog when an application reads the
clipboard. The user must approve the dialog before the terminal sends a response.
The default timeout of 10 seconds allows time for human interaction. If the user denies
the dialog, or no response is received within given timeout, this method returns
``None``.
:arg float timeout: Timeout in seconds. A generous timeout is recommended because the user
may need to interact with a permission dialog.
:arg str selection: The X11 selection target -- ``'c'`` for clipboard (default),
``'p'`` for primary.
:rtype: str or None
:returns: The clipboard text, or ``None`` if denied or timeout is reached.
terminal.Terminal.get_color_schememethodQuery the terminal's color scheme preference (dark or light mode).
Query the terminal's color scheme preference (dark or light mode).
Sends a ``CSI ? 996 n`` Device Status Report query. Terminals that support color-scheme
reporting respond with ``CSI ? 997 ; Ps n`` where *Ps* is ``1`` for dark mode or ``2`` for
light mode. Uses a CPR boundary guard for fast negative detection.
This relates to Mode 2031 (``COLOR_PALETTE_UPDATES``) (not implemented).
.. seealso::
`Color palette update notifications
<https://contour-terminal.org/vt-extensions/color-palette-update-notifications/>`_
:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: str or None
:returns: ``'dark'``, ``'light'``, or ``None`` if unsupported.
terminal.Terminal.does_kitty_querymethodDetect Kitty with XTGETTCAP query extensions.
Detect Kitty with XTGETTCAP query extensions.
This is a trifle convenience wrapper of :meth:`get_xtgettcap()`.
This method probes for ``kitty-query-name`` support. A successful response indicates that
some set of Kitty query extensions are available.
To retrieve their values, follow up with :meth:`get_xtgettcap` directly, for example:
.. code-block:: python
>>> term = Terminal()
>>> term.does_kitty_query()
True
>>> term.get_xtgettcap(caps=[f"kitty-query-{key}" for key in [
"font_family", "font_size", "dpi_x", "dpi_y"]])
TermcapResponse(supported=True, capabilities={
'kitty-query-font_family': 'NotoSansMono-Regular',
'kitty-query-font_size': '19',
'kitty-query-dpi_x': '96',
'kitty-query-dpi_y': '96'})
:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.get_decrqssmethodQuery terminal state via DECRQSS (Request Status String).
Query terminal state via DECRQSS (Request Status String).
Sends ``DCS $ q <setting_id> ST`` and decodes the response.
Returns the parameter value string on success, with the echoed
setting identifier stripped. Returns ``None`` when the terminal
does not support DECRQSS or the setting is invalid.
Results are not cached -- DECRQSS queries runtime state that
may change between calls (cursor style, margins, SGR, etc.).
Use :class:`~hamingjur.Terminal.Decrqss` for setting
identifiers::
term = Terminal()
term.get_decrqss(term.Decrqss.DECSCUSR) # cursor style
term.get_decrqss(term.Decrqss.DECSTBM) # scroll region
.. seealso::
`DECRQSS specification
<https://vt100.net/docs/vt510-rm/DECRQSS.html>`_
The first query may also make an XTVERSION query, :meth:`get_software_version`,
to avoid a DECRQSS query to terminals with leaky output (Terminal.app).
:arg str setting_id: Setting identifier to query (default: SGR).
:arg float timeout: Timeout in seconds.
:rtype: str or None
terminal.Terminal.does_decrqssmethodDetect DECRQSS (Request Status String) support.
Detect DECRQSS (Request Status String) support.
Sends a ``DECRQSS`` query for the current SGR state. A valid
response indicates the terminal supports status string queries.
.. seealso::
`DECRQSS specification
<https://vt100.net/docs/vt510-rm/DECRQSS.html>`_
:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.does_styled_underlinesmethodDetect extended underline style support (curly, dotted, dashed).
Detect extended underline style support (curly, dotted, dashed).
Queries the terminal's ``Smulx`` terminfo capability via XTGETTCAP.
When supported, the terminal can render underline styles beyond the
standard single underline, such as ``CSI 4:3 m`` (curly).
:arg float timeout: Timeout in seconds for XTGETTCAP query.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.does_colored_underlinesmethodDetect colored underline support (``CSI 58;2;r;g;b m``).
Detect Kitty text sizing protocol support (OSC 66).
Tests width and scale text sizing by sending OSC 66 probes and
measuring cursor position delta. Supported terminals may write
up to 2 destructive spaces at the current cursor position, while
unsupported terminals typically produce no output.
Responses are cached unless *force* is True.
:arg float timeout: Timeout in seconds for each cursor position query.
:arg bool force: Bypass cached result.
:rtype: TextSizingResult
:returns: Result with ``.width`` and ``.scale`` boolean attributes.
terminal.Terminal.mouse_enabledcontext managerContext manager for enabling mouse tracking with various reporting modes.
Context manager for enabling bracketed paste mode.
When enabled, pasted text is wrapped with special escape sequences,
allowing applications to distinguish pasted content from typed input.
:arg float timeout: Timeout for mode query (default 1.0s)
Example::
with term.bracketed_paste():
inp = term.inkey()
if inp.name == 'BRACKETED_PASTE':
pasted_text = inp.text
print(f"You pasted: {pasted_text}")
terminal.Terminal.synchronized_outputcontext managerContext manager for enabling synchronized output mode.
Context manager for enabling synchronized output mode.
Buffers all terminal output until the context exits, eliminating screen flicker during
redraws. Perfect for animations and full-screen updates.
:arg float timeout: Timeout for mode query (default 1.0s)
terminal.Terminal.focus_eventscontext managerContext manager for enabling focus event reporting.
Context manager for enabling focus event reporting.
Reports when the terminal window gains or loses focus, useful for pausing animations or
updating status indicators.
:arg float timeout: Timeout for mode query (default 1.0s)
terminal.Terminal.notify_on_resizecontext managerReceive resize events through inline reports or a scoped SIGWINCH fallback.
Receive resize events through inline reports or a scoped SIGWINCH fallback.
When enabled, the terminal will automatically send resize events as in-band sequences
whenever the window size changes. These events are received by :meth:`inkey` as
keystroke events with :attr:`~.Keystroke.name` equal to ``'RESIZE_EVENT'``.
The new dimensions are automatically cached and available immediately through the
standard :attr:`height`, :attr:`width`, :attr:`pixel_height`, and :attr:`pixel_width`
properties without additional ioctl system calls.
When inline reporting is unavailable on Unix, a pipe wakes both inkey() and
async_inkey() on SIGWINCH and synthesizes the same RESIZE_EVENT. Enter the signal
fallback on the main thread. The previous signal handler is chained and restored.
:arg float timeout: Timeout for mode query (default 1.0s)
Example::
with term.notify_on_resize():
while True:
inp = term.inkey(timeout=0.1)
if inp.name == 'RESIZE_EVENT':
# Dimensions updated automatically
redraw_display(term.height, term.width)
elif inp == 'q':
break
Query sixel graphics pixel dimensions.
Returns the maximum height and width in pixels for sixel graphics
rendering. Detection order (from most to least reliable):
1. XTWINOPS 16t (CSI 16 t) - Character cell size, multiplied by rows/cols
2. XTWINOPS 14t (CSI 14 t) - Text area size in pixels
3. XTSMGRAPHICS - Sixel graphics query
4. TIOCSWINSZ / In-band resize - System ioctl / event pixel dimensions
The cell-based calculation (method 1) is preferred because it accounts
for the actual drawable text area, excluding window margins and
decorations.
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``(-1, -1)`` is returned without inquiry.
:arg float timeout: Timeout in seconds for queries
:arg bool force: Bypass cache and re-query the terminal
:rtype: tuple
:returns: ``(height, width)`` in pixels, or ``(-1, -1)`` if unsupported/timeout
terminal.Terminal.get_sixel_colorsmethodQuery number of sixel color registers (XTSMGRAPHICS).
hamingjur.terminal.Terminal.get_sixel_colors(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> int
Query number of sixel color registers (XTSMGRAPHICS).
Returns the maximum number of color registers available for sixel
graphics rendering. If XTSMGRAPHICS query fails but the terminal
advertises Sixel support via DA1 (Device Attributes), returns 256
as a sensible default.
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``-1`` is returned without inquiry.
:arg float timeout: Timeout in seconds for both possible queries
:arg bool force: Bypass cache and re-query the terminal
:rtype: int
:returns: Number of color registers, 256 if DA1 advertises sixel but
XTSMGRAPHICS fails, or ``-1`` if unsupported/timeout
terminal.Terminal.get_cell_height_and_widthmethodQuery character cell pixel dimensions (XTWINOPS).
Query character cell pixel dimensions (XTWINOPS).
Returns the height and width in pixels of a single character cell.
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``(-1, -1)`` is returned without inquiry.
:arg float timeout: Timeout in seconds for the query
:arg bool force: Bypass cache and re-query the terminal
:rtype: tuple
:returns: ``(height, width)`` in pixels, or ``(-1, -1)`` if unsupported/timeout
terminal.Terminal.invalidate_geometrymethodForget cached cell/window pixels after a resize, font change, or reconnection.
Query the current Kitty keyboard protocol flags.
Sends a Kitty keyboard protocol query to the terminal and returns a
:class:`KittyKeyboardProtocol` instance with the current flags. This
method is not normally used directly, rather it is used by the
:meth:`enable_kitty_keyboard` context manager on entrance to discover
and restore the previous state on exit.
When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``None`` is returned.
In many cases a ``timeout`` value (in seconds) should be set, as it is
possible for a terminal that succeeds :attr:`is_a_tty` to fail to respond
to either Kitty keyboard protocol state request, or the simple device
attribute request query carried with it! And not just "dumb" terminals
fail to respond, even some fairly modern terminals like Konsole.
If a Kitty keyboard protocol query fails to respond within the
``timeout`` specified, ``None`` is returned. If this was the first Kitty
keyboard protocol query, all subsequent queries return ``None`` unless
``force=True`` is set.
**No state caching is performed** - each call re-queries the terminal unless
the first query previously failed (sticky failure) and ``force=False``.
:arg float timeout: Timeout in seconds to await terminal response
:arg bool force: Force active terminal inquiry in all cases
:rtype: KittyKeyboardProtocol or None
:returns: KittyKeyboardProtocol instance with current flags, or None if unsupported/timeout
terminal.Terminal.enable_kitty_keyboardcontext managerContext manager that enables Kitty keyboard protocol features.
Context manager that enables Kitty keyboard protocol features.
:arg bool disambiguate: Enable disambiguated escape codes (fixes issues
with Esc vs sequences)
:arg bool report_events: Report key repeat and release events
:arg bool report_alternates: Report shifted and base layout keys for shortcuts
:arg bool report_all_keys: Report all keys as escape codes (including text keys)
:arg bool report_text: Report associated text with key events (requires report_all_keys)
:arg int mode: Protocol mode (1=set/clear specified flags, 2=set only, 3=clear only)
:arg float timeout: Timeout for querying current flags before setting new ones
:arg bool force: Force sequences to be emitted even if timeout previously occurred
Always queries current state before setting new flags and restores previous state on exit.
Example::
with term.enable_kitty_keyboard(disambiguate=True):
# Now Alt+C won't conflict with Ctrl+C
key = term.inkey()
if key.alt and key.is_alt('c'):
print("Alt+C pressed")
.. note:: A ``timeout`` value should be set to avoid blocking when the
terminal does not respond to DA1 or kitty protocol queries, which
may happen with some kinds of "dumb" terminals, even some modern
terminals like Konsole.
terminal.Terminal.fullscreencontext managerContext manager that switches to secondary screen, restoring on exit.
Context manager that switches to secondary screen, restoring on exit.
Under the hood, this switches between the primary screen buffer and
the secondary one. The primary one is saved on entry and restored on
exit. Likewise, the secondary contents are also stable and are
faithfully restored on the next entry::
with term.fullscreen():
main()
.. note:: There is only one primary and one secondary screen buffer.
:meth:`fullscreen` calls cannot be nested, only one should be
entered at a time.
terminal.Terminal.hidden_cursorcontext managerContext manager that hides the cursor, setting visibility on exit.
Context manager that hides the cursor, setting visibility on exit.
with term.hidden_cursor():
main()
.. note:: :meth:`hidden_cursor` calls cannot be nested: only one
should be entered at a time.
terminal.Terminal.cursor_shapecontext managerContext manager that sets cursor shape, restoring default on exit.
Context manager that sets cursor shape, restoring default on exit.
:arg style: A :class:`CursorShape` constant or string name
(e.g. ``'blinking_bar'``).
Uses DECSCUSR (DEC Set Cursor Style) escape sequences::
with term.cursor_shape(term.CursorShape.BLINKING_BAR):
main()
String names are also accepted::
with term.cursor_shape('steady_underline'):
main()
On exit, the cursor is reset to the terminal default (DECSCUSR 0).
.. note:: DECSCUSR is supported by most modern terminals including
xterm, VTE-based terminals, iTerm2, Windows Terminal, kitty,
ghostty, alacritty, and WezTerm.
terminal.Terminal.no_line_wrapcontext managerContext manager that disables line wrapping, enabling on exit.
Context manager that disables line wrapping, enabling on exit.
Uses DEC Auto Wrap Mode (DECAWM) to control whether text reaching the
right edge wraps to the next line::
with term.no_line_wrap():
print(term.move_x(0) + 'x' * 200) # Clips, doesn't wrap
On exit, line wrapping is unconditionally enabled as terminals should
prefer line-wrapping mode for normal operation.
.. note:: :meth:`no_line_wrap` calls cannot be nested: only one
should be entered at a time.
terminal.Terminal.scroll_regioncontext managerContext manager that sets a scrolling region, resetting on exit.
Context manager that sets a scrolling region, resetting on exit.
:arg int top: Top row of the scrolling region (0-indexed). Defaults to 0.
:arg int height: Number of rows in the scrolling region. Defaults to
``self.height - top`` (extending to the bottom of the screen).
:return: a context manager.
:rtype: Iterator
A scrolling region restricts scrolling to a portion of the screen. When text
scrolls within the region, content outside the region remains fixed. This is
useful for creating interfaces with fixed headers, footers, or status bars::
with term.fullscreen(), term.scroll_region(top=1, height=term.height - 2):
# row 0 and the last row remain fixed
# scrolling happens only in the middle region
for i in range(100):
print(f'Line {i}')
The cursor position may be reset to the home position when the scroll region
changes. Use :meth:`move_yx` to reposition as needed after entering the
context.
.. note:: :meth:`scroll_region` calls cannot be nested: only one
should be entered at a time.
terminal.Terminal.move_xymethodA callable string that moves the cursor to the given ``(x, y)`` screen coordinates.
A callable string that moves the cursor to the given ``(x, y)`` screen coordinates.
:arg int x: horizontal position, from left, *0*, to right edge of screen, *self.width - 1*.
:arg int y: vertical position, from top, *0*, to bottom of screen, *self.height - 1*.
:rtype: ParameterizingString
:returns: Callable string that moves the cursor to the given coordinates
terminal.Terminal.move_yxmethodA callable string that moves the cursor to the given ``(y, x)`` screen coordinates.
A callable string that moves the cursor to the given ``(y, x)`` screen coordinates.
:arg int y: vertical position, from top, *0*, to bottom of screen, *self.height - 1*.
:arg int x: horizontal position, from left, *0*, to right edge of screen, *self.width - 1*.
:rtype: ParameterizingString
:returns: Callable string that moves the cursor to the given coordinates
terminal.Terminal.move_leftpropertyMove cursor 1 cells to the left, or callable string for n>1 cells.
A callable string that sets the foreground color.
:rtype: ParameterizingString
The capability is unparameterized until called and passed a number, at which point it
returns another string which represents a specific color change. This second string can
further be called to color a piece of text and set everything back to normal afterward.
This should not be used directly, but rather a specific color by name or
:meth:`~.Terminal.color_rgb` value.
terminal.Terminal.color_rgbmethodProvides callable formatting string to set foreground color to the specified RGB color.
Provides callable formatting string to set foreground color to the specified RGB color.
:arg int red: 8-bit RGB value of Red (0-255).
:arg int green: 8-bit RGB value of Green (0-255).
:arg int blue: 8-bit RGB value of Blue (0-255).
:rtype: FormattingString
:returns: Callable string that sets the foreground color.
If the terminal does not support RGB color, the nearest supported
color will be determined using :py:attr:`color_distance_algorithm`.
terminal.Terminal.color_hexmethodProvides callable formatting string to set foreground color from hex.
Provides callable formatting string to set foreground color from hex.
:arg str hex_color: Hex color in ``#RGB``, ``#RRGGBB``, or ``#RRRRGGGGBBBB`` format.
The ``#`` prefix is optional.
:rtype: FormattingString
:returns: Callable string that sets the foreground color.
If the terminal does not support RGB color, the nearest supported
color will be determined using :py:attr:`color_distance_algorithm`.
See :func:`~hamingjur.colorspace.hex_to_rgb` for supported hex formats.
terminal.Terminal.on_colorpropertyA callable capability that sets the background color.
Provides callable formatting string to set background color to the specified RGB color.
:arg int red: 8-bit RGB value of Red (0-255).
:arg int green: 8-bit RGB value of Green (0-255).
:arg int blue: 8-bit RGB value of Blue (0-255).
:rtype: FormattingString
:returns: Callable string that sets the background color.
If the terminal does not support RGB color, the nearest supported
color will be determined using :py:attr:`color_distance_algorithm`.
terminal.Terminal.on_color_hexmethodProvides callable formatting string to set background color from hex.
Provides callable formatting string to set background color from hex.
:arg str hex_color: Hex color in ``#RGB``, ``#RRGGBB``, or ``#RRRRGGGGBBBB`` format.
The ``#`` prefix is optional.
:rtype: FormattingString
:returns: Callable string that sets the background color.
If the terminal does not support RGB color, the nearest supported
color will be determined using :py:attr:`color_distance_algorithm`.
See :func:`~hamingjur.colorspace.hex_to_rgb` for supported hex formats.
terminal.Terminal.formattermethodProvides callable formatting string to set color and other text formatting options.
Provides callable formatting string to set color and other text formatting options.
:arg str value: Sugary, ordinary, or compound formatted terminal capability,
such as "red_on_white", "normal", "red", or "bold_on_black".
:rtype: :class:`FormattingString` or :class:`NullCallableString`
:returns: Callable string that sets color and other text formatting options
Calling ``term.formatter('bold_on_red')`` is equivalent to ``term.bold_on_red``, but a
string that is not a valid text formatter will return a :class:`NullCallableString`.
This is intended to allow validation of text formatters without the possibility of
inadvertently returning another terminal capability.
terminal.Terminal.rgb_downconvertmethodTranslate an RGB color to a color code of the terminal's color depth.
hamingjur.terminal.Terminal.rgb_downconvert(red: int, green: int, blue: int) -> int
Translate an RGB color to a color code of the terminal's color depth.
This method is only be used to downconvert for terminals of 256 or fewer colors.
:arg int red: RGB value of Red (0-255).
:arg int green: RGB value of Green (0-255).
:arg int blue: RGB value of Blue (0-255).
:rtype: int
:returns: Color code of downconverted RGB color
terminal.Terminal.normalpropertyA capability that resets all video attributes.
A capability that resets all video attributes.
:rtype: str
``normal`` is an alias for ``sgr0`` or ``exit_attribute_mode``. Any
styling attributes previously applied, such as foreground or
background colors, reverse video, or bold are reset to defaults.
terminal.Terminal.linkmethodDisplay ``text`` that when touched or clicked, navigates to ``url``.
Display ``text`` that when touched or clicked, navigates to ``url``.
Optional ``url_id`` may be specified, so that non-adjacent cells can reference a single
target, all cells painted with the same "id" will highlight on hover, rather than any
individual one, as described in "Hovering and underlining the id parameter" of gist
https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda.
:param str url: Hyperlink URL.
:param str text: Clickable text.
:param str url_id: Optional 'id'.
:rtype: str
:returns: String of ``text`` as a hyperlink to ``url``.
:raises ValueError: If a URL or ID contains control characters or an ID contains delimiters.
terminal.Terminal.set_window_titlemethodReturn sequence to set the terminal title.
Return sequence to set the terminal title.
Uses xterm OSC (Operating System Command) sequences to set the
window and/or icon title.
:param str title: Title text. Any embedded escape or BEL characters
are stripped to prevent sequence injection.
:param int mode: OSC mode -- 0 sets both icon name and window title,
1 sets icon name only, 2 sets window title only.
:rtype: str
:returns: Escape sequence string that sets the terminal title,
or empty string when :attr:`does_styling` is ``False``.
terminal.Terminal.window_titlecontext managerContext manager that sets terminal title, restoring on exit.
Context manager that sets terminal title, restoring on exit.
Uses the xterm title stack (XTWINOPS push/pop) to save and
restore the previous title. Not all terminals support the title
stack -- those that do not will simply set the title without
restoring it on exit.
:param str title: Title text.
:param int mode: OSC mode -- 0 sets both icon name and window title,
1 sets icon name only, 2 sets window title only.
terminal.Terminal.progress_barmethodReturn OSC 9;4 sequence for terminal progress bar support.
Return OSC 9;4 sequence for terminal progress bar support.
Support for 'OSC 9;4' cannot be detected. It is generally safe to write to unsupported
terminals. Some terminals display a graphical progress indicator in the taskbar and window
menu or status bar matching the given value (0-100). Supported by at least Windows
Terminal.exe, ConEmu, Ghostty, kitty, and iTerm2.
:param state: Progress state. Accepts either an integer or a string name:
- ``0`` or ``'clear'``: Remove progress indicator
- ``1`` or ``'normal'``: Set progress to *value* (0 to 100)
- ``2`` or ``'error'``: Error state (typically red)
- ``3`` or ``'indeterminate'``: Indeterminate / pulsing
- ``4`` or ``'paused'``: Paused state (typically yellow)
:param int value: Progress value as integer of percent (0 to 100). Required when state is
``'normal'`` or ``1``. Terminals are expected to ignore 'value' for all other states.
:rtype: str
:returns: OSC 9;4 escape sequence, or ``''`` when :attr:`does_styling` is ``False``.
:raises ValueError: on bad ``state`` identifier or invalid or out of bounds ``value``.
.. seealso:: https://ghostty.org/docs/vt/osc/conemu#change-progress-state-(osc-94)
terminal.Terminal.streampropertyRead-only property: stream the terminal outputs to.
Read-only property: stream the terminal outputs to.
This is a convenience attribute. It is used internally for implied
writes performed by context managers :meth:`~.hidden_cursor`,
:meth:`~.fullscreen`, :meth:`~.location`, and :meth:`~.keypad`.
terminal.Terminal.number_of_colorspropertyNumber of colors supported by terminal.
hamingjur.terminal.Terminal.number_of_colors -> int
Number of colors supported by terminal.
Common return values are 0, 8, 16, 256, or 1 << 24.
This may be used to test whether the terminal supports colors, and at what depth, if that's
a concern.
If this property is assigned a value of 88, the value 16 will be saved. This is due to the
the rarity of 88 color support and the inconsistency of behavior between implementations.
Assigning this property to a value other than 0, 4, 8, 16, 88, 256, or 1 << 24 will raise an
:py:exc:`AssertionError`.
terminal.Terminal.color_distance_algorithmpropertyColor distance algorithm used by :meth:`rgb_downconvert`.
Color distance algorithm used by :meth:`rgb_downconvert`.
The slowest, but most accurate, 'cie2000', is default. Other available options are 'rgb',
'rgb-weighted', 'cie76', and 'cie94'. This function is only be used to downconvert for
terminals of 256 or fewer colors.
terminal.Terminal.ljustmethodLeft-align ``text``, which may contain terminal sequences.
Left-align ``text``, which may contain terminal sequences.
:arg str text: String to be aligned
:arg int width: Total width to fill with aligned text. If
unspecified, the whole width of the terminal is filled.
:arg str fillchar: String for padding the right of ``text``
:rtype: str
:returns: String of ``text``, left-aligned by ``width``.
terminal.Terminal.rjustmethodRight-align ``text``, which may contain terminal sequences.
Right-align ``text``, which may contain terminal sequences.
:arg str text: String to be aligned
:arg int width: Total width to fill with aligned text. If
unspecified, the whole width of the terminal is used.
:arg str fillchar: String for padding the left of ``text``
:rtype: str
:returns: String of ``text``, right-aligned by ``width``.
terminal.Terminal.centermethodCenter ``text``, which may contain terminal sequences.
Center ``text``, which may contain terminal sequences.
:arg str text: String to be centered
:arg int width: Total width in which to center text. If
unspecified, the whole width of the terminal is used.
:arg str fillchar: String for padding the left and right of ``text``
:rtype: str
:returns: String of ``text``, centered by ``width``
terminal.Terminal.text_sizedmethodWrap ``text`` in a text sizing escape sequence (OSC 66).
Wrap ``text`` in a text sizing escape sequence (OSC 66).
Returns ``text`` unchanged when the terminal does not support text sizing, providing
graceful degradation.
:arg str text: Text payload.
:arg int scale: Scale factor (1 to 7).
:arg int width: Width in cells (0 to 7). 0 means auto-calculate
from the inner text.
:arg int numerator: Fractional scaling numerator (0 to 15).
:arg int denominator: Fractional scaling denominator (0 to 15).
:arg vertical_align: Vertical alignment: ('top', 'bottom', 'center'), or protocol code
(0=top, 1=bottom, 2=center).
:arg horizontal_align: Horizontal alignment. ('left', 'right', 'center') or protocol code
(0=left, 1=right, 2=center).
:rtype: str
:returns: Text wrapped in an OSC 66 escape sequence, or plain
``text`` on unsupported terminals.
:raises ValueError: when the encoded ``text`` exceeds 4096 bytes.
:raises ValueError: when ``vertical_align`` or ``horizontal_align`` is an
unrecognized string value.
.. seealso:: `Kitty Text Sizing Protocol
<https://sw.kovidgoyal.net/kitty/text-sizing-protocol/>`_
.. note:: Because the first call to :meth:`Terminal.text_sized` will cause the side effect
of writing destructive spaces to the columns and row following the current cursor
position as required for detection of `kitty text sizing protocol`_, it is suggested
to first call :meth:`Terminal.does_text_sizing` during program initialization.
The result is permanently cached and all further calls to these methods return
immediately without this side effect.
terminal.Terminal.clipmethodReturn a window of ``text`` spanning display columns ``start`` to ``end``.
Return a window of ``text`` spanning display columns ``start`` to ``end``.
Terminal sequences are retained, wide characters split at a boundary are
replaced by ``fillchar``, and horizontal cursor movement is interpreted by
:func:`wcwidth.clip`. The detected :attr:`ambiguous_width` and
:attr:`term_program` are applied.
:arg str text: Text to clip, may contain terminal sequences
:arg int start: Absolute starting column, inclusive (default 0)
:arg int end: Absolute ending column, exclusive; -1 (default) means
"to the end of the line"
:arg \**kwargs: See :func:`wcwidth.clip`
:rtype: str
:returns: ``text`` clipped to display columns (start, end)
>>> term.clip('hello world', 6)
'world'
terminal.Terminal.truncatemethodTruncate ``text`` to ``width`` printable characters, retaining terminal sequences.
Truncate ``text`` to ``width`` printable characters, retaining terminal sequences.
Wide characters (such as CJK or emoji) that would partially exceed
``width`` are replaced with space padding to maintain exact width.
:arg str text: Text to truncate
:arg int width: The width to truncate to. If unspecified, the whole
width of the terminal is used.
:rtype: str
:returns: ``text`` truncated to exactly ``width`` printable characters
>>> term.truncate('xyz\x1b[0;3m', 2)
'xy\x1b[0;3m'
terminal.Terminal.lengthmethodReturn printable length of a string containing sequences.
hamingjur.terminal.Terminal.length(text: str) -> int
Return printable length of a string containing sequences.
Returns the maximum horizontal cursor extent reached while processing
the string. Backspace and cursor-left movements do not reduce the
length below the maximum position reached.
:arg str text: String to measure. May contain terminal sequences.
:rtype: int
:returns: The maximum terminal character cell position reached
Wide characters that consume 2 character cells are supported:
>>> term = Terminal()
>>> term.length(term.clear + term.red('コンニチハ'))
10
.. note:: Sequences such as 'clear', which is considered as a
"movement sequence" because it would move the cursor to
(y, x)(0, 0), are evaluated as a printable length of
*0*.
terminal.Terminal.stripmethodReturn ``text`` without sequences and leading or trailing whitespace.
Return ``text`` without sequences and leading or trailing whitespace.
:rtype: str
:returns: Text with leading and trailing whitespace removed
>>> term.strip(' \x1b[0;3m xyz ')
'xyz'
terminal.Terminal.rstripmethodReturn ``text`` without terminal sequences or trailing whitespace.
Return ``text`` without terminal sequences or leading whitespace.
:rtype: str
:returns: Text with terminal sequences and leading whitespace removed
>>> term.lstrip(' \x1b[0;3m xyz ')
'xyz '
terminal.Terminal.strip_seqsmethodReturn ``text`` stripped of only its terminal sequences.
Return ``text`` stripped of only its terminal sequences.
:rtype: str
:returns: Text with terminal sequences removed
>>> term.strip_seqs('\x1b[0;3mxyz')
'xyz'
>>> term.strip_seqs(term.cuf(5) + term.red('test'))
' test'
.. note:: Non-destructive sequences that adjust horizontal distance
(such as ``\b`` or ``term.cuf(5)``) are replaced by destructive
space or erasing.
terminal.Terminal.split_seqsmethodReturn ``text`` split by individual character elements and sequences.
Return ``text`` split by individual character elements and sequences.
:arg str text: String containing sequences
:arg int maxsplit: When maxsplit is nonzero, at most maxsplit splits
occur, and the remainder of the string is returned as the final element
of the list (same meaning is argument for :func:`re.split`).
:rtype: list[str]
:returns: List of sequences and individual characters
>>> term.split_seqs(term.underline('xyz'))
['\x1b[4m', 'x', 'y', 'z', '\x1b(B', '\x1b[m']
>>> term.split_seqs(term.underline('xyz'), 1)
['\x1b[4m', r'xyz\x1b(B\x1b[m']
terminal.Terminal.wrapmethodText-wrap a string, returning a list of wrapped lines.
Text-wrap a string, returning a list of wrapped lines.
:arg str text: Unlike :func:`textwrap.wrap`, ``text`` may contain
terminal sequences, such as colors, bold, or underline. By
default, tabs in ``text`` are expanded by
:func:`string.expandtabs`.
:arg int width: Unlike :func:`textwrap.wrap`, ``width`` will
default to the width of the attached terminal.
:arg \**kwargs: See :py:class:`textwrap.TextWrapper`
:rtype: list
:returns: List of wrapped lines
:raises ValueError: for non-positive values of ``width``.
See :class:`textwrap.TextWrapper` for keyword arguments that can
customize wrapping behaviour.
terminal.Terminal.getchmethodRead, decode, and return the next byte from the keyboard stream.
Read, decode, and return the next byte from the keyboard stream.
:arg bool decode_latin1: If True, decode byte as latin-1 (for legacy mouse
sequences with 8-bit coordinates).
:rtype: unicode
:returns: a single unicode character, or ``''`` if a multi-byte
sequence has not yet been fully received.
:raises EOFError: When the keyboard stream has reached end-of-file.
This method name and behavior mimics curses ``getch(void)``, and
it supports :meth:`inkey`, reading only one byte from
the keyboard string at a time. This method should always return
without blocking if called after :meth:`kbhit` has returned True.
Implementers of alternate input stream methods should override
this method.
terminal.Terminal.ungetchmethodBuffer input data to be discovered by next call to :meth:`~.inkey`.
Return whether a keypress has been detected on the keyboard.
This method is used by :meth:`inkey` to determine if a byte may
be read using :meth:`getch` without blocking. The standard
implementation simply uses the :func:`select.select` call on stdin.
:arg float timeout: When ``timeout`` is 0, this call is
non-blocking, otherwise blocking indefinitely until keypress
is detected when None (default). When ``timeout`` is a
positive number, returns after ``timeout`` seconds have
elapsed (float).
:rtype: bool
:returns: True if a keypress is awaiting to be read on the keyboard
attached to this terminal. When input is not a terminal, False is
always returned.
terminal.Terminal.cbreakcontext managerAllow each keystroke to be read immediately after it is pressed.
Allow each keystroke to be read immediately after it is pressed.
This is a context manager for :func:`tty.setcbreak`.
This context manager activates 'rare' mode, the opposite of 'cooked'
mode: On entry, :func:`tty.setcbreak` mode is activated disabling
line-buffering of keyboard input and turning off automatic echo of
input as output.
.. note:: You must explicitly print any user input you would like
displayed. If you provide any kind of editing, you must handle
backspace and other line-editing control functions in this mode
as well!
**Normally**, characters received from the keyboard cannot be read
by Python until the *Return* key is pressed. Also known as *cooked* or
*canonical input* mode, it allows the tty driver to provide
line-editing before shuttling the input to your program and is the
(implicit) default terminal mode set by most unix shells before
executing programs.
Technically, this context manager sets the :mod:`termios` attributes
of the terminal attached to :obj:`sys.__stdin__`.
.. note:: :func:`tty.setcbreak` sets ``VMIN = 1`` and ``VTIME = 0``,
see http://www.unixwiz.net/techtips/termios-vmin-vtime.html
terminal.Terminal.rawcontext managerA context manager for :func:`tty.setraw`.
A context manager for :func:`tty.setraw`.
Although both :meth:`cbreak` and :meth:`raw` modes allow each keystroke
to be read immediately after it is pressed, Raw mode disables
processing of input and output by the terminal driver.
In cbreak mode, special input characters such as ``^C`` or ``^S`` are
interpreted by the terminal driver and excluded from the stdin stream.
In raw mode these values are received by the :meth:`inkey` method.
Because output processing is not done by the terminal driver, the
newline ``'\n'`` is not enough, you must also print carriage return to
ensure that the cursor is returned to the first column::
with term.raw():
print("printing in raw mode", end="\r\n")
terminal.Terminal.keypadcontext managerContext manager that enables directional keypad input.
Context manager that enables directional keypad input.
On entry, this puts the terminal into "keyboard_transmit" mode by
emitting the keypad_xmit (smkx) capability. On exit, it emits
keypad_local (rmkx).
On an IBM-PC keyboard with numeric keypad of terminal-type *xterm*,
with numlock off, the lower-left diagonal key transmits sequence
``\\x1b[F``, translated to :class:`~.Terminal` attribute
``KEY_END``.
However, upon entering :meth:`keypad`, ``\\x1b[OF`` is transmitted,
translating to ``KEY_LL`` (lower-left key), allowing you to determine
diagonal direction keys.
terminal.Terminal.flushinpmethodUnbuffer and return all input available within ``timeout``.
Unbuffer and return all input available within ``timeout``.
When legacy mouse sequence ``'\x1b[M'`` is detected in input stream,
all remaining bytes are decoded as latin1 to handle 8-bit coordinates.
terminal.Terminal.inkeymethodRead and return the next keyboard event within given timeout.
Read and return the next keyboard event within given timeout.
Generally, this should be used inside the :meth:`raw` or :meth:`cbreak` context manager.
:arg float timeout: Number of seconds to wait for a keystroke before
returning. When ``None`` (default), this method may block
indefinitely.
:arg float esc_delay: Time in seconds to block after Escape key
is received to await another key sequence beginning with
escape such as *KEY_LEFT*, sequence ``'\x1b[D'``, before returning a
:class:`~.Keystroke` instance for ``KEY_ESCAPE``.
Users may override the default value of ``esc_delay`` in seconds,
using environment value of ``ESCDELAY`` as milliseconds, see
`ncurses(3)`_ section labeled *ESCDELAY* for details. Setting
the value as an argument to this function will override any
such preference.
:arg bool capture_cpr: Prefer matches of ``CPR_RESPONSE`` over conflicting vt220 Legacy
function keys (eg. ``KEY_F3``, ``KEY_SHIFT_F3``).
:rtype: :class:`~.Keystroke`.
:returns: :class:`~.Keystroke`, which may be empty (``''``) if
``timeout`` is specified and keystroke is not received.
.. note:: When used without the context manager :meth:`cbreak`, or
:meth:`raw`, :obj:`sys.__stdin__` remains line-buffered, and this
function will block until the return key is pressed!
.. note:: On Windows, a 10 ms sleep is added to the key press detection loop to reduce CPU
load. Due to the behavior of :py:func:`time.sleep` on Windows, this will actually
result in a 15.6 ms delay when using the default `time resolution
<https://docs.microsoft.com/en-us/windows/win32/api/timeapi/nf-timeapi-timebeginperiod>`_.
Decreasing the time resolution will reduce this to 10 ms, while increasing it, which
is rarely done, will have a perceptable impact on the behavior.
_`ncurses(3)`: https://www.man7.org/linux/man-pages/man3/ncurses.3x.html
terminal.Terminal.async_inkeymethodAsynchronous version of :meth:`inkey` for use with :mod:`asyncio`.
Asynchronous version of :meth:`inkey` for use with :mod:`asyncio`.
Read and return the next keyboard event within given timeout, yielding
control to the asyncio event loop while waiting for input rather than
blocking the thread.
Uses :meth:`asyncio.AbstractEventLoop.add_reader` on the keyboard file
descriptor, reusing the same :func:`~.resolve_sequence`, keymap, and
:class:`~.Keystroke` internals as the synchronous :meth:`inkey`.
Must be called within a :meth:`cbreak` or :meth:`raw` context, just
like :meth:`inkey`.
:arg float timeout: Number of seconds to wait for a keystroke before
returning. When ``None`` (default), this method may block
indefinitely.
:arg float esc_delay: Time in seconds to wait after Escape key
is received to disambiguate bare Escape from escape sequences.
:arg bool capture_cpr: Prefer matches of ``CPR_RESPONSE`` over conflicting vt220 Legacy
function keys (eg. ``KEY_F3``, ``KEY_SHIFT_F3``).
:rtype: :class:`~.Keystroke`
:returns: :class:`~.Keystroke`, which may be empty (``''``) if
``timeout`` is specified and keystroke is not received.
terminal.WINSZclassStructure represents return value of :const:`termios.TIOCGWINSZ`.
Encode all graphics actions and transports, streaming direct payloads.
Keys use the protocol's spelling. This supports raster formats 24/32/100, Silkie
packed grayscale (1/2/4/8), RGB565 (16), HDR (64) and vectors (200),
animation frames (a=f), vector patches (a=e), and services (a=v). For t=f/t=t/t=s/t=g, data
names a resource already owned by the caller; this function never allocates or deletes
operating-system resources.
:raises ValueError: If arguments or protocol data are invalid.
graphics.imagefunctionTransmit an image; all formats except PNG require dimensions.
Transmit an image; all formats except PNG require dimensions.
Grayscale formats 1/2/4/8 pack pixels most-significant first, padding each row
to a byte boundary. Format 16 is little-endian RGB565. Data is already packed;
no quantization or conversion is performed. Source formats do not depend on
the display's color model or precision.
:raises ValueError: If arguments or protocol data are invalid.
graphics.placefunctionPlace a stored image; supports cropping, offsets, z-order and relative placements.
Build any vector record, including groups, paths, symbols, ink and gradients.
Sequence values become comma-separated lists. Use text_record() for text; path data must already
use the protocol's whitespace-free SVG syntax.
:raises ValueError: If arguments or protocol data are invalid.
graphics.text_recordfunctionEncode shaped/styled vector text with arbitrary Unicode and layout properties.
Decode a vector service reply, raising ValueError for terminal errors.
:raises ValueError: If the terminal reports an error or the result is malformed.
graphics.placeholderfunctionYield Unicode placeholder rows for a virtual placement (a=p,U=1).
Discover formats and probe local file/SHM access on this connection.
Successful negotiation is cached; force=True refreshes after reconnection.
GPU support is advertised only: gpu_surface() still requires an external descriptor.
A remote connection cannot gain a local transport merely by advertising it.
:raises OSError: If resource allocation fails beyond permission/platform refusal.
graphics.Graphics.transfersmethodReturn usable enum-valued image transfers, probing actual local resource access.
Fit a PIL image to pixels or cells and choose its smallest cheap lossless payload.
With no target, fit the current viewport. Resizes invalidate cell geometry;
display reports update precision. The source image remains available for redraw.
:raises ValueError: If pixel and cell units are mixed.
:raises RuntimeError: If graphics support or required pixel geometry is unavailable.
graphics.Graphics.drawmethodDraw a PIL image, choosing packing, compression and a negotiated transfer.
Draw a PIL image, choosing packing, compression and a negotiated transfer.
x/y are zero-based cell coordinates; omit both to use the cursor. Local resources
survive until acknowledgement and are cleaned on failures. A timeout raises rather
than silently redrawing. Returns None without styling; requires hamingjur[images].
:raises ValueError: If geometry, prepared formats or requested transfers are invalid.
graphics.Graphics.adaptivecontext managerTrack window and display changes during an input loop, restoring reporting on exit.
Fit a PIL image without upscaling, then compare cheap lossless encodings.
Display matching is the only color reduction; set match_display=False to keep
source precision. Alpha is retained. PNG palettes, packed grayscale, RGB565,
raw RGB/RGBA and fast zlib are compared where accepted, without JPEG or dithering.
The original image is never modified. Pillow is required only for this API.
:raises TypeError: If source is not a PIL image.
:raises ValueError: If no accepted format represents the resulting pixels losslessly.
imaging.image_resourcecontext managerOwn a local resource until its query/upload is acknowledged, including error cleanup.
Own a local resource until its query/upload is acknowledged, including error cleanup.
:raises ValueError: If the transfer does not use a local file or SHM allocation.
hamingjur.silkie25 entries
Silkie discovery, tablet/touch input, gestures, ink, haptics, fonts and timing.
silkie.TabletModeclassTablet reporting bits; unsupported or refused bits are read back as off.
Set stereo text depth and/or vertical phase, or reset both with no arguments.
Pixel depth uses reference pixels at 1920 pixels per eye; phase uses physical
pixels. Omitted attributes are preserved. The terminal applies user limits.
:raises ValueError: If depth forms conflict or values exceed their wire representation.
silkie.agent_requestfunctionEncode one SSH-agent request; expires is an absolute Unix millisecond deadline.
The selector versions, graphics media and formats advertised by a terminal.
Constructor
-----------
Parse a capability report, retaining its original fields.
silkie.Capabilities.supportsmethodCheck the advertised version of a selector, not its current hardware support.
One OSC 777 selector, with commands, queries and restoring mode contexts.
Constructor
-----------
Bind a selector to the shared client and query transport.
silkie.Channel.commandmethodReturn a sequence without performing I/O.
Set a reporting mode, yield granted bits, and restore its previous value.
Raises RuntimeError when the mode cannot be read. Nested contexts restore the enclosing
mode. Cleanup runs even if read-back or application code fails.
:raises RuntimeError: If the mode is unavailable or read-back times out.
silkie.AgentChannelclassExplicit SSH-agent packet transport; no sockets, key caching or automatic retries.
Exchange one complete packet, matching ID, connection and provider generation.
Keep connection and generation stable for a local agent connection, probe before
each packet, and close on generation changes or timeouts. Requests are never retried.
A transport failure is returned as an agent failure packet plus an error field.
silkie.AgentChannel.closemethodClose a pinned provider connection; its token must never be reused.
Bound Silkie protocol client, available as ``term.silkie``.
Every selector has a named channel. Commands use documented field names,
including device descriptions/labels, brush configuration and haptic patterns.
Received messages are available through ``term.inkey().protocol_event``.
Constructor
-----------
Create channels and per-terminal discovery state.
silkie.Silkie.channelmethodAccess a future selector without waiting for a library update.
hamingjur.protocols.integer(value: int, name: str, minimum: int=0, maximum: Optional[int]=None) -> int
Validate an integer, with upper bounds only where the protocol requires them.
:raises ValueError: If the value is not an integer in the protocol range.
protocols.tokenfunctionValidate a protocol selector or field name without restricting its length.
Validate a protocol selector or field name without restricting its length.
:raises ValueError: If the name contains characters outside the protocol alphabet.
protocols.safefunctionValidate an ASCII field so it cannot inject another field or escape sequence.
Validate an ASCII field so it cannot inject another field or escape sequence.
:raises ValueError: If a field contains control characters or delimiters.
protocols.encode_fieldsfunctionEncode fields, retaining insertion order and unknown extension keys.
Decode an OSC 99 return route, ordered from application to outer terminal.
:raises ValueError: If a hop has invalid components, delimiters or a window ID.
protocols.ProtocolEventclassA complete terminal message, preserving all fields and its wire representation.
Encode a file-transfer command using descriptive field names.
Handles all commands and transports, including rsync signature/delta bytes. Applications own the
transfer state, filesystem decisions and rsync algorithm. No local files are opened as a side
effect of receiving a terminal message.
:raises TypeError: If a payload has the wrong type.
:raises ValueError: If arguments or protocol data are invalid.
kitty.file_datafunctionStream one file/signature/delta, ending with end_data (no total-size cap).
A unicode-derived class for describing a single "keystroke".
A class instance describes a single keystroke received on input, which may
contain multiple characters as a multibyte sequence, which is indicated by
properties :attr:`is_sequence` returning ``True``. Note that keystrokes may
also represent mouse input, bracketed paste, or focus in/out events
depending on enabled terminal modes.
The string :attr:`name` of the sequence is used to identify in code logic,
such as ``'KEY_LEFT'`` to represent a common and human-readable form of
the Keystroke this class instance represents.
keyboard.Keystroke.protocol_eventpropertyStructured Kitty/Silkie message, or None for ordinary keyboard/mouse input.
Special application key name.
This is the best equality attribute to use for special keys, as raw string value of the 'F1'
key can be received in many different values.
The 'name' property will return a reliable constant, eg. ``'KEY_F1'``.
The name supports "modifiers", such as ``'KEY_CTRL_F1'``,
``'KEY_CTRL_ALT_F1'``, ``'KEY_CTRL_ALT_SHIFT_F1'``
When using a keyboard protocol with event reporting, names include an
event-type suffix: ``'KEY_CTRL_J_REPEATED'`` for repeat and
``'KEY_CTRL_J_RELEASED'`` for release events. Press events have no
suffix. See :attr:`key_name` for the same name without the suffix.
For mouse events, the name includes the ``'MOUSE_'`` prefix followed by the
button/action name, such as ``'MOUSE_LEFT'``, ``'MOUSE_MOTION'``,
``'MOUSE_RIGHT_MOTION'``, ``'MOUSE_LEFT_RELEASED'``.
For other DEC events:
- Focus events: 'FOCUS_IN' or 'FOCUS_OUT'
- Bracketed paste: 'BRACKETED_PASTE'
- Resize events: 'RESIZE_EVENT'
For terminal query responses:
- Cursor position report: 'CPR_RESPONSE' (row >= 2 only;
row 1 is ambiguous with F3+modifier)
When non-None, all phrases begin with either 'KEY', 'MOUSE', 'FOCUS_IN', 'FOCUS_OUT',
'BRACKETED_PASTE', or 'RESIZE_EVENT', with one exception: 'CSI' is returned for '\\x1b['
in legacy (non-kitty-protocol) mode to indicate the beginning of a presumed unsupported
input sequence. In kitty keyboard protocol mode, the '[' key uses the name
'KEY_LEFT_SQUARE_BRACKET' (with modifier and event-type suffixes as appropriate).
If this value is None, then it can probably be assumed that the value is an unsurprising
textual character without any modifiers, like the letter ``'a'``.
keyboard.Keystroke.key_namepropertyKey identity without event-type suffix.
Key identity without event-type suffix.
Like :attr:`name`, but without ``_RELEASED`` and ``_REPEATED``
suffixes, so that press, repeat, and release events for the same
key all return the same value. Useful for key-map lookups when
tracking press/release pairs.
:rtype: str or None
keyboard.Keystroke.codepropertyLegacy curses-alike keycode value (int).
Whether this keystroke uses a special keyboard protocol mode.
Returns True for Kitty, ModifyOtherKeys, or LegacyCSIModifier protocols, which use negative
mode values (SpecialInternalKitty=-1, SpecialInternalModifyOtherKeys=-2,
SpecialInternalLegacyCSIModifier=-3).
:rtype: bool
:returns: True if using special keyboard protocol mode
keyboard.Keystroke.pressedpropertyWhether this is a key press event.
Whether this is a key press event.
:rtype: bool
:returns: True if this is a key press event (event_type=1 or not specified), False for
repeat or release events
keyboard.Keystroke.repeatedpropertyWhether this is a key repeat event.
Character for this key, even for release events.
Like :attr:`value`, but does not suppress the character for
release events. For press and repeat events, identical to
:attr:`value`.
:rtype: str
keyboard.Keystroke.modepropertyDEC Private Mode associated with this keystroke, if any.
DEC Private Mode associated with this keystroke, if any.
:rtype: hamingjur.dec_modes.DecPrivateMode or None
:returns: The :class:`~hamingjur.dec_modes.DecPrivateMode` enum value
associated with this keystroke, or ``None`` if this is not a DEC mode event.
.. note:: Mode names beginning SpecialInternal with negative values (-1,
-2, -3) are used to track how some kinds of application keys are
matched.
keyboard.Keystroke.mouse_yxpropertyMouse position as (y, x) tuple for mouse events.
Mouse position as (y, x) tuple for mouse events.
This is particularly useful with terminal movement functions:
``term.move_yx(*keystroke.mouse_yx)``
:rtype: tuple of (int, int)
:returns: (y, x) coordinate tuple (0-indexed) for mouse events,
or ``(-1, -1)`` if not a mouse event
keyboard.Keystroke.mouse_xypropertyMouse position as (x, y) tuple for mouse events.
Mouse position as (x, y) tuple for mouse events.
:rtype: tuple of (int, int)
:returns: (x, y) coordinate tuple (0-indexed) for mouse events,
or ``(-1, -1)`` if not a mouse event
keyboard.Keystroke.cpr_yxpropertyCursor position as (y, x) tuple for Cursor Position Report.
Cursor position as (y, x) tuple for Cursor Position Report.
:rtype: tuple of (int, int)
:returns: (y, x) coordinate tuple (0-indexed) for cursor position report,
or ``(-1, -1)`` if not a CPR_RESPONSE
keyboard.Keystroke.cpr_xypropertyCursor position as (x, y) tuple for Cursor Position Report.
Cursor position as (x, y) tuple for Cursor Position Report.
:rtype: tuple of (int, int)
:returns: (x, y) coordinate tuple (0-indexed) for cursor position report,
or ``(-1, -1)`` if not a CPR_RESPONSE
keyboard.Keystroke.xtgettcappropertyCapabilities reported by an XTGETTCAP response.
Pasted text for bracketed paste events.
:rtype: str or None
:returns: The pasted text for ``BRACKETED_PASTE`` events,
or ``None`` if not a bracketed paste event
keyboard.get_curses_keycodesfunctionReturn mapping of curses key-names paired by their keycode integer value.
Return mapping of curses key-names paired by their keycode integer value.
:rtype: dict
:returns: Dictionary of (name, code) pairs for curses keyboard constant
values and their mnemonic name. Such as code ``260``, with the value of
its key-name identity, ``'KEY_LEFT'``.
keyboard.get_keyboard_codesfunctionReturn mapping of keycode integer values paired by their curses key name.
Return mapping of keycode integer values paired by their curses key name.
:rtype: dict
:returns: Dictionary of (code, name) pairs for curses keyboard constant
values and their mnemonic name. Such as key ``260``, with the value of
its identity, ``'KEY_LEFT'``.
These keys are derived from the attributes by the same of the curses(jinxed) module,
with the following exceptions:
* ``KEY_DELETE`` in place of ``KEY_DC``
* ``KEY_INSERT`` in place of ``KEY_IC``
* ``KEY_PGUP`` in place of ``KEY_PPAGE``
* ``KEY_PGDOWN`` in place of ``KEY_NPAGE``
* ``KEY_ESCAPE`` in place of ``KEY_EXIT``
* ``KEY_SUP`` in place of ``KEY_SR``
* ``KEY_SDOWN`` in place of ``KEY_SF``
This function is the inverse of :func:`get_curses_keycodes`. With the
given override "mixins" listed above, the keycode for the delete key will
map to our imaginary ``KEY_DELETE`` mnemonic, effectively erasing the
phrase ``KEY_DC`` from our code vocabulary for anyone that wishes to use
the return value to determine the key-name by keycode.
keyboard.get_keyboard_sequencesfunctionReturn mapping of keyboard sequences paired by keycodes.
Return mapping of keyboard sequences paired by keycodes.
:arg hamingjur.Terminal term: :class:`~.Terminal` instance.
:returns: mapping of keyboard unicode sequences paired by keycodes
as integer. This is used as the argument ``mapper`` to
the supporting function :func:`resolve_sequence`.
:rtype: OrderedDict
Initialize and return a keyboard map and sequence lookup table,
(sequence, keycode) from :class:`~.Terminal` instance ``term``,
where ``sequence`` is a multibyte input sequence of unicode
characters, such as ``'\x1b[D'``, and ``keycode`` is an integer
value, matching curses constant such as term.KEY_LEFT.
The return value is an OrderedDict instance, with their keys
sorted longest-first.
keyboard.get_leading_prefixesfunctionReturn a set of proper prefixes for given sequence of strings.
Return a set of proper prefixes for given sequence of strings.
:arg iterable sequences
:rtype: set
:return: Set of all string prefixes
Given an iterable of strings, all textparts leading up to the final
string is returned as a unique set. This function supports the
:meth:`~.Terminal.inkey` method by determining whether the given
input is a sequence that **may** lead to a final matching pattern.
>>> prefixes(['abc', 'abdf', 'e', 'jkl'])
set(['a', 'ab', 'abd', 'j', 'jk'])
keyboard.resolve_sequencefunctionReturn a single :class:`Keystroke` instance for given sequence ``text``.
Return a single :class:`Keystroke` instance for given sequence ``text``.
:arg str text: string of characters received from terminal input stream.
:arg OrderedDict mapper: unicode multibyte sequences, such as ``'\x1b[D'``
paired by their integer value (260)
:arg dict codes: a :type:`dict` of integer values (such as 260) paired
by their mnemonic name, such as ``'KEY_LEFT'``.
:arg set prefixes: Set of all valid sequence prefixes for quick matching
:arg bool final: Whether this is the final resolution attempt (no more input expected)
:arg dict dec_mode_cache: Dictionary of DEC private mode states (mode number -> state value)
:arg bool capture_cpr: Prefer matches of ``CPR_RESPONSE`` over conflicting vt220 Legacy
function keys (eg. ``KEY_F3``, ``KEY_SHIFT_F3``).
:rtype: Keystroke
:returns: Keystroke instance for the given sequence
The given ``text`` may extend beyond a matching sequence, such as
``u\x1b[Dxxx`` returns a :class:`Keystroke` instance of attribute
:attr:`Keystroke.sequence` valued only ``u\x1b[D``. It is up to
calls to determine that ``xxx`` remains unresolved.
In an ideal world, we could detect and resolve only for key sequences
expected in the current terminal mode. For example, only the enabling of
mode 1036 (META_SENDS_ESC) would match for 2-character ESC+char sequences.
But terminals are unpredictable, the popular terminal "Konsole" does
not negotiate about any DEC Private modes but transmits metaSendsEscape
anyway, so exhaustive match is performed in all cases.
keyboard.DeviceAttributeclassRepresents a terminal's Device Attributes (DA1) response.
Represents a terminal's Device Attributes (DA1) response.
Device Attributes queries allow discovering terminal capabilities and type.
The primary DA1 query sends CSI c and expects a response like::
CSI ? Psc ; Ps1 ; Ps2 ; ... ; Psn c
Where Psc is the service class (architectural class) and Ps1...Psn are
supported extensions/capabilities.
Constructor
-----------
Initialize DeviceAttribute instance.
:arg str raw: Original response string from terminal
:arg int service_class: Service class number (first parameter)
:arg list extensions: List of extension numbers (remaining parameters)
Whether the terminal advertises OSC 52 clipboard support.
Extension 52 in DA1 indicates the terminal supports writing to the system clipboard via the
OSC 52 protocol.
:rtype: bool
:returns: True if extension 52 is present in device attributes
keyboard.DeviceAttribute.from_matchmethodCreate DeviceAttribute from regex match object.
Create DeviceAttribute from regex match object.
:arg re.Match match: Regex match object with groups for service_class and extensions
:rtype: DeviceAttribute
:returns: DeviceAttribute instance parsed from match
keyboard.SoftwareVersionclassRepresents a terminal's software name and version from XTVERSION response.
Represents a terminal's software name and version from XTVERSION response.
Constructor
-----------
Initialize SoftwareVersion instance.
:arg str raw: Original response string from terminal
:arg str name: Software name (e.g., "kitty", "XTerm")
:arg str version: Version string (e.g., "0.24.2", "367") or empty string if no version
Create SoftwareVersion from regex match object.
:arg re.Match match: Regex match object with group for software text
:rtype: SoftwareVersion
:returns: SoftwareVersion instance parsed from match
Represents Kitty keyboard protocol flags.
Encapsulates the integer flag value returned by Kitty keyboard protocol queries and provides
properties for individual flag bits and a method to convert back to enable_kitty_keyboard()
arguments.
Constructor
-----------
Initialize with raw integer flag value.
:arg int value: Raw integer flags value from Kitty keyboard protocol query
keyboard.KittyKeyboardProtocol.disambiguatepropertyWhether disambiguated escape codes are enabled (bit 1).
Return dictionary of arguments suitable for enable_kitty_keyboard().
:rtype: dict
:returns: Dictionary with boolean flags suitable for passing as keyword arguments to
enable_kitty_keyboard()
hamingjur.mouse5 entries
Sub-module providing mouse event handling.
mouse.MouseEventclassMouse event with button, coordinates, and modifier information.
Mouse event with button, coordinates, and modifier information.
A unified mouse event structure that supports both legacy and SGR mouse protocols. Provides a
dynamic button property that returns human-readable button names like "LEFT", "SCROLL_UP",
"CTRL_LEFT", etc.
:ivar int button_value: Raw button number with modifiers stripped (0=left, 1=middle, 2=right,
3=none, 64=scroll up, 65=scroll down, 66-67 for buttons 6-7, and 128-131 for buttons 8-11).
:ivar int x: Horizontal position (0-indexed, in cells or pixels depending on mode).
:ivar int y: Vertical position (0-indexed, in cells or pixels depending on mode).
:ivar bool released: True if this is a button release event.
:ivar bool shift: True if Shift modifier is pressed.
:ivar bool meta: True if Meta/Alt modifier is pressed.
:ivar bool ctrl: True if Ctrl modifier is pressed.
:ivar bool is_motion: True if motion is being reported (drag or all- motion mode).
:ivar bool is_wheel: True if this is a scroll wheel event.
Constructor
-----------
Initialize a MouseEvent.
:param int button_value: Raw button number.
:param int x: Horizontal position.
:param int y: Vertical position.
:param bool released: Whether this is a button release event.
:param bool shift: Whether Shift modifier is pressed.
:param bool meta: Whether Meta/Alt modifier is pressed.
:param bool ctrl: Whether Ctrl modifier is pressed.
:param bool is_motion: Whether motion is being reported.
:param bool is_wheel: Whether this is a scroll wheel event.
mouse.MouseEvent.is_leavepropertyKitty SGR pixel mouse-leave event; coordinates and buttons must be ignored.
Return human-readable button name.
Generates button names that include modifiers, button type, motion/release state:
- "LEFT", "MIDDLE", "RIGHT" for standard mouse buttons
- "LEFT_RELEASED", "MIDDLE_RELEASED", "RIGHT_RELEASED" for button releases
- "RELEASED" for a legacy release, which does not report which button was released
- "SCROLL_UP", "SCROLL_DOWN" for wheel events
- "MOTION" for mouse movement with no button pressed
- "LEFT_MOTION", "MIDDLE_MOTION", "RIGHT_MOTION" for drag events
- "CTRL_LEFT", "SHIFT_SCROLL_UP", "CTRL_SHIFT_META_MOTION" with modifiers
- "BUTTON_6" through "BUTTON_11" for extended mouse buttons
:rtype: str
:returns: Button name with modifiers, button type, and motion/release state.
mouse.MouseEvent.from_sgr_matchmethodParse SGR mouse event from regex match.
Parse SGR mouse event from regex match.
Handles both SGR (mode 1006) and SGR-Pixels (mode 1016) since they
use identical wire formats: CSI < b;x;y m/M. The difference is semantic:
- Mode 1006: coordinates represent character cell positions
- Mode 1016: coordinates represent pixel positions
Applications must interpret x,y coordinates based on which mode was enabled.
The protocol sends 1-indexed coordinates (top-left is 1,1), but we convert
to 0-indexed (top-left is 0,0) to match hamingjur's terminal movement functions.
:param Match match: Regex match object with groups 'b', 'x', 'y', 'type'.
:rtype: MouseEvent
:returns: Parsed MouseEvent instance.
mouse.MouseEvent.from_legacy_matchmethodParse legacy mouse event (X10/1000/1002/1003) from regex match.
Parse legacy mouse event (X10/1000/1002/1003) from regex match.
The protocol sends 1-indexed coordinates (top-left is 1,1), but we convert to 0-indexed
(top-left is 0,0) to match hamingjur's terminal movement functions.
Each coordinate is transmitted as a single byte of ``value + 32``, so no position beyond
223 can be expressed. Windows Terminal and the console host (``conhost.exe``) share a VT
input layer that *discards* any legacy mouse event where either coordinate exceeds 95,
rather than transmit a byte above 127. Both are limitations of the terminal without
workaround, the SGR protocol is the only remedy.
:param Match match: Regex match object with groups 'cb', 'cx', 'cy'.
:rtype: MouseEvent
:returns: Parsed MouseEvent instance.
hamingjur.line_editor20 entries
Headless line editor with history, auto-suggest, and grapheme-aware editing.
This module provides :class:`LineEditor` for single-line input with readline-style
editing and :class:`LineHistory` for command recall.
line_editor.LineEditResultclassResult of processing a keystroke.
In-memory command history with navigation and prefix search.
:param max_entries: Optional maximum history size; None retains all entries.
Constructor
-----------
Initialize history, with an optional caller-selected retention limit.
line_editor.LineHistory.addmethodAppend *line* to history, skipping empty and consecutive duplicates.
Headless single-line editor with grapheme-aware cursor movement.
Feed keystrokes via :meth:`feed_key`, read display state via
:attr:`display`. Accepts hamingjur :class:`~.Keystroke` objects
directly (dispatching on ``.name``), or plain strings for testing.
Custom keymap handlers must be callables accepting a single
:class:`LineEditor` argument and returning a :class:`LineEditResult`::
def my_handler(editor: LineEditor) -> LineEditResult:
...
Constructor
-----------
Initialize editor with optional history, display, and keymap settings.
line_editor.LineEditor.historypropertyReturn the attached :class:`LineHistory` instance.
Fast-path render for a single grapheme inserted at end of buffer.
:param term: Hamingjur :class:`~.Terminal` instance.
:param row: Terminal row for the input line.
:param grapheme: The grapheme cluster just inserted.
:returns: Escape-sequence string, or ``None`` if a full redraw is needed.
line_editor.LineEditor.render_backspacemethodFast-path render after a backspace at end of buffer.
Fast-path render after a backspace at end of buffer.
:param term: Hamingjur :class:`~.Terminal` instance.
:param row: Terminal row for the input line.
:returns: Escape-sequence string, or ``None`` if a full redraw is needed.
line_editor.LineEditor.feed_keymethodProcess one keystroke and return a :class:`LineEditResult`.
Encode an XTWINOPS operation, retaining omitted parameters and zero values.
This includes queries, resize/move requests, stacking, fullscreen/maximize, and title-stack
operations. Support and permission are terminal-dependent.
:raises ValueError: If an operation or parameter is not a nonnegative integer.
window.resizefunctionRequest a text area size in cells or pixels, leaving omitted dimensions unchanged.
Request a text area size in cells or pixels, leaving omitted dimensions unchanged.
Zero requests the screen's corresponding dimension. Kitty/Silkie reject these standard resize
requests; their OS windows require opt-in remote control.
:raises ValueError: If units are mixed, no size is supplied, or values are invalid.
window.WindowclassTerminal window queries and explicit requests, available as ``term.window``.
Terminal window queries and explicit requests, available as ``term.window``.
Constructor
-----------
Bind to the terminal's stream and input-preserving query transport.
window.Window.sendmethodSend an XTWINOPS command; it does not imply that the request was granted.
Encode any remote-control command, including async and streaming envelope fields.
The terminal must permit remote control. Password authentication requires an externally
encrypted envelope passed to packet(); plaintext passwords are rejected.
:raises ValueError: If command/envelope fields are invalid or include a plaintext password.
remote_control.responsefunctionDecode a complete response and return its data, preserving terminal errors.
hamingjur.remote_control.response(frame: str) -> Any
Decode a complete response and return its data, preserving terminal errors.
:raises ValueError: If the response is malformed.
:raises RemoteControlError: If the terminal rejects or fails the request.
remote_control.RemoteControlclassExplicit remote-control client; construction never connects or changes settings.
Explicit remote-control client; construction never connects or changes settings.
Use term.remote_control for the current terminal, or RemoteControl(address=...)
for an explicitly configured Unix/TCP listener. Calls must be serialized when
sharing a terminal: ordinary synchronous replies have no correlation ID.
Constructor
-----------
Choose a terminal or socket transport, without reading environment addresses.
:raises ValueError: If neither or both transports are specified.
remote_control.RemoteControl.callmethodSend an explicit command and return its data; no subprocess is invoked.
Send an explicit command and return its data; no subprocess is invoked.
:raises RuntimeError: If terminal output is disabled.
:raises TimeoutError: If no complete reply arrives within the deadline.
:raises RemoteControlError: If the terminal reports failure or refusal.
remote_control.RemoteControl.resize_windowmethodResize the calling OS window, or an explicitly matched window, in cells or pixels.
Resize the calling OS window, or an explicitly matched window, in cells or pixels.
Zero leaves a dimension unchanged. Incremental sizes may be negative. Successful
acknowledgement is not a guarantee that the window manager used the requested size.
:raises ValueError: If units/dimensions are invalid or no size is specified.
hamingjur.control4 entries
ECMA-48 control-sequence encoders for terminal operations and future protocols.
control.csifunctionEncode a CSI instruction with numeric/subparameters, private and intermediate bytes.
Encode a CSI instruction with numeric/subparameters, private and intermediate bytes.
None preserves an omitted parameter. Strings allow colon-separated subparameters, such as SGR
underline styles. No arbitrary parameter-count or string-size limit applies.
:raises ValueError: If fields do not follow ECMA-48 CSI grammar.
control.oscfunctionEncode an OSC string, including Unicode, without allowing control injection.
Encode OSC 133 prompt (A), input (B), output (C), or command completion (D).
Optional protocol fields are preserved. A prompt marker can reset Silkie input modes;
applications using those modes should enable them after marking their prompt.
:raises ValueError: If marker fields contain delimiters or status is misplaced.
shell.ShellclassExplicit shell integration output, available as ``term.shell``.
Convert standard RGB color to XYZ color.
D65/2° standard illuminant.
:arg int red: RGB value of Red.
:arg int green: RGB value of Green.
:arg int blue: RGB value of Blue.
:returns: Tuple (X, Y, Z) representing XYZ color
:rtype: tuple
color.xyz_to_labfunctionConvert XYZ color to CIE-Lab color.
Convert XYZ color to CIE-Lab color.
:arg float x_val: XYZ value of X.
:arg float y_val: XYZ value of Y.
:arg float z_val: XYZ value of Z.
:returns: Tuple (L, a, b) representing CIE-Lab color
:rtype: tuple D65/2° standard illuminant
color.rgb_to_labfunctionConvert RGB color to CIE-Lab color.
Convert RGB color to CIE-Lab color.
:arg int red: RGB value of Red.
:arg int green: RGB value of Green.
:arg int blue: RGB value of Blue.
:returns: Tuple (L, a, b) representing CIE-Lab color
:rtype: tuple D65/2° standard illuminant
color.dist_rgbfunctionDetermine distance between two rgb colors.
Determine distance between two rgb colors.
:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float
This works by treating RGB colors as coordinates in three dimensional
space and finding the closest point within the configured color range
using the formula::
d^2 = (r2 - r1)^2 + (g2 - g1)^2 + (b2 - b1)^2
For efficiency, the square of the distance is returned
which is sufficient for comparisons
color.dist_rgb_weightedfunctionDetermine the weighted distance between two rgb colors.
Determine the weighted distance between two rgb colors.
:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float Similar to a standard distance formula, the values are weighted to approximate
human perception of color differences For efficiency, the square of the distance is returned
which is sufficient for comparisons
color.dist_cie76functionDetermine distance between two rgb colors using the CIE76 algorithm.
Determine distance between two rgb colors using the CIE76 algorithm.
:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float For efficiency, the square of the distance is returned which is sufficient for
comparisons
color.dist_cie94functionDetermine distance between two rgb colors using the CIE94 algorithm.
Determine distance between two rgb colors using the CIE94 algorithm.
:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float For efficiency, the square of the distance is returned which is sufficient for
comparisons
color.dist_cie2000functionDetermine distance between two rgb colors using the CIE2000 algorithm.
Determine distance between two rgb colors using the CIE2000 algorithm.
:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float For efficiency, the square of the distance is returned which is sufficient for
comparisons
color.xterm256color_from_rgbfunctionConvert RGB values to xterm 256-color cube index and RGB approximation.
Convert RGB values to xterm 256-color cube index and RGB approximation.
Uses the 6x6x6 color cube (indices 16-231) with levels [0,95,135,175,215,255].
:arg int red: RGB value of Red (0-255).
:arg int green: RGB value of Green (0-255).
:arg int blue: RGB value of Blue (0-255).
:returns: Tuple (cube_index, (r, g, b)) representing the xterm cube index and RGB approximation
:rtype: tuple
color.xterm256gray_from_rgbfunctionConvert RGB values to xterm 256-color grayscale index and RGB approximation.
Convert RGB values to xterm 256-color grayscale index and RGB approximation.
Uses the 24 grayscale entries (indices 232-255) with values 8+10*i.
:arg int red: RGB value of Red (0-255).
:arg int green: RGB value of Green (0-255).
:arg int blue: RGB value of Blue (0-255).
:returns: Tuple (gray_index, (r, g, b)) representing the xterm gray index and RGB approximation
:rtype: tuple
Convert hex color to RGB tuple.
:arg str hex_color: Hex color string. Accepts 3-digit (``#RGB``), 6-digit
(``#RRGGBB``), or 12-digit (``#RRRRGGGGBBBB``, 16-bit per channel,
converted to 8-bit). The ``#`` prefix is optional.
:returns: Tuple (r, g, b) with 8-bit values (0-255).
:raises ValueError: If hex_color is not a valid hex color string.
colorspace.rgb_to_hexfunctionConvert RGB values to hex color string.
Convert RGB values to hex color string.
:arg int red: Red component (0-255).
:arg int green: Green component (0-255).
:arg int blue: Blue component (0-255).
:arg bool maybe_short: If True, return ``#RGB`` when possible.
Shortening is only possible when each component has repeating hex digits
(e.g., ``0xaa`` -> ``a``).
:returns: Hex color string in ``#RRGGBB`` format (or ``#RGB`` if maybe_short).
colorspace.xparse_colorfunctionScale a hex color component to 16-bit or 8-bit per XParseColor specification.
hamingjur.colorspace.xparse_color(hex_component: str, bits: int=16) -> int
Scale a hex color component to 16-bit or 8-bit per XParseColor specification.
XParseColor is the X11 color parsing standard used by terminals when responding
to OSC 10/11 color queries. Each color component in the ``rgb:R/G/B`` response
can be 1-4 hex digits, representing 4-bit to 16-bit precision.
XParseColor uses **scaling** (bit replication) to expand shorter values to
16-bit. This differs from HTML/CSS shorthand which uses digit doubling:
- XParseColor ``rgb:`` format (scaling): ``f`` -> ``ffff``, ``0f`` -> ``0f0f``
- HTML/CSS shorthand (doubling): ``#f`` -> ``#ff``, ``#0f`` -> ``#0f``
Scaling examples:
- 1 hex digit (4-bit): ``f`` -> ``ffff`` (15 -> 65535)
- 2 hex digits (8-bit): ``e5`` -> ``e5e5`` (229 -> 58853)
- 3 hex digits (12-bit): ``abc`` -> ``abca`` (2748 -> 43978)
- 4 hex digits (16-bit): ``e5e5`` -> ``e5e5`` (unchanged)
:arg str hex_component: A single hex color component (1-4 hex digits).
:arg int bits: Output precision: 16 (default, 0-65535) or 8 (0-255).
:returns: Scaled integer value at the requested bit depth.
:raises ValueError: If hex_component length is not 1-4 or bits is invalid.
hamingjur.cursor_shape2 entries
Module providing DECSCUSR cursor shape support.
cursor_shape.CursorShapeclassDECSCUSR (DEC Set Cursor Style) cursor shape constants.
DECSCUSR (DEC Set Cursor Style) cursor shape constants.
Each constant corresponds to a cursor style parameter (0-6) used in
the DECSCUSR escape sequence ``CSI Ps SP q``.
Usage with the :meth:`~.Terminal.cursor_shape` context manager::
with term.cursor_shape(term.CursorShape.BLINKING_BAR):
# cursor is a blinking bar
main()
# cursor is restored to terminal default
String names are also accepted::
with term.cursor_shape('blinking_bar'):
main()
Available shapes:
====================== ===== ============================
Constant Value Description
====================== ===== ============================
``DEFAULT`` 0 Reset to terminal default
``BLINKING_BLOCK`` 1 Blinking block cursor
``STEADY_BLOCK`` 2 Steady (non-blinking) block
``BLINKING_UNDERLINE`` 3 Blinking underline cursor
``STEADY_UNDERLINE`` 4 Steady underline cursor
``BLINKING_BAR`` 5 Blinking bar (line) cursor
``STEADY_BAR`` 6 Steady bar (line) cursor
===================== ===== ============================
hamingjur.cursor_shape.CursorShape.sequence(style: int | str) -> str
Return the DECSCUSR escape sequence for the given cursor style.
:arg style: An integer constant (0-6) or a string name (e.g. ``'blinking_bar'``).
:returns: The escape sequence string.
:raises ValueError: If *style* is not a valid cursor shape.
hamingjur.dec_modes14 entries
Class definitions for DEC Private Modes and their Response values.
dec_modes.DecModeResponseclassContainer for DEC Private Mode query response.
Container for DEC Private Mode query response.
Use helper properties :attr:`~DecModeResponse.supported`,
:attr:`~DecModeResponse.enabled`, :attr:`~DecModeResponse.permanent`,
and :attr:`~DecModeResponse.failed` to interpret responses rather than
checking numeric values directly.
Constructor
-----------
Initialize response for a DEC private mode query.
:param mode: DEC private mode number
:type mode: int
:param value: Response value from terminal
:type value: int
:raises TypeError: If mode is not an integer
Numeric response value for compatibility.
Prefer using helper properties like :attr:`~DecModeResponse.enabled`
instead of checking this value directly.
:rtype: int
dec_modes.DecModeResponse.recognizedpropertyCheck if the terminal recognizes this mode.
Check if the terminal recognizes this mode.
True for any DECRPM response value > 0 (SET, RESET, PERMANENTLY_SET, or PERMANENTLY_RESET).
This indicates the terminal knows about the mode, but does not guarantee the application can
use or control it.
:rtype: bool
:returns: True if terminal acknowledges this mode
dec_modes.DecModeResponse.supportedpropertyCheck if the mode is supported and usable by the terminal.
Check if the mode is supported and usable by the terminal.
True for values SET (1), RESET (2), and PERMANENTLY_SET (3). PERMANENTLY_RESET (4) is
excluded: the terminal acknowledges the mode but it is permanently off and cannot be
enabled, so it is not usable by applications. See also xterm patch #395 and the Contour
synchronized-output spec which both treat value 4 as effectively unsupported.
:rtype: bool
:returns: True if mode is usable (changeable or permanently enabled)
dec_modes.DecModeResponse.enabledpropertyCheck if the mode is currently enabled.
Return response as a dictionary.
:rtype: dict
:returns: Dictionary with keys ``value``, ``value_description``,
``mode_description``, ``mode_name``, ``supported``, ``enabled``,
and ``changeable``.
dec_modes.DecPrivateModeclassDEC Private Mode with mnemonic name and description.
DEC Private Mode with mnemonic name and description.
Each instance provides:
- :attr:`~DecPrivateMode.value`: Numeric private mode identifier
- :attr:`~DecPrivateMode.name`: Mnemonic name or "UNKNOWN" for unrecognized modes
- :attr:`~DecPrivateMode.long_description`: Full description of mode functionality
Constructor
-----------
Initialize DEC Private Mode with numeric identifier.
:param value: Numeric DEC private mode identifier
:type value: int
A Unicode string which can be called as a parameterizing termcap.
For example::
>>> from hamingjur import Terminal
>>> term = Terminal()
>>> color = ParameterizingString(term.color, term.normal, 'color')
>>> color(9)('color #9')
'\x1b[91mcolor #9\x1b(B\x1b[m'
formatters.ParameterizingString.__call__methodReturning :class:`FormattingString` instance for given parameters.
Returning :class:`FormattingString` instance for given parameters.
Return evaluated terminal capability (self), receiving arguments
``*args``, followed by the terminating sequence (self.normal) into
a :class:`FormattingString` capable of being called.
:raises TypeError: Mismatch between capability and arguments
:raises jinxed.error: :func:`jinxed.tparm` raised an exception
:rtype: :class:`FormattingString` or :class:`NullCallableString`
:returns: Callable string for given parameters
formatters.ParameterizingProxyStringclassA Unicode string which can be called to proxy missing termcap entries.
A Unicode string which can be called to proxy missing termcap entries.
.. deprecated 1.40::
All previously-proxied terminfo(5) capabilities are now provided directly by the capability
database in jinxed. This class is unused by hamingjur but kept for API compatibility.
This class mirrors the behavior of :class:`ParameterizingString`, except that instead of a
capability name, receives a format string, and callable to filter the given positional ``*args``
of :meth:`ParameterizingProxyString.__call__` into a terminal sequence.
For example::
>>> from hamingjur import Terminal
>>> term = Terminal('screen')
>>> hpa = ParameterizingString(term.hpa, term.normal, 'hpa')
>>> hpa(9)
''
>>> fmt = '\x1b[{0}G'
>>> fmt_arg = lambda *arg: (arg[0] + 1,)
>>> hpa = ParameterizingProxyString((fmt, fmt_arg), term.normal, 'hpa')
>>> hpa(9)
'\x1b[10G'
formatters.ParameterizingProxyString.__call__methodReturning :class:`FormattingString` instance for given parameters.
Returning :class:`FormattingString` instance for given parameters.
Arguments are determined by the capability. For example, ``hpa``
(move_x) receives only a single integer, whereas ``cup`` (move)
receives two integers. See documentation in terminfo(5) for the
given capability.
:rtype: FormattingString
:returns: Callable string for given parameters
formatters.FormattingStringclassA Unicode string which doubles as a callable.
A Unicode string which doubles as a callable.
This is used for terminal attributes, so that it may be used both
directly, or as a callable. When used directly, it simply emits
the given terminal sequence. When used as a callable, it wraps the
given (string) argument with the 2nd argument used by the class
constructor::
>>> from hamingjur import Terminal
>>> term = Terminal()
>>> style = FormattingString(term.bright_blue, term.normal)
>>> print(repr(style))
'\x1b[94m'
>>> style('Big Blue')
'\x1b[94mBig Blue\x1b(B\x1b[m'
formatters.FormattingString.__call__methodReturn ``text`` joined by ``sequence`` and ``normal``.
Return ``text`` joined by ``sequence`` and ``normal``.
:raises TypeError: Not a string type
:rtype: str
:returns: Arguments wrapped in sequence and normal
formatters.FormattingOtherStringclassA Unicode string which doubles as a callable for another sequence when called.
A Unicode string which doubles as a callable for another sequence when called.
This is used for the :meth:`~.Terminal.move_up`, ``down``, ``left``, and ``right()``
family of functions::
>>> from hamingjur import Terminal
>>> term = Terminal()
>>> move_right = FormattingOtherString(term.cuf1, term.cuf)
>>> print(repr(move_right))
'\x1b[C'
>>> print(repr(move_right(666)))
'\x1b[666C'
>>> print(repr(move_right()))
'\x1b[C'
formatters.FormattingOtherString.__call__methodReturn ``text`` by ``target``.
A dummy callable Unicode alternative to :class:`FormattingString`.
This is used for colors on terminals that do not support colors, it is just a basic form of
unicode that may also act as a callable.
formatters.NullCallableString.__call__methodAllow empty string to be callable, returning given string, if any.
Allow empty string to be callable, returning given string, if any.
When called with an int as the first arg, return an empty Unicode. An int is a good hint
that I am a :class:`ParameterizingString`, as there are only about half a dozen string-
returning capabilities listed in terminfo(5) which accept non-int arguments, they are seldom
used.
When called with a non-int as the first arg (no no args at all), return the first arg,
acting in place of :class:`FormattingString` without any attributes.
formatters.get_proxy_stringfunctionProxy and return callable string for proxied attributes.
Proxy and return callable string for proxied attributes.
.. deprecated 1.40::
All previously-proxied terminfo(5) capabilities are now provided directly by the capability
database in jinxed as "patches" in
https://github.com/Rockhopper-Technologies/jinxed/blob/main/terminals.toml.
This function always returns ``None``.
formatters.split_compoundfunctionSplit compound formatting string into segments.
Split compound formatting string into segments.
>>> split_compound('bold_underline_bright_blue_on_red')
['bold', 'underline', 'bright_blue', 'on_red']
:arg str compound: a string that may contain compounds, separated by
underline (``_``).
:rtype: list
:returns: List of formatting string segments
formatters.resolve_capabilityfunctionResolve a raw terminal capability using :func:`tigetstr`.
Resolve a raw terminal capability using :func:`tigetstr`.
:arg Terminal term: :class:`~.Terminal` instance.
:arg str attr: terminal capability name.
:returns: string of the given terminal capability named by ``attr``,
which may be empty ('') if not found or not supported by the
given :attr:`~.Terminal.kind`.
:rtype: str
formatters.resolve_colorfunctionResolve a simple color name to a callable capability.
Resolve a simple color name to a callable capability.
This function supports :func:`resolve_attribute`.
:arg Terminal term: :class:`~.Terminal` instance.
:arg str color: any string found in set :const:`COLORS`.
:returns: a string class instance which emits the terminal sequence
for the given color, and may be used as a callable to wrap the
given string with such sequence.
:returns: :class:`NullCallableString` when
:attr:`~.Terminal.number_of_colors` is 0,
otherwise :class:`FormattingString`.
:rtype: :class:`NullCallableString` or :class:`FormattingString`
formatters.resolve_attributefunctionResolve a terminal attribute name into a capability class.
Resolve a terminal attribute name into a capability class.
:arg Terminal term: :class:`~.Terminal` instance.
:arg str attr: Sugary, ordinary, or compound formatted terminal
capability, such as "red_on_white", "normal", "red", or
"bold_on_black".
:returns: a string class instance which emits the terminal sequence
for the given terminal capability, or may be used as a callable to
wrap the given string with such sequence.
:returns: :class:`NullCallableString` when
:attr:`~.Terminal.number_of_colors` is 0,
otherwise :class:`FormattingString`.
:rtype: :class:`NullCallableString` or :class:`FormattingString`
hamingjur.sequences20 entries
Module providing 'sequence awareness'.
sequences.TermcapclassTerminal capability of given variable name and pattern.
Terminal capability of given variable name and pattern.
Constructor
-----------
Class initializer.
:arg str name: name describing capability.
:arg str pattern: regular expression string.
:arg str attribute: :class:`~.Terminal` attribute used to build
this terminal capability.
:arg int nparams: number of positional arguments for callable.
sequences.Termcap.named_patternpropertyRegular expression pattern for capability with named group.
hamingjur.sequences.Termcap.horizontal_distance(text: str) -> int
Horizontal carriage adjusted by capability, may be negative.
:rtype: int
:arg str text: for capabilities *parm_left_cursor*, *parm_right_cursor*, provide the
matching sequence text, its interpreted distance is returned.
:returns: 0 except for matching '
:raises ValueError: ``text`` does not match regex for capability
sequences.Termcap.buildmethodClass factory builder for given capability definition.
Class factory builder for given capability definition.
:arg str name: Variable name given for this pattern.
:arg str capability: A unicode string representing a terminal
capability to build for. When ``nparams`` is non-zero, it
must be a callable unicode string, such as the result from
``getattr(term, 'bold')``.
:arg str attribute: The terminfo(5) capability name by which this
pattern is known.
:arg int nparams: number of positional arguments for callable.
:arg int numeric: Value to substitute into capability to when generating pattern
:arg bool match_grouped: If the numeric pattern should be
grouped, ``(\d+)`` when ``True``, ``\d+`` default.
:arg bool match_any: When keyword argument ``nparams`` is given,
*any* numeric found in output is suitable for building as
pattern ``(\d+)``. Otherwise, only the first matching value of
range *(numeric - 1)* through *(numeric + 1)* will be replaced by
pattern ``(\d+)`` in builder.
:arg bool match_optional: When ``True``, building of numeric patterns
containing ``(\d+)`` will be built as optional, ``(\d+)?``.
:rtype: hamingjur.sequences.Termcap
:returns: Terminal capability instance for given capability definition
sequences.SequenceclassA "sequence-aware" version of the base :class:`str` class.
A "sequence-aware" version of the base :class:`str` class.
This unicode-derived class understands the effect of escape sequences
of printable length, allowing a properly implemented :meth:`rjust`,
:meth:`ljust`, :meth:`center`, and :meth:`length`.
.. note:: that other than :meth:`Sequence.padd`, this is just a thin layer
over :mod:`wcwidth`, kept by name for API compatibility.
Return string containing sequences, left-adjusted.
:arg int width: Total width given to left-adjust ``text``.
:arg str fillchar: String for padding right-of ``text``.
:returns: String of ``text``, left-aligned by ``width``.
:rtype: str
Return string containing sequences, right-adjusted.
:arg int width: Total width given to right-adjust ``text``.
:arg str fillchar: String for padding left-of ``text``.
:returns: String of ``text``, right-aligned by ``width``.
:rtype: str
Return string containing sequences, centered.
:arg int width: Total width given to center ``text``.
:arg str fillchar: String for padding left and right-of ``text``.
:returns: String of ``text``, centered by ``width``.
:rtype: str
sequences.Sequence.clipmethodReturn a window of this string spanning display columns ``start`` to ``end``.
Return a window of this string spanning display columns ``start`` to ``end``.
Like :meth:`~.Terminal.clip`, which documents the arguments. Cursor movement
is interpreted by :func:`wcwidth.clip`, and the terminal's detected
``ambiguous_width`` and ``term_program`` are applied.
:rtype: str
:returns: This string clipped to display columns (start, end)
sequences.Sequence.truncatemethodTruncate a string in a sequence-aware manner.
Truncate a string in a sequence-aware manner.
Any printable characters beyond ``width`` are removed, while all
sequences remain in place. Horizontal cursor movement is interpreted
by :func:`wcwidth.clip`.
Wide characters (such as CJK or emoji) that would partially exceed
``width`` are replaced with space padding to maintain exact width.
SGR (terminal styling) sequences are propagated: the result begins
with any active style at the start position and ends with a reset
sequence if styles were active.
:arg int width: The printable width to truncate the string to.
:rtype: str
:returns: String truncated to exactly ``width`` printable characters.
sequences.Sequence.lengthmethodReturn the printable length of string containing sequences.
Return the printable length of string containing sequences.
Returns the maximum horizontal cursor extent reached while processing
the string. Backspace and cursor-left movements do not reduce the
length below the maximum position reached.
Some characters may consume more than one cell, mainly CJK (Chinese,
Japanese, Korean) and Emojis and some kinds of symbols.
For example:
>>> from hamingjur import Terminal
>>> from hamingjur.sequences import Sequence
>>> term = Terminal()
>>> msg = term.clear + term.red('コンニチハ')
>>> Sequence(msg, term).length()
10
.. note:: Although accounted for, strings containing sequences such
as ``term.clear`` will not give accurate returns, it is not
considered lengthy (a length of 0).
sequences.Sequence.stripmethodReturn string of sequences, leading and trailing whitespace removed.
Return string of sequences, leading and trailing whitespace removed.
:arg str chars: Remove characters in chars instead of whitespace.
:rtype: str
:returns: string of sequences with leading and trailing whitespace removed.
sequences.Sequence.lstripmethodReturn string of all sequences and leading whitespace removed.
Return string of all sequences and leading whitespace removed.
:arg str chars: Remove characters in chars instead of whitespace.
:rtype: str
:returns: string of sequences with leading removed.
sequences.Sequence.rstripmethodReturn string of all sequences and trailing whitespace removed.
Return string of all sequences and trailing whitespace removed.
:arg str chars: Remove characters in chars instead of whitespace.
:rtype: str
:returns: string of sequences with trailing removed.
sequences.Sequence.strip_seqsmethodReturn ``text`` stripped of only its terminal sequences.
Return non-destructive horizontal movement as destructive spacing.
:arg bool strip: Strip terminal sequences
:rtype: str
:returns: Text adjusted for horizontal movement
sequences.iter_parsefunctionGenerator yields (text, capability) for characters of ``text``.
Generator yields (text, capability) for characters of ``text``.
value for ``capability`` may be ``None``, where ``text`` is
:class:`str` of length 1. Otherwise, ``text`` is a full
matching sequence of given capability.
.. note:: Previously used by SequenceTextWrapper, sequence-aware text
wrapping now exists in wcwidth as :func:`wcwidth.wrap`. This function
is kept for API compatibility and used by :func:`measure_length`.
sequences.measure_lengthfunctionKept for API compatibility.
Read, decode, and return the next byte from the keyboard stream.
:arg bool decode_latin1: If True, decode byte as latin-1 (for legacy mouse
sequences with 8-bit coordinates).
:rtype: unicode
:returns: a single unicode character, or ``''`` if a multi-byte
sequence has not yet been fully received.
For versions of Windows 10.0.10586 and later, the console is expected
to be in ENABLE_VIRTUAL_TERMINAL_INPUT mode and the default method is
called.
For older versions of Windows, msvcrt.getwch() is used. If the received
character is ``\x00`` or ``\xe0``, the next character is
automatically retrieved.
When native console events (mouse, resize) have been synthesized
into escape sequences, buffered characters are returned first.
win_terminal.Terminal.kbhitmethodReturn whether a keypress has been detected on the keyboard.
Return whether a keypress has been detected on the keyboard.
This method is used by :meth:`inkey` to determine if a byte may
be read using :meth:`getch` without blocking.
Uses :class:`jinxed.win32.ConsoleInput` for efficient, non-polling
input detection. Non-key-down events (key-up releases, resize)
are consumed so they do not cause spurious returns.
When native event handling is enabled, ``MOUSE_EVENT`` and
``WINDOW_BUFFER_SIZE_EVENT`` records are converted to escape
sequences and buffered for :meth:`getch`.
:arg float timeout: When ``timeout`` is 0, this call is
non-blocking, otherwise blocking indefinitely until keypress
is detected when None (default). When ``timeout`` is a
positive number, returns after ``timeout`` seconds have
elapsed (float).
:rtype: bool
:returns: True if a keypress is awaiting to be read on the keyboard
attached to this terminal within the given ``timeout``.
win_terminal.Terminal.mouse_enabledcontext managerContext manager for enabling mouse tracking.
Context manager for enabling mouse tracking.
Probes the terminal for DEC private mode support (SGR mouse,
mode 1006). If supported, delegates to the base class so that
escape-sequence-based mouse tracking is used natively.
Otherwise, falls back to enabling ``ENABLE_MOUSE_INPUT`` on
the console handle and converting native ``MOUSE_EVENT``
records into SGR escape sequences so that :meth:`inkey`
returns standard :class:`~.Keystroke` objects with
``MOUSE_*`` names.
Accepts the same keyword arguments as
:meth:`~hamingjur.terminal.Terminal.mouse_enabled`.
win_terminal.Terminal.does_mousemethodCheck if the terminal supports mouse tracking.
Check if the terminal supports mouse tracking.
Returns ``True`` on Windows when connected to a real console
with styling enabled. The terminal may support DEC private
modes for mouse (probed at enable time), but the native
console API is always available as a fallback.
win_terminal.Terminal.notify_on_resizecontext managerContext manager for enabling in-band window resize notifications.
Context manager for enabling in-band window resize notifications.
Probes the terminal for DEC private mode 2048 support. If
supported, delegates to the base class. Otherwise, falls back
to enabling ``ENABLE_WINDOW_INPUT`` on the console handle and
converting native ``WINDOW_BUFFER_SIZE_EVENT`` records into
DEC mode 2048 escape sequences so that :meth:`inkey` returns
a :class:`~.Keystroke` with ``name == 'RESIZE_EVENT'``.
DEC mode 2048 is not yet supported by Windows Terminal
(`microsoft/terminal#19618
<https://github.com/microsoft/terminal/issues/19618>`_),
so the native fallback is currently always used.
Accepts the same keyword arguments as
:meth:`~hamingjur.terminal.Terminal.notify_on_resize`.
win_terminal.Terminal.does_inband_resizemethodCheck if the terminal supports in-band window resize notifications.
Check if the terminal supports in-band window resize notifications.
Returns ``True`` on Windows when connected to a real console
with styling enabled. The terminal may support DEC mode 2048
(probed at enable time), but the native console
``WINDOW_BUFFER_SIZE_EVENT`` is always available as a fallback.
win_terminal.Terminal.cbreakcontext managerAllow each keystroke to be read immediately after it is pressed.
Allow each keystroke to be read immediately after it is pressed.
This is a context manager for ``jinxed.w32.setcbreak()``.
.. note:: You must explicitly print any user input you would like
displayed. If you provide any kind of editing, you must handle
backspace and other line-editing control functions in this mode
as well!
**Normally**, characters received from the keyboard cannot be read
by Python until the *Return* key is pressed. Also known as *cooked* or
*canonical input* mode, it allows the tty driver to provide
line-editing before shuttling the input to your program and is the
(implicit) default terminal mode set by most unix shells before
executing programs.
win_terminal.Terminal.rawcontext managerA context manager for ``jinxed.w32.setcbreak()``.
A context manager for ``jinxed.w32.setcbreak()``.
Although both :meth:`break` and :meth:`raw` modes allow each keystroke
to be read immediately after it is pressed, Raw mode disables
processing of input and output.
In cbreak mode, special input characters such as ``^C`` are
interpreted by the terminal driver and excluded from the stdin stream.
In raw mode these values are receive by the :meth:`inkey` method.
hamingjur.resizing1 entries
Scoped SIGWINCH wakeups for synchronous and asynchronous terminal input.
resizing.signal_resizescontext managerWake input with a pipe; signals coalesce into the current OS window size.
Wake input with a pipe; signals coalesce into the current OS window size.
:raises RuntimeError: If signal fallback is entered outside the main thread.
This reference is generated from the checkout’s public Python declarations, without importing platform-specific modules. Constructor signatures, keyword-only arguments, return annotations, enums, and fields come directly from source. Original docstrings retain reStructuredText notation and examples. Inherited methods live under their defining class; dynamic terminal capabilities such as term.bold_green are resolved at runtime.
Common exports: hamingjur.Terminal, LineEditor, LineHistory, Transfer, ImageSupport, PreparedImage, DrawnImage, and the graphics, kitty, protocols, and silkie modules. Definitions are linked under their source modules above. The platform selects the terminal implementation on import.
08 / OPEN SOURCE
Contributing & upstream.
Work on Hamingjur
Contributions are welcome through GitHub pull requests. The contribution guide covers editable installs, tox, code style, and test coverage. Include a regression test with a bug fix and tests for a new feature.
Hamingjur is an independent fork of Blessed, building on work by Jeff Quast, Avram Lubkin, and the Blessed community. Blessed was forked from Erik Rose’s blessings.
The MIT license retains the copyright notices for Jeff Quast (2014) and Erik Rose (2011), alongside Adam DePrince’s fork contributions (2026). The portable terminal foundation comes from that shared work.