Skip to content

xnano_core._xnano_core

xnano_core._xnano_core

xnano_core._xnano_core

Type stubs for the compiled module behind the xnano_core package.

Every class and function here is implemented in Rust. The compiled module is the package initializer, so xnano_core._xnano_core._core_types sits next to it.

Classes:

  • Point –

    A cell position, counted in columns (x) and rows (y) from the top-left.

  • Size –

    A width and a height, counted in cells.

  • Rectangle –

    A rectangle of cells with half-open bounds.

  • Color –

    A terminal color: a named palette color, a palette index or a true color.

  • Style –

    A foreground color, a background color and text modifiers.

  • Clock –

    The time source a runtime reads, either real or stepped by hand.

  • SimulationClock –

    A clock derived from a parent clock, with its own rate and stopped state.

  • TextSpan –

    A run of text with one style.

  • StyledText –

    Text made of differently styled spans.

  • TextLine –

    One wrapped line of a TextLayout.

  • TextLayout –

    Text wrapped to a width, with conversions between cells and string offsets.

  • TextEditor –

    An editable text buffer with a cursor and undo history.

  • Editor –

    Draw a TextEditor into a buffer.

  • KeyEvent –

    A key press, repeat or release.

  • MouseEvent –

    A mouse press, release, drag, move or scroll.

  • Event –

    Something that happened: input, a resize, a timer or a frame.

  • KeyBinding –

    A key and modifiers to match against key events.

  • EventStream –

    The events a runtime reports, as an iterator.

  • Waker –

    A handle other threads use to wake a runtime and run code on its thread.

  • Hook –

    A registered callback that can be paused, reprioritized or cancelled.

  • ScheduledCall –

    A callback scheduled on a clock with call_later or call_every.

  • KeyboardCapabilities –

    What the terminal's keyboard protocol can report.

  • InputOptions –

    The input modes a live terminal asks for.

  • TerminalOptions –

    How a live runtime takes over the terminal.

  • Cursor –

    The one cursor a terminal has.

  • InputState –

    The keys and pointer position a runtime currently sees.

  • Device –

    The display and terminal a runtime draws on.

  • HitArea –

    A named rectangle that receives mouse hits without needing painted text.

  • FocusScope –

    A group of input targets, optionally modal.

  • InputRouter –

    Routes input events to buffers: handlers, hit areas, focus and scopes.

  • TerminalCapabilities –

    What a terminal can display.

  • Expression –

    A value or action described now and evaluated later against a buffer or runtime.

  • Predicate –

    A condition that evaluates to True or False.

  • Value –

    An expression that evaluates to a value.

  • NumericValue –

    A numeric expression that supports comparisons and arithmetic.

  • Operation –

    An action that changes a buffer, applied with Buffer.update.

  • Property –

    A reference to a concrete property of a buffer or runtime.

  • NumericProperty –

    A reference to a numeric property that can be read, computed with and assigned.

  • SetValue –

    Assign a value to a property.

  • SequenceOperation –

    Apply several operations in order as one operation.

  • Conditional –

    Apply one operation when a condition is true and optionally another when it is not.

  • Resize –

    Resize the target buffer to width by height cells.

  • Move –

    Move the target buffer relative to its current position in its parent.

  • Place –

    Move the target buffer to an absolute position in its parent.

  • Write –

    Write text into the target at a cell position.

  • WriteCellText –

    Write text addressed by column and row instead of x and y.

  • Fill –

    Fill every cell of the target with one cell.

  • Clear –

    Blank cells that hide whatever is behind them.

  • Foreground –

    Set the foreground color of every cell of the target.

  • Background –

    Set the background color of every cell of the target.

  • ApplyStyle –

    Patch a Style onto every cell of the target.

  • Border –

    Draw a border around the edge of the target.

  • Paste –

    Copy the cells of another buffer or region into the target.

  • Pixels –

    Draw ordered RGB pixels into the target.

  • Raster –

    Draw a row-major RGBA8 image into the target as pixels.

  • SetState –

    Assign a state branch and publish one validated commit.

  • ApplyStatePatch –

    Apply a JSON patch to a state branch in one validated commit.

  • Effect –

    A composable animation with editable and bindable settings.

  • Fade –

    Fade the colors of the target toward a foreground and background color.

  • Dissolve –

    Dissolve the glyphs of the target away cell by cell.

  • Glitch –

    Randomly corrupt and displace glyphs of the target.

  • Fuzz –

    Replace a percentage of the visible glyphs of the target with noise glyphs, once.

  • CancelEffect –

    Stop the running effect that was started with key.

  • SizeRule –

    How much space one child takes along a layout's main axis.

  • Layout –

    Arrange attached children within the parent's content area.

  • ItemList –

    Selectable styled items with editable selection and scrolling.

  • Gauge –

    A filled progress bar that repaints when its ratio changes.

  • LineGauge –

    A progress indicator drawn with line symbols.

  • Sparkline –

    A compact history of numeric samples.

  • Bar –

    One labelled value in a bar chart.

  • BarGroup –

    A labelled group of bars.

  • BarChart –

    Grouped bars with editable values and styles.

  • TableCell –

    Styled content displayed in a table cell.

  • TableRow –

    A row of cells with height and spacing.

  • Table –

    A retained table with row, column and cell selection.

  • Scrollbar –

    A scrollbar showing position within content.

  • Tabs –

    Selectable titles with editable padding, divider and styles.

  • Drawing –

    An immutable picture made of rows of text or palette pixels.

  • DrawingFrame –

    One frame of a DrawingAnimation.

  • DrawingAnimation –

    A sequence of timed drawings.

  • Draw –

    Draw a Drawing into the target.

  • AnimateDrawing –

    Play a DrawingAnimation on a mounted buffer.

  • Cell –

    A detached grapheme with its style, copied out of or written into a surface.

  • PixelView –

    A raster view that draws logical pixels into the cells of a surface.

  • Surface –

    A grid of cells that text, styles, pixels and operations can be applied to.

  • Region –

    A fixed rectangle of a buffer that shares the buffer's cells.

  • Buffer –

    A layer of cells with a position, a size and the hooks that animate it.

  • StepResult –

    What one Runtime.step() did.

  • Runtime –

    A session that mounts buffers, runs hooks and schedules, and draws frames.

  • FrameMetrics –

    Timing of the frames a runtime has drawn.

  • FrameSnapshot –

    An immutable copy of a drawn frame.

  • ErrorDetail –

    One labelled problem of an ErrorReport.

  • ErrorReport –

    One or more labelled problems, formatted like a pydantic ValidationError.

  • ReportedError –

    An error raised with an ErrorReport as its one argument.

  • RenderError –

    A recoverable failure while drawing a frame; the failed frame is not committed.

  • UnsupportedOperationError –

    The registry of the target cannot apply the operation it was given.

  • RuntimeRequiredError –

    An operation needs a buffer mounted on an active runtime.

  • InvalidRegionError –

    A region no longer fits inside its resized buffer.

  • CellGridError –

    Packed cell data is malformed, incompatible or over a resource limit.

  • CellGridInfo –

    The header of a packed cell grid.

  • CellAnimationInfo –

    The header of a packed cell animation.

  • DecodeLimits –

    Upper bounds checked before packed cell data is accepted.

  • TerminalStateValidationError –

    Raised when a value or a change does not satisfy a state schema.

  • TerminalStateConflictError –

    Raised when a change was prepared against a revision that is no longer current.

  • TerminalStateAccessError –

    Raised when a change touches a path that an observation did not grant for writing.

  • TerminalStateIssue –

    One problem found while validating a value against a schema.

  • TerminalStateSchema –

    A compiled schema that validates state values.

  • TerminalStateSnapshot –

    An immutable view of a state tree, or of one branch of it, at one revision.

  • TerminalStateSelection –

    Values read from several paths at one consistent revision.

  • TerminalStatePatch –

    A list of edits to a state tree, in the JSON Patch format (RFC 6902).

  • TerminalStateChange –

    The result of one committed change: what changed and the state before and after.

  • TerminalStateSubscription –

    A registration that delivers state changes until it is cancelled.

  • TerminalStateTransaction –

    Staged edits that publish together or not at all.

  • TerminalStateStore –

    Thread-safe state storage with schema validation, revisions and notifications.

  • TerminalStateObservation –

    A record of what was read from a store, and which paths may be written.

  • Paragraph –

    Styled text that can wrap, align and scroll.

  • CustomWidget –

    A widget drawn by a Python function.

  • Live –

    Operations that are applied again whenever something they show changes.

  • CanvasLine –

    A straight line between two points, optionally filled down to a baseline.

  • CanvasRectangle –

    An axis-aligned rectangle outline.

  • CanvasCircle –

    A circle outline.

  • CanvasPoints –

    A set of single points.

  • CanvasMap –

    The world map, in longitude and latitude (use bounds (-180, 180) and (-90, 90)).

  • CanvasLabel –

    Text printed at a position, always on top of the shapes.

  • CanvasLayer –

    Saves what was drawn so far as a layer; the shapes after it draw on top.

  • CanvasMarker –

    Switches the marker the shapes after it are drawn with.

  • Canvas –

    A coordinate plane that shapes, points and labels are drawn on.

  • Widget –

    A buffer painted from editable settings or bound expressions.

  • BlockTitle –

    A styled title positioned on the top or bottom border of a block.

  • Block –

    Borders, titles and padding shared by retained widgets.

  • DynamicStyle –

    A style whose colors may follow expressions.

  • ListItem –

    Styled content displayed by an item list.

  • SparklineBar –

    A sample with an optional individual style.

  • ChartAxis –

    An editable axis with bounds, labels and a title.

  • ChartDataset –

    An editable series of points displayed by a chart.

  • Chart –

    Point series drawn against shared editable axes.

  • Calendar –

    A monthly calendar with editable dates and styles for events.

  • StateReference –

    A branch of a state store that can be read, written or bound.

  • CellFilter –

    A composable selection of cells affected by an animation.

  • RunningEffect –

    Playback controls and progress for a started animation.

  • EffectManager –

    Start, replace, inspect and cancel animations on a runtime.

  • Offset –

    A displacement in terminal columns and rows.

  • Margin –

    Horizontal and vertical inset distances.

  • Customization –

    A named, typed set of parameters that is also an operation.

  • OperationChain –

    Operations applied one after another when they cannot become one native sequence.

  • Trigger –

    When something runs, and which events count.

  • ExpressionScope –

    A named group of expressions, such as the parent's size or the terminal's clock.

  • ParentExpressionScope –

    The geometry of the enclosing buffer, as expressions.

  • RootExpressionScope –

    The geometry and clock of the root terminal, as expressions.

  • BufferExpressionScope –

    A buffer's own position and size, as expressions.

  • KeyboardExpressionScope –

    The latest key event, as expressions.

  • MouseExpressionScope –

    The latest mouse button or motion report, as expressions.

  • ScrollExpressionScope –

    The mouse wheel steps of the current step, as expressions.

Functions:

Attributes:

is_optimized_build module-attribute

is_optimized_build: bool

Whether the extension was built with optimizations and without coverage instrumentation. Timing any other build says nothing.

ParentScope module-attribute

ParentScope: ParentExpressionScope

The parent's geometry: ParentScope.width, ParentScope.height, ParentScope.size.

RootScope module-attribute

The terminal's geometry and clock: RootScope.width, RootScope.time, ...

BufferScope module-attribute

BufferScope: BufferExpressionScope

A buffer's own geometry: BufferScope.x, BufferScope.width, ...

KeyboardScope module-attribute

KeyboardScope: KeyboardExpressionScope

The latest key event: KeyboardScope.key, KeyboardScope.kind, KeyboardScope.binding.

MouseScope module-attribute

The latest mouse button or motion report: MouseScope.position, MouseScope.is_down, ...

ScrollScope module-attribute

ScrollScope: ScrollExpressionScope

The latest wheel report of the current step: ScrollScope.x and ScrollScope.y.

X module-attribute

The horizontal position of a buffer or region, in terminal cells.

Y module-attribute

The vertical position of a buffer or region, in terminal cells.

Width module-attribute

The width of a buffer or region, in terminal cells.

Height module-attribute

Height: NumericValue[int | float]

The height of a buffer or region, in terminal cells.

TimeElapsed module-attribute

TimeElapsed: NumericValue[int | float]

The elapsed runtime time, in seconds.

TimeDelta module-attribute

TimeDelta: NumericValue[int | float]

The elapsed time since the previous runtime frame, in seconds.

TimeElapsedMilliseconds module-attribute

TimeElapsedMilliseconds: NumericValue[int | float]

The elapsed runtime time, in milliseconds.

TimeDeltaMilliseconds module-attribute

TimeDeltaMilliseconds: NumericValue[int | float]

The elapsed time since the previous runtime frame, in milliseconds.

Frame module-attribute

The current runtime frame number.

FPS module-attribute

The runtime's estimated frames per second.

DeviceWidth module-attribute

DeviceWidth: NumericValue[int | float]

DeviceHeight module-attribute

DeviceHeight: NumericValue[int | float]

Position module-attribute

Position: Value[Point]

The position of a buffer or region as a Point.

Bounds module-attribute

Bounds: Value[Rectangle]

The full bounds of a buffer or region as a Rectangle.

BufferSize module-attribute

BufferSize: Value[Size]

The dimensions of a buffer as a Size.

Focused module-attribute

Focused: Value[bool]

Whether the runtime has focus.

Running module-attribute

Running: Value[bool]

Whether the runtime is running.

ParentSize module-attribute

ParentSize: Value[Size]

The size of the parent buffer, or of the buffer a region belongs to.

Evaluating it raises TypeError for a buffer without a parent.

ParentWidth module-attribute

ParentWidth: NumericValue[int]

The width of the parent buffer, in cells.

ParentHeight module-attribute

ParentHeight: NumericValue[int]

The height of the parent buffer, in cells.

ScreenPosition module-attribute

ScreenPosition: Value[Point]

The top-left cell of a buffer or region on the screen, counting every parent offset.

ScreenBounds module-attribute

ScreenBounds: Value[Rectangle]

The rectangle of a buffer or region on the screen, counting every parent offset.

PointerPosition module-attribute

PointerPosition: Value[Point | None]

The cell under the pointer, or None until the runtime has seen the pointer.

It is the last known cell, held between events. MousePosition is the cell of the event being handled. Reading it needs a mounted runtime.

KeyboardKey module-attribute

KeyboardKey: Value[str | None]

The key of the latest key event, or None while the latest input was not a key.

KeyboardKind module-attribute

KeyboardKind: Value[Literal['press', 'repeat', 'release'] | None]

Whether the latest key event was a press, repeat or release, or None.

KeyboardBinding module-attribute

KeyboardBinding: Value[str | None]

The latest key event with its modifiers, such as 'ctrl+s', or None.

MouseButtonValue module-attribute

MouseButtonValue: Value[MouseButton | None]

The button of the latest button or motion report, or None.

MouseKind module-attribute

MouseKind: Value[Literal['press', 'release', 'drag', 'move'] | None]

The kind of the latest button or motion report, or None (also for a wheel report).

MousePosition module-attribute

MousePosition: Value[Point | None]

The cell of the latest button or motion report, or None.

PointerPosition is the last cell the pointer was seen at, whatever came since; this one belongs to the event being handled.

MouseIsDown module-attribute

MouseIsDown: Predicate

Whether any mouse button is held.

ScrollX module-attribute

ScrollX: NumericValue[int]

Horizontal steps of the latest wheel report of the current step (right is positive).

ScrollY module-attribute

ScrollY: NumericValue[int]

Vertical steps of the latest wheel report of the step (down is positive, up is -1).

BufferRegion module-attribute

BufferRegion: Value[Rectangle]

The rectangle of a buffer on the screen, counting every parent offset.

Layer module-attribute

The paint order of a buffer among its siblings. Assign it with Layer(2).

IsVisible module-attribute

IsVisible: Property[bool]

Whether a buffer is drawn. Assign it with IsVisible(False).

Point

Point(x: int = 0, y: int = 0)

A cell position, counted in columns (x) and rows (y) from the top-left.

Maps to ratatui::layout::Position.

Parameters:

  • x (int, default: 0 ) –

    The column.

  • y (int, default: 0 ) –

    The row.

Attributes:

  • x (int) –

    The column.

  • y (int) –

    The row.

Examples:

point = Point(2, 3) + Point(1, 1)
assert (point.x, point.y) == (3, 4)
assert point - Point(3, 4) == Point(0, 0)

Create a Point.

Parameters:

  • x (int, default: 0 ) –

    int. Defaults to 0.

  • y (int, default: 0 ) –

    int. Defaults to 0.

Methods:

  • __add__ –

    Add two positions component by component.

  • __sub__ –

    Subtract two positions component by component.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, x: int = 0, y: int = 0) -> None:
    """
    Create a Point.

    Args:
        x: ``int``. Defaults to ``0``.
        y: ``int``. Defaults to ``0``.
    """

x property

x: int

The column.

y property

y: int

The row.

__add__

__add__(other: Point | Offset) -> Point

Add two positions component by component.

Examples:

assert Point(1, 2) + Point(3, 4) == Point(4, 6)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __add__(self, other: Point | Offset) -> Point:
    """
    Add two positions component by component.

    Examples:
        ```python
        assert Point(1, 2) + Point(3, 4) == Point(4, 6)
        ```
    """

__sub__

__sub__(other: Point | Offset) -> Point

Subtract two positions component by component.

Examples:

assert Point(4, 6) - Point(3, 4) == Point(1, 2)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __sub__(self, other: Point | Offset) -> Point:
    """
    Subtract two positions component by component.

    Examples:
        ```python
        assert Point(4, 6) - Point(3, 4) == Point(1, 2)
        ```
    """

Size

Size(width: int = 0, height: int = 0)

A width and a height, counted in cells.

Maps to ratatui::layout::Size.

Parameters:

  • width (int, default: 0 ) –

    The number of columns.

  • height (int, default: 0 ) –

    The number of rows.

Attributes:

Examples:

size = Size(80, 24)
assert (size.width, size.height) == (80, 24)

Create a Size.

Parameters:

  • width (int, default: 0 ) –

    int. Defaults to 0.

  • height (int, default: 0 ) –

    int. Defaults to 0.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, width: int = 0, height: int = 0) -> None:
    """
    Create a Size.

    Args:
        width: ``int``. Defaults to ``0``.
        height: ``int``. Defaults to ``0``.
    """

width property

width: int

The number of columns.

height property

height: int

The number of rows.

Rectangle

Rectangle(x: int = 0, y: int = 0, width: int = 0, height: int = 0)

A rectangle of cells with half-open bounds.

The left and top edges are inclusive, and the right and bottom edges are exclusive.

Maps to ratatui::layout::Rect.

Parameters:

  • x (int, default: 0 ) –

    The left column.

  • y (int, default: 0 ) –

    The top row.

  • width (int, default: 0 ) –

    The number of columns.

  • height (int, default: 0 ) –

    The number of rows.

Attributes:

Examples:

area = Rectangle(2, 1, 10, 4)
assert area.area == 40
assert area.contains(Point(2, 1))
assert not area.contains(Point(12, 1))

Create a Rectangle.

Parameters:

  • x (int, default: 0 ) –

    int. Defaults to 0.

  • y (int, default: 0 ) –

    int. Defaults to 0.

  • width (int, default: 0 ) –

    int. Defaults to 0.

  • height (int, default: 0 ) –

    int. Defaults to 0.

Methods:

  • contains –

    Whether point lies inside the rectangle.

  • intersects –

    Whether the two rectangles share at least one cell.

  • intersection –

    The cells both rectangles share. The result is empty when they do not overlap.

  • union –

    The smallest rectangle that holds both rectangles.

  • translate –

    Move the rectangle by a number of columns and rows.

  • inset –

    Shrink the rectangle by a margin on every side.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, x: int = 0, y: int = 0, width: int = 0, height: int = 0) -> None:
    """
    Create a Rectangle.

    Args:
        x: ``int``. Defaults to ``0``.
        y: ``int``. Defaults to ``0``.
        width: ``int``. Defaults to ``0``.
        height: ``int``. Defaults to ``0``.
    """

x property

x: int

The left column.

y property

y: int

The top row.

width property

width: int

The number of columns.

height property

height: int

The number of rows.

position property

position: Point

The top-left corner.

size property

size: Size

The width and height.

area property

area: int

The number of cells, width * height.

is_empty property

is_empty: bool

Whether the rectangle holds no cells.

contains

contains(point: Point) -> bool

Whether point lies inside the rectangle.

Examples:

area = Rectangle(0, 0, 4, 2)
assert area.contains(Point(3, 1))
assert not area.contains(Point(4, 1))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def contains(self, point: Point) -> bool:
    """
    Whether ``point`` lies inside the rectangle.

    Examples:
        ```python
        area = Rectangle(0, 0, 4, 2)
        assert area.contains(Point(3, 1))
        assert not area.contains(Point(4, 1))
        ```
    """

intersects

intersects(other: Rectangle) -> bool

Whether the two rectangles share at least one cell.

Examples:

assert Rectangle(0, 0, 4, 4).intersects(Rectangle(3, 3, 4, 4))
assert not Rectangle(0, 0, 4, 4).intersects(Rectangle(4, 0, 4, 4))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def intersects(self, other: Rectangle) -> bool:
    """
    Whether the two rectangles share at least one cell.

    Examples:
        ```python
        assert Rectangle(0, 0, 4, 4).intersects(Rectangle(3, 3, 4, 4))
        assert not Rectangle(0, 0, 4, 4).intersects(Rectangle(4, 0, 4, 4))
        ```
    """

intersection

intersection(other: Rectangle) -> Rectangle

The cells both rectangles share. The result is empty when they do not overlap.

Examples:

shared = Rectangle(0, 0, 10, 5).intersection(Rectangle(5, 2, 10, 10))
assert shared == Rectangle(5, 2, 5, 3)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def intersection(self, other: Rectangle) -> Rectangle:
    """
    The cells both rectangles share. The result is empty when they do not overlap.

    Examples:
        ```python
        shared = Rectangle(0, 0, 10, 5).intersection(Rectangle(5, 2, 10, 10))
        assert shared == Rectangle(5, 2, 5, 3)
        ```
    """

union

union(other: Rectangle) -> Rectangle

The smallest rectangle that holds both rectangles.

Examples:

joined = Rectangle(0, 0, 10, 5).union(Rectangle(8, 8, 4, 4))
assert joined == Rectangle(0, 0, 12, 12)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def union(self, other: Rectangle) -> Rectangle:
    """
    The smallest rectangle that holds both rectangles.

    Examples:
        ```python
        joined = Rectangle(0, 0, 10, 5).union(Rectangle(8, 8, 4, 4))
        assert joined == Rectangle(0, 0, 12, 12)
        ```
    """

translate

translate(x: int = 0, y: int = 0) -> Rectangle

Move the rectangle by a number of columns and rows.

Parameters:

  • x (int, default: 0 ) –

    Columns to move right; negative values move left.

  • y (int, default: 0 ) –

    Rows to move down; negative values move up.

Examples:

assert Rectangle(0, 0, 4, 2).translate(2, 1) == Rectangle(2, 1, 4, 2)
assert Rectangle(5, 5, 4, 2).translate(x=-1, y=-2) == Rectangle(4, 3, 4, 2)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def translate(self, x: int = 0, y: int = 0) -> Rectangle:
    """
    Move the rectangle by a number of columns and rows.

    Args:
        x: Columns to move right; negative values move left.
        y: Rows to move down; negative values move up.

    Examples:
        ```python
        assert Rectangle(0, 0, 4, 2).translate(2, 1) == Rectangle(2, 1, 4, 2)
        assert Rectangle(5, 5, 4, 2).translate(x=-1, y=-2) == Rectangle(4, 3, 4, 2)
        ```
    """

inset

inset(horizontal: int = 0, vertical: int = 0) -> Rectangle

Shrink the rectangle by a margin on every side.

Examples:

assert Rectangle(0, 0, 10, 5).inset(1, 1) == Rectangle(1, 1, 8, 3)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def inset(self, horizontal: int = 0, vertical: int = 0) -> Rectangle:
    """
    Shrink the rectangle by a margin on every side.

    Examples:
        ```python
        assert Rectangle(0, 0, 10, 5).inset(1, 1) == Rectangle(1, 1, 8, 3)
        ```
    """

Color

Color(value: ColorName | str | tuple[int, int, int])

A terminal color: a named palette color, a palette index or a true color.

Maps to ratatui::style::Color.

Parameters:

  • value (ColorName | str | tuple[int, int, int]) –

    A color name such as 'red' or 'light_blue', a hex string such as '#ff8800', a palette index string such as '4', or a (red, green, blue) tuple.

Attributes:

Raises:

Examples:

assert Color('#ff8800').to_rgb() == (255, 136, 0)
assert Color((1, 2, 3)) == Color.from_rgb(1, 2, 3)
assert Color('red').to_rgb() is None

Create a Color.

Parameters:

Methods:

  • parse –

    Parse a color name, hex string or palette index string.

  • from_tailwind –

    A true color from a Tailwind palette and shade.

  • indexed –

    A color from the 256-color palette.

  • from_rgb –

    A true color from red, green and blue values between 0 and 255.

  • to_rgb –

    The (red, green, blue) values of a true color, or None for named and indexed colors.

  • to_hex –

    The color as a '#rrggbb' string.

  • from_hsl –

    A true color from hue, saturation and lightness.

  • from_hsv –

    A true color from hue, saturation and value.

  • random –

    A random true color, or a random shade of base.

  • to_hsl –

    The hue (degrees), saturation and lightness (percentages) of the color.

  • to_hsv –

    The hue (degrees), saturation and value (percentages) of the color.

  • lerp –

    The color between this one and other.

  • lighten –

    A lighter color for a positive amount, a darker one for a negative amount.

  • darken –

    A darker color.

  • inverse –

    The color that has each red, green and blue channel inverted.

  • saturate –

    The color with its saturation scaled.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, value: ColorName | str | tuple[int, int, int]) -> None:
    """
    Create a Color.

    Args:
        value: ``ColorName | str | tuple[int, int, int]``.
    """

black class-attribute

black: Color

The black terminal color.

red class-attribute

red: Color

The red terminal color.

green class-attribute

green: Color

The green terminal color.

yellow class-attribute

yellow: Color

The yellow terminal color.

blue class-attribute

blue: Color

The blue terminal color.

magenta class-attribute

magenta: Color

The magenta terminal color.

cyan class-attribute

cyan: Color

The cyan terminal color.

gray class-attribute

gray: Color

The gray terminal color.

dark_gray class-attribute

dark_gray: Color

The dark gray terminal color.

light_red class-attribute

light_red: Color

The light red terminal color.

light_green class-attribute

light_green: Color

The light green terminal color.

light_yellow class-attribute

light_yellow: Color

The light yellow terminal color.

light_blue class-attribute

light_blue: Color

The light blue terminal color.

light_magenta class-attribute

light_magenta: Color

The light magenta terminal color.

light_cyan class-attribute

light_cyan: Color

The light cyan terminal color.

white class-attribute

white: Color

The white terminal color.

reset class-attribute

reset: Color

The reset terminal color, which follows the terminal theme.

is_reset property

is_reset: bool

Whether this is the reset color, which follows the terminal's theme.

parse classmethod

parse(value: ColorName | str) -> Color

Parse a color name, hex string or palette index string.

Examples:

assert Color.parse('light_blue') == Color('light_blue')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def parse(cls, value: ColorName | str) -> Color:
    """
    Parse a color name, hex string or palette index string.

    Examples:
        ```python
        assert Color.parse('light_blue') == Color('light_blue')
        ```
    """

from_tailwind classmethod

from_tailwind(palette: TailwindColorName, shade: TailwindColorShade) -> Color

A true color from a Tailwind palette and shade.

Color does not read a name such as 'slate-400'. Pass the palette and the shade here.

Parameters:

Raises:

  • ValueError –

    palette is not a palette, or shade is not a shade.

Examples:

assert Color.from_tailwind('red', 500).to_rgb() == (239, 68, 68)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_tailwind(
    cls, palette: TailwindColorName, shade: TailwindColorShade
) -> Color:
    """
    A true color from a Tailwind palette and shade.

    ``Color`` does not read a name such as ``'slate-400'``. Pass the palette and the
    shade here.

    Args:
        palette: A palette such as ``'slate'`` or ``'red'``.
        shade: ``50``, ``100`` through ``900``, or ``950``.

    Raises:
        ValueError: ``palette`` is not a palette, or ``shade`` is not a shade.

    Examples:
        ```python
        assert Color.from_tailwind('red', 500).to_rgb() == (239, 68, 68)
        ```
    """

indexed classmethod

indexed(index: int) -> Color

A color from the 256-color palette.

Examples:

color = Color.indexed(202)
assert color.to_rgb() is None
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def indexed(cls, index: int) -> Color:
    """
    A color from the 256-color palette.

    Examples:
        ```python
        color = Color.indexed(202)
        assert color.to_rgb() is None
        ```
    """

from_rgb classmethod

from_rgb(red: int, green: int, blue: int) -> Color

A true color from red, green and blue values between 0 and 255.

Examples:

assert Color.from_rgb(255, 0, 0).to_rgb() == (255, 0, 0)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_rgb(cls, red: int, green: int, blue: int) -> Color:
    """
    A true color from red, green and blue values between 0 and 255.

    Examples:
        ```python
        assert Color.from_rgb(255, 0, 0).to_rgb() == (255, 0, 0)
        ```
    """

to_rgb

to_rgb() -> tuple[int, int, int] | None

The (red, green, blue) values of a true color, or None for named and indexed colors.

Examples:

assert Color('#010203').to_rgb() == (1, 2, 3)
assert Color.indexed(4).to_rgb() is None
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_rgb(self) -> tuple[int, int, int] | None:
    """
    The ``(red, green, blue)`` values of a true color, or ``None`` for named and indexed colors.

    Examples:
        ```python
        assert Color('#010203').to_rgb() == (1, 2, 3)
        assert Color.indexed(4).to_rgb() is None
        ```
    """

to_hex

to_hex() -> str

The color as a '#rrggbb' string.

Only a true color has one, as with to_rgb.

Raises:

  • ValueError –

    The color is named, indexed or reset, which the terminal's theme chooses.

Examples:

assert Color((255, 136, 0)).to_hex() == '#ff8800'
assert Color('#FF8800').to_hex() == '#ff8800'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_hex(self) -> str:
    """
    The color as a ``'#rrggbb'`` string.

    Only a true color has one, as with [`to_rgb`][xnano_core._xnano_core.Color.to_rgb].

    Raises:
        ValueError: The color is named, indexed or ``reset``, which the terminal's theme
            chooses.

    Examples:
        ```python
        assert Color((255, 136, 0)).to_hex() == '#ff8800'
        assert Color('#FF8800').to_hex() == '#ff8800'
        ```
    """

from_hsl classmethod

from_hsl(hue: float, saturation: float, lightness: float) -> Color

A true color from hue, saturation and lightness.

Parameters:

  • hue (float) –

    Degrees from 0 to 360.

  • saturation (float) –

    A percentage from 0 to 100.

  • lightness (float) –

    A percentage from 0 to 100.

Raises:

Examples:

assert Color.from_hsl(0, 100, 50).to_hex() == '#ff0000'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_hsl(cls, hue: float, saturation: float, lightness: float) -> Color:
    """
    A true color from hue, saturation and lightness.

    Args:
        hue: Degrees from 0 to 360.
        saturation: A percentage from 0 to 100.
        lightness: A percentage from 0 to 100.

    Raises:
        ValueError: A value is out of range.

    Examples:
        ```python
        assert Color.from_hsl(0, 100, 50).to_hex() == '#ff0000'
        ```
    """

from_hsv classmethod

from_hsv(hue: float, saturation: float, value: float) -> Color

A true color from hue, saturation and value.

Parameters:

  • hue (float) –

    Degrees from 0 to 360.

  • saturation (float) –

    A percentage from 0 to 100.

  • value (float) –

    A percentage from 0 to 100.

Raises:

Examples:

assert Color.from_hsv(120, 100, 100).to_hex() == '#00ff00'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_hsv(cls, hue: float, saturation: float, value: float) -> Color:
    """
    A true color from hue, saturation and value.

    Args:
        hue: Degrees from 0 to 360.
        saturation: A percentage from 0 to 100.
        value: A percentage from 0 to 100.

    Raises:
        ValueError: A value is out of range.

    Examples:
        ```python
        assert Color.from_hsv(120, 100, 100).to_hex() == '#00ff00'
        ```
    """

random classmethod

random(base: Color | ColorName | str | tuple[int, int, int] | None = None) -> Color

A random true color, or a random shade of base.

Without base every red, green and blue channel is picked at random. With base the color keeps its hue and saturation and takes a random lightness from 15 to 85 percent, so every color it returns is a lighter or darker shade of base. The colors come from Python's random module, so random.seed(...) repeats them.

Parameters:

Raises:

  • ValueError –

    base is Color.reset, or not a color.

Examples:

import random

random.seed(7)
first = Color.random()
random.seed(7)
assert Color.random() == first

hue, saturation, _ = Color.random('#3366cc').to_hsl()
assert round(hue) == 220 and round(saturation) == 60
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def random(
    cls, base: Color | ColorName | str | tuple[int, int, int] | None = None
) -> Color:
    """
    A random true color, or a random shade of ``base``.

    Without ``base`` every red, green and blue channel is picked at random. With ``base``
    the color keeps its hue and saturation and takes a random lightness from 15 to 85
    percent, so every color it returns is a lighter or darker shade of ``base``. The
    colors come from Python's [`random`](https://docs.python.org/3/library/random.html)
    module, so ``random.seed(...)`` repeats them.

    Args:
        base: The color to pick shades of, or ``None`` for any color.

    Raises:
        ValueError: ``base`` is ``Color.reset``, or not a color.

    Examples:
        ```python
        import random

        random.seed(7)
        first = Color.random()
        random.seed(7)
        assert Color.random() == first

        hue, saturation, _ = Color.random('#3366cc').to_hsl()
        assert round(hue) == 220 and round(saturation) == 60
        ```
    """

to_hsl

to_hsl() -> tuple[float, float, float]

The hue (degrees), saturation and lightness (percentages) of the color.

Named and indexed colors use their standard values.

Raises:

Examples:

hue, saturation, lightness = Color('#ff0000').to_hsl()
assert round(hue) == 0
assert round(saturation) == 100
assert round(lightness) == 50
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_hsl(self) -> tuple[float, float, float]:
    """
    The hue (degrees), saturation and lightness (percentages) of the color.

    Named and indexed colors use their standard values.

    Raises:
        ValueError: The color is ``reset``.

    Examples:
        ```python
        hue, saturation, lightness = Color('#ff0000').to_hsl()
        assert round(hue) == 0
        assert round(saturation) == 100
        assert round(lightness) == 50
        ```
    """

to_hsv

to_hsv() -> tuple[float, float, float]

The hue (degrees), saturation and value (percentages) of the color.

Named and indexed colors use their standard values.

Raises:

Examples:

hue, saturation, value = Color('#00ff00').to_hsv()
assert round(hue) == 120
assert round(saturation) == 100
assert round(value) == 100
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_hsv(self) -> tuple[float, float, float]:
    """
    The hue (degrees), saturation and value (percentages) of the color.

    Named and indexed colors use their standard values.

    Raises:
        ValueError: The color is ``reset``.

    Examples:
        ```python
        hue, saturation, value = Color('#00ff00').to_hsv()
        assert round(hue) == 120
        assert round(saturation) == 100
        assert round(value) == 100
        ```
    """

lerp

lerp(other: Color | ColorName | str | tuple[int, int, int], ratio: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl') -> Color

The color between this one and other.

Parameters:

  • other (Color | ColorName | str | tuple[int, int, int]) –

    The color to blend toward.

  • ratio (float) –

    0.0 is this color and 1.0 is other.

  • color_space (Literal['rgb', 'hsl', 'hsv'], default: 'hsl' ) –

    The space the blend runs through. 'hsl' and 'hsv' keep colors vivid in the middle; 'rgb' is the straight average.

Raises:

  • ValueError –

    A color is reset, or color_space is not a color space.

Examples:

middle = Color('#000000').lerp('#ffffff', 0.5, color_space='rgb')
red, green, blue = middle.to_rgb()
assert red == green == blue
assert 126 <= red <= 129
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def lerp(
    self,
    other: Color | ColorName | str | tuple[int, int, int],
    ratio: float,
    *,
    color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl',
) -> Color:
    """
    The color between this one and ``other``.

    Args:
        other: The color to blend toward.
        ratio: ``0.0`` is this color and ``1.0`` is ``other``.
        color_space: The space the blend runs through. ``'hsl'`` and ``'hsv'`` keep colors
            vivid in the middle; ``'rgb'`` is the straight average.

    Raises:
        ValueError: A color is ``reset``, or ``color_space`` is not a color space.

    Examples:
        ```python
        middle = Color('#000000').lerp('#ffffff', 0.5, color_space='rgb')
        red, green, blue = middle.to_rgb()
        assert red == green == blue
        assert 126 <= red <= 129
        ```
    """

lighten

lighten(amount: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl') -> Color

A lighter color for a positive amount, a darker one for a negative amount.

Parameters:

  • amount (float) –

    A fraction from -1.0 (black) to 1.0 (white).

  • color_space (Literal['rgb', 'hsl', 'hsv'], default: 'hsl' ) –

    The space the change runs through.

Raises:

  • ValueError –

    The color is reset, or color_space is not a color space.

Examples:

base = Color('#336699')
assert base.lighten(0.2).to_hsl()[2] > base.to_hsl()[2]
assert base.lighten(-0.2).to_hsl()[2] < base.to_hsl()[2]
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def lighten(
    self, amount: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl'
) -> Color:
    """
    A lighter color for a positive ``amount``, a darker one for a negative ``amount``.

    Args:
        amount: A fraction from -1.0 (black) to 1.0 (white).
        color_space: The space the change runs through.

    Raises:
        ValueError: The color is ``reset``, or ``color_space`` is not a color space.

    Examples:
        ```python
        base = Color('#336699')
        assert base.lighten(0.2).to_hsl()[2] > base.to_hsl()[2]
        assert base.lighten(-0.2).to_hsl()[2] < base.to_hsl()[2]
        ```
    """

darken

darken(amount: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl') -> Color

A darker color.

Parameters:

  • amount (float) –

    A fraction from 0.0 (unchanged) to 1.0 (black). Use lighten to make a color lighter.

  • color_space (Literal['rgb', 'hsl', 'hsv'], default: 'hsl' ) –

    The space the change runs through.

Returns:

  • Color –

    The darkened color; the original is unchanged.

Raises:

  • ValueError –

    amount is outside 0.0 to 1.0, the color is reset, or color_space is not a color space.

Examples:

assert Color('#808080').darken(1.0).to_rgb() == (0, 0, 0)
base = Color('#336699')
assert base.darken(0.2).to_hsl()[2] < base.to_hsl()[2]
assert base.darken(0.0) == base
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def darken(
    self, amount: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl'
) -> Color:
    """
    A darker color.

    Args:
        amount: A fraction from 0.0 (unchanged) to 1.0 (black). Use
            [`lighten`][xnano_core._xnano_core.Color.lighten] to make a color lighter.
        color_space: The space the change runs through.

    Returns:
        The darkened color; the original is unchanged.

    Raises:
        ValueError: ``amount`` is outside 0.0 to 1.0, the color is ``reset``, or
            ``color_space`` is not a color space.

    Examples:
        ```python
        assert Color('#808080').darken(1.0).to_rgb() == (0, 0, 0)
        base = Color('#336699')
        assert base.darken(0.2).to_hsl()[2] < base.to_hsl()[2]
        assert base.darken(0.0) == base
        ```
    """

inverse

inverse() -> Color

The color that has each red, green and blue channel inverted.

Named and indexed colors are inverted through their standard values, so the result is always a true color.

Returns:

  • Color –

    The inverted true color; the original is unchanged.

Raises:

  • ValueError –

    The color is reset, which has no fixed value.

Examples:

assert Color('#ff8000').inverse().to_hex() == '#007fff'
assert Color('#ff8000').inverse().inverse() == Color('#ff8000')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def inverse(self) -> Color:
    """
    The color that has each red, green and blue channel inverted.

    Named and indexed colors are inverted through their standard values, so the result
    is always a true color.

    Returns:
        The inverted true color; the original is unchanged.

    Raises:
        ValueError: The color is ``reset``, which has no fixed value.

    Examples:
        ```python
        assert Color('#ff8000').inverse().to_hex() == '#007fff'
        assert Color('#ff8000').inverse().inverse() == Color('#ff8000')
        ```
    """

saturate

saturate(factor: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl') -> Color

The color with its saturation scaled.

Parameters:

  • factor (float) –

    0.0 removes the saturation, 1.0 keeps it and more than 1.0 boosts it.

  • color_space (Literal['rgb', 'hsl', 'hsv'], default: 'hsl' ) –

    The space the change runs through.

Raises:

  • ValueError –

    The color is reset, or color_space is not a color space.

Examples:

gray = Color('#336699').saturate(0.0)
assert round(gray.to_hsl()[1]) == 0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def saturate(
    self, factor: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl'
) -> Color:
    """
    The color with its saturation scaled.

    Args:
        factor: ``0.0`` removes the saturation, ``1.0`` keeps it and more than ``1.0``
            boosts it.
        color_space: The space the change runs through.

    Raises:
        ValueError: The color is ``reset``, or ``color_space`` is not a color space.

    Examples:
        ```python
        gray = Color('#336699').saturate(0.0)
        assert round(gray.to_hsl()[1]) == 0
        ```
    """

Style

Style(foreground: ColorValue | None = None, background: ColorValue | None = None, *, bold: bool = False, dim: bool = False, italic: bool = False, underline: bool = False, blink: bool = False, reverse: bool = False, hidden: bool = False, crossed_out: bool = False, rapid_blink: bool = False, underline_color: ColorValue | None = None)

A foreground color, a background color and text modifiers.

Maps to ratatui::style::Style.

Parameters:

  • foreground (ColorValue | None, default: None ) –

    The text color.

  • background (ColorValue | None, default: None ) –

    The cell background color.

  • bold (bool, default: False ) –

    Whether text is bold.

  • dim (bool, default: False ) –

    Whether text is dimmed.

  • italic (bool, default: False ) –

    Whether text is italic.

  • underline (bool, default: False ) –

    Whether text is underlined.

  • blink (bool, default: False ) –

    Whether text blinks.

  • reverse (bool, default: False ) –

    Whether foreground and background swap.

  • hidden (bool, default: False ) –

    Whether text is hidden.

  • crossed_out (bool, default: False ) –

    Whether text is struck through.

Attributes:

Examples:

style = Style('red', 'black', bold=True)
assert style.foreground == Color('red')
assert 'bold' in style.modifiers

Create a Style.

Parameters:

  • foreground (ColorValue | None, default: None ) –

    ColorValue | None. Defaults to None.

  • background (ColorValue | None, default: None ) –

    ColorValue | None. Defaults to None.

  • bold (bool, default: False ) –

    bool. Defaults to False.

  • dim (bool, default: False ) –

    bool. Defaults to False.

  • italic (bool, default: False ) –

    bool. Defaults to False.

  • underline (bool, default: False ) –

    bool. Defaults to False.

  • blink (bool, default: False ) –

    bool. Defaults to False.

  • reverse (bool, default: False ) –

    bool. Defaults to False.

  • hidden (bool, default: False ) –

    bool. Defaults to False.

  • crossed_out (bool, default: False ) –

    bool. Defaults to False.

  • rapid_blink (bool, default: False ) –

    bool. Defaults to False.

  • underline_color (ColorValue | None, default: None ) –

    ColorValue | None. Defaults to None.

Methods:

  • patch –

    A style where every value other sets replaces this style's value.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    foreground: ColorValue | None = None,
    background: ColorValue | None = None,
    *,
    bold: bool = False,
    dim: bool = False,
    italic: bool = False,
    underline: bool = False,
    blink: bool = False,
    reverse: bool = False,
    hidden: bool = False,
    crossed_out: bool = False,
    rapid_blink: bool = False,
    underline_color: ColorValue | None = None,
) -> None:
    """
    Create a Style.

    Args:
        foreground: ``ColorValue | None``. Defaults to ``None``.
        background: ``ColorValue | None``. Defaults to ``None``.
        bold: ``bool``. Defaults to ``False``.
        dim: ``bool``. Defaults to ``False``.
        italic: ``bool``. Defaults to ``False``.
        underline: ``bool``. Defaults to ``False``.
        blink: ``bool``. Defaults to ``False``.
        reverse: ``bool``. Defaults to ``False``.
        hidden: ``bool``. Defaults to ``False``.
        crossed_out: ``bool``. Defaults to ``False``.
        rapid_blink: ``bool``. Defaults to ``False``.
        underline_color: ``ColorValue | None``. Defaults to ``None``.
    """

foreground property

foreground: Color | None

The text color, or None when unset.

background property

background: Color | None

The background color, or None when unset.

modifiers property

modifiers: frozenset[Modifier]

The enabled text modifiers.

patch

patch(other: Style) -> Style

A style where every value other sets replaces this style's value.

Examples:

base = Style('red', bold=True)
patched = base.patch(Style(italic=True))
assert patched.foreground == Color('red')
assert patched.modifiers == {'bold', 'italic'}
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def patch(self, other: Style) -> Style:
    """
    A style where every value ``other`` sets replaces this style's value.

    Examples:
        ```python
        base = Style('red', bold=True)
        patched = base.patch(Style(italic=True))
        assert patched.foreground == Color('red')
        assert patched.modifiers == {'bold', 'italic'}
        ```
    """

Clock

The time source a runtime reads, either real or stepped by hand.

A monotonic clock follows real time, so wall-clock adjustments never affect it. A manual clock moves only when you step it, which makes tests and replays exact. Either kind can be stopped; a stopped clock does not move until it is resumed or stepped by hand.

Attributes:

Examples:

clock = Clock.manual()
clock.step(1500)
assert clock.elapsed_seconds == 1.5
assert clock.source == 'manual'

Methods:

  • monotonic –

    A clock that follows real elapsed time.

  • manual –

    A clock that moves only through step.

  • stop –

    Stop time from advancing.

  • resume –

    Let time advance again after it was stopped.

  • step –

    Move time forward by exactly milliseconds.

  • derive –

    Create a clock that follows this one at a different speed.

source property

source: Literal['monotonic', 'manual']

Whether the clock follows real time or is stepped by hand.

elapsed_seconds property

elapsed_seconds: float

Seconds since the clock started.

elapsed_milliseconds property

elapsed_milliseconds: float

Milliseconds since the clock started.

delta_seconds property

delta_seconds: float

Seconds between the two most recent frames.

delta_milliseconds property

delta_milliseconds: float

Milliseconds between the two most recent frames.

frame property

frame: int

The number of frames the clock has counted.

frames_per_second property

frames_per_second: float

The rate at which the runtime drew its recent frames, in frames per second.

Only frames the runtime draws count, and it draws when something changed, at most once per frame interval. A monotonic clock measures the rate in real time, time spent stopped included; a manual clock measures it in its own time, so it is the rate its steps imply. It is 0.0 until a few frames have been drawn.

is_stopped property

is_stopped: bool

Whether the clock is stopped.

monotonic classmethod

monotonic(*, elapsed_seconds: float = 0.0, frame: int = 0) -> Clock

A clock that follows real elapsed time.

Parameters:

  • elapsed_seconds (float, default: 0.0 ) –

    The time the clock starts at, zero or more.

  • frame (int, default: 0 ) –

    The number of frames the clock has already counted, zero or more.

Returns:

  • Clock –

    A running clock that follows real time.

Raises:

  • ValueError –

    elapsed_seconds is negative or not finite, or frame is negative.

Examples:

clock = Clock.monotonic()
assert clock.source == 'monotonic'

continued = Clock.monotonic(elapsed_seconds=2.0, frame=120)
assert continued.elapsed_seconds >= 2.0
assert continued.frame == 120
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def monotonic(cls, *, elapsed_seconds: float = 0.0, frame: int = 0) -> Clock:
    """
    A clock that follows real elapsed time.

    Args:
        elapsed_seconds: The time the clock starts at, zero or more.
        frame: The number of frames the clock has already counted, zero or more.

    Returns:
        A running clock that follows real time.

    Raises:
        ValueError: ``elapsed_seconds`` is negative or not finite, or ``frame`` is
            negative.

    Examples:
        ```python
        clock = Clock.monotonic()
        assert clock.source == 'monotonic'

        continued = Clock.monotonic(elapsed_seconds=2.0, frame=120)
        assert continued.elapsed_seconds >= 2.0
        assert continued.frame == 120
        ```
    """

manual classmethod

manual(*, elapsed_seconds: float = 0.0) -> Clock

A clock that moves only through step.

Parameters:

  • elapsed_seconds (float, default: 0.0 ) –

    The time the clock starts at, zero or more.

Raises:

  • ValueError –

    elapsed_seconds is negative or not finite.

Examples:

clock = Clock.manual(elapsed_seconds=2.0)
assert clock.elapsed_milliseconds == 2000.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def manual(cls, *, elapsed_seconds: float = 0.0) -> Clock:
    """
    A clock that moves only through [`step`][xnano_core._xnano_core.Clock.step].

    Args:
        elapsed_seconds: The time the clock starts at, zero or more.

    Raises:
        ValueError: ``elapsed_seconds`` is negative or not finite.

    Examples:
        ```python
        clock = Clock.manual(elapsed_seconds=2.0)
        assert clock.elapsed_milliseconds == 2000.0
        ```
    """

stop

stop() -> None

Stop time from advancing.

The time spent stopped is not counted in elapsed_seconds.

Examples:

clock = Clock.manual()
clock.stop()
assert clock.is_stopped
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def stop(self) -> None:
    """
    Stop time from advancing.

    The time spent stopped is not counted in ``elapsed_seconds``.

    Examples:
        ```python
        clock = Clock.manual()
        clock.stop()
        assert clock.is_stopped
        ```
    """

resume

resume() -> None

Let time advance again after it was stopped.

Examples:

clock = Clock.manual()
clock.stop()
clock.resume()
assert not clock.is_stopped
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def resume(self) -> None:
    """
    Let time advance again after it was stopped.

    Examples:
        ```python
        clock = Clock.manual()
        clock.stop()
        clock.resume()
        assert not clock.is_stopped
        ```
    """

step

step(milliseconds: int) -> None

Move time forward by exactly milliseconds.

A manual clock can always be stepped. A monotonic clock can be stepped only while it is stopped, which lets a stopped clock advance one frame at a time.

Parameters:

  • milliseconds (int) –

    How far to move, zero or more.

Raises:

  • ValueError –

    milliseconds is negative, or the clock is a monotonic clock that is running.

Examples:

clock = Clock.monotonic()
clock.stop()
before = clock.elapsed_milliseconds
clock.step(250)
assert abs(clock.elapsed_milliseconds - (before + 250.0)) < 1e-6

manual = Clock.manual()
manual.step(100)
assert manual.elapsed_milliseconds == 100.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def step(self, milliseconds: int) -> None:
    """
    Move time forward by exactly ``milliseconds``.

    A manual clock can always be stepped. A monotonic clock can be stepped only while it
    is stopped, which lets a stopped clock advance one frame at a time.

    Args:
        milliseconds: How far to move, zero or more.

    Raises:
        ValueError: ``milliseconds`` is negative, or the clock is a monotonic clock
            that is running.

    Examples:
        ```python
        clock = Clock.monotonic()
        clock.stop()
        before = clock.elapsed_milliseconds
        clock.step(250)
        assert abs(clock.elapsed_milliseconds - (before + 250.0)) < 1e-6

        manual = Clock.manual()
        manual.step(100)
        assert manual.elapsed_milliseconds == 100.0
        ```
    """

derive

derive(*, rate: float = 1.0, is_stopped: bool = False) -> SimulationClock

Create a clock that follows this one at a different speed.

Parameters:

  • rate (float, default: 1.0 ) –

    How fast the new clock runs compared to this one. Zero or more.

  • is_stopped (bool, default: False ) –

    Whether the new clock starts stopped.

Examples:

clock = Clock.manual()
slow_motion = clock.derive(rate=0.5)
assert slow_motion.rate == 0.5
assert slow_motion.parent.source == 'manual'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def derive(self, *, rate: float = 1.0, is_stopped: bool = False) -> SimulationClock:
    """
    Create a clock that follows this one at a different speed.

    Args:
        rate: How fast the new clock runs compared to this one. Zero or more.
        is_stopped: Whether the new clock starts stopped.

    Examples:
        ```python
        clock = Clock.manual()
        slow_motion = clock.derive(rate=0.5)
        assert slow_motion.rate == 0.5
        assert slow_motion.parent.source == 'manual'
        ```
    """

SimulationClock

A clock derived from a parent clock, with its own rate and stopped state.

Changing the rate keeps elapsed time continuous. Rates are finite and nonnegative.

Attributes:

  • parent (Clock) –

    The clock this clock follows.

  • rate (float) –

    How fast this clock runs compared to its parent. Assign to change it.

  • is_stopped (bool) –

    Whether this clock is stopped. Assign to stop or resume it.

  • elapsed_seconds (float) –

    Seconds of simulation time.

  • delta_seconds (float) –

    Seconds of simulation time between the two most recent calls to sample.

Examples:

simulation = Clock.manual().derive(rate=1.0)
simulation.rate = 2.0
simulation.is_stopped = True
assert simulation.rate == 2.0
assert simulation.is_stopped

Methods:

  • sample –

    Record the current elapsed time so delta_seconds reports time since this sample.

  • stop –

    Stop this clock without affecting its parent.

  • resume –

    Resume this clock after it was stopped.

parent property

parent: Clock

The clock this clock follows.

rate property writable

rate: float

How fast this clock runs compared to its parent. Assign to change it.

is_stopped property writable

is_stopped: bool

Whether this clock is stopped. Assign to stop or resume it.

elapsed_seconds property

elapsed_seconds: float

Seconds of simulation time.

delta_seconds property

delta_seconds: float

Seconds of simulation time between the two most recent calls to sample.

sample

sample() -> None

Record the current elapsed time so delta_seconds reports time since this sample.

Call once for each simulation frame whose elapsed time you want to measure.

Examples:

parent = Clock.manual()
simulation = parent.derive(rate=2.0)
simulation.sample()
parent.step(100)
simulation.sample()
assert simulation.delta_seconds == 0.2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def sample(self) -> None:
    """
    Record the current elapsed time so ``delta_seconds`` reports time since this sample.

    Call once for each simulation frame whose elapsed time you want to measure.

    Examples:
        ```python
        parent = Clock.manual()
        simulation = parent.derive(rate=2.0)
        simulation.sample()
        parent.step(100)
        simulation.sample()
        assert simulation.delta_seconds == 0.2
        ```
    """

stop

stop() -> None

Stop this clock without affecting its parent.

Examples:

simulation = Clock.manual().derive()
simulation.stop()
assert simulation.is_stopped
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def stop(self) -> None:
    """
    Stop this clock without affecting its parent.

    Examples:
        ```python
        simulation = Clock.manual().derive()
        simulation.stop()
        assert simulation.is_stopped
        ```
    """

resume

resume() -> None

Resume this clock after it was stopped.

Examples:

simulation = Clock.manual().derive(is_stopped=True)
simulation.resume()
assert not simulation.is_stopped
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def resume(self) -> None:
    """
    Resume this clock after it was stopped.

    Examples:
        ```python
        simulation = Clock.manual().derive(is_stopped=True)
        simulation.resume()
        assert not simulation.is_stopped
        ```
    """

TextSpan

TextSpan(text: str, *, style: Style | None = None)

A run of text with one style.

Maps to ratatui::text::Span.

Parameters:

  • text (str) –

    The text.

  • style (Style | None, default: None ) –

    The style of the whole run.

Attributes:

Examples:

span = TextSpan('warning', style=Style('yellow', bold=True))
assert span.text == 'warning'
assert 'bold' in span.style.modifiers

Create a TextSpan.

Parameters:

  • text (str) –

    str.

  • style (Style | None, default: None ) –

    Style | None. Defaults to None.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, text: str, *, style: Style | None = None) -> None:
    """
    Create a TextSpan.

    Args:
        text: ``str``.
        style: ``Style | None``. Defaults to ``None``.
    """

text property

text: str

The text of the run.

style property

style: Style

The style of the run.

StyledText

StyledText(spans: Sequence[TextSpan])

Text made of differently styled spans.

Parameters:

Attributes:

Examples:

text = StyledText([TextSpan('error: ', style=Style('red')), TextSpan('disk full')])
assert str(text) == 'error: disk full'
assert len(text.spans) == 2

Create a StyledText.

Parameters:

Methods:

  • from_ansi –

    Read the text that a program prints for a terminal, with its ANSI colors and styles.

  • __str__ –

    The text without styles.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, spans: Sequence[TextSpan]) -> None:
    """
    Create a StyledText.

    Args:
        spans: ``Sequence[TextSpan]``.
    """

spans property

spans: tuple[TextSpan, ...]

The runs of text, in order.

from_ansi classmethod

from_ansi(text: str) -> StyledText

Read the text that a program prints for a terminal, with its ANSI colors and styles.

Use it for the output of a command, a log file or a library that prints in color. The SGR sequences set the colors (the 16 named colors, the 256 palette colors and true colors) and the text modifiers. A newline starts a new line, a tab moves to the next column that is a multiple of eight, and a carriage return moves back to the start of the line, so the text after it writes over the line, as on a terminal. Every other control character and escape sequence (cursor movement, erasing, titles and modes) is removed. A final newline does not start an empty line.

Parameters:

  • text (str) –

    The text, with its escape sequences.

Returns:

  • StyledText –

    The styled text, with a newline between two lines.

Examples:

text = StyledText.from_ansi('\x1b[1;31merror:\x1b[0m disk full')
assert str(text) == 'error: disk full'
assert text.spans[0].style == Style('red', bold=True)

progress = StyledText.from_ansi('downloading 10%\rdownloading 100%\n')
assert str(progress) == 'downloading 100%'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_ansi(cls, text: str) -> StyledText:
    """
    Read the text that a program prints for a terminal, with its ANSI colors and styles.

    Use it for the output of a command, a log file or a library that prints in color.
    The SGR sequences set the colors (the 16 named colors, the 256 palette colors and
    true colors) and the text modifiers. A newline starts a new line, a tab moves to the
    next column that is a multiple of eight, and a carriage return moves back to the
    start of the line, so the text after it writes over the line, as on a terminal.
    Every other control character and escape sequence (cursor movement, erasing,
    titles and modes) is removed. A final newline does not start an empty line.

    Args:
        text: The text, with its escape sequences.

    Returns:
        The styled text, with a newline between two lines.

    Examples:
        ```python
        text = StyledText.from_ansi('\\x1b[1;31merror:\\x1b[0m disk full')
        assert str(text) == 'error: disk full'
        assert text.spans[0].style == Style('red', bold=True)

        progress = StyledText.from_ansi('downloading 10%\\rdownloading 100%\\n')
        assert str(progress) == 'downloading 100%'
        ```
    """

__str__

__str__() -> str

The text without styles.

Examples:

assert str(StyledText([TextSpan('a'), TextSpan('b')])) == 'ab'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __str__(self) -> str:
    """
    The text without styles.

    Examples:
        ```python
        assert str(StyledText([TextSpan('a'), TextSpan('b')])) == 'ab'
        ```
    """

TextLine

One wrapped line of a TextLayout.

Attributes:

  • text (str) –

    The text of the line.

  • start_offset (int) –

    Where the line starts in the original text, counted in Python string offsets.

  • end_offset (int) –

    Where the line ends in the original text, counted in Python string offsets.

  • width (int) –

    The number of cells the line occupies.

Examples:

layout = layout_text('hello world', width=6)
line = layout.lines[0]
assert line.text == 'hello '
assert (line.start_offset, line.end_offset, line.width) == (0, 6, 6)

text property

text: str

The text of the line.

start_offset property

start_offset: int

Where the line starts in the original text, counted in Python string offsets.

end_offset property

end_offset: int

Where the line ends in the original text, counted in Python string offsets.

width property

width: int

The number of cells the line occupies.

TextLayout

Text wrapped to a width, with conversions between cells and string offsets.

Cell positions and Python string offsets agree at grapheme boundaries.

Attributes:

Examples:

layout = layout_text('hello world foo', width=8, cursor_offset=3)
assert [line.text for line in layout.lines] == ['hello ', 'world ', 'foo']
assert layout.cursor_cell == (3, 0)

Methods:

lines property

lines: tuple[TextLine, ...]

The wrapped lines.

cursor_cell property

cursor_cell: tuple[int, int] | None

The (column, row) of the cursor, or None when no cursor was given.

text_offset_at

text_offset_at(column: int, row: int) -> int

The string offset under a cell.

Examples:

layout = layout_text('hello world', width=6)
assert layout.text_offset_at(2, 1) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def text_offset_at(self, column: int, row: int) -> int:
    """
    The string offset under a cell.

    Examples:
        ```python
        layout = layout_text('hello world', width=6)
        assert layout.text_offset_at(2, 1) == 8
        ```
    """

cell_at_text_offset

cell_at_text_offset(offset: int) -> tuple[int, int]

The (column, row) of a string offset.

Examples:

layout = layout_text('hello world', width=6)
assert layout.cell_at_text_offset(8) == (2, 1)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def cell_at_text_offset(self, offset: int) -> tuple[int, int]:
    """
    The ``(column, row)`` of a string offset.

    Examples:
        ```python
        layout = layout_text('hello world', width=6)
        assert layout.cell_at_text_offset(8) == (2, 1)
        ```
    """

TextEditor

TextEditor(text: str = '', *, is_single_line: bool = False)

An editable text buffer with a cursor and undo history.

Draw it with Editor.

Parameters:

  • text (str, default: '' ) –

    The starting text.

  • is_single_line (bool, default: False ) –

    Whether line breaks are refused.

Attributes:

Examples:

editor = TextEditor('abc')
editor.move_cursor(3)
editor.insert_text('d')
assert editor.text == 'abcd'
assert editor.undo()
assert editor.text == 'abc'

Create a TextEditor.

Parameters:

  • text (str, default: '' ) –

    str. Defaults to ''.

  • is_single_line (bool, default: False ) –

    bool. Defaults to False.

Methods:

  • set_text –

    Replace all text.

  • insert_text –

    Insert text at the cursor.

  • handle_key –

    Apply a key press to the text and cursor.

  • move_cursor –

    Move the cursor to a string offset.

  • undo –

    Undo the most recent edit.

  • redo –

    Redo the most recently undone edit.

  • layout –

    Wrap the text to a width and locate the cursor.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, text: str = '', *, is_single_line: bool = False) -> None:
    """
    Create a TextEditor.

    Args:
        text: ``str``. Defaults to ``''``.
        is_single_line: ``bool``. Defaults to ``False``.
    """

text property

text: str

The current text.

is_single_line property

is_single_line: bool

Whether line breaks are refused.

cursor_offset property

cursor_offset: int

The cursor position, counted in Python string offsets.

placeholder_text property writable

placeholder_text: str

The text shown while the editor is empty. Assign to change it.

set_text

set_text(text: str) -> None

Replace all text.

Examples:

editor = TextEditor('old')
editor.set_text('new')
assert editor.text == 'new'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def set_text(self, text: str) -> None:
    """
    Replace all text.

    Examples:
        ```python
        editor = TextEditor('old')
        editor.set_text('new')
        assert editor.text == 'new'
        ```
    """

insert_text

insert_text(text: str) -> None

Insert text at the cursor.

Examples:

editor = TextEditor('ac')
editor.move_cursor(1)
editor.insert_text('b')
assert editor.text == 'abc'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def insert_text(self, text: str) -> None:
    """
    Insert text at the cursor.

    Examples:
        ```python
        editor = TextEditor('ac')
        editor.move_cursor(1)
        editor.insert_text('b')
        assert editor.text == 'abc'
        ```
    """

handle_key

handle_key(key: KeyEvent) -> bool

Apply a key press to the text and cursor.

Parameters:

Returns:

  • bool –

    Whether the editor used the key.

Examples:

editor = TextEditor()
assert editor.handle_key(Event.key_press('x').key)
assert editor.text == 'x'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def handle_key(self, key: KeyEvent) -> bool:
    """
    Apply a key press to the text and cursor.

    Args:
        key: The key event.

    Returns:
        Whether the editor used the key.

    Examples:
        ```python
        editor = TextEditor()
        assert editor.handle_key(Event.key_press('x').key)
        assert editor.text == 'x'
        ```
    """

move_cursor

move_cursor(offset: int) -> None

Move the cursor to a string offset.

Examples:

editor = TextEditor('hello')
editor.move_cursor(2)
assert editor.cursor_offset == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def move_cursor(self, offset: int) -> None:
    """
    Move the cursor to a string offset.

    Examples:
        ```python
        editor = TextEditor('hello')
        editor.move_cursor(2)
        assert editor.cursor_offset == 2
        ```
    """

undo

undo() -> bool

Undo the most recent edit.

Returns:

  • bool –

    Whether there was an edit to undo.

Examples:

editor = TextEditor('a')
editor.insert_text('b')
assert editor.undo()
assert not TextEditor().undo()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def undo(self) -> bool:
    """
    Undo the most recent edit.

    Returns:
        Whether there was an edit to undo.

    Examples:
        ```python
        editor = TextEditor('a')
        editor.insert_text('b')
        assert editor.undo()
        assert not TextEditor().undo()
        ```
    """

redo

redo() -> bool

Redo the most recently undone edit.

Returns:

  • bool –

    Whether there was an edit to redo.

Examples:

editor = TextEditor('a')
editor.insert_text('b')
editor.undo()
assert editor.redo()
assert editor.text == 'ab'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def redo(self) -> bool:
    """
    Redo the most recently undone edit.

    Returns:
        Whether there was an edit to redo.

    Examples:
        ```python
        editor = TextEditor('a')
        editor.insert_text('b')
        editor.undo()
        assert editor.redo()
        assert editor.text == 'ab'
        ```
    """

layout

layout(*, width: int, should_wrap: bool = True) -> TextLayout

Wrap the text to a width and locate the cursor.

Examples:

editor = TextEditor('hello world')
layout = editor.layout(width=6)
assert len(layout.lines) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def layout(self, *, width: int, should_wrap: bool = True) -> TextLayout:
    """
    Wrap the text to a width and locate the cursor.

    Examples:
        ```python
        editor = TextEditor('hello world')
        layout = editor.layout(width=6)
        assert len(layout.lines) == 2
        ```
    """

Editor

Editor(editor: TextEditor, *, area: Rectangle | None = None, style: Style | None = None, first_row: int = 0, should_wrap: bool = True, should_show_cursor: bool = True, mode: WriteMode = 'preserve_background')

Bases: Operation

Draw a TextEditor into a buffer.

Parameters:

  • editor (TextEditor) –

    The editor to draw.

  • area (Rectangle | None, default: None ) –

    The region to draw into. Defaults to the whole target.

  • style (Style | None, default: None ) –

    The style of the text.

  • first_row (int, default: 0 ) –

    The first wrapped row to show, for scrolling.

  • should_wrap (bool, default: True ) –

    Whether long lines wrap.

  • should_show_cursor (bool, default: True ) –

    Whether the cursor cell is highlighted.

  • mode (WriteMode, default: 'preserve_background' ) –

    How text treats the background already in the cells.

Examples:

editor = TextEditor('hi')
buffer = Buffer(width=5, height=1)
buffer.update(Editor(editor, area=Rectangle(0, 0, 5, 1)))
assert buffer.text.startswith('hi')

Create a Editor.

Parameters:

  • editor (TextEditor) –

    TextEditor.

  • area (Rectangle | None, default: None ) –

    Rectangle | None. Defaults to None.

  • style (Style | None, default: None ) –

    Style | None. Defaults to None.

  • first_row (int, default: 0 ) –

    int. Defaults to 0.

  • should_wrap (bool, default: True ) –

    bool. Defaults to True.

  • should_show_cursor (bool, default: True ) –

    bool. Defaults to True.

  • mode (WriteMode, default: 'preserve_background' ) –

    WriteMode. Defaults to 'preserve_background'.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    editor: TextEditor,
    *,
    area: Rectangle | None = None,
    style: Style | None = None,
    first_row: int = 0,
    should_wrap: bool = True,
    should_show_cursor: bool = True,
    mode: WriteMode = 'preserve_background',
) -> None:
    """
    Create a Editor.

    Args:
        editor: ``TextEditor``.
        area: ``Rectangle | None``. Defaults to ``None``.
        style: ``Style | None``. Defaults to ``None``.
        first_row: ``int``. Defaults to ``0``.
        should_wrap: ``bool``. Defaults to ``True``.
        should_show_cursor: ``bool``. Defaults to ``True``.
        mode: ``WriteMode``. Defaults to ``'preserve_background'``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab').then(Write('c', x=2)))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def then(self, other: Operation) -> Operation:
    """
    An operation that applies this operation, then ``other``.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab').then(Write('c', x=2)))
        assert buffer.text.startswith('abc')
        ```
    """

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
    """
    An operation that applies only while ``condition`` is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('wide').when(width > 4))
        assert buffer.text.startswith('wide')
        ```
    """

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab') | Write('c', x=2))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Operation) -> Operation:
    """
    Combine this operation with ``other`` so both run in sequence.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab') | Write('c', x=2))
        assert buffer.text.startswith('abc')
        ```
    """

KeyEvent

A key press, repeat or release.

Get one from Event.key or build an event with Event.key_press.

Attributes:

Examples:

key = Event.key_press('ctrl+c').key
assert key.key == 'c'
assert key.modifiers == {'control'}
assert key.matches('ctrl+c')

Methods:

  • matches –

    Whether this event is the key and modifiers of binding.

key property

key: str

The key name, such as 'a', 'enter' or 'page_up'.

text property

text: str | None

The text the key types, or None for control keys and chords.

modifiers property

modifiers: frozenset[KeyModifier]

The modifier keys held.

kind property

Whether the key was pressed, repeated or released.

matches

matches(binding: str | KeyBinding) -> bool

Whether this event is the key and modifiers of binding.

Examples:

key = Event.key_press('shift+tab').key
assert key.matches('shift+tab')
assert not key.matches('tab')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def matches(self, binding: str | KeyBinding) -> bool:
    """
    Whether this event is the key and modifiers of ``binding``.

    Examples:
        ```python
        key = Event.key_press('shift+tab').key
        assert key.matches('shift+tab')
        assert not key.matches('tab')
        ```
    """

MouseEvent

A mouse press, release, drag, move or scroll.

Attributes:

  • position (Point) –

    The cell under the pointer.

  • column (int) –

    The column under the pointer.

  • row (int) –

    The row under the pointer.

  • kind (MouseEventKind) –

    What the mouse did.

  • button (MouseButton | None) –

    The button involved, or None for moves and scrolls.

  • scroll_x (int) –

    Horizontal scroll steps, negative for left and positive for right.

  • scroll_y (int) –

    Vertical scroll steps, negative for up and positive for down.

Examples:

mouse = Event.mouse_event(column=4, row=2, kind='press', button='left').mouse
assert (mouse.column, mouse.row) == (4, 2)
assert mouse.button == 'left'

position property

position: Point

The cell under the pointer.

column property

column: int

The column under the pointer.

row property

row: int

The row under the pointer.

kind property

What the mouse did.

button property

button: MouseButton | None

The button involved, or None for moves and scrolls.

scroll_x property

scroll_x: int

Horizontal scroll steps, negative for left and positive for right.

scroll_y property

scroll_y: int

Vertical scroll steps, negative for up and positive for down.

Event

Something that happened: input, a resize, a timer or a frame.

Hooks and the runtime report everything as an event. Build events with the class methods to test code without a terminal.

Attributes:

  • kind (EventKind) –

    What the event reports.

  • timestamp_seconds (float) –

    Seconds on the runtime clock when the event happened.

  • key (KeyEvent | None) –

    The key details of a key event, otherwise None.

  • mouse (MouseEvent | None) –

    The mouse details of a mouse event, otherwise None.

  • pasted_text (str | None) –

    The pasted text of a paste event, otherwise None.

  • size (Size | None) –

    The new size of a resize event, otherwise None.

  • timer_key (str | None) –

    The key of a timer event, otherwise None.

  • custom_name (str | None) –

    The name of a custom event, otherwise None.

  • custom_data (str | None) –

    The data of a custom event, otherwise None.

Examples:

event = Event.key_press('q')
assert event.kind == 'key'
assert event.key.key == 'q'
assert Event.resize(width=80, height=24).size == Size(80, 24)

Methods:

  • key_press –

    A key event for a key name with optional +-joined modifiers.

  • paste –

    A paste event.

  • resize –

    A resize event.

  • mouse_event –

    A mouse event.

  • tick –

    Create a tick event, as a runtime with a tick interval reports.

  • timer –

    Create a timer event for the timer called key.

  • wake –

    Create a wake event, which only makes a runtime run an iteration.

  • exit_requested –

    Create the event a runtime reports when the application is asked to exit.

  • custom –

    Create an event your application defines.

  • focus_gained –

    An event reporting that the terminal window gained focus.

  • focus_lost –

    An event reporting that the terminal window lost focus.

kind property

kind: EventKind

What the event reports.

timestamp_seconds property

timestamp_seconds: float

Seconds on the runtime clock when the event happened.

key property

key: KeyEvent | None

The key details of a key event, otherwise None.

mouse property

mouse: MouseEvent | None

The mouse details of a mouse event, otherwise None.

pasted_text property

pasted_text: str | None

The pasted text of a paste event, otherwise None.

size property

size: Size | None

The new size of a resize event, otherwise None.

timer_key property

timer_key: str | None

The key of a timer event, otherwise None.

custom_name property

custom_name: str | None

The name of a custom event, otherwise None.

custom_data property

custom_data: str | None

The data of a custom event, otherwise None.

key_press classmethod

key_press(binding: str, *, kind: KeyEventKind = 'press') -> Event

A key event for a key name with optional +-joined modifiers.

Parameters:

  • binding (str) –

    The key, such as 'q', 'enter' or 'ctrl+c'.

  • kind (KeyEventKind, default: 'press' ) –

    Whether the key is pressed, repeated or released.

Raises:

  • ValueError –

    binding is not a valid key or kind is unknown.

Examples:

event = Event.key_press('alt+enter')
assert event.key.key == 'enter'
assert event.key.modifiers == {'alt'}
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def key_press(cls, binding: str, *, kind: KeyEventKind = 'press') -> Event:
    """
    A key event for a key name with optional ``+``-joined modifiers.

    Args:
        binding: The key, such as ``'q'``, ``'enter'`` or ``'ctrl+c'``.
        kind: Whether the key is pressed, repeated or released.

    Raises:
        ValueError: ``binding`` is not a valid key or ``kind`` is unknown.

    Examples:
        ```python
        event = Event.key_press('alt+enter')
        assert event.key.key == 'enter'
        assert event.key.modifiers == {'alt'}
        ```
    """

paste classmethod

paste(text: str) -> Event

A paste event.

Examples:

assert Event.paste('hello').pasted_text == 'hello'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def paste(cls, text: str) -> Event:
    """
    A paste event.

    Examples:
        ```python
        assert Event.paste('hello').pasted_text == 'hello'
        ```
    """

resize classmethod

resize(*, width: int, height: int) -> Event

A resize event.

Examples:

assert Event.resize(width=3, height=2).size.height == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def resize(cls, *, width: int, height: int) -> Event:
    """
    A resize event.

    Examples:
        ```python
        assert Event.resize(width=3, height=2).size.height == 2
        ```
    """

mouse_event classmethod

mouse_event(*, column: int, row: int, kind: MouseEventKind, button: MouseButton | None = None, scroll_x: int = 0, scroll_y: int = 0) -> Event

A mouse event.

Parameters:

  • column (int) –

    The column under the pointer.

  • row (int) –

    The row under the pointer.

  • kind (MouseEventKind) –

    What the mouse did.

  • button (MouseButton | None, default: None ) –

    The button involved in a press, release or drag.

  • scroll_x (int, default: 0 ) –

    Horizontal scroll steps, negative for left and positive for right.

  • scroll_y (int, default: 0 ) –

    Vertical scroll steps, negative for up and positive for down.

Examples:

event = Event.mouse_event(column=0, row=0, kind='scroll', scroll_y=-1)
assert event.mouse.scroll_y == -1

sideways = Event.mouse_event(column=0, row=0, kind='scroll', scroll_x=2)
assert (sideways.mouse.scroll_x, sideways.mouse.scroll_y) == (2, 0)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def mouse_event(
    cls,
    *,
    column: int,
    row: int,
    kind: MouseEventKind,
    button: MouseButton | None = None,
    scroll_x: int = 0,
    scroll_y: int = 0,
) -> Event:
    """
    A mouse event.

    Args:
        column: The column under the pointer.
        row: The row under the pointer.
        kind: What the mouse did.
        button: The button involved in a press, release or drag.
        scroll_x: Horizontal scroll steps, negative for left and positive for right.
        scroll_y: Vertical scroll steps, negative for up and positive for down.

    Examples:
        ```python
        event = Event.mouse_event(column=0, row=0, kind='scroll', scroll_y=-1)
        assert event.mouse.scroll_y == -1

        sideways = Event.mouse_event(column=0, row=0, kind='scroll', scroll_x=2)
        assert (sideways.mouse.scroll_x, sideways.mouse.scroll_y) == (2, 0)
        ```
    """

tick classmethod

tick() -> Event

Create a tick event, as a runtime with a tick interval reports.

Examples:

assert Event.tick().kind == 'tick'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def tick(cls) -> Event:
    """
    Create a tick event, as a runtime with a tick interval reports.

    Examples:
        ```python
        assert Event.tick().kind == 'tick'
        ```
    """

timer classmethod

timer(key: str) -> Event

Create a timer event for the timer called key.

Examples:

assert Event.timer('blink').timer_key == 'blink'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def timer(cls, key: str) -> Event:
    """
    Create a timer event for the timer called ``key``.

    Examples:
        ```python
        assert Event.timer('blink').timer_key == 'blink'
        ```
    """

wake classmethod

wake() -> Event

Create a wake event, which only makes a runtime run an iteration.

Examples:

assert Event.wake().kind == 'wake'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def wake(cls) -> Event:
    """
    Create a wake event, which only makes a runtime run an iteration.

    Examples:
        ```python
        assert Event.wake().kind == 'wake'
        ```
    """

exit_requested classmethod

exit_requested() -> Event

Create the event a runtime reports when the application is asked to exit.

Examples:

assert Event.exit_requested().kind == 'exit_requested'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def exit_requested(cls) -> Event:
    """
    Create the event a runtime reports when the application is asked to exit.

    Examples:
        ```python
        assert Event.exit_requested().kind == 'exit_requested'
        ```
    """

custom classmethod

custom(name: str, *, data: str | None = None) -> Event

Create an event your application defines.

Inject it with Runtime.inject and listen for it with a hook on 'custom' events. Text such as JSON can travel in data.

Parameters:

  • name (str) –

    What the event is, such as 'volume_changed'.

  • data (str | None, default: None ) –

    Optional text that travels with the event.

Raises:

Examples:

event = Event.custom('volume_changed', data='40')
assert event.kind == 'custom'
assert (event.custom_name, event.custom_data) == ('volume_changed', '40')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def custom(cls, name: str, *, data: str | None = None) -> Event:
    """
    Create an event your application defines.

    Inject it with [`Runtime.inject`][xnano_core._xnano_core.Runtime.inject] and listen
    for it with a hook on ``'custom'`` events. Text such as JSON can travel in ``data``.

    Args:
        name: What the event is, such as ``'volume_changed'``.
        data: Optional text that travels with the event.

    Raises:
        ValueError: The name is empty.

    Examples:
        ```python
        event = Event.custom('volume_changed', data='40')
        assert event.kind == 'custom'
        assert (event.custom_name, event.custom_data) == ('volume_changed', '40')
        ```
    """

focus_gained classmethod

focus_gained() -> Event

An event reporting that the terminal window gained focus.

Examples:

assert Event.focus_gained().kind == 'focus_gained'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def focus_gained(cls) -> Event:
    """
    An event reporting that the terminal window gained focus.

    Examples:
        ```python
        assert Event.focus_gained().kind == 'focus_gained'
        ```
    """

focus_lost classmethod

focus_lost() -> Event

An event reporting that the terminal window lost focus.

Examples:

assert Event.focus_lost().kind == 'focus_lost'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def focus_lost(cls) -> Event:
    """
    An event reporting that the terminal window lost focus.

    Examples:
        ```python
        assert Event.focus_lost().kind == 'focus_lost'
        ```
    """

KeyBinding

A key and modifiers to match against key events.

Examples:

binding = KeyBinding.parse('ctrl+q')
assert binding.matches(Event.key_press('ctrl+q'))
assert not binding.matches(Event.key_press('q'))

Methods:

  • parse –

    Parse text such as 'q', 'ctrl+c', 'shift+tab' or 'alt+enter'.

  • matches –

    Whether event is this key with exactly these modifiers.

parse classmethod

parse(binding: str) -> KeyBinding

Parse text such as 'q', 'ctrl+c', 'shift+tab' or 'alt+enter'.

Raises:

  • ValueError –

    binding is empty or names an unknown key or modifier.

Examples:

assert KeyBinding.parse('ctrl+shift+z').matches(Event.key_press('ctrl+shift+z'))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def parse(cls, binding: str) -> KeyBinding:
    """
    Parse text such as ``'q'``, ``'ctrl+c'``, ``'shift+tab'`` or ``'alt+enter'``.

    Raises:
        ValueError: ``binding`` is empty or names an unknown key or modifier.

    Examples:
        ```python
        assert KeyBinding.parse('ctrl+shift+z').matches(Event.key_press('ctrl+shift+z'))
        ```
    """

matches

matches(event: Event | KeyEvent) -> bool

Whether event is this key with exactly these modifiers.

Examples:

assert KeyBinding.parse('enter').matches(Event.key_press('enter'))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def matches(self, event: Event | KeyEvent) -> bool:
    """
    Whether ``event`` is this key with exactly these modifiers.

    Examples:
        ```python
        assert KeyBinding.parse('enter').matches(Event.key_press('enter'))
        ```
    """

EventStream

The events a runtime reports, as an iterator.

Get one from Runtime.events. Iterate it synchronously with for or asynchronously with async for.

Examples:

with Runtime.offscreen(width=10, height=3) as runtime:
    runtime.mount(Buffer(), geometry='inherit')
    stream = runtime.events()
    runtime.inject(Event.key_press('q'))
    runtime.step()
    assert next(stream).key.key == 'q'

Waker

A handle other threads use to wake a runtime and run code on its thread.

Get one from Runtime.waker. It is the only object besides call_soon_threadsafe that is safe to use from another thread.

Examples:

calls = []
with Runtime.offscreen(width=10, height=3) as runtime:
    waker = runtime.waker()
    waker.call_soon(calls.append, 'woken')
    runtime.step()
assert calls == ['woken']

Methods:

  • call_soon –

    Run callback with arguments on the runtime's thread at its next step.

  • wake –

    Wake the runtime so its next step does not wait.

call_soon

call_soon(callback: Callable[..., object], *arguments: object) -> None

Run callback with arguments on the runtime's thread at its next step.

Examples:

results = []
with Runtime.offscreen(width=10, height=3) as runtime:
    runtime.waker().call_soon(results.append, 1)
    runtime.step()
assert results == [1]
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def call_soon(self, callback: Callable[..., object], *arguments: object) -> None:
    """
    Run ``callback`` with ``arguments`` on the runtime's thread at its next step.

    Examples:
        ```python
        results = []
        with Runtime.offscreen(width=10, height=3) as runtime:
            runtime.waker().call_soon(results.append, 1)
            runtime.step()
        assert results == [1]
        ```
    """

wake

wake() -> None

Wake the runtime so its next step does not wait.

Examples:

with Runtime.offscreen(width=10, height=3) as runtime:
    runtime.waker().wake()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def wake(self) -> None:
    """
    Wake the runtime so its next step does not wait.

    Examples:
        ```python
        with Runtime.offscreen(width=10, height=3) as runtime:
            runtime.waker().wake()
        ```
    """

Hook

A registered callback that can be paused, reprioritized or cancelled.

Higher priorities run first, and ties keep registration order. Register hooks with Surface.add_hook.

Attributes:

Examples:

seen = []
with Runtime.offscreen(width=10, height=3) as runtime:
    buffer = Buffer()
    runtime.mount(buffer, geometry='inherit')
    hook = buffer.add_hook(lambda context: seen.append('key'), events=('key',))
    runtime.inject(Event.key_press('a'))
    runtime.step()
    hook.enabled = False
    runtime.inject(Event.key_press('b'))
    runtime.step()
    hook.cancel()
assert seen == ['key']
assert hook.is_cancelled

Methods:

  • cancel –

    Remove the hook permanently.

enabled property writable

enabled: bool

Whether the hook runs. Assign False to pause it and True to resume.

priority property

priority: int

The hook's priority.

is_cancelled property

is_cancelled: bool

Whether the hook was cancelled.

cancel

cancel() -> None

Remove the hook permanently.

Examples:

buffer = Buffer()
hook = buffer.add_hook(lambda context: None)
hook.cancel()
assert hook.is_cancelled
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def cancel(self) -> None:
    """
    Remove the hook permanently.

    Examples:
        ```python
        buffer = Buffer()
        hook = buffer.add_hook(lambda context: None)
        hook.cancel()
        assert hook.is_cancelled
        ```
    """

ScheduledCall

A callback scheduled on a clock with call_later or call_every.

Attributes:

Examples:

calls = []
with Runtime.offscreen(width=10, height=3) as runtime:
    scheduled = runtime.call_later(1.0, lambda: calls.append('done'))
    runtime.advance_clock(1000)
    runtime.step()
assert calls == ['done']
assert not scheduled.is_cancelled

Methods:

  • cancel –

    Stop the call from running.

is_cancelled property

is_cancelled: bool

Whether the call was cancelled.

cancel

cancel() -> None

Stop the call from running.

Examples:

with Runtime.offscreen(width=10, height=3) as runtime:
    scheduled = runtime.call_later(5.0, lambda: None)
    scheduled.cancel()
    assert scheduled.is_cancelled
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def cancel(self) -> None:
    """
    Stop the call from running.

    Examples:
        ```python
        with Runtime.offscreen(width=10, height=3) as runtime:
            scheduled = runtime.call_later(5.0, lambda: None)
            scheduled.cancel()
            assert scheduled.is_cancelled
        ```
    """

KeyboardCapabilities

What the terminal's keyboard protocol can report.

Attributes:

Examples:

with Runtime.offscreen(width=10, height=3) as runtime:
    capabilities = runtime.device.keyboard
    assert capabilities.enhancement in ('supported', 'unsupported', 'unknown')

enhancement property

enhancement: CapabilityStatus

Whether the enhanced keyboard protocol is available.

disambiguates_keys property

disambiguates_keys: bool

Whether keys such as escape and alt+key are told apart.

reports_event_types property

reports_event_types: bool

Whether key repeats and releases are reported.

reports_all_keys property

reports_all_keys: bool

Whether modifier keys on their own are reported.

unavailable_reason property

unavailable_reason: str | None

Why the enhanced protocol is unavailable, or None.

enabled_features property

enabled_features: frozenset[Literal['disambiguate', 'event_types', 'all_keys']]

The protocol features that are switched on.

InputOptions

InputOptions(*, mouse: Literal['off', 'buttons', 'motion'] = 'off', scroll: bool = False, bracketed_paste: bool = True, focus_reporting: bool = True, keyboard: Literal['off', 'basic', 'disambiguated', 'release_events'] = 'basic', capability_timeout_milliseconds: int = 200, interrupt: Literal['event', 'stop'] = 'event')

The input modes a live terminal asks for.

Requested modes are negotiated with the terminal and restored when the runtime closes.

Parameters:

  • mouse (Literal['off', 'buttons', 'motion'], default: 'off' ) –

    The requested mouse mode. Button and motion reports reach the runtime only when this is not 'off'.

  • scroll (bool, default: False ) –

    Whether mouse wheel reports reach the runtime. It is independent of mouse: InputOptions(scroll=True) delivers the wheel and no button or motion reports.

  • bracketed_paste (bool, default: True ) –

    Whether pasted text arrives as one paste event.

  • focus_reporting (bool, default: True ) –

    Whether the terminal reports focus changes.

  • keyboard (Literal['off', 'basic', 'disambiguated', 'release_events'], default: 'basic' ) –

    The requested keyboard mode. 'off' drops key events that come from the terminal, except Ctrl+C when interrupt is 'stop', so a runtime without a keyboard can still be stopped.

  • capability_timeout_milliseconds (int, default: 200 ) –

    How long to wait for capability answers.

  • interrupt (Literal['event', 'stop'], default: 'event' ) –

    Whether Ctrl+C becomes an 'event' or 'stop' the runtime.

Raises:

  • ValueError –

    A mode is not one of the listed values.

Attributes:

Examples:

options = InputOptions(mouse='buttons', keyboard='release_events')
assert options.mouse == 'buttons'
terminal = TerminalOptions(input=options)

wheel_only = InputOptions(scroll=True, keyboard='off', interrupt='stop')
assert wheel_only.scroll and wheel_only.mouse == 'off'
assert wheel_only.keyboard == 'off'

Create a InputOptions.

Parameters:

  • mouse (Literal['off', 'buttons', 'motion'], default: 'off' ) –

    Literal['off', 'buttons', 'motion']. Defaults to 'off'.

  • scroll (bool, default: False ) –

    bool. Defaults to False.

  • bracketed_paste (bool, default: True ) –

    bool. Defaults to True.

  • focus_reporting (bool, default: True ) –

    bool. Defaults to True.

  • keyboard (Literal['off', 'basic', 'disambiguated', 'release_events'], default: 'basic' ) –

    Literal['off', 'basic', 'disambiguated', 'release_events']. Defaults to 'basic'.

  • capability_timeout_milliseconds (int, default: 200 ) –

    int. Defaults to 200.

  • interrupt (Literal['event', 'stop'], default: 'event' ) –

    Literal['event', 'stop']. Defaults to 'event'.

Methods:

  • __repr__ –

    Every option in keyword form.

  • __eq__ –

    Whether other is an InputOptions with the same options.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    *,
    mouse: Literal['off', 'buttons', 'motion'] = 'off',
    scroll: bool = False,
    bracketed_paste: bool = True,
    focus_reporting: bool = True,
    keyboard: Literal['off', 'basic', 'disambiguated', 'release_events'] = 'basic',
    capability_timeout_milliseconds: int = 200,
    interrupt: Literal['event', 'stop'] = 'event',
) -> None:
    """
    Create a InputOptions.

    Args:
        mouse: ``Literal['off', 'buttons', 'motion']``. Defaults to ``'off'``.
        scroll: ``bool``. Defaults to ``False``.
        bracketed_paste: ``bool``. Defaults to ``True``.
        focus_reporting: ``bool``. Defaults to ``True``.
        keyboard: ``Literal['off', 'basic', 'disambiguated', 'release_events']``. Defaults
            to ``'basic'``.
        capability_timeout_milliseconds: ``int``. Defaults to ``200``.
        interrupt: ``Literal['event', 'stop']``. Defaults to ``'event'``.
    """

mouse property

mouse: Literal['off', 'buttons', 'motion']

The requested mouse mode.

scroll property

scroll: bool

Whether mouse wheel reports are requested.

bracketed_paste property

bracketed_paste: bool

Whether bracketed paste is requested.

focus_reporting property

focus_reporting: bool

Whether focus reporting is requested.

keyboard property

keyboard: Literal['off', 'basic', 'disambiguated', 'release_events']

The requested keyboard mode.

capability_timeout_milliseconds property

capability_timeout_milliseconds: int

How long capability queries wait.

interrupt property

interrupt: Literal['event', 'stop']

How Ctrl+C is handled.

__repr__

__repr__() -> str

Every option in keyword form.

Examples:

assert repr(InputOptions(scroll=True)).startswith("InputOptions(mouse='off', scroll=True")
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __repr__(self) -> str:
    """
    Every option in keyword form.

    Examples:
        ```python
        assert repr(InputOptions(scroll=True)).startswith("InputOptions(mouse='off', scroll=True")
        ```
    """

__eq__

__eq__(other: object) -> bool

Whether other is an InputOptions with the same options.

Examples:

assert InputOptions(scroll=True) == InputOptions(scroll=True)
assert InputOptions(scroll=True) != InputOptions()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> bool:
    """
    Whether ``other`` is an ``InputOptions`` with the same options.

    Examples:
        ```python
        assert InputOptions(scroll=True) == InputOptions(scroll=True)
        assert InputOptions(scroll=True) != InputOptions()
        ```
    """

TerminalOptions

TerminalOptions(*, input: InputOptions | None = None, alternate_screen: bool = True, raw_mode: bool = True, drain_reports_on_exit: bool = True, drain_timeout_milliseconds: int = 250, should_capture_output: bool = True, should_clear_on_close: bool = False)

How a live runtime takes over the terminal.

Parameters:

  • input (InputOptions | None, default: None ) –

    The input modes to request.

  • alternate_screen (bool, default: True ) –

    Whether to draw on the alternate screen.

  • raw_mode (bool, default: True ) –

    Whether to put the terminal in raw mode.

  • drain_reports_on_exit (bool, default: True ) –

    Whether to discard pending terminal replies on exit.

  • drain_timeout_milliseconds (int, default: 250 ) –

    How long to wait while discarding replies.

  • should_clear_on_close (bool, default: False ) –

    Whether the area the runtime drew in is erased when it closes, instead of staying on the screen. Applies when the alternate screen is not used, such as an inline runtime.

  • should_capture_output (bool, default: True ) –

    Whether text written to standard output and standard error while the session is open is held back instead of reaching the screen. It is printed to the stream it was written to when the runtime closes, or read earlier with Runtime.take_captured_output. Captured on Unix only.

Attributes:

Examples:

options = TerminalOptions(alternate_screen=False)
assert options.raw_mode
assert not options.alternate_screen
assert options.should_capture_output
assert not options.should_clear_on_close

Create a TerminalOptions.

Parameters:

  • input (InputOptions | None, default: None ) –

    InputOptions | None. Defaults to None.

  • alternate_screen (bool, default: True ) –

    bool. Defaults to True.

  • raw_mode (bool, default: True ) –

    bool. Defaults to True.

  • drain_reports_on_exit (bool, default: True ) –

    bool. Defaults to True.

  • drain_timeout_milliseconds (int, default: 250 ) –

    int. Defaults to 250.

  • should_capture_output (bool, default: True ) –

    bool. Defaults to True.

  • should_clear_on_close (bool, default: False ) –

    bool. Defaults to False.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    *,
    input: InputOptions | None = None,
    alternate_screen: bool = True,
    raw_mode: bool = True,
    drain_reports_on_exit: bool = True,
    drain_timeout_milliseconds: int = 250,
    should_capture_output: bool = True,
    should_clear_on_close: bool = False,
) -> None:
    """
    Create a TerminalOptions.

    Args:
        input: ``InputOptions | None``. Defaults to ``None``.
        alternate_screen: ``bool``. Defaults to ``True``.
        raw_mode: ``bool``. Defaults to ``True``.
        drain_reports_on_exit: ``bool``. Defaults to ``True``.
        drain_timeout_milliseconds: ``int``. Defaults to ``250``.
        should_capture_output: ``bool``. Defaults to ``True``.
        should_clear_on_close: ``bool``. Defaults to ``False``.
    """

input property

input: InputOptions

The requested input modes.

alternate_screen property

alternate_screen: bool

Whether the alternate screen is used.

raw_mode property

raw_mode: bool

Whether raw mode is used.

drain_reports_on_exit property

drain_reports_on_exit: bool

Whether pending terminal replies are discarded on exit.

drain_timeout_milliseconds property

drain_timeout_milliseconds: int

How long discarding replies may take.

should_capture_output property

should_capture_output: bool

Whether text printed during the session is held back from the screen.

should_clear_on_close property

should_clear_on_close: bool

Whether the runtime's area is erased when it closes.

Cursor

The one cursor a terminal has.

A runtime has exactly one cursor, so it belongs to the runtime rather than to any buffer. It is hidden until it is given a position. Every property may be changed from any thread, and a change is drawn on the next frame even when no cell changed. A live runtime gives the user's own cursor back when it closes.

Get it from Runtime.cursor.

Attributes:

  • position (Point | None) –

    The cell the cursor is at, counted from the top-left of the runtime's area.

  • shape (CursorShape | None) –

    'block', 'bar' or 'underline'; None keeps the user's own shape.

  • is_blinking (bool) –

    Whether the cursor blinks. Setting it without a shape uses a block.

  • is_visible (bool) –

    Whether the cursor is shown when it has a position. True by default.

Examples:

with Runtime.offscreen(width=10, height=3) as runtime:
    runtime.mount(Buffer(), geometry='inherit')
    runtime.cursor.position = (3, 1)
    runtime.cursor.shape = 'bar'
    frame = runtime.render()
    assert frame.cursor_position == Point(3, 1)
    runtime.cursor.is_visible = False
    assert not runtime.render().is_cursor_visible

Methods:

  • follow –

    Keep the cursor at a place inside a buffer, wherever the buffer is.

position property writable

position: Point | None

The cell the cursor is at, counted from the top-left of the runtime's area.

Assign a Point, an (x, y) pair or None to hide the cursor. Assigning a position stops the cursor following a buffer. A cursor outside the area is not shown.

shape property writable

shape: CursorShape | None

'block', 'bar' or 'underline'; None keeps the user's own shape.

Raises:

is_blinking property writable

is_blinking: bool

Whether the cursor blinks. Setting it without a shape uses a block.

is_visible property writable

is_visible: bool

Whether the cursor is shown when it has a position. True by default.

follow

follow(buffer: Buffer | None, *, x: int = 0, y: int = 0) -> None

Keep the cursor at a place inside a buffer, wherever the buffer is.

The cursor is hidden while the buffer or any buffer above it is hidden.

Parameters:

  • buffer (Buffer | None) –

    The buffer to follow, or None to stop following.

  • x (int, default: 0 ) –

    The column inside the buffer.

  • y (int, default: 0 ) –

    The row inside the buffer.

Examples:

with Runtime.offscreen(width=10, height=3) as runtime:
    field = Buffer(width=6, height=1, x=2, y=1)
    runtime.mount(field)
    runtime.cursor.follow(field, x=4)
    assert runtime.render().cursor_position == Point(6, 1)
    field.x = 3
    assert runtime.render().cursor_position == Point(7, 1)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def follow(self, buffer: Buffer | None, *, x: int = 0, y: int = 0) -> None:
    """
    Keep the cursor at a place inside a buffer, wherever the buffer is.

    The cursor is hidden while the buffer or any buffer above it is hidden.

    Args:
        buffer: The buffer to follow, or ``None`` to stop following.
        x: The column inside the buffer.
        y: The row inside the buffer.

    Examples:
        ```python
        with Runtime.offscreen(width=10, height=3) as runtime:
            field = Buffer(width=6, height=1, x=2, y=1)
            runtime.mount(field)
            runtime.cursor.follow(field, x=4)
            assert runtime.render().cursor_position == Point(6, 1)
            field.x = 3
            assert runtime.render().cursor_position == Point(7, 1)
        ```
    """

InputState

The keys and pointer position a runtime currently sees.

Reliable pressed keys require negotiated release reporting. In reliable mode keys are cleared on focus loss, unmount and shutdown. When release reporting is unavailable, pressed_keys is empty and the opt-in timeout estimates appear in estimated_pressed_keys instead, so an estimate never passes as a real held key.

Attributes:

  • held_keys_available (bool) –

    Whether the terminal reports key releases.

  • pressed_keys (frozenset[str]) –

    The keys currently held, when releases are reported, and the held mouse buttons as 'mouse_left', 'mouse_right' and 'mouse_middle'.

  • estimated_pressed_keys (frozenset[str]) –

    The keys guessed to be held from a timeout, when estimates are enabled.

  • pointer_cell (tuple[int, int] | None) –

    The (column, row) under the pointer, or None.

  • last_key (str | None) –

    The key of the latest key event, or None while the latest input was not a key.

  • last_key_kind (Literal['press', 'repeat', 'release'] | None) –

    'press', 'repeat' or 'release' for the latest key event, or None.

  • last_binding (str | None) –

    The latest key event with its modifiers as text such as 'ctrl+s', or None. Modifiers come in the order ctrl, alt, shift, super, meta, hyper.

  • last_mouse_button (MouseButton | None) –

    'left', 'right' or 'middle' for the latest button or motion report, or None.

  • last_mouse_kind (Literal['press', 'release', 'drag', 'move'] | None) –

    'press', 'release', 'drag' or 'move' for the latest button or motion report. None for a wheel report and while the latest input was not a mouse event.

  • last_mouse_position (tuple[int, int] | None) –

    The (column, row) of the latest button or motion report, or None. Unlike pointer_cell it is cleared by any other kind of input.

  • scroll_x (int) –

    The horizontal steps of the latest wheel report of the current step (right is positive), 0 when no wheel report arrived or any other input followed it.

  • scroll_y (int) –

    The vertical steps of the latest wheel report of the current step (down is positive, so scrolling up is -1), 0 when no wheel report arrived or any other input followed it.

  • is_mouse_down (bool) –

    Whether any mouse button is held.

  • last_pasted_text (str | None) –

    The text of the latest paste, or None while the latest input was not a paste.

Each kind of input clears the "latest" values of the other kinds, so a value is None unless the latest input was of its kind. Held mouse buttons are named 'mouse_left', 'mouse_right' and 'mouse_middle' in pressed_keys.

Examples:

with Runtime.offscreen(width=10, height=3) as runtime:
    state = runtime.input
    assert state.pressed_keys == frozenset()
    assert state.pointer_cell is None

    runtime.inject(Event.key_press('ctrl+s'))
    runtime.step()
    assert state.last_key == 's' and state.last_binding == 'ctrl+s'

    runtime.inject(Event.mouse_event(column=4, row=1, kind='press', button='left'))
    runtime.step()
    assert state.is_mouse_down and 'mouse_left' in state.pressed_keys
    assert state.last_mouse_position == (4, 1) and state.last_key is None

    runtime.inject(Event.mouse_event(column=4, row=1, kind='release', button='left'))
    runtime.inject(Event.mouse_event(column=4, row=1, kind='scroll', scroll_y=-1))
    runtime.step()
    assert not state.is_mouse_down
    assert state.scroll_y == -1 and state.last_mouse_kind is None

    runtime.step()
    assert state.scroll_y == 0

Methods:

  • estimate_holds –

    Guess held keys from key repeats when releases are not reported.

held_keys_available property

held_keys_available: bool

Whether the terminal reports key releases.

pressed_keys property

pressed_keys: frozenset[str]

The keys currently held, when releases are reported.

estimated_pressed_keys property

estimated_pressed_keys: frozenset[str]

The keys guessed to be held from a timeout, when estimates are enabled.

pointer_cell property

pointer_cell: tuple[int, int] | None

The (column, row) under the pointer, or None.

last_key property

last_key: str | None

The key of the latest key event, or None.

last_key_kind property

last_key_kind: Literal['press', 'repeat', 'release'] | None

Whether the latest key event was a press, repeat or release.

last_binding property

last_binding: str | None

The latest key event with its modifiers, such as 'ctrl+s'.

last_mouse_button property

last_mouse_button: MouseButton | None

The button of the latest button or motion report.

last_mouse_kind property

last_mouse_kind: Literal['press', 'release', 'drag', 'move'] | None

The kind of the latest button or motion report; None for a wheel report.

last_mouse_position property

last_mouse_position: tuple[int, int] | None

The (column, row) of the latest button or motion report.

scroll_x property

scroll_x: int

The horizontal steps of the latest wheel report of the current step.

scroll_y property

scroll_y: int

The vertical steps of the latest wheel report of the current step.

is_mouse_down property

is_mouse_down: bool

Whether any mouse button is held.

last_pasted_text property

last_pasted_text: str | None

The text of the latest paste.

estimate_holds

estimate_holds(*, timeout_seconds: float | None = None) -> None

Guess held keys from key repeats when releases are not reported.

A terminal repeats only the newest key held, so a press of a different key ends the estimate of the key before it, and at most one key is estimated at a time.

Parameters:

  • timeout_seconds (float | None, default: None ) –

    How long after the last repeat a key counts as held. Positive. None turns estimates off. The timeout cannot account for the operating system's initial repeat delay.

Examples:

with Runtime.offscreen(width=10, height=3) as runtime:
    runtime.mount(Buffer())
    runtime.input.estimate_holds(timeout_seconds=0.5)
    runtime.inject(Event.key_press('left'))
    runtime.inject(Event.key_press('right'))
    runtime.step()
    assert runtime.input.estimated_pressed_keys == {'right'}
    runtime.input.estimate_holds(timeout_seconds=None)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def estimate_holds(self, *, timeout_seconds: float | None = None) -> None:
    """
    Guess held keys from key repeats when releases are not reported.

    A terminal repeats only the newest key held, so a press of a different key ends the
    estimate of the key before it, and at most one key is estimated at a time.

    Args:
        timeout_seconds: How long after the last repeat a key counts as held. Positive.
            ``None`` turns estimates off. The timeout cannot account for the operating
            system's initial repeat delay.

    Examples:
        ```python
        with Runtime.offscreen(width=10, height=3) as runtime:
            runtime.mount(Buffer())
            runtime.input.estimate_holds(timeout_seconds=0.5)
            runtime.inject(Event.key_press('left'))
            runtime.inject(Event.key_press('right'))
            runtime.step()
            assert runtime.input.estimated_pressed_keys == {'right'}
            runtime.input.estimate_holds(timeout_seconds=None)
        ```
    """

Device

The display and terminal a runtime draws on.

Attributes:

Examples:

with Runtime.offscreen(width=40, height=10) as runtime:
    device = runtime.device
    assert device.backend == 'offscreen'
    assert device.size == Size(40, 10)

backend property

backend: Literal['terminal', 'offscreen']

Whether output goes to a real terminal or an in-memory screen.

size property

size: Size

The size of the display in cells.

window_size_in_pixels property

window_size_in_pixels: Size | None

The size of the window in pixels, or None when unknown.

capabilities property

capabilities: TerminalCapabilities

What the terminal can display.

keyboard property

What the keyboard protocol can report.

is_focused property

is_focused: bool

Whether the terminal window has focus.

is_inline property

is_inline: bool

Whether the runtime draws inline instead of taking the whole screen.

is_raw_mode_enabled property

is_raw_mode_enabled: bool

Whether raw mode is on.

is_mouse_capture_enabled property

is_mouse_capture_enabled: bool

Whether mouse capture is on.

is_bracketed_paste_enabled property

is_bracketed_paste_enabled: bool

Whether bracketed paste is on.

is_focus_reporting_enabled property

is_focus_reporting_enabled: bool

Whether focus reporting is on.

is_alternate_screen_enabled property

is_alternate_screen_enabled: bool

Whether the alternate screen is on.

HitArea

A named rectangle that receives mouse hits without needing painted text.

Create one with InputRouter.hit_area.

Attributes:

  • key (str) –

    The name the hit area was registered with.

  • bounds (Rectangle) –

    The rectangle, relative to the target. Assign to move or resize it.

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    buffer = Buffer()
    runtime.mount(buffer, geometry='inherit')
    area = runtime.router.hit_area('button', target=buffer, bounds=Rectangle(2, 1, 4, 2))
    assert area.key == 'button'
    area.bounds = Rectangle(0, 0, 2, 2)
    area.remove()

Methods:

  • remove –

    Unregister the hit area.

key property

key: str

The name the hit area was registered with.

bounds property writable

bounds: Rectangle

The rectangle, relative to the target. Assign to move or resize it.

remove

remove() -> None

Unregister the hit area.

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    buffer = Buffer()
    runtime.mount(buffer, geometry='inherit')
    area = runtime.router.hit_area('x', target=buffer, bounds=Rectangle(0, 0, 2, 2))
    area.remove()
    assert runtime.router.hit_test(0, 0) == ()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def remove(self) -> None:
    """
    Unregister the hit area.

    Examples:
        ```python
        with Runtime.offscreen(width=20, height=5) as runtime:
            buffer = Buffer()
            runtime.mount(buffer, geometry='inherit')
            area = runtime.router.hit_area('x', target=buffer, bounds=Rectangle(0, 0, 2, 2))
            area.remove()
            assert runtime.router.hit_test(0, 0) == ()
        ```
    """

FocusScope

A group of input targets, optionally modal.

Modal scopes receive input first. Scopes change routing only, never application state. Use it as a context manager to close it automatically.

Attributes:

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    dialog = Buffer(width=10, height=3)
    runtime.mount(dialog)
    with runtime.router.scope(dialog, modal=True) as scope:
        assert scope.is_active
    assert not scope.is_active

Methods:

  • close –

    Close the scope.

is_active property

is_active: bool

Whether the scope is open.

close

close() -> None

Close the scope.

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    dialog = Buffer(width=10, height=3)
    runtime.mount(dialog)
    scope = runtime.router.scope(dialog)
    scope.close()
    assert not scope.is_active
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def close(self) -> None:
    """
    Close the scope.

    Examples:
        ```python
        with Runtime.offscreen(width=20, height=5) as runtime:
            dialog = Buffer(width=10, height=3)
            runtime.mount(dialog)
            scope = runtime.router.scope(dialog)
            scope.close()
            assert not scope.is_active
        ```
    """

InputRouter

Routes input events to buffers: handlers, hit areas, focus and scopes.

Get it from Runtime.router.

Examples:

seen = []
with Runtime.offscreen(width=20, height=5) as runtime:
    buffer = Buffer()
    runtime.mount(buffer, geometry='inherit')
    runtime.router.on(lambda context: seen.append(context.event.key.key), target=buffer, events=('key',))
    runtime.inject(Event.key_press('z'))
    runtime.step()
assert seen == ['z']

Methods:

  • on –

    Call callback when an event reaches target.

  • hit_area –

    Register target-local geometry without requiring painted glyphs.

  • hit_test –

    The hit areas under a cell, topmost first.

  • scope –

    Open a focus scope around target.

  • focus –

    Give target input focus.

  • clear_focus –

    Remove input focus from every buffer.

on

on(callback: Callable[[EventContext], None], *, target: Buffer | Region, events: Sequence[EventKind] = ('key', 'mouse', 'paste'), binding: KeyBinding | str | None = None, priority: int = 0) -> Hook

Call callback when an event reaches target.

Parameters:

  • callback (Callable[[EventContext], None]) –

    Called with an EventContext.

  • target (Buffer | Region) –

    The buffer or region that receives the events.

  • events (Sequence[EventKind], default: ('key', 'mouse', 'paste') ) –

    Which kinds of events to handle.

  • binding (KeyBinding | str | None, default: None ) –

    Only handle key events matching this binding.

  • priority (int, default: 0 ) –

    Higher priorities run first.

Returns:

  • Hook –

    A hook to pause or cancel the handler.

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    buffer = Buffer()
    runtime.mount(buffer, geometry='inherit')
    hook = runtime.router.on(lambda context: context.consume(), target=buffer, binding='ctrl+q')
    hook.cancel()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def on(
    self,
    callback: Callable[[EventContext], None],
    *,
    target: Buffer | Region,
    events: Sequence[EventKind] = ('key', 'mouse', 'paste'),
    binding: KeyBinding | str | None = None,
    priority: int = 0,
) -> Hook:
    """
    Call ``callback`` when an event reaches ``target``.

    Args:
        callback: Called with an ``EventContext``.
        target: The buffer or region that receives the events.
        events: Which kinds of events to handle.
        binding: Only handle key events matching this binding.
        priority: Higher priorities run first.

    Returns:
        A hook to pause or cancel the handler.

    Examples:
        ```python
        with Runtime.offscreen(width=20, height=5) as runtime:
            buffer = Buffer()
            runtime.mount(buffer, geometry='inherit')
            hook = runtime.router.on(lambda context: context.consume(), target=buffer, binding='ctrl+q')
            hook.cancel()
        ```
    """

hit_area

hit_area(key: str, *, target: Buffer | Region, bounds: Rectangle, layer: int = 0) -> HitArea

Register target-local geometry without requiring painted glyphs.

Parameters:

  • key (str) –

    A name for the hit area.

  • target (Buffer | Region) –

    The buffer or region the bounds are relative to.

  • bounds (Rectangle) –

    The hit rectangle.

  • layer (int, default: 0 ) –

    Higher layers are hit first.

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    buffer = Buffer()
    runtime.mount(buffer, geometry='inherit')
    runtime.router.hit_area('button', target=buffer, bounds=Rectangle(2, 1, 4, 2))
    assert runtime.router.hit_test(3, 1)[0].key == 'button'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def hit_area(
    self, key: str, *, target: Buffer | Region, bounds: Rectangle, layer: int = 0
) -> HitArea:
    """
    Register target-local geometry without requiring painted glyphs.

    Args:
        key: A name for the hit area.
        target: The buffer or region the bounds are relative to.
        bounds: The hit rectangle.
        layer: Higher layers are hit first.

    Examples:
        ```python
        with Runtime.offscreen(width=20, height=5) as runtime:
            buffer = Buffer()
            runtime.mount(buffer, geometry='inherit')
            runtime.router.hit_area('button', target=buffer, bounds=Rectangle(2, 1, 4, 2))
            assert runtime.router.hit_test(3, 1)[0].key == 'button'
        ```
    """

hit_test

hit_test(column: int, row: int) -> tuple[HitArea, ...]

The hit areas under a cell, topmost first.

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    assert runtime.router.hit_test(0, 0) == ()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def hit_test(self, column: int, row: int) -> tuple[HitArea, ...]:
    """
    The hit areas under a cell, topmost first.

    Examples:
        ```python
        with Runtime.offscreen(width=20, height=5) as runtime:
            assert runtime.router.hit_test(0, 0) == ()
        ```
    """

scope

scope(target: Buffer, *, modal: bool = False) -> FocusScope

Open a focus scope around target.

Parameters:

  • target (Buffer) –

    The buffer whose subtree forms the scope.

  • modal (bool, default: False ) –

    Whether the scope receives input before everything else.

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    dialog = Buffer(width=10, height=3)
    runtime.mount(dialog)
    with runtime.router.scope(dialog, modal=True) as scope:
        assert scope.is_active
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def scope(self, target: Buffer, *, modal: bool = False) -> FocusScope:
    """
    Open a focus scope around ``target``.

    Args:
        target: The buffer whose subtree forms the scope.
        modal: Whether the scope receives input before everything else.

    Examples:
        ```python
        with Runtime.offscreen(width=20, height=5) as runtime:
            dialog = Buffer(width=10, height=3)
            runtime.mount(dialog)
            with runtime.router.scope(dialog, modal=True) as scope:
                assert scope.is_active
        ```
    """

focus

focus(target: Buffer) -> bool

Give target input focus.

Returns:

  • bool –

    Whether the buffer could take focus.

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    buffer = Buffer()
    runtime.mount(buffer, geometry='inherit')
    assert runtime.router.focus(buffer) in (True, False)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def focus(self, target: Buffer) -> bool:
    """
    Give ``target`` input focus.

    Returns:
        Whether the buffer could take focus.

    Examples:
        ```python
        with Runtime.offscreen(width=20, height=5) as runtime:
            buffer = Buffer()
            runtime.mount(buffer, geometry='inherit')
            assert runtime.router.focus(buffer) in (True, False)
        ```
    """

clear_focus

clear_focus() -> None

Remove input focus from every buffer.

Examples:

with Runtime.offscreen(width=20, height=5) as runtime:
    runtime.router.clear_focus()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def clear_focus(self) -> None:
    """
    Remove input focus from every buffer.

    Examples:
        ```python
        with Runtime.offscreen(width=20, height=5) as runtime:
            runtime.router.clear_focus()
        ```
    """

TerminalCapabilities

What a terminal can display.

Attributes:

Examples:

capabilities = detect_terminal_capabilities(timeout_milliseconds=10)
assert capabilities.graphics_protocol in ('half_blocks', 'kitty', 'sixel', 'iterm2')

is_terminal property

is_terminal: bool

Whether standard output is a terminal.

is_live_terminal_available property

is_live_terminal_available: bool

Whether a live terminal runtime can run here.

color_profile property

color_profile: ColorProfile

How many colors the terminal displays.

graphics_protocol property

graphics_protocol: Literal['half_blocks', 'kitty', 'sixel', 'iterm2']

The best image protocol the terminal supports.

cell_size_in_pixels property

cell_size_in_pixels: tuple[int, int] | None

The (width, height) of one cell in pixels, or None when unknown.

synchronized_output property

synchronized_output: CapabilityStatus

Whether the terminal supports synchronized output.

Expression

Bases: Generic[ValueType_co]

A value or action described now and evaluated later against a buffer or runtime.

Evaluation is explicit. Using an expression where Python wants a truth value raises TypeError; combine conditions with &, | and ~ instead.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=8, height=1)
assert buffer.inspect(width + 2) == 10
assert (width + 2).evaluate(EvaluationContext(buffer=buffer)) == 10

Methods:

  • evaluate –

    Compute the expression's value.

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

Predicate

Bases: Expression[bool]

A condition that evaluates to True or False.

Build predicates by comparing values, then combine them with &, | and ~. == and != also build predicates, so (Width > 4) == False is a condition and not a bool.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
buffer = Buffer(width=8, height=2)
assert buffer.inspect((width > 4) & (height < 3))
assert not buffer.inspect(~(width > 4))

Methods:

  • __and__ –

    True when both predicates are true.

  • __or__ –

    True when either predicate is true.

  • __invert__ –

    True when the predicate is false.

  • __eq__ –

    A predicate that is true when this condition has the same truth value as other.

  • __ne__ –

    A predicate that is true when this condition has a different truth value than other.

  • __hash__ –

    The identity hash, which keeps predicates usable in sets and dictionaries.

  • choose –

    A value that is when_true while the condition holds and when_false otherwise.

  • evaluate –

    Compute the expression's value.

__and__

__and__(other: Predicate) -> Predicate

True when both predicates are true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=8, height=1)
assert buffer.inspect((width > 4) & (width < 10))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __and__(self, other: Predicate) -> Predicate:
    """
    True when both predicates are true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=8, height=1)
        assert buffer.inspect((width > 4) & (width < 10))
        ```
    """

__or__

__or__(other: Predicate) -> Predicate

True when either predicate is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=8, height=1)
assert buffer.inspect((width < 4) | (width > 6))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Predicate) -> Predicate:
    """
    True when either predicate is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=8, height=1)
        assert buffer.inspect((width < 4) | (width > 6))
        ```
    """

__invert__

__invert__() -> Predicate

True when the predicate is false.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=8, height=1)
assert buffer.inspect(~(width < 4))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __invert__(self) -> Predicate:
    """
    True when the predicate is false.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=8, height=1)
        assert buffer.inspect(~(width < 4))
        ```
    """

__eq__

__eq__(other: object) -> Predicate

A predicate that is true when this condition has the same truth value as other.

Examples:

from xnano_core._xnano_core import Width

wide = Width > 4
assert Buffer(width=2, height=1).inspect(wide == False)  # noqa: E712
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when this condition has the same truth value as ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        wide = Width > 4
        assert Buffer(width=2, height=1).inspect(wide == False)  # noqa: E712
        ```
    """

__ne__

__ne__(other: object) -> Predicate

A predicate that is true when this condition has a different truth value than other.

Examples:

from xnano_core._xnano_core import Width

wide = Width > 4
assert Buffer(width=2, height=1).inspect(wide != True)  # noqa: E712
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when this condition has a different truth value than ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        wide = Width > 4
        assert Buffer(width=2, height=1).inspect(wide != True)  # noqa: E712
        ```
    """

__hash__

__hash__() -> int

The identity hash, which keeps predicates usable in sets and dictionaries.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __hash__(self) -> int:
    """The identity hash, which keeps predicates usable in sets and dictionaries."""

choose

choose(when_true: NumberType, when_false: NumberType) -> NumericValue[NumberType]
choose(when_true: NumericValue[NumberType], when_false: NumericValue[NumberType] | NumberType) -> NumericValue[NumberType]
choose(when_true: ChoiceType | Value[ChoiceType], when_false: ChoiceType | Value[ChoiceType]) -> Value[ChoiceType]
choose(when_true: object, when_false: object) -> Value[object]

A value that is when_true while the condition holds and when_false otherwise.

Numbers give a NumericValue, so the result supports arithmetic and ordering. Raises TypeError when evaluated if the predicate is not a condition.

Examples:

from xnano_core._xnano_core import Width

wide = Width > 10
assert Buffer(width=20, height=1).inspect(wide.choose(1, 2)) == 1
assert Buffer(width=4, height=1).inspect(wide.choose(1, 2)) == 2
assert Buffer(width=4, height=1).inspect(wide.choose(Width, 0) + 1) == 1
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def choose(self, when_true: object, when_false: object) -> Value[object]:
    """
    A value that is ``when_true`` while the condition holds and ``when_false`` otherwise.

    Numbers give a [`NumericValue`][xnano_core._xnano_core.NumericValue], so the result
    supports arithmetic and ordering. Raises ``TypeError`` when evaluated if the predicate
    is not a condition.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        wide = Width > 10
        assert Buffer(width=20, height=1).inspect(wide.choose(1, 2)) == 1
        assert Buffer(width=4, height=1).inspect(wide.choose(1, 2)) == 2
        assert Buffer(width=4, height=1).inspect(wide.choose(Width, 0) + 1) == 1
        ```
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

Value

Bases: Expression[ValueType]

An expression that evaluates to a value.

== and != build conditions, as equals and not_equals do. A comparison with a value that has not been seen yet, such as the key before any key was pressed, is false (!= included) and never an error. Comparing with the literal None raises TypeError because that condition could never hold; to test that a key arrived, compare with the key itself or register the hook for the 'key' event. A value is hashed by identity, so expressions stay usable in sets and dictionaries. Because == builds a condition, in and .index() on a list or tuple of expressions raise TypeError as soon as they compare an expression with a different item; look an expression up by identity (any(item is value for item in items)) or keep expressions in a set or dictionary. Comparing an expression with an object that cannot be an expression, such as object(), gives False for == and True for !=.

Attributes:

Examples:

from xnano_core._xnano_core import _reference

bounds = _reference('Bounds', 'value')
assert isinstance(bounds, Value)
buffer = Buffer(width=4, height=1)
assert buffer.inspect(bounds.equals(Rectangle(0, 0, 4, 1)))
assert buffer.inspect(bounds == Rectangle(0, 0, 4, 1))

Methods:

  • equals –

    A predicate that is true when the value equals other.

  • not_equals –

    A predicate that is true when the value differs from other.

  • contains –

    A condition that is true while this rectangle contains the point other.

  • __eq__ –

    A predicate that is true when the value equals other; the same as equals.

  • __ne__ –

    A predicate that is true when the value differs from other; the same as not_equals.

  • __hash__ –

    The identity hash, which keeps expressions usable in sets and dictionaries.

  • evaluate –

    Compute the expression's value.

x property

The column of a Point or the left edge of a Rectangle.

Examples:

from xnano_core._xnano_core import Position

assert Buffer(width=4, height=1, x=3, y=2).inspect(Position.x) == 3

y property

The row of a Point or the top edge of a Rectangle.

Examples:

from xnano_core._xnano_core import Position

assert Buffer(width=4, height=1, x=3, y=2).inspect(Position.y) == 2

width property

width: NumericValue[int]

The width of a Size or a Rectangle.

Examples:

from xnano_core._xnano_core import BufferSize

assert Buffer(width=6, height=2).inspect(BufferSize.width) == 6

height property

height: NumericValue[int]

The height of a Size or a Rectangle.

Examples:

from xnano_core._xnano_core import BufferSize

assert Buffer(width=6, height=2).inspect(BufferSize.height) == 2

right property

right: NumericValue[int]

The first column after a Rectangle.

Examples:

from xnano_core._xnano_core import Bounds

assert Buffer(width=6, height=2, x=1).inspect(Bounds.right) == 7

bottom property

bottom: NumericValue[int]

The first row after a Rectangle.

Examples:

from xnano_core._xnano_core import Bounds

assert Buffer(width=6, height=2, y=1).inspect(Bounds.bottom) == 3

equals

equals(other: ValueType | Value[ValueType]) -> Predicate

A predicate that is true when the value equals other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def equals(self, other: ValueType | Value[ValueType]) -> Predicate:
    """
    A predicate that is true when the value equals ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width.equals(20))
        ```
    """

not_equals

not_equals(other: ValueType | Value[ValueType]) -> Predicate

A predicate that is true when the value differs from other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def not_equals(self, other: ValueType | Value[ValueType]) -> Predicate:
    """
    A predicate that is true when the value differs from ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width.not_equals(5))
        ```
    """

contains

contains(other: Point | Value[Point] | Value[Point | None]) -> Predicate

A condition that is true while this rectangle contains the point other.

It is false, never an error, while either side has no value yet, such as a mouse position before any mouse event.

Parameters:

Examples:

from xnano_core._xnano_core import Bounds, Point

buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def contains(
    self: Value[Rectangle],
    other: Point | Value[Point] | Value[Point | None],
) -> Predicate:
    """
    A condition that is true while this rectangle contains the point ``other``.

    It is false, never an error, while either side has no value yet, such as a mouse
    position before any mouse event.

    Args:
        other: The ``Point`` (or an expression that produces one) to look for.

    Examples:
        ```python
        from xnano_core._xnano_core import Bounds, Point

        buffer = Buffer(width=4, height=2)
        assert buffer.inspect(Bounds.contains(Point(3, 1)))
        assert not buffer.inspect(Bounds.contains(Point(4, 1)))
        ```
    """

__eq__

__eq__(other: object) -> Predicate

A predicate that is true when the value equals other; the same as equals.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when the value equals ``other``; the same as ``equals``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width == 20)
        ```
    """

__ne__

__ne__(other: object) -> Predicate

A predicate that is true when the value differs from other; the same as not_equals.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when the value differs from ``other``; the same as ``not_equals``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width != 5)
        ```
    """

__hash__

__hash__() -> int

The identity hash, which keeps expressions usable in sets and dictionaries.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __hash__(self) -> int:
    """The identity hash, which keeps expressions usable in sets and dictionaries."""

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

NumericValue

Bases: Value[NumberType]

A numeric expression that supports comparisons and arithmetic.

Arithmetic and comparisons build new expressions instead of computing right away.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=8, height=3)
assert buffer.inspect(width + 2) == 10
assert buffer.inspect(10 - width) == 2
assert buffer.inspect(width > 4)
assert buffer.inspect(-width) == -8

Methods:

  • __lt__ –

    A predicate that is true when the value is less than other.

  • __le__ –

    A predicate that is true when the value is at most other.

  • __gt__ –

    A predicate that is true when the value is greater than other.

  • __ge__ –

    A predicate that is true when the value is at least other.

  • __add__ –

    The sum of the value and other.

  • __sub__ –

    The value minus other.

  • __mul__ –

    The product of the value and other.

  • __truediv__ –

    The value divided by other.

  • __mod__ –

    The remainder of dividing the value by other.

  • __neg__ –

    The value with its sign flipped.

  • __rtruediv__ –

    other divided by the value.

  • __rmod__ –

    The remainder of dividing other by the value.

  • __floordiv__ –

    The value divided by other, rounded toward negative infinity like Python's //.

  • __rfloordiv__ –

    other divided by the value, rounded toward negative infinity.

  • __pow__ –

    The value raised to the power other.

  • __rpow__ –

    other raised to the power of the value.

  • __abs__ –

    The absolute value.

  • __floor__ –

    The value rounded down to a whole number, used by math.floor.

  • __ceil__ –

    The value rounded up to a whole number, used by math.ceil.

  • __round__ –

    The value rounded to the nearest whole number, halves away from zero.

  • minimum –

    The smaller of the value and other.

  • maximum –

    The larger of the value and other.

  • clamp –

    The value limited to the range from lowest to highest.

  • evaluate –

    Compute the expression's value.

  • equals –

    A predicate that is true when the value equals other.

  • not_equals –

    A predicate that is true when the value differs from other.

  • contains –

    A condition that is true while this rectangle contains the point other.

  • __eq__ –

    A predicate that is true when the value equals other; the same as equals.

  • __ne__ –

    A predicate that is true when the value differs from other; the same as not_equals.

  • __hash__ –

    The identity hash, which keeps expressions usable in sets and dictionaries.

Attributes:

x property

The column of a Point or the left edge of a Rectangle.

Examples:

from xnano_core._xnano_core import Position

assert Buffer(width=4, height=1, x=3, y=2).inspect(Position.x) == 3

y property

The row of a Point or the top edge of a Rectangle.

Examples:

from xnano_core._xnano_core import Position

assert Buffer(width=4, height=1, x=3, y=2).inspect(Position.y) == 2

width property

width: NumericValue[int]

The width of a Size or a Rectangle.

Examples:

from xnano_core._xnano_core import BufferSize

assert Buffer(width=6, height=2).inspect(BufferSize.width) == 6

height property

height: NumericValue[int]

The height of a Size or a Rectangle.

Examples:

from xnano_core._xnano_core import BufferSize

assert Buffer(width=6, height=2).inspect(BufferSize.height) == 2

right property

right: NumericValue[int]

The first column after a Rectangle.

Examples:

from xnano_core._xnano_core import Bounds

assert Buffer(width=6, height=2, x=1).inspect(Bounds.right) == 7

bottom property

bottom: NumericValue[int]

The first row after a Rectangle.

Examples:

from xnano_core._xnano_core import Bounds

assert Buffer(width=6, height=2, y=1).inspect(Bounds.bottom) == 3

__lt__

A predicate that is true when the value is less than other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=3, height=1).inspect(width < 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __lt__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
    """
    A predicate that is true when the value is less than ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=3, height=1).inspect(width < 4)
        ```
    """

__le__

A predicate that is true when the value is at most other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width <= 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __le__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
    """
    A predicate that is true when the value is at most ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=4, height=1).inspect(width <= 4)
        ```
    """

__gt__

A predicate that is true when the value is greater than other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=5, height=1).inspect(width > 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __gt__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
    """
    A predicate that is true when the value is greater than ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=5, height=1).inspect(width > 4)
        ```
    """

__ge__

A predicate that is true when the value is at least other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width >= 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ge__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
    """
    A predicate that is true when the value is at least ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=4, height=1).inspect(width >= 4)
        ```
    """

__add__

The sum of the value and other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width + 1) == 5
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __add__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The sum of the value and ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=4, height=1).inspect(width + 1) == 5
        ```
    """

__sub__

The value minus other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width - 1) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __sub__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The value minus ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=4, height=1).inspect(width - 1) == 3
        ```
    """

__mul__

The product of the value and other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
assert Buffer(width=4, height=3).inspect(width * height) == 12
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __mul__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The product of the value and ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        height = _reference('Height', 'numeric_property')
        assert Buffer(width=4, height=3).inspect(width * height) == 12
        ```
    """

__truediv__

__truediv__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]

The value divided by other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width / 2) == 4.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __truediv__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The value divided by ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=8, height=1).inspect(width / 2) == 4.0
        ```
    """

__mod__

The remainder of dividing the value by other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width % 3) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __mod__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The remainder of dividing the value by ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=8, height=1).inspect(width % 3) == 2
        ```
    """

__neg__

__neg__() -> NumericValue[NumberType]

The value with its sign flipped.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(-width) == -8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __neg__(self) -> NumericValue[NumberType]:
    """
    The value with its sign flipped.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=8, height=1).inspect(-width) == -8
        ```
    """

__rtruediv__

__rtruediv__(other: float) -> NumericValue[float]

other divided by the value.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=8, height=1).inspect(16 / Width) == 2.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __rtruediv__(self, other: float) -> NumericValue[float]:
    """
    ``other`` divided by the value.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=8, height=1).inspect(16 / Width) == 2.0
        ```
    """

__rmod__

__rmod__(other: float) -> NumericValue[float]

The remainder of dividing other by the value.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=3, height=1).inspect(10 % Width) == 1
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __rmod__(self, other: float) -> NumericValue[float]:
    """
    The remainder of dividing ``other`` by the value.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=3, height=1).inspect(10 % Width) == 1
        ```
    """

__floordiv__

__floordiv__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[int | float]

The value divided by other, rounded toward negative infinity like Python's //.

Dividing by zero raises ZeroDivisionError when the expression is evaluated.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=7, height=1).inspect(Width // 2) == 3
assert Buffer(width=7, height=1).inspect(-Width // 2) == -4
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __floordiv__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[int | float]:
    """
    The value divided by ``other``, rounded toward negative infinity like Python's ``//``.

    Dividing by zero raises ``ZeroDivisionError`` when the expression is evaluated.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=7, height=1).inspect(Width // 2) == 3
        assert Buffer(width=7, height=1).inspect(-Width // 2) == -4
        ```
    """

__rfloordiv__

__rfloordiv__(other: float) -> NumericValue[int | float]

other divided by the value, rounded toward negative infinity.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=4, height=1).inspect(9 // Width) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __rfloordiv__(self, other: float) -> NumericValue[int | float]:
    """
    ``other`` divided by the value, rounded toward negative infinity.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=4, height=1).inspect(9 // Width) == 2
        ```
    """

__pow__

__pow__(other: float | NumericValue[int] | NumericValue[float], modulo: None = None) -> NumericValue[int | float]

The value raised to the power other.

Whole-number results stay integers; a negative or fractional exponent gives a float.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=3, height=1).inspect(Width**2) == 9
assert Buffer(width=4, height=1).inspect(Width**0.5) == 2.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __pow__(
    self, other: float | NumericValue[int] | NumericValue[float], modulo: None = None
) -> NumericValue[int | float]:
    """
    The value raised to the power ``other``.

    Whole-number results stay integers; a negative or fractional exponent gives a float.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=3, height=1).inspect(Width**2) == 9
        assert Buffer(width=4, height=1).inspect(Width**0.5) == 2.0
        ```
    """

__rpow__

__rpow__(other: float, modulo: None = None) -> NumericValue[int | float]

other raised to the power of the value.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=3, height=1).inspect(2**Width) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __rpow__(self, other: float, modulo: None = None) -> NumericValue[int | float]:
    """
    ``other`` raised to the power of the value.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=3, height=1).inspect(2**Width) == 8
        ```
    """

__abs__

__abs__() -> NumericValue[NumberType]

The absolute value.

Examples:

from xnano_core._xnano_core import X

assert Buffer(width=1, height=1, x=-5).inspect(abs(X)) == 5
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __abs__(self) -> NumericValue[NumberType]:
    """
    The absolute value.

    Examples:
        ```python
        from xnano_core._xnano_core import X

        assert Buffer(width=1, height=1, x=-5).inspect(abs(X)) == 5
        ```
    """

__floor__

__floor__() -> NumericValue[int]

The value rounded down to a whole number, used by math.floor.

Examples:

import math

from xnano_core._xnano_core import Width

assert Buffer(width=7, height=1).inspect(math.floor(Width / 2)) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __floor__(self) -> NumericValue[int]:
    """
    The value rounded down to a whole number, used by ``math.floor``.

    Examples:
        ```python
        import math

        from xnano_core._xnano_core import Width

        assert Buffer(width=7, height=1).inspect(math.floor(Width / 2)) == 3
        ```
    """

__ceil__

__ceil__() -> NumericValue[int]

The value rounded up to a whole number, used by math.ceil.

Examples:

import math

from xnano_core._xnano_core import Width

assert Buffer(width=7, height=1).inspect(math.ceil(Width / 2)) == 4
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ceil__(self) -> NumericValue[int]:
    """
    The value rounded up to a whole number, used by ``math.ceil``.

    Examples:
        ```python
        import math

        from xnano_core._xnano_core import Width

        assert Buffer(width=7, height=1).inspect(math.ceil(Width / 2)) == 4
        ```
    """

__round__

__round__(digits: None = None) -> NumericValue[int]

The value rounded to the nearest whole number, halves away from zero.

Unlike Python's round, a half rounds away from zero, so 2.5 becomes 3. Passing a number of digits raises TypeError.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=5, height=1).inspect(round(Width / 2)) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __round__(self, digits: None = None) -> NumericValue[int]:
    """
    The value rounded to the nearest whole number, halves away from zero.

    Unlike Python's ``round``, a half rounds away from zero, so ``2.5`` becomes ``3``.
    Passing a number of digits raises ``TypeError``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=5, height=1).inspect(round(Width / 2)) == 3
        ```
    """

minimum

minimum(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]

The smaller of the value and other.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=20, height=1).inspect(Width.minimum(8)) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def minimum(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[NumberType]:
    """
    The smaller of the value and ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=20, height=1).inspect(Width.minimum(8)) == 8
        ```
    """

maximum

maximum(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]

The larger of the value and other.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=2, height=1).inspect(Width.maximum(8)) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def maximum(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[NumberType]:
    """
    The larger of the value and ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=2, height=1).inspect(Width.maximum(8)) == 8
        ```
    """

clamp

clamp(lowest: float | NumericValue[int] | NumericValue[float], highest: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]

The value limited to the range from lowest to highest.

Raises TypeError when evaluated if lowest is greater than highest.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=50, height=1).inspect(Width.clamp(0, 10)) == 10
assert Buffer(width=5, height=1).inspect(Width.clamp(8, 10)) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def clamp(
    self,
    lowest: float | NumericValue[int] | NumericValue[float],
    highest: float | NumericValue[int] | NumericValue[float],
) -> NumericValue[NumberType]:
    """
    The value limited to the range from ``lowest`` to ``highest``.

    Raises ``TypeError`` when evaluated if ``lowest`` is greater than ``highest``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=50, height=1).inspect(Width.clamp(0, 10)) == 10
        assert Buffer(width=5, height=1).inspect(Width.clamp(8, 10)) == 8
        ```
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

equals

equals(other: ValueType | Value[ValueType]) -> Predicate

A predicate that is true when the value equals other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def equals(self, other: ValueType | Value[ValueType]) -> Predicate:
    """
    A predicate that is true when the value equals ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width.equals(20))
        ```
    """

not_equals

not_equals(other: ValueType | Value[ValueType]) -> Predicate

A predicate that is true when the value differs from other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def not_equals(self, other: ValueType | Value[ValueType]) -> Predicate:
    """
    A predicate that is true when the value differs from ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width.not_equals(5))
        ```
    """

contains

contains(other: Point | Value[Point] | Value[Point | None]) -> Predicate

A condition that is true while this rectangle contains the point other.

It is false, never an error, while either side has no value yet, such as a mouse position before any mouse event.

Parameters:

Examples:

from xnano_core._xnano_core import Bounds, Point

buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def contains(
    self: Value[Rectangle],
    other: Point | Value[Point] | Value[Point | None],
) -> Predicate:
    """
    A condition that is true while this rectangle contains the point ``other``.

    It is false, never an error, while either side has no value yet, such as a mouse
    position before any mouse event.

    Args:
        other: The ``Point`` (or an expression that produces one) to look for.

    Examples:
        ```python
        from xnano_core._xnano_core import Bounds, Point

        buffer = Buffer(width=4, height=2)
        assert buffer.inspect(Bounds.contains(Point(3, 1)))
        assert not buffer.inspect(Bounds.contains(Point(4, 1)))
        ```
    """

__eq__

__eq__(other: object) -> Predicate

A predicate that is true when the value equals other; the same as equals.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when the value equals ``other``; the same as ``equals``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width == 20)
        ```
    """

__ne__

__ne__(other: object) -> Predicate

A predicate that is true when the value differs from other; the same as not_equals.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when the value differs from ``other``; the same as ``not_equals``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width != 5)
        ```
    """

__hash__

__hash__() -> int

The identity hash, which keeps expressions usable in sets and dictionaries.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __hash__(self) -> int:
    """The identity hash, which keeps expressions usable in sets and dictionaries."""

Operation

Bases: Expression[None]

An action that changes a buffer, applied with Buffer.update.

Operations apply in argument order. update accepts operations only, not query expressions. Combine operations with then and when.

Examples:

buffer = Buffer(width=8, height=1)
buffer.update(Write('hi'), Foreground('red'))
assert buffer.text.startswith('hi')

Methods:

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

  • evaluate –

    Compute the expression's value.

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab').then(Write('c', x=2)))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def then(self, other: Operation) -> Operation:
    """
    An operation that applies this operation, then ``other``.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab').then(Write('c', x=2)))
        assert buffer.text.startswith('abc')
        ```
    """

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
    """
    An operation that applies only while ``condition`` is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('wide').when(width > 4))
        assert buffer.text.startswith('wide')
        ```
    """

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab') | Write('c', x=2))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Operation) -> Operation:
    """
    Combine this operation with ``other`` so both run in sequence.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab') | Write('c', x=2))
        assert buffer.text.startswith('abc')
        ```
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

Property

Bases: Value[ValueType]

A reference to a concrete property of a buffer or runtime.

Reading it gives the current value. Calling it creates an assignment operation.

Attributes:

  • name (str) –

    The name of the referenced property.

Examples:

from xnano_core._xnano_core import _reference

position = _reference('Position', 'property')
buffer = Buffer(width=4, height=1)
buffer.update(position(Point(3, 2)))
assert buffer.inspect(position) == Point(3, 2)
assert position.name == 'Position'

Methods:

  • __call__ –

    An operation that assigns value to the property.

  • evaluate –

    Compute the expression's value.

  • equals –

    A predicate that is true when the value equals other.

  • not_equals –

    A predicate that is true when the value differs from other.

  • contains –

    A condition that is true while this rectangle contains the point other.

  • __eq__ –

    A predicate that is true when the value equals other; the same as equals.

  • __ne__ –

    A predicate that is true when the value differs from other; the same as not_equals.

  • __hash__ –

    The identity hash, which keeps expressions usable in sets and dictionaries.

name property

name: str

The name of the referenced property.

x property

The column of a Point or the left edge of a Rectangle.

Examples:

from xnano_core._xnano_core import Position

assert Buffer(width=4, height=1, x=3, y=2).inspect(Position.x) == 3

y property

The row of a Point or the top edge of a Rectangle.

Examples:

from xnano_core._xnano_core import Position

assert Buffer(width=4, height=1, x=3, y=2).inspect(Position.y) == 2

width property

width: NumericValue[int]

The width of a Size or a Rectangle.

Examples:

from xnano_core._xnano_core import BufferSize

assert Buffer(width=6, height=2).inspect(BufferSize.width) == 6

height property

height: NumericValue[int]

The height of a Size or a Rectangle.

Examples:

from xnano_core._xnano_core import BufferSize

assert Buffer(width=6, height=2).inspect(BufferSize.height) == 2

right property

right: NumericValue[int]

The first column after a Rectangle.

Examples:

from xnano_core._xnano_core import Bounds

assert Buffer(width=6, height=2, x=1).inspect(Bounds.right) == 7

bottom property

bottom: NumericValue[int]

The first row after a Rectangle.

Examples:

from xnano_core._xnano_core import Bounds

assert Buffer(width=6, height=2, y=1).inspect(Bounds.bottom) == 3

__call__

__call__(value: ValueType | Value[ValueType]) -> SetValue[ValueType]

An operation that assigns value to the property.

Examples:

from xnano_core._xnano_core import _reference

size = _reference('Size', 'property')
buffer = Buffer(width=4, height=1)
buffer.update(size(Size(6, 2)))
assert buffer.width == 6
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __call__(self, value: ValueType | Value[ValueType]) -> SetValue[ValueType]:
    """
    An operation that assigns ``value`` to the property.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        size = _reference('Size', 'property')
        buffer = Buffer(width=4, height=1)
        buffer.update(size(Size(6, 2)))
        assert buffer.width == 6
        ```
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

equals

equals(other: ValueType | Value[ValueType]) -> Predicate

A predicate that is true when the value equals other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def equals(self, other: ValueType | Value[ValueType]) -> Predicate:
    """
    A predicate that is true when the value equals ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width.equals(20))
        ```
    """

not_equals

not_equals(other: ValueType | Value[ValueType]) -> Predicate

A predicate that is true when the value differs from other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def not_equals(self, other: ValueType | Value[ValueType]) -> Predicate:
    """
    A predicate that is true when the value differs from ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width.not_equals(5))
        ```
    """

contains

contains(other: Point | Value[Point] | Value[Point | None]) -> Predicate

A condition that is true while this rectangle contains the point other.

It is false, never an error, while either side has no value yet, such as a mouse position before any mouse event.

Parameters:

Examples:

from xnano_core._xnano_core import Bounds, Point

buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def contains(
    self: Value[Rectangle],
    other: Point | Value[Point] | Value[Point | None],
) -> Predicate:
    """
    A condition that is true while this rectangle contains the point ``other``.

    It is false, never an error, while either side has no value yet, such as a mouse
    position before any mouse event.

    Args:
        other: The ``Point`` (or an expression that produces one) to look for.

    Examples:
        ```python
        from xnano_core._xnano_core import Bounds, Point

        buffer = Buffer(width=4, height=2)
        assert buffer.inspect(Bounds.contains(Point(3, 1)))
        assert not buffer.inspect(Bounds.contains(Point(4, 1)))
        ```
    """

__eq__

__eq__(other: object) -> Predicate

A predicate that is true when the value equals other; the same as equals.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when the value equals ``other``; the same as ``equals``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width == 20)
        ```
    """

__ne__

__ne__(other: object) -> Predicate

A predicate that is true when the value differs from other; the same as not_equals.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when the value differs from ``other``; the same as ``not_equals``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width != 5)
        ```
    """

__hash__

__hash__() -> int

The identity hash, which keeps expressions usable in sets and dictionaries.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __hash__(self) -> int:
    """The identity hash, which keeps expressions usable in sets and dictionaries."""

NumericProperty

Bases: NumericValue[NumberType]

A reference to a numeric property that can be read, computed with and assigned.

Attributes:

  • name (str) –

    The name of the referenced property.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=4, height=1)
buffer.update(width(10))
assert buffer.width == 10
buffer.update(width(width * 2))
assert buffer.width == 20

Methods:

  • __call__ –

    An operation that assigns value to the property.

  • evaluate –

    Compute the expression's value.

  • equals –

    A predicate that is true when the value equals other.

  • not_equals –

    A predicate that is true when the value differs from other.

  • contains –

    A condition that is true while this rectangle contains the point other.

  • __eq__ –

    A predicate that is true when the value equals other; the same as equals.

  • __ne__ –

    A predicate that is true when the value differs from other; the same as not_equals.

  • __hash__ –

    The identity hash, which keeps expressions usable in sets and dictionaries.

  • __lt__ –

    A predicate that is true when the value is less than other.

  • __le__ –

    A predicate that is true when the value is at most other.

  • __gt__ –

    A predicate that is true when the value is greater than other.

  • __ge__ –

    A predicate that is true when the value is at least other.

  • __add__ –

    The sum of the value and other.

  • __sub__ –

    The value minus other.

  • __mul__ –

    The product of the value and other.

  • __truediv__ –

    The value divided by other.

  • __mod__ –

    The remainder of dividing the value by other.

  • __neg__ –

    The value with its sign flipped.

  • __rtruediv__ –

    other divided by the value.

  • __rmod__ –

    The remainder of dividing other by the value.

  • __floordiv__ –

    The value divided by other, rounded toward negative infinity like Python's //.

  • __rfloordiv__ –

    other divided by the value, rounded toward negative infinity.

  • __pow__ –

    The value raised to the power other.

  • __rpow__ –

    other raised to the power of the value.

  • __abs__ –

    The absolute value.

  • __floor__ –

    The value rounded down to a whole number, used by math.floor.

  • __ceil__ –

    The value rounded up to a whole number, used by math.ceil.

  • __round__ –

    The value rounded to the nearest whole number, halves away from zero.

  • minimum –

    The smaller of the value and other.

  • maximum –

    The larger of the value and other.

  • clamp –

    The value limited to the range from lowest to highest.

name property

name: str

The name of the referenced property.

x property

The column of a Point or the left edge of a Rectangle.

Examples:

from xnano_core._xnano_core import Position

assert Buffer(width=4, height=1, x=3, y=2).inspect(Position.x) == 3

y property

The row of a Point or the top edge of a Rectangle.

Examples:

from xnano_core._xnano_core import Position

assert Buffer(width=4, height=1, x=3, y=2).inspect(Position.y) == 2

width property

width: NumericValue[int]

The width of a Size or a Rectangle.

Examples:

from xnano_core._xnano_core import BufferSize

assert Buffer(width=6, height=2).inspect(BufferSize.width) == 6

height property

height: NumericValue[int]

The height of a Size or a Rectangle.

Examples:

from xnano_core._xnano_core import BufferSize

assert Buffer(width=6, height=2).inspect(BufferSize.height) == 2

right property

right: NumericValue[int]

The first column after a Rectangle.

Examples:

from xnano_core._xnano_core import Bounds

assert Buffer(width=6, height=2, x=1).inspect(Bounds.right) == 7

bottom property

bottom: NumericValue[int]

The first row after a Rectangle.

Examples:

from xnano_core._xnano_core import Bounds

assert Buffer(width=6, height=2, y=1).inspect(Bounds.bottom) == 3

__call__

__call__(value: NumberType | Value[NumberType]) -> SetValue[NumberType]

An operation that assigns value to the property.

Examples:

from xnano_core._xnano_core import _reference

height = _reference('Height', 'numeric_property')
buffer = Buffer(width=4, height=1)
buffer.update(height(3))
assert buffer.height == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __call__(self, value: NumberType | Value[NumberType]) -> SetValue[NumberType]:
    """
    An operation that assigns ``value`` to the property.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        height = _reference('Height', 'numeric_property')
        buffer = Buffer(width=4, height=1)
        buffer.update(height(3))
        assert buffer.height == 3
        ```
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

equals

equals(other: ValueType | Value[ValueType]) -> Predicate

A predicate that is true when the value equals other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def equals(self, other: ValueType | Value[ValueType]) -> Predicate:
    """
    A predicate that is true when the value equals ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width.equals(20))
        ```
    """

not_equals

not_equals(other: ValueType | Value[ValueType]) -> Predicate

A predicate that is true when the value differs from other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def not_equals(self, other: ValueType | Value[ValueType]) -> Predicate:
    """
    A predicate that is true when the value differs from ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width.not_equals(5))
        ```
    """

contains

contains(other: Point | Value[Point] | Value[Point | None]) -> Predicate

A condition that is true while this rectangle contains the point other.

It is false, never an error, while either side has no value yet, such as a mouse position before any mouse event.

Parameters:

Examples:

from xnano_core._xnano_core import Bounds, Point

buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def contains(
    self: Value[Rectangle],
    other: Point | Value[Point] | Value[Point | None],
) -> Predicate:
    """
    A condition that is true while this rectangle contains the point ``other``.

    It is false, never an error, while either side has no value yet, such as a mouse
    position before any mouse event.

    Args:
        other: The ``Point`` (or an expression that produces one) to look for.

    Examples:
        ```python
        from xnano_core._xnano_core import Bounds, Point

        buffer = Buffer(width=4, height=2)
        assert buffer.inspect(Bounds.contains(Point(3, 1)))
        assert not buffer.inspect(Bounds.contains(Point(4, 1)))
        ```
    """

__eq__

__eq__(other: object) -> Predicate

A predicate that is true when the value equals other; the same as equals.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when the value equals ``other``; the same as ``equals``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width == 20)
        ```
    """

__ne__

__ne__(other: object) -> Predicate

A predicate that is true when the value differs from other; the same as not_equals.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate:  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
    """
    A predicate that is true when the value differs from ``other``; the same as ``not_equals``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=20, height=1).inspect(width != 5)
        ```
    """

__hash__

__hash__() -> int

The identity hash, which keeps expressions usable in sets and dictionaries.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __hash__(self) -> int:
    """The identity hash, which keeps expressions usable in sets and dictionaries."""

__lt__

A predicate that is true when the value is less than other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=3, height=1).inspect(width < 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __lt__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
    """
    A predicate that is true when the value is less than ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=3, height=1).inspect(width < 4)
        ```
    """

__le__

A predicate that is true when the value is at most other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width <= 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __le__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
    """
    A predicate that is true when the value is at most ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=4, height=1).inspect(width <= 4)
        ```
    """

__gt__

A predicate that is true when the value is greater than other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=5, height=1).inspect(width > 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __gt__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
    """
    A predicate that is true when the value is greater than ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=5, height=1).inspect(width > 4)
        ```
    """

__ge__

A predicate that is true when the value is at least other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width >= 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ge__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
    """
    A predicate that is true when the value is at least ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=4, height=1).inspect(width >= 4)
        ```
    """

__add__

The sum of the value and other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width + 1) == 5
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __add__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The sum of the value and ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=4, height=1).inspect(width + 1) == 5
        ```
    """

__sub__

The value minus other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width - 1) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __sub__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The value minus ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=4, height=1).inspect(width - 1) == 3
        ```
    """

__mul__

The product of the value and other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
assert Buffer(width=4, height=3).inspect(width * height) == 12
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __mul__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The product of the value and ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        height = _reference('Height', 'numeric_property')
        assert Buffer(width=4, height=3).inspect(width * height) == 12
        ```
    """

__truediv__

__truediv__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]

The value divided by other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width / 2) == 4.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __truediv__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The value divided by ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=8, height=1).inspect(width / 2) == 4.0
        ```
    """

__mod__

The remainder of dividing the value by other.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width % 3) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __mod__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
    """
    The remainder of dividing the value by ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=8, height=1).inspect(width % 3) == 2
        ```
    """

__neg__

__neg__() -> NumericValue[NumberType]

The value with its sign flipped.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(-width) == -8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __neg__(self) -> NumericValue[NumberType]:
    """
    The value with its sign flipped.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        assert Buffer(width=8, height=1).inspect(-width) == -8
        ```
    """

__rtruediv__

__rtruediv__(other: float) -> NumericValue[float]

other divided by the value.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=8, height=1).inspect(16 / Width) == 2.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __rtruediv__(self, other: float) -> NumericValue[float]:
    """
    ``other`` divided by the value.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=8, height=1).inspect(16 / Width) == 2.0
        ```
    """

__rmod__

__rmod__(other: float) -> NumericValue[float]

The remainder of dividing other by the value.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=3, height=1).inspect(10 % Width) == 1
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __rmod__(self, other: float) -> NumericValue[float]:
    """
    The remainder of dividing ``other`` by the value.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=3, height=1).inspect(10 % Width) == 1
        ```
    """

__floordiv__

__floordiv__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[int | float]

The value divided by other, rounded toward negative infinity like Python's //.

Dividing by zero raises ZeroDivisionError when the expression is evaluated.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=7, height=1).inspect(Width // 2) == 3
assert Buffer(width=7, height=1).inspect(-Width // 2) == -4
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __floordiv__(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[int | float]:
    """
    The value divided by ``other``, rounded toward negative infinity like Python's ``//``.

    Dividing by zero raises ``ZeroDivisionError`` when the expression is evaluated.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=7, height=1).inspect(Width // 2) == 3
        assert Buffer(width=7, height=1).inspect(-Width // 2) == -4
        ```
    """

__rfloordiv__

__rfloordiv__(other: float) -> NumericValue[int | float]

other divided by the value, rounded toward negative infinity.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=4, height=1).inspect(9 // Width) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __rfloordiv__(self, other: float) -> NumericValue[int | float]:
    """
    ``other`` divided by the value, rounded toward negative infinity.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=4, height=1).inspect(9 // Width) == 2
        ```
    """

__pow__

__pow__(other: float | NumericValue[int] | NumericValue[float], modulo: None = None) -> NumericValue[int | float]

The value raised to the power other.

Whole-number results stay integers; a negative or fractional exponent gives a float.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=3, height=1).inspect(Width**2) == 9
assert Buffer(width=4, height=1).inspect(Width**0.5) == 2.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __pow__(
    self, other: float | NumericValue[int] | NumericValue[float], modulo: None = None
) -> NumericValue[int | float]:
    """
    The value raised to the power ``other``.

    Whole-number results stay integers; a negative or fractional exponent gives a float.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=3, height=1).inspect(Width**2) == 9
        assert Buffer(width=4, height=1).inspect(Width**0.5) == 2.0
        ```
    """

__rpow__

__rpow__(other: float, modulo: None = None) -> NumericValue[int | float]

other raised to the power of the value.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=3, height=1).inspect(2**Width) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __rpow__(self, other: float, modulo: None = None) -> NumericValue[int | float]:
    """
    ``other`` raised to the power of the value.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=3, height=1).inspect(2**Width) == 8
        ```
    """

__abs__

__abs__() -> NumericValue[NumberType]

The absolute value.

Examples:

from xnano_core._xnano_core import X

assert Buffer(width=1, height=1, x=-5).inspect(abs(X)) == 5
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __abs__(self) -> NumericValue[NumberType]:
    """
    The absolute value.

    Examples:
        ```python
        from xnano_core._xnano_core import X

        assert Buffer(width=1, height=1, x=-5).inspect(abs(X)) == 5
        ```
    """

__floor__

__floor__() -> NumericValue[int]

The value rounded down to a whole number, used by math.floor.

Examples:

import math

from xnano_core._xnano_core import Width

assert Buffer(width=7, height=1).inspect(math.floor(Width / 2)) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __floor__(self) -> NumericValue[int]:
    """
    The value rounded down to a whole number, used by ``math.floor``.

    Examples:
        ```python
        import math

        from xnano_core._xnano_core import Width

        assert Buffer(width=7, height=1).inspect(math.floor(Width / 2)) == 3
        ```
    """

__ceil__

__ceil__() -> NumericValue[int]

The value rounded up to a whole number, used by math.ceil.

Examples:

import math

from xnano_core._xnano_core import Width

assert Buffer(width=7, height=1).inspect(math.ceil(Width / 2)) == 4
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ceil__(self) -> NumericValue[int]:
    """
    The value rounded up to a whole number, used by ``math.ceil``.

    Examples:
        ```python
        import math

        from xnano_core._xnano_core import Width

        assert Buffer(width=7, height=1).inspect(math.ceil(Width / 2)) == 4
        ```
    """

__round__

__round__(digits: None = None) -> NumericValue[int]

The value rounded to the nearest whole number, halves away from zero.

Unlike Python's round, a half rounds away from zero, so 2.5 becomes 3. Passing a number of digits raises TypeError.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=5, height=1).inspect(round(Width / 2)) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __round__(self, digits: None = None) -> NumericValue[int]:
    """
    The value rounded to the nearest whole number, halves away from zero.

    Unlike Python's ``round``, a half rounds away from zero, so ``2.5`` becomes ``3``.
    Passing a number of digits raises ``TypeError``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=5, height=1).inspect(round(Width / 2)) == 3
        ```
    """

minimum

minimum(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]

The smaller of the value and other.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=20, height=1).inspect(Width.minimum(8)) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def minimum(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[NumberType]:
    """
    The smaller of the value and ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=20, height=1).inspect(Width.minimum(8)) == 8
        ```
    """

maximum

maximum(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]

The larger of the value and other.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=2, height=1).inspect(Width.maximum(8)) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def maximum(
    self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[NumberType]:
    """
    The larger of the value and ``other``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=2, height=1).inspect(Width.maximum(8)) == 8
        ```
    """

clamp

clamp(lowest: float | NumericValue[int] | NumericValue[float], highest: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]

The value limited to the range from lowest to highest.

Raises TypeError when evaluated if lowest is greater than highest.

Examples:

from xnano_core._xnano_core import Width

assert Buffer(width=50, height=1).inspect(Width.clamp(0, 10)) == 10
assert Buffer(width=5, height=1).inspect(Width.clamp(8, 10)) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def clamp(
    self,
    lowest: float | NumericValue[int] | NumericValue[float],
    highest: float | NumericValue[int] | NumericValue[float],
) -> NumericValue[NumberType]:
    """
    The value limited to the range from ``lowest`` to ``highest``.

    Raises ``TypeError`` when evaluated if ``lowest`` is greater than ``highest``.

    Examples:
        ```python
        from xnano_core._xnano_core import Width

        assert Buffer(width=50, height=1).inspect(Width.clamp(0, 10)) == 10
        assert Buffer(width=5, height=1).inspect(Width.clamp(8, 10)) == 8
        ```
    """

SetValue

SetValue(property: Property[ValueType] | NumericProperty[int] | NumericProperty[float], value: ValueType | Value[ValueType])

Bases: Operation, Generic[ValueType]

Assign a value to a property.

Calling a property creates the same operation, so width(10) and SetValue(width, 10) are equivalent.

Parameters:

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=4, height=1)
buffer.update(SetValue(width, 9))
assert buffer.width == 9

Create a SetValue.

Parameters:

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    property: Property[ValueType] | NumericProperty[int] | NumericProperty[float],
    value: ValueType | Value[ValueType],
) -> None:
    """
    Create a SetValue.

    Args:
        property: ``Property[ValueType] | NumericProperty[int] | NumericProperty[float]``.
        value: ``ValueType | Value[ValueType]``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab').then(Write('c', x=2)))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def then(self, other: Operation) -> Operation:
    """
    An operation that applies this operation, then ``other``.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab').then(Write('c', x=2)))
        assert buffer.text.startswith('abc')
        ```
    """

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
    """
    An operation that applies only while ``condition`` is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('wide').when(width > 4))
        assert buffer.text.startswith('wide')
        ```
    """

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab') | Write('c', x=2))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Operation) -> Operation:
    """
    Combine this operation with ``other`` so both run in sequence.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab') | Write('c', x=2))
        assert buffer.text.startswith('abc')
        ```
    """

SequenceOperation

SequenceOperation(*operations: Operation)

Bases: Operation

Apply several operations in order as one operation.

Parameters:

  • *operations (Operation, default: () ) –

    The operations to apply.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(SequenceOperation(Clear(), Write('seq')))
assert buffer.text.startswith('seq')

Create a SequenceOperation.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, *operations: Operation) -> None:
    """
    Create a SequenceOperation.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab').then(Write('c', x=2)))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def then(self, other: Operation) -> Operation:
    """
    An operation that applies this operation, then ``other``.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab').then(Write('c', x=2)))
        assert buffer.text.startswith('abc')
        ```
    """

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
    """
    An operation that applies only while ``condition`` is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('wide').when(width > 4))
        assert buffer.text.startswith('wide')
        ```
    """

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab') | Write('c', x=2))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Operation) -> Operation:
    """
    Combine this operation with ``other`` so both run in sequence.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab') | Write('c', x=2))
        assert buffer.text.startswith('abc')
        ```
    """

Conditional

Conditional(condition: Predicate, operation: Operation, *, otherwise: Operation | None = None)

Bases: Operation

Apply one operation when a condition is true and optionally another when it is not.

Parameters:

  • condition (Predicate) –

    The predicate to test each time the operation applies.

  • operation (Operation) –

    Applied when the condition is true.

  • otherwise (Operation | None, default: None ) –

    Applied when the condition is false.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Conditional(width > 100, Write('big'), otherwise=Write('small')))
assert buffer.text.startswith('small')

Create a Conditional.

Parameters:

  • condition (Predicate) –

    Predicate.

  • operation (Operation) –

    Operation.

  • otherwise (Operation | None, default: None ) –

    Operation | None. Defaults to None.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    condition: Predicate,
    operation: Operation,
    *,
    otherwise: Operation | None = None,
) -> None:
    """
    Create a Conditional.

    Args:
        condition: ``Predicate``.
        operation: ``Operation``.
        otherwise: ``Operation | None``. Defaults to ``None``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab').then(Write('c', x=2)))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def then(self, other: Operation) -> Operation:
    """
    An operation that applies this operation, then ``other``.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab').then(Write('c', x=2)))
        assert buffer.text.startswith('abc')
        ```
    """

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
    """
    An operation that applies only while ``condition`` is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('wide').when(width > 4))
        assert buffer.text.startswith('wide')
        ```
    """

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab') | Write('c', x=2))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Operation) -> Operation:
    """
    Combine this operation with ``other`` so both run in sequence.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab') | Write('c', x=2))
        assert buffer.text.startswith('abc')
        ```
    """

Resize

Resize(width: int, height: int)

Bases: Operation

Resize the target buffer to width by height cells.

Existing content is kept where it still fits and cleared where the buffer grows.

Parameters:

  • width (int) –

    The new width in cells.

  • height (int) –

    The new height in cells.

Examples:

buffer = Buffer(width=10, height=3)
buffer.update(Resize(6, 2))
assert (buffer.width, buffer.height) == (6, 2)

Create a Resize.

Parameters:

  • width (int) –

    int.

  • height (int) –

    int.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, width: int, height: int) -> None:
    """
    Create a Resize.

    Args:
        width: ``int``.
        height: ``int``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab').then(Write('c', x=2)))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def then(self, other: Operation) -> Operation:
    """
    An operation that applies this operation, then ``other``.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab').then(Write('c', x=2)))
        assert buffer.text.startswith('abc')
        ```
    """

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
    """
    An operation that applies only while ``condition`` is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('wide').when(width > 4))
        assert buffer.text.startswith('wide')
        ```
    """

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab') | Write('c', x=2))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Operation) -> Operation:
    """
    Combine this operation with ``other`` so both run in sequence.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab') | Write('c', x=2))
        assert buffer.text.startswith('abc')
        ```
    """

Move

Move(x: int = 0, y: int = 0)

Bases: Operation

Move the target buffer relative to its current position in its parent.

Parameters:

  • x (int, default: 0 ) –

    Columns to move right; negative values move left.

  • y (int, default: 0 ) –

    Rows to move down; negative values move up.

Examples:

buffer = Buffer(width=4, height=1, x=2, y=1)
buffer.update(Move(1, 1))
assert (buffer.x, buffer.y) == (3, 2)
buffer.update(Move(x=-2, y=-1))
assert (buffer.x, buffer.y) == (1, 1)

Create a Move.

Parameters:

  • x (int, default: 0 ) –

    int. Defaults to 0.

  • y (int, default: 0 ) –

    int. Defaults to 0.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, x: int = 0, y: int = 0) -> None:
    """
    Create a Move.

    Args:
        x: ``int``. Defaults to ``0``.
        y: ``int``. Defaults to ``0``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab').then(Write('c', x=2)))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def then(self, other: Operation) -> Operation:
    """
    An operation that applies this operation, then ``other``.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab').then(Write('c', x=2)))
        assert buffer.text.startswith('abc')
        ```
    """

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
    """
    An operation that applies only while ``condition`` is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('wide').when(width > 4))
        assert buffer.text.startswith('wide')
        ```
    """

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab') | Write('c', x=2))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Operation) -> Operation:
    """
    Combine this operation with ``other`` so both run in sequence.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab') | Write('c', x=2))
        assert buffer.text.startswith('abc')
        ```
    """

Place

Place(x: int, y: int)

Bases: Operation

Move the target buffer to an absolute position in its parent.

Parameters:

  • x (int) –

    The column in the parent.

  • y (int) –

    The row in the parent.

Examples:

buffer = Buffer(width=4, height=1)
buffer.update(Place(5, 2))
assert (buffer.x, buffer.y) == (5, 2)

Create a Place.

Parameters:

  • x (int) –

    int.

  • y (int) –

    int.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, x: int, y: int) -> None:
    """
    Create a Place.

    Args:
        x: ``int``.
        y: ``int``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab').then(Write('c', x=2)))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def then(self, other: Operation) -> Operation:
    """
    An operation that applies this operation, then ``other``.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab').then(Write('c', x=2)))
        assert buffer.text.startswith('abc')
        ```
    """

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
    """
    An operation that applies only while ``condition`` is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('wide').when(width > 4))
        assert buffer.text.startswith('wide')
        ```
    """

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab') | Write('c', x=2))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Operation) -> Operation:
    """
    Combine this operation with ``other`` so both run in sequence.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab') | Write('c', x=2))
        assert buffer.text.startswith('abc')
        ```
    """

Write

Write(text: TextContent, *, x: int = 0, y: int = 0, style: Style | None = None, mode: WriteMode = 'replace')

Bases: Operation

Write text into the target at a cell position.

Text is clipped by display columns, whole graphemes are preserved and wide characters repair their continuation cells.

Parameters:

  • text (TextContent) –

    A string, a StyledText or a sequence of both.

  • x (int, default: 0 ) –

    The first column to write to.

  • y (int, default: 0 ) –

    The row to write to.

  • style (Style | None, default: None ) –

    The style applied to the written cells.

  • mode (WriteMode, default: 'replace' ) –

    'replace' overwrites the cell style; 'preserve_background' keeps the background that is already in the cell.

Examples:

buffer = Buffer(width=8, height=2)
buffer.update(Write('hi', x=1, y=1, style=Style('red')))
assert buffer.render(format='text').split('\n')[1].strip() == 'hi'
assert buffer[1, 1].foreground.to_rgb() is None
assert str(buffer[1, 1].foreground) == "Color('red')"

painted = Buffer(width=3, height=1)
painted.update(Write('a', style=Style('red', 'blue')))
painted.update(Write('b', mode='preserve_background', style=Style('green')))
assert str(painted[0, 0].background) == "Color('blue')"

Create a Write.

Parameters:

  • text (TextContent) –

    TextContent.

  • x (int, default: 0 ) –

    int. Defaults to 0.

  • y (int, default: 0 ) –

    int. Defaults to 0.

  • style (Style | None, default: None ) –

    Style | None. Defaults to None.

  • mode (WriteMode, default: 'replace' ) –

    WriteMode. Defaults to 'replace'.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    text: TextContent,
    *,
    x: int = 0,
    y: int = 0,
    style: Style | None = None,
    mode: WriteMode = 'replace',
) -> None:
    """
    Create a Write.

    Args:
        text: ``TextContent``.
        x: ``int``. Defaults to ``0``.
        y: ``int``. Defaults to ``0``.
        style: ``Style | None``. Defaults to ``None``.
        mode: ``WriteMode``. Defaults to ``'replace'``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
    """
    Compute the expression's value.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        context = EvaluationContext(buffer=Buffer(width=5, height=1))
        assert (width * 2).evaluate(context) == 10
        ```
    """

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab').then(Write('c', x=2)))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def then(self, other: Operation) -> Operation:
    """
    An operation that applies this operation, then ``other``.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab').then(Write('c', x=2)))
        assert buffer.text.startswith('abc')
        ```
    """

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
    """
    An operation that applies only while ``condition`` is true.

    Examples:
        ```python
        from xnano_core._xnano_core import _reference

        width = _reference('Width', 'numeric_property')
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('wide').when(width > 4))
        assert buffer.text.startswith('wide')
        ```
    """

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(Write('ab') | Write('c', x=2))
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, other: Operation) -> Operation:
    """
    Combine this operation with ``other`` so both run in sequence.

    Examples:
        ```python
        buffer = Buffer(width=6, height=1)
        buffer.update(Write('ab') | Write('c', x=2))
        assert buffer.text.startswith('abc')
        ```
    """

WriteCellText

WriteCellText(text: TextContent, *, column: int = 0, row: int = 0, style: Style | None = None, mode: WriteMode = 'replace')

Bases: Write

Write text addressed by column and row instead of x and y.

It behaves exactly like Write; use it when the position is a cell index rather than a coordinate.

Parameters:

  • text (TextContent) –

    A string, a StyledText or a sequence of both.

  • column (int, default: 0 ) –

    The first column to write to.

  • row (int, default: 0 ) –

    The row to write to.

  • style (Style | None, default: None ) –

    The style applied to the written cells.

  • mode (WriteMode, default: 'replace' ) –

    'replace' or 'preserve_background'.

Examples:

buffer = Buffer(width=6, height=1)
buffer.update(WriteCellText('ab', column=2))
assert buffer.text.strip() == 'ab'
assert buffer[2, 0].symbol == 'a'

Create a WriteCellText.

Parameters:

  • text (TextContent) –

    TextContent.

  • column (int, default: 0 ) –

    int. Defaults to 0.

  • row (int, default: 0 ) –

    int. Defaults to 0.

  • style (Style | None, default: None ) –

    Style | None. Defaults to None.

  • mode (WriteMode, default: 'replace' ) –

    WriteMode. Defaults to 'replace'.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    text: TextContent,
    *,
    column: int = 0,
    row: int = 0,
    style: Style | None = None,
    mode: WriteMode = 'replace',
) -> None:
    """
    Create a WriteCellText.

    Args:
        text: ``TextContent``.
        column: ``int``. Defaults to ``0``.
        row: ``int``. Defaults to ``0``.
        style: ``Style | None``. Defaults to ``None``.
        mode: ``WriteMode``. Defaults to ``'replace'``.
    """

evaluate

evaluate(c