Skip to content

xnano.operations

xnano.operations

xnano.operations

Operations that change or animate a buffer, placement or canvas.

Pass operations to update or pipe them with |. Create a reusable hook from a function with hook, or build typed style, border, block and effect customizations with fx.

Classes:

  • Customization –

    Base class for all customization dataclasses returned by fx.

  • ApplyStyle –

    Patch a Style onto every cell of the target.

  • Background –

    Set the background color of every cell of the target.

  • Border –

    Draw a border around the edge of the target.

  • Clear –

    Blank cells that hide whatever is behind them.

  • Fill –

    Fill every cell of the target with one cell.

  • Foreground –

    Set the foreground color of every cell of the target.

  • Layout –

    Arrange attached children within the parent's content area.

  • Margin –

    Horizontal and vertical inset distances.

  • Move –

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

  • Operation –

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

  • Paste –

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

  • Place –

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

  • Resize –

    Resize the target buffer to width by height cells.

  • Write –

    Write text into the target at a cell position.

  • ContextualOperation –

    A reusable hook that can be piped onto any canvas or placement.

Functions:

  • fx –

    Create a typed dataclass customization for a fill, layout,

  • hook –

    Describe a hook once, to attach to any canvas or placement later.

Attributes:

OperationResult module-attribute

OperationResult: TypeAlias = '_core.Operation | _core.Style | Customization | None'

What a function decorated with hook may return.

Customization

Customization(kind: str, /, **parameters: object)

Bases: Customization

Base class for all customization dataclasses returned by fx.

Every customization is both a dataclass holding its typed parameters and a native Customization operation that can be piped with | or passed to add and update. The parameters are read when it is applied, so editing a field changes what it does.

Attributes:

  • customization_kind (str) –

    Identifier of the customization kind (such as 'fill' or 'effect.dissolve').

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.

  • kinds –

    The name of every kind of customization.

  • defaults –

    The parameter names of a kind with their defaults, in order.

  • build –

    The core object this customization stands for: a Style, Border, Effect,

  • to_operation –

    The core operation that applies this customization.

  • to_audio_effect –

    The audio effect behind an 'audio.*' customization.

  • apply_to_surface –

    Apply this customization to a buffer, widget or region.

  • apply_to –

    Apply this customization to a canvas, placement or surface.

  • cancel –

    Stop this effect on the target it was applied to.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, kind: str, /, **parameters: object) -> None: ...

customization_kind instance-attribute

customization_kind: str

The kind, such as 'style' or 'effect.fade_to'.

parameters property

parameters: dict[str, object]

The parameters by name, with defaults filled in.

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')
        ```
    """

kinds staticmethod

kinds() -> list[str]

The name of every kind of customization.

Examples:

assert 'style' in Customization.kinds()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@staticmethod
def kinds() -> list[str]:
    """
    The name of every kind of customization.

    Examples:
        ```python
        assert 'style' in Customization.kinds()
        ```
    """

defaults staticmethod

defaults(kind: str) -> dict[str, object]

The parameter names of a kind with their defaults, in order.

Raises:

  • ValueError –

    kind is not a customization kind.

Examples:

assert Customization.defaults('margin') == {'horizontal': 0, 'vertical': 0}
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@staticmethod
def defaults(kind: str) -> dict[str, object]:
    """
    The parameter names of a kind with their defaults, in order.

    Raises:
        ValueError: ``kind`` is not a customization kind.

    Examples:
        ```python
        assert Customization.defaults('margin') == {'horizontal': 0, 'vertical': 0}
        ```
    """

build

build() -> object

The core object this customization stands for: a Style, Border, Effect, Block, Margin, audio effect and so on, with all of its own methods.

Examples:

assert isinstance(Customization('style', bold=True).build(), Style)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def build(self) -> object:
    """
    The core object this customization stands for: a ``Style``, ``Border``, ``Effect``,
    ``Block``, ``Margin``, audio effect and so on, with all of its own methods.

    Examples:
        ```python
        assert isinstance(Customization('style', bold=True).build(), Style)
        ```
    """

to_operation

to_operation() -> Operation

The core operation that applies this customization.

Raises:

  • TypeError –

    The kind is not applied as an operation, such as 'block'.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_operation(self) -> Operation:
    """
    The core operation that applies this customization.

    Raises:
        TypeError: The kind is not applied as an operation, such as ``'block'``.
    """

to_audio_effect

to_audio_effect() -> object

The audio effect behind an 'audio.*' customization.

Raises:

  • TypeError –

    The kind is not an audio effect.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_audio_effect(self) -> object:
    """
    The audio effect behind an ``'audio.*'`` customization.

    Raises:
        TypeError: The kind is not an audio effect.
    """

apply_to_surface

apply_to_surface(surface: Surface) -> None

Apply this customization to a buffer, widget or region.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def apply_to_surface(self, surface: Surface) -> None:
    """Apply this customization to a buffer, widget or region."""

apply_to

apply_to(target: Canvas[object, object] | Placement[object, object] | Surface) -> None

Apply this customization to a canvas, placement or surface.

It stays attached to the target: after this, assigning one of its fields applies it again, so a customization from fx is a live handle on what it changed. A running effect is stopped and started again with the new values.

Parameters:

Source code in xnano/_customize.py
def apply_to(
    self,
    target: Canvas[object, object] | Placement[object, object] | _core.Surface,
) -> None:
    """
    Apply this customization to a canvas, placement or surface.

    It stays attached to the target: after this, assigning one of its fields applies it
    again, so a customization from ``fx`` is a live handle on what it changed. A running
    effect is stopped and started again with the new values.

    Args:
        target: The target to apply the customization to.
    """
    from xnano.canvas import Canvas
    from xnano.placement import Placement

    self._attach(target)
    if isinstance(target, (Placement, Canvas)):
        target._buffer.update(self)
        if self.customization_kind.startswith('effect.'):
            target._canvas._record_effect(self, target)
    elif isinstance(target, _core.Surface):
        target.update(self)

cancel

cancel() -> None

Stop this effect on the target it was applied to.

Does nothing for an effect that was never applied or has already finished, and for a customization that is not an effect.

Examples:

import xnano
from xnano.operations import fx

with xnano.new('hi', width=4, height=1) as canvas:
    fade = fx('effect.fade_to', foreground='red', duration_milliseconds=5000)
    fade.apply_to(canvas)
    fade.cancel()
    fade.cancel()
Source code in xnano/_customize.py
def cancel(self) -> None:
    """
    Stop this effect on the target it was applied to.

    Does nothing for an effect that was never applied or has already finished, and for a
    customization that is not an effect.

    Examples:
        ```python
        import xnano
        from xnano.operations import fx

        with xnano.new('hi', width=4, height=1) as canvas:
            fade = fx('effect.fade_to', foreground='red', duration_milliseconds=5000)
            fade.apply_to(canvas)
            fade.cancel()
            fade.cancel()
        ```
    """
    target = self.__dict__.get('_target')
    key = getattr(self, 'key', None)
    if target is None or not isinstance(key, str):
        return
    if not self.customization_kind.startswith('effect.'):
        return
    surface = target._buffer if hasattr(target, '_buffer') else target
    surface.update(_core.CancelEffect(key))

ApplyStyle

ApplyStyle(style: Style)

Bases: Operation

Patch a Style onto every cell of the target.

Colors and modifiers the style leaves unset are kept.

Parameters:

  • style (Style) –

    The style to patch onto each cell.

Examples:

buffer = Buffer(width=3, height=1)
buffer.update(Write('abc'), ApplyStyle(Style('green', bold=True)))
assert 'bold' in buffer[0, 0].style.modifiers

Create a ApplyStyle.

Parameters:

  • style (Style) –

    Style.

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, style: Style) -> None:
    """
    Create a ApplyStyle.

    Args:
        style: ``Style``.
    """

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')
        ```
    """

Background

Background(color: ColorValue)

Bases: Operation

Set the background color of every cell of the target.

Parameters:

  • color (ColorValue) –

    A Color, a color name, a hex string or an (red, green, blue) tuple.

Examples:

buffer = Buffer(width=3, height=1)
buffer.update(Background((0, 0, 255)))
assert buffer[0, 0].background.to_rgb() == (0, 0, 255)

Create a Background.

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, color: ColorValue) -> None:
    """
    Create a Background.

    Args:
        color: ``ColorValue``.
    """

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')
        ```
    """

Border

Border(kind: BorderKind = 'plain', *, style: Style | None = None)

Bases: Operation

Draw a border around the edge of the target.

Maps to ratatui::widgets::Block with BorderType.

Parameters:

  • kind (BorderKind, default: 'plain' ) –

    'plain', 'rounded', 'double' or 'thick'.

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

    The style of the border cells.

Examples:

buffer = Buffer(width=6, height=3)
buffer.update(Border('rounded'))
assert buffer.render(format='text').split('\n')[0] == '╭────╮'

Create a Border.

Parameters:

  • kind (BorderKind, default: 'plain' ) –

    BorderKind. Defaults to 'plain'.

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

    Style | 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,
    kind: BorderKind = 'plain',
    *,
    style: Style | None = None,
) -> None:
    """
    Create a Border.

    Args:
        kind: ``BorderKind``. Defaults to ``'plain'``.
        style: ``Style | 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')
        ```
    """

Clear

Clear(*, symbol: str | Expression[str] | None = None, style: Style | DynamicStyle | None = None, width: int | None = None, height: int | None = None, x: int = 0, y: int = 0)

Bases: Widget

Blank cells that hide whatever is behind them.

Maps to ratatui::widgets::Clear.

Parameters:

  • symbol (str | Expression[str] | None, default: None ) –

    The one-column symbol every cell shows. Defaults to a space.

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

    The style of every cell.

  • width (int | None, default: None ) –

    The widget's width in cells. Defaults to 10.

  • height (int | None, default: None ) –

    The widget's height in cells. Defaults to 3.

  • x (int, default: 0 ) –

    The column in the parent.

  • y (int, default: 0 ) –

    The row in the parent.

Raises:

  • ValueError –

    symbol is not exactly one column wide.

Attributes:

Examples:

clear = Clear(symbol='.', width=4, height=1)
assert clear.render(format='text') == '....'
clear.symbol = '#'
assert clear.render(format='text') == '####'

Create a Clear.

Parameters:

  • symbol (str | Expression[str] | None, default: None ) –

    str | Expression[str] | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

  • width (int | None, default: None ) –

    int | None. Defaults to None.

  • height (int | None, default: None ) –

    int | None. Defaults to None.

  • x (int, default: 0 ) –

    int. Defaults to 0.

  • y (int, default: 0 ) –

    int. Defaults to 0.

Methods:

  • __setitem__ –

    Replace one cell with a Cell or a single grapheme.

  • write –

    Write text starting at a cell.

  • fill –

    Set every cell of the surface.

  • set_background_colors –

    Set the background color of a block of cells in one pass.

  • set_foreground_colors –

    Set the foreground color of a block of cells in one pass.

  • pixels –

    Return a pixel view that draws into this surface.

  • update –

    Apply operations in argument order.

  • inspect –

    Evaluate an expression against this surface and return its value.

  • supports –

    Return whether the buffer's registry can apply an operation type.

  • add_hook –

    Run a callback when the runtime reports matching events for this surface.

  • invalidate –

    Ask the runtime to redraw an area, or the whole surface.

  • to_cell_grid –

    Pack the surface into the cell grid byte format.

  • __or__ –

    Apply operation to this surface and return the surface.

  • with_text –

    Create a buffer sized to fit some text.

  • with_size –

    Create a blank buffer of a given size.

  • with_cells –

    Create a buffer from cells in row-major order.

  • from_cell_grid –

    Create a buffer from the cell grid byte format.

  • from_cell_animation –

    Create a buffer showing one frame of a packed cell animation.

  • region –

    Return a region covering a rectangle of the buffer.

  • resize –

    Change the size, keeping the cells that still fit.

  • paste –

    Copy the cells of another buffer or region into this one.

  • attach –

    Attach a child buffer as a retained layer of this one.

  • detach –

    Remove an attached child.

  • __call__ –

    Return a lazy render of the buffer.

  • render –

    Compose the visible children and serialize the buffer.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    *,
    symbol: str | Expression[str] | None = None,
    style: Style | DynamicStyle | None = None,
    width: int | None = None,
    height: int | None = None,
    x: int = 0,
    y: int = 0,
) -> None:
    """
    Create a Clear.

    Args:
        symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        width: ``int | None``. Defaults to ``None``.
        height: ``int | None``. Defaults to ``None``.
        x: ``int``. Defaults to ``0``.
        y: ``int``. Defaults to ``0``.
    """

width property writable

width: int

The width in cells. Assigning resizes the buffer.

height property writable

height: int

The height in cells. Assigning resizes the buffer.

x property writable

x: int

The column of the buffer in its parent. Assigning moves the buffer.

y property writable

y: int

The row of the buffer in its parent. Assigning moves the buffer.

position property writable

position: Point

The Point of the buffer in its parent. Assigning moves the buffer.

size property writable

size: Size

The Size of the buffer. Assigning resizes the buffer.

bounds property

bounds: Rectangle

The buffer's rectangle in its parent.

layer property writable

layer: int

The stacking order among siblings; higher layers are drawn on top.

Examples:

parent = Buffer(width=6, height=1)
below = Buffer('a')
above = Buffer('b')
parent.attach(below)
parent.attach(above)
below.layer = 1
assert parent.render(format='text') == 'a'

is_visible property writable

is_visible: bool

Whether the buffer is drawn. Hidden buffers still keep their content.

is_focusable property writable

is_focusable: bool

Whether the buffer can receive input focus.

content property writable

content: Region

The whole buffer as a region. Assigning text replaces the content.

cells property

cells: Region

The same view as content; there is only one store of cells.

text property

text: str

The plain text of the buffer's own cells, without mounted children.

revision property

revision: int

A number that increases every time the buffer's cells or geometry change.

children property

children: tuple[Buffer, ...]

The attached child buffers in attachment order.

registry property

registry: Registry

The registry that decides which operations this buffer can apply.

symbol property writable

symbol: str | Expression[str]

The symbol used to erase each cell; a space leaves the area blank.

style property writable

The colors and text modifiers applied to the cleared cells.

__setitem__

__setitem__(key: Coordinate, value: Cell | str) -> None

Replace one cell with a Cell or a single grapheme.

Examples:

buffer = Buffer(width=3, height=1)
buffer[2, 0] = 'z'
buffer[0, 0] = Cell('a', foreground='green')
assert buffer.text == 'a z'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __setitem__(self, key: Coordinate, value: Cell | str) -> None:
    """
    Replace one cell with a ``Cell`` or a single grapheme.

    Examples:
        ```python
        buffer = Buffer(width=3, height=1)
        buffer[2, 0] = 'z'
        buffer[0, 0] = Cell('a', foreground='green')
        assert buffer.text == 'a z'
        ```
    """

write

write(text: TextContent, *, x: int = 0, y: int = 0, style: Style | None = None, mode: WriteMode = 'replace') -> None

Write text starting at a cell.

Text is clipped by display columns, whole graphemes are kept together and the continuation cells of wide characters are repaired.

Parameters:

  • text (TextContent) –

    A string or styled text.

  • x (int, default: 0 ) –

    The starting column.

  • y (int, default: 0 ) –

    The starting row.

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

    A style applied to the written cells.

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

    'replace' overwrites the cell; 'preserve_background' keeps the background already there.

Examples:

buffer = Buffer(width=6, height=2)
buffer.write('hi', x=1, y=0, style=Style(foreground='red'))
assert buffer[1, 0].foreground == Color('red')
assert buffer.text.split('\n')[0] == ' hi'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def write(
    self,
    text: TextContent,
    *,
    x: int = 0,
    y: int = 0,
    style: Style | None = None,
    mode: WriteMode = 'replace',
) -> None:
    """
    Write text starting at a cell.

    Text is clipped by display columns, whole graphemes are kept together and the
    continuation cells of wide characters are repaired.

    Args:
        text: A string or styled text.
        x: The starting column.
        y: The starting row.
        style: A style applied to the written cells.
        mode: ``'replace'`` overwrites the cell; ``'preserve_background'`` keeps
            the background already there.

    Examples:
        ```python
        buffer = Buffer(width=6, height=2)
        buffer.write('hi', x=1, y=0, style=Style(foreground='red'))
        assert buffer[1, 0].foreground == Color('red')
        assert buffer.text.split('\\n')[0] == ' hi'
        ```
    """

fill

fill(cell: Cell | str = ' ') -> None

Set every cell of the surface.

Examples:

buffer = Buffer(width=3, height=1)
buffer.fill('#')
assert buffer.text == '###'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def fill(self, cell: Cell | str = ' ') -> None:
    """
    Set every cell of the surface.

    Examples:
        ```python
        buffer = Buffer(width=3, height=1)
        buffer.fill('#')
        assert buffer.text == '###'
        ```
    """

set_background_colors

set_background_colors(colors: Sequence[ColorValue | None], *, width: int, x: int = 0, y: int = 0) -> None

Set the background color of a block of cells in one pass.

Symbols and foreground colors are kept, and the whole block counts as one change (the revision grows by one).

Parameters:

  • colors (Sequence[ColorValue | None]) –

    A flat, row-major sequence of colors (names, (r, g, b) tuples or Color values). None leaves a cell alone.

  • width (int) –

    The number of colors in one row of colors.

  • x (int, default: 0 ) –

    The column of the block's top-left cell in this surface.

  • y (int, default: 0 ) –

    The row of the block's top-left cell in this surface.

Raises:

  • ValueError –

    width is below 1, len(colors) is not a multiple of width, or the block does not fit inside the surface, or an entry is not a color.

  • TypeError –

    colors is a single string instead of a sequence of colors, or an entry has no color meaning.

Examples:

buffer = Buffer(width=3, height=2)
buffer.write('abc')
buffer.set_background_colors(['red', None, (0, 0, 255), 'green'], width=2, x=1)
assert buffer[1, 0].background == Color('red')
assert buffer[2, 0].background == Color.reset
assert buffer[1, 1].background == Color('#0000ff')
assert buffer[2, 1].background == Color('green')
assert buffer[1, 0].symbol == 'b'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def set_background_colors(
    self,
    colors: Sequence[ColorValue | None],
    *,
    width: int,
    x: int = 0,
    y: int = 0,
) -> None:
    """
    Set the background color of a block of cells in one pass.

    Symbols and foreground colors are kept, and the whole block counts as one change (the
    revision grows by one).

    Args:
        colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
            [`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
        width: The number of colors in one row of ``colors``.
        x: The column of the block's top-left cell in this surface.
        y: The row of the block's top-left cell in this surface.

    Raises:
        ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
            the block does not fit inside the surface, or an entry is not a color.
        TypeError: ``colors`` is a single string instead of a sequence of colors, or an
            entry has no color meaning.

    Examples:
        ```python
        buffer = Buffer(width=3, height=2)
        buffer.write('abc')
        buffer.set_background_colors(['red', None, (0, 0, 255), 'green'], width=2, x=1)
        assert buffer[1, 0].background == Color('red')
        assert buffer[2, 0].background == Color.reset
        assert buffer[1, 1].background == Color('#0000ff')
        assert buffer[2, 1].background == Color('green')
        assert buffer[1, 0].symbol == 'b'
        ```
    """

set_foreground_colors

set_foreground_colors(colors: Sequence[ColorValue | None], *, width: int, x: int = 0, y: int = 0) -> None

Set the foreground color of a block of cells in one pass.

Symbols and background colors are kept, and the whole block counts as one change (the revision grows by one).

Parameters:

  • colors (Sequence[ColorValue | None]) –

    A flat, row-major sequence of colors (names, (r, g, b) tuples or Color values). None leaves a cell alone.

  • width (int) –

    The number of colors in one row of colors.

  • x (int, default: 0 ) –

    The column of the block's top-left cell in this surface.

  • y (int, default: 0 ) –

    The row of the block's top-left cell in this surface.

Raises:

  • ValueError –

    width is below 1, len(colors) is not a multiple of width, or the block does not fit inside the surface, or an entry is not a color.

  • TypeError –

    colors is a single string instead of a sequence of colors, or an entry has no color meaning.

Examples:

buffer = Buffer(width=3, height=2)
buffer.write('abc')
buffer.set_foreground_colors(['red', None, (0, 0, 255), 'green'], width=2, x=1)
assert buffer[1, 0].foreground == Color('red')
assert buffer[2, 0].foreground == Color.reset
assert buffer[1, 1].foreground == Color('#0000ff')
assert buffer[2, 1].foreground == Color('green')
assert buffer[1, 0].symbol == 'b'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def set_foreground_colors(
    self,
    colors: Sequence[ColorValue | None],
    *,
    width: int,
    x: int = 0,
    y: int = 0,
) -> None:
    """
    Set the foreground color of a block of cells in one pass.

    Symbols and background colors are kept, and the whole block counts as one change (the
    revision grows by one).

    Args:
        colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
            [`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
        width: The number of colors in one row of ``colors``.
        x: The column of the block's top-left cell in this surface.
        y: The row of the block's top-left cell in this surface.

    Raises:
        ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
            the block does not fit inside the surface, or an entry is not a color.
        TypeError: ``colors`` is a single string instead of a sequence of colors, or an
            entry has no color meaning.

    Examples:
        ```python
        buffer = Buffer(width=3, height=2)
        buffer.write('abc')
        buffer.set_foreground_colors(['red', None, (0, 0, 255), 'green'], width=2, x=1)
        assert buffer[1, 0].foreground == Color('red')
        assert buffer[2, 0].foreground == Color.reset
        assert buffer[1, 1].foreground == Color('#0000ff')
        assert buffer[2, 1].foreground == Color('green')
        assert buffer[1, 0].symbol == 'b'
        ```
    """

pixels

pixels(*, encoding: PixelEncoding = 'half_blocks') -> PixelView

Return a pixel view that draws into this surface.

Parameters:

  • encoding (PixelEncoding, default: 'half_blocks' ) –

    'half_blocks' for one column and two rows per cell or 'braille' for two columns and four rows per cell.

Examples:

buffer = Buffer(width=3, height=2)
assert (buffer.pixels().width, buffer.pixels().height) == (3, 4)
assert (buffer.pixels(encoding='braille').width) == 6
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def pixels(self, *, encoding: PixelEncoding = 'half_blocks') -> PixelView:
    """
    Return a pixel view that draws into this surface.

    Args:
        encoding: ``'half_blocks'`` for one column and two rows per cell or
            ``'braille'`` for two columns and four rows per cell.

    Examples:
        ```python
        buffer = Buffer(width=3, height=2)
        assert (buffer.pixels().width, buffer.pixels().height) == (3, 4)
        assert (buffer.pixels(encoding='braille').width) == 6
        ```
    """

update

update(*operations: Operation) -> None

Apply operations in argument order.

Raises:

Examples:

buffer = Buffer(width=8, height=3)
buffer.update(Border('rounded'), Write('hi', x=1, y=1))
assert buffer[0, 0].symbol == '╭'
assert buffer[1, 1].symbol == 'h'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def update(self, *operations: Operation) -> None:
    """
    Apply operations in argument order.

    Raises:
        UnsupportedOperationError: The surface's registry cannot apply an operation.
        RuntimeRequiredError: An operation needs a mounted buffer on a runtime.

    Examples:
        ```python
        buffer = Buffer(width=8, height=3)
        buffer.update(Border('rounded'), Write('hi', x=1, y=1))
        assert buffer[0, 0].symbol == '╭'
        assert buffer[1, 1].symbol == 'h'
        ```
    """

inspect

inspect(expression: Expression[ValueType]) -> ValueType

Evaluate an expression against this surface and return its value.

Examples:

width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
buffer = Buffer(width=8, height=3)
assert buffer.inspect(width) == 8
assert buffer.inspect(width * height) == 24
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def inspect(self, expression: Expression[ValueType]) -> ValueType:
    """
    Evaluate an expression against this surface and return its value.

    Examples:
        ```python
        width = _reference('Width', 'numeric_property')
        height = _reference('Height', 'numeric_property')
        buffer = Buffer(width=8, height=3)
        assert buffer.inspect(width) == 8
        assert buffer.inspect(width * height) == 24
        ```
    """

supports

supports(operation: type[Operation]) -> bool

Return whether the buffer's registry can apply an operation type.

Examples:

assert Buffer(width=1, height=1).supports(Fill)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def supports(self, operation: type[Operation]) -> bool:
    """
    Return whether the buffer's registry can apply an operation type.

    Examples:
        ```python
        assert Buffer(width=1, height=1).supports(Fill)
        ```
    """

add_hook

add_hook(callback: HookCallback, *, condition: Predicate | None = None, events: Sequence[HookEventKind] = ('tick',), priority: int = 0, once: bool = False) -> Hook

Run a callback when the runtime reports matching events for this surface.

Parameters:

  • callback (HookCallback) –

    Called with a context for the event.

  • condition (Predicate | None, default: None ) –

    An expression that must be true for the callback to run.

  • events (Sequence[HookEventKind], default: ('tick',) ) –

    The event kinds to listen to.

  • priority (int, default: 0 ) –

    Hooks with higher priority run first.

  • once (bool, default: False ) –

    Whether to remove the hook after its first run.

Returns:

  • Hook –

    The registered hook, which can be cancelled.

Examples:

keys = []
with Runtime.offscreen(width=10, height=2) as runtime:
    buffer = Buffer()
    runtime.mount(buffer, geometry='inherit')
    buffer.add_hook(lambda context: keys.append(context.event.key.key), events=['key'])
    runtime.dispatch(Event.key_press('a'))
    runtime.step()
assert keys == ['a']
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def add_hook(
    self,
    callback: HookCallback,
    *,
    condition: Predicate | None = None,
    events: Sequence[HookEventKind] = ('tick',),
    priority: int = 0,
    once: bool = False,
) -> Hook:
    """
    Run a callback when the runtime reports matching events for this surface.

    Args:
        callback: Called with a context for the event.
        condition: An expression that must be true for the callback to run.
        events: The event kinds to listen to.
        priority: Hooks with higher priority run first.
        once: Whether to remove the hook after its first run.

    Returns:
        The registered hook, which can be cancelled.

    Examples:
        ```python
        keys = []
        with Runtime.offscreen(width=10, height=2) as runtime:
            buffer = Buffer()
            runtime.mount(buffer, geometry='inherit')
            buffer.add_hook(lambda context: keys.append(context.event.key.key), events=['key'])
            runtime.dispatch(Event.key_press('a'))
            runtime.step()
        assert keys == ['a']
        ```
    """

invalidate

invalidate(area: Rectangle | None = None) -> None

Ask the runtime to redraw an area, or the whole surface.

Examples:

buffer = Buffer(width=4, height=2)
buffer.invalidate(Rectangle(0, 0, 2, 1))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def invalidate(self, area: Rectangle | None = None) -> None:
    """
    Ask the runtime to redraw an area, or the whole surface.

    Examples:
        ```python
        buffer = Buffer(width=4, height=2)
        buffer.invalidate(Rectangle(0, 0, 2, 1))
        ```
    """

to_cell_grid

to_cell_grid() -> bytes

Pack the surface into the cell grid byte format.

Examples:

packed = Buffer.with_text('abc').to_cell_grid()
assert cell_grid_to_text(packed) == ['abc']
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_cell_grid(self) -> bytes:
    """
    Pack the surface into the cell grid byte format.

    Examples:
        ```python
        packed = Buffer.with_text('abc').to_cell_grid()
        assert cell_grid_to_text(packed) == ['abc']
        ```
    """

__or__

__or__(operation: Operation | Style) -> Self

Apply operation to this surface and return the surface.

Examples:

buffer = Buffer(width=6, height=1) | Write('abc')
assert buffer.text.startswith('abc')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __or__(self, operation: Operation | Style) -> Self:
    """
    Apply ``operation`` to this surface and return the surface.

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

with_text classmethod

with_text(text: TextContent, *, style: Style | None = None) -> Buffer

Create a buffer sized to fit some text.

Examples:

buffer = Buffer.with_text('abc')
assert (buffer.width, buffer.height) == (3, 1)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def with_text(cls, text: TextContent, *, style: Style | None = None) -> Buffer:
    """
    Create a buffer sized to fit some text.

    Examples:
        ```python
        buffer = Buffer.with_text('abc')
        assert (buffer.width, buffer.height) == (3, 1)
        ```
    """

with_size classmethod

with_size(width: int, height: int) -> Buffer

Create a blank buffer of a given size.

Examples:

assert Buffer.with_size(5, 2).width == 5
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def with_size(cls, width: int, height: int) -> Buffer:
    """
    Create a blank buffer of a given size.

    Examples:
        ```python
        assert Buffer.with_size(5, 2).width == 5
        ```
    """

with_cells classmethod

with_cells(cells: Sequence[Cell], *, width: int, height: int) -> Buffer

Create a buffer from cells in row-major order.

Examples:

buffer = Buffer.with_cells([Cell('a'), Cell('b')], width=2, height=1)
assert buffer.text == 'ab'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def with_cells(cls, cells: Sequence[Cell], *, width: int, height: int) -> Buffer:
    """
    Create a buffer from cells in row-major order.

    Examples:
        ```python
        buffer = Buffer.with_cells([Cell('a'), Cell('b')], width=2, height=1)
        assert buffer.text == 'ab'
        ```
    """

from_cell_grid classmethod

from_cell_grid(packed: bytes) -> Buffer

Create a buffer from the cell grid byte format.

Raises:

Examples:

packed = Buffer.with_text('hi').to_cell_grid()
assert Buffer.from_cell_grid(packed).text == 'hi'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_cell_grid(cls, packed: bytes) -> Buffer:
    """
    Create a buffer from the cell grid byte format.

    Raises:
        CellGridError: The bytes are not a valid cell grid.

    Examples:
        ```python
        packed = Buffer.with_text('hi').to_cell_grid()
        assert Buffer.from_cell_grid(packed).text == 'hi'
        ```
    """

from_cell_animation classmethod

from_cell_animation(packed: bytes, *, start_milliseconds: int = 0) -> Buffer

Create a buffer showing one frame of a packed cell animation.

Parameters:

  • packed (bytes) –

    The cell animation bytes.

  • start_milliseconds (int, default: 0 ) –

    The point in the animation to show.

Raises:

Examples:

frames = [Buffer.with_text('a').to_cell_grid(), Buffer.with_text('b').to_cell_grid()]
packed = pack_cell_animation(frames, frame_durations_milliseconds=[50, 50])
assert Buffer.from_cell_animation(packed, start_milliseconds=60).text == 'b'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_cell_animation(cls, packed: bytes, *, start_milliseconds: int = 0) -> Buffer:
    """
    Create a buffer showing one frame of a packed cell animation.

    Args:
        packed: The cell animation bytes.
        start_milliseconds: The point in the animation to show.

    Raises:
        CellGridError: The bytes are not a valid cell animation.

    Examples:
        ```python
        frames = [Buffer.with_text('a').to_cell_grid(), Buffer.with_text('b').to_cell_grid()]
        packed = pack_cell_animation(frames, frame_durations_milliseconds=[50, 50])
        assert Buffer.from_cell_animation(packed, start_milliseconds=60).text == 'b'
        ```
    """

region

region(bounds: Rectangle) -> Region

Return a region covering a rectangle of the buffer.

Examples:

buffer = Buffer(width=4, height=2)
assert buffer.region(Rectangle(1, 0, 2, 2)).bounds == Rectangle(1, 0, 2, 2)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def region(self, bounds: Rectangle) -> Region:
    """
    Return a region covering a rectangle of the buffer.

    Examples:
        ```python
        buffer = Buffer(width=4, height=2)
        assert buffer.region(Rectangle(1, 0, 2, 2)).bounds == Rectangle(1, 0, 2, 2)
        ```
    """

resize

resize(width: int, height: int) -> None

Change the size, keeping the cells that still fit.

Examples:

buffer = Buffer.with_text('abcd')
buffer.resize(2, 1)
assert buffer.text == 'ab'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def resize(self, width: int, height: int) -> None:
    """
    Change the size, keeping the cells that still fit.

    Examples:
        ```python
        buffer = Buffer.with_text('abcd')
        buffer.resize(2, 1)
        assert buffer.text == 'ab'
        ```
    """

paste

paste(source: Buffer | Region, *, x: int = 0, y: int = 0, mode: PasteMode = 'replace') -> None

Copy the cells of another buffer or region into this one.

Parameters:

  • source (Buffer | Region) –

    The cells to copy.

  • x (int, default: 0 ) –

    The destination column of the source's left edge.

  • y (int, default: 0 ) –

    The destination row of the source's top edge.

  • mode (PasteMode, default: 'replace' ) –

    'replace' copies every cell, 'preserve_background' keeps the destination background and 'transparent' skips cells that are marked transparent.

Examples:

sprite = Buffer.with_text('ab')
canvas = Buffer(width=5, height=1)
canvas.paste(sprite, x=2)
assert canvas.text == '  ab'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def paste(
    self,
    source: Buffer | Region,
    *,
    x: int = 0,
    y: int = 0,
    mode: PasteMode = 'replace',
) -> None:
    """
    Copy the cells of another buffer or region into this one.

    Args:
        source: The cells to copy.
        x: The destination column of the source's left edge.
        y: The destination row of the source's top edge.
        mode: ``'replace'`` copies every cell, ``'preserve_background'`` keeps
            the destination background and ``'transparent'`` skips cells that
            are marked transparent.

    Examples:
        ```python
        sprite = Buffer.with_text('ab')
        canvas = Buffer(width=5, height=1)
        canvas.paste(sprite, x=2)
        assert canvas.text == '  ab'
        ```
    """

attach

attach(child: Buffer, *, geometry: GeometryMode = 'explicit', mode: PasteMode = 'replace') -> None

Attach a child buffer as a retained layer of this one.

The child keeps its own cells and is composited when this buffer is drawn, ordered by layer and then by attachment order. A child with geometry='inherit' always fills the parent's content rectangle. The 'transparent' mode skips cells explicitly marked transparent, not spaces.

Raises:

Examples:

parent = Buffer(width=8, height=3)
child = Buffer('hi', x=2, y=1)
parent.attach(child)
assert parent.children == (child,)
assert parent.render(format='text').split('\n')[1] == '  hi'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def attach(
    self,
    child: Buffer,
    *,
    geometry: GeometryMode = 'explicit',
    mode: PasteMode = 'replace',
) -> None:
    """
    Attach a child buffer as a retained layer of this one.

    The child keeps its own cells and is composited when this buffer is drawn,
    ordered by ``layer`` and then by attachment order. A child with
    ``geometry='inherit'`` always fills the parent's content rectangle. The
    ``'transparent'`` mode skips cells explicitly marked transparent, not spaces.

    Raises:
        ValueError: The child already has a parent.

    Examples:
        ```python
        parent = Buffer(width=8, height=3)
        child = Buffer('hi', x=2, y=1)
        parent.attach(child)
        assert parent.children == (child,)
        assert parent.render(format='text').split('\\n')[1] == '  hi'
        ```
    """

detach

detach(child: Buffer) -> None

Remove an attached child.

Examples:

parent = Buffer(width=4, height=1)
child = Buffer('x')
parent.attach(child)
parent.detach(child)
assert parent.children == ()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def detach(self, child: Buffer) -> None:
    """
    Remove an attached child.

    Examples:
        ```python
        parent = Buffer(width=4, height=1)
        child = Buffer('x')
        parent.attach(child)
        parent.detach(child)
        assert parent.children == ()
        ```
    """

__call__

__call__(*, runtime: Runtime | None = None) -> Rendering

Return a lazy render of the buffer.

str(rendering) serializes the buffer without touching a terminal. Using the result as a context manager mounts the buffer on runtime (or opens a live runtime) and unmounts it on exit.

Examples:

buffer = Buffer.with_text('hi')
assert 'hi' in str(buffer())

with Runtime.offscreen(width=8, height=2) as runtime:
    with buffer(runtime=runtime) as context:
        assert context.runtime is runtime
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __call__(self, *, runtime: Runtime | None = None) -> Rendering:
    """
    Return a lazy render of the buffer.

    ``str(rendering)`` serializes the buffer without touching a terminal. Using
    the result as a context manager mounts the buffer on ``runtime`` (or opens a
    live runtime) and unmounts it on exit.

    Examples:
        ```python
        buffer = Buffer.with_text('hi')
        assert 'hi' in str(buffer())

        with Runtime.offscreen(width=8, height=2) as runtime:
            with buffer(runtime=runtime) as context:
                assert context.runtime is runtime
        ```
    """

render

render(*, format: RenderFormat = 'ansi') -> str

Compose the visible children and serialize the buffer.

No terminal or device is opened.

Parameters:

  • format (RenderFormat, default: 'ansi' ) –

    'text' for plain rows or 'ansi' for text with styling escape sequences.

Examples:

buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def render(self, *, format: RenderFormat = 'ansi') -> str:
    """
    Compose the visible children and serialize the buffer.

    No terminal or device is opened.

    Args:
        format: ``'text'`` for plain rows or ``'ansi'`` for text with styling
            escape sequences.

    Examples:
        ```python
        buffer = Buffer.with_text('hi', style=Style(foreground='red'))
        assert buffer.render(format='text') == 'hi'
        assert '\\x1b[' in buffer.render(format='ansi')
        ```
    """

Fill

Fill(cell: Cell | str = ' ')

Bases: Operation

Fill every cell of the target with one cell.

Parameters:

  • cell (Cell | str, default: ' ' ) –

    A Cell or a one-grapheme string.

Examples:

buffer = Buffer(width=3, height=2)
buffer.update(Fill('#'))
assert buffer.text == '###\n###'

Create a Fill.

Parameters:

  • cell (Cell | str, default: ' ' ) –

    Cell | str. Defaults to ' '.

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, cell: Cell | str = ' ') -> None:
    """
    Create a Fill.

    Args:
        cell: ``Cell | str``. Defaults to ``' '``.
    """

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')
        ```
    """

Foreground

Foreground(color: ColorValue)

Bases: Operation

Set the foreground color of every cell of the target.

Parameters:

  • color (ColorValue) –

    A Color, a color name, a hex string or an (red, green, blue) tuple.

Examples:

buffer = Buffer(width=3, height=1)
buffer.update(Write('abc'), Foreground('red'))
assert str(buffer[0, 0].foreground) == "Color('red')"

Create a Foreground.

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, color: ColorValue) -> None:
    """
    Create a Foreground.

    Args:
        color: ``ColorValue``.
    """

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')
        ```
    """

Layout

Layout(arrangement: Literal['row', 'column', 'overlay'] = 'column', *, sizes: Sequence[SizeRule] = (), spacing: int = 0, padding: int = 0)

Bases: Operation

Arrange attached children within the parent's content area.

Overlay children inherit that area unless explicitly positioned. Row and column children default to equal fill; missing size rules never mean zero-sized children. All output is clipped to the authoritative frame.

Maps to ratatui::layout::Layout for 'row' and 'column'.

Parameters:

  • arrangement (Literal['row', 'column', 'overlay'], default: 'column' ) –

    'row', 'column' or 'overlay'.

  • sizes (Sequence[SizeRule], default: () ) –

    One SizeRule per child along the main axis.

  • spacing (int, default: 0 ) –

    Cells between children.

  • padding (int, default: 0 ) –

    Cells between the parent's edge and its children.

Examples:

parent = Buffer(width=12, height=3)
left, right = Buffer(), Buffer()
parent.attach(left, geometry='inherit')
parent.attach(right, geometry='inherit')
parent.update(
    Layout('row', sizes=[SizeRule.cells(4), SizeRule.fill()], spacing=1)
)
assert (left.width, right.x, right.width) == (4, 5, 7)

Create a Layout.

Parameters:

  • arrangement (Literal['row', 'column', 'overlay'], default: 'column' ) –

    Literal['row', 'column', 'overlay']. Defaults to 'column'.

  • sizes (Sequence[SizeRule], default: () ) –

    Sequence[SizeRule]. Defaults to ().

  • spacing (int, default: 0 ) –

    int. Defaults to 0.

  • padding (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,
    arrangement: Literal['row', 'column', 'overlay'] = 'column',
    *,
    sizes: Sequence[SizeRule] = (),
    spacing: int = 0,
    padding: int = 0,
) -> None:
    """
    Create a Layout.

    Args:
        arrangement: ``Literal['row', 'column', 'overlay']``. Defaults to ``'column'``.
        sizes: ``Sequence[SizeRule]``. Defaults to ``()``.
        spacing: ``int``. Defaults to ``0``.
        padding: ``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')
        ```
    """

Margin

Margin(horizontal: int | Expression[int | float] = 0, vertical: int | Expression[int | float] = 0)

Horizontal and vertical inset distances.

Attributes:

  • vertical (int) –

    The number of cells inset from the top and bottom edges.

  • horizontal (int) –

    The number of cells inset from the left and right edges.

Examples:

assert Margin(1, 2).horizontal == 1

Create a Margin.

Parameters:

  • horizontal (int | Expression[int | float], default: 0 ) –

    int | Expression[int | float]. Defaults to 0.

  • vertical (int | Expression[int | float], default: 0 ) –

    int | Expression[int | float]. Defaults to 0.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    /,
    horizontal: int | Expression[int | float] = 0,
    vertical: int | Expression[int | float] = 0,
) -> None:
    """
    Create a Margin.

    Args:
        horizontal: ``int | Expression[int | float]``. Defaults to ``0``.
        vertical: ``int | Expression[int | float]``. Defaults to ``0``.
    """

vertical property

vertical: int

The number of cells inset from the top and bottom edges.

horizontal property

horizontal: int

The number of cells inset from the left and right edges.

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')
        ```
    """

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:

  • 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.

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')
        ```
    """

Paste

Paste(source: Buffer | Region, *, x: int = 0, y: int = 0, mode: WriteMode = 'replace')

Bases: Operation

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

The source is snapshotted when the operation is created, so the operation can be applied repeatedly and always copies the same cells.

Parameters:

  • source (Buffer | Region) –

    The buffer or region to copy from.

  • x (int, default: 0 ) –

    The destination column of the source's top-left cell.

  • y (int, default: 0 ) –

    The destination row of the source's top-left cell.

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

    How copied cells combine with the destination.

Examples:

source = Buffer(width=2, height=1)
source.update(Write('ab'))
target = Buffer(width=4, height=1)
target.update(Fill('.'), Paste(source, x=1))
assert target.text == '.ab.'

Create a Paste.

Parameters:

  • source (Buffer | Region) –

    Buffer | Region.

  • x (int, default: 0 ) –

    int. Defaults to 0.

  • y (int, default: 0 ) –

    int. Defaults to 0.

  • 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,
    source: Buffer | Region,
    *,
    x: int = 0,
    y: int = 0,
    mode: WriteMode = 'replace',
) -> None:
    """
    Create a Paste.

    Args:
        source: ``Buffer | Region``.
        x: ``int``. Defaults to ``0``.
        y: ``int``. Defaults to ``0``.
        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')
        ```
    """

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')
        ```
    """

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')
        ```
    """

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')
        ```
    """

ContextualOperation

ContextualOperation(callback: Callable[[Context[DepsT, StateT]], object] | None = None, *, on: HookKind | None = None, every: float | None = None, after: float | None = None, keys: tuple[str, ...] = (), when: When[DepsT, StateT] | None = None, requires_deps: bool = False, steps: Sequence[Operation] = ())

Bases: Operation, Generic[DepsT, StateT]

A reusable hook that can be piped onto any canvas or placement.

Build one with hook. Apply it with |, |= or update, and it attaches the same hook that target.hook(function, ...) would.

Attributes:

  • on (HookKind | None) –

    When the hook runs, or None for every input event.

  • every (float | None) –

    Seconds ('tick') or beats ('beat') between runs, or None.

  • after (float | None) –

    Delay before the one run, or None.

  • keys (tuple[str, ...]) –

    Key names an on='key' hook reacts to.

Examples:

import xnano

counted = []

@xnano.hook(on='tick', every=0.5)
def count(context: xnano.Context) -> None:
    counted.append(context.time.elapsed)

with xnano.new(width=16, height=1) as canvas:
    canvas | count
    canvas.step(delta_seconds=1.0)
assert len(counted) == 2

Create a reusable hook. Use hook instead of calling this.

Parameters:

  • callback (Callable[[Context[DepsT, StateT]], object] | None, default: None ) –

    Function called with a Context when the hook runs.

  • on (HookKind | None, default: None ) –

    What the hook listens to.

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

    Interval between runs.

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

    Delay before the one run.

  • keys (tuple[str, ...], default: () ) –

    Key names to react to when on='key'.

  • when (When[DepsT, StateT] | None, default: None ) –

    A condition that must hold.

  • requires_deps (bool, default: False ) –

    Whether the hook needs the canvas's dependencies.

  • steps (Sequence[Operation], default: () ) –

    Chained operations to apply in sequence.

Methods:

  • then –

    Return a new operation that applies this operation and then other.

  • __or__ –

    Combine this operation with another operation or style.

  • __ror__ –

    Apply this operation to target when piped with target | operation.

  • apply_to_surface –

    Apply the chained steps of this operation to a core Surface.

  • apply_to –

    Attach this hook to target, or apply its chained steps.

  • evaluate –

    Compute the expression's value.

  • when –

    An operation that applies only while condition is true.

Source code in xnano/operations.py
def __init__(
    self,
    callback: Callable[[Context[DepsT, StateT]], object] | None = None,
    *,
    on: HookKind | None = None,
    every: float | None = None,
    after: float | None = None,
    keys: tuple[str, ...] = (),
    when: When[DepsT, StateT] | None = None,
    requires_deps: bool = False,
    steps: Sequence[_core.Operation] = (),
) -> None:
    """
    Create a reusable hook. Use [`hook`][xnano.operations.hook] instead of calling this.

    Args:
        callback: Function called with a [`Context`][xnano.context.Context] when the hook
            runs.
        on: What the hook listens to.
        every: Interval between runs.
        after: Delay before the one run.
        keys: Key names to react to when ``on='key'``.
        when: A condition that must hold.
        requires_deps: Whether the hook needs the canvas's dependencies.
        steps: Chained operations to apply in sequence.
    """
    super().__init__()
    self._callback = callback
    self._hook_on = on
    self._every = every
    self._after = after
    self._keys = tuple(keys)
    self._when = when
    self._requires_deps = requires_deps
    self._steps: tuple[_core.Operation, ...] = tuple(steps)

on property

on: HookKind | None

What the hook listens to, or None for every input event.

every property

every: float | None

Interval between runs, or None.

after property

after: float | None

Delay before the one run, or None.

keys property

keys: tuple[str, ...]

Key names an on='key' hook reacts to.

then

then(other: Operation) -> ContextualOperation[DepsT, StateT]

Return a new operation that applies this operation and then other.

Parameters:

  • other (Operation) –

    The next operation to run.

Source code in xnano/operations.py
def then(self, other: _core.Operation) -> ContextualOperation[DepsT, StateT]:
    """
    Return a new operation that applies this operation and then ``other``.

    Args:
        other: The next operation to run.
    """
    combined: list[_core.Operation] = list(self._steps) if self._steps else [self]
    if isinstance(other, ContextualOperation) and other._steps:
        combined.extend(other._steps)
    else:
        combined.append(other)
    return ContextualOperation(steps=combined)

__or__

__or__(other: Operation | Style) -> ContextualOperation[DepsT, StateT]

Combine this operation with another operation or style.

Source code in xnano/operations.py
def __or__(  # type: ignore[override]
    self, other: _core.Operation | _core.Style
) -> ContextualOperation[DepsT, StateT]:
    """Combine this operation with another operation or style."""
    if isinstance(other, _core.Style):
        return self.then(_core.ApplyStyle(other))
    return self.then(other)

__ror__

__ror__(target: TargetT) -> TargetT

Apply this operation to target when piped with target | operation.

Source code in xnano/operations.py
def __ror__(self, target: TargetT) -> TargetT:
    """Apply this operation to ``target`` when piped with ``target | operation``."""
    if isinstance(target, _core.Operation):
        return cast('TargetT', ContextualOperation(steps=(target, self)))
    self.apply_to(
        cast(
            'Canvas[DepsT, StateT] | Placement[DepsT, StateT] | _core.Surface',
            target,
        )
    )
    return target

apply_to_surface

apply_to_surface(surface: Surface) -> None

Apply the chained steps of this operation to a core Surface.

A hook has no surface to listen on, so only its chained steps apply.

Parameters:

  • surface (Surface) –

    The buffer or region to modify.

Source code in xnano/operations.py
def apply_to_surface(self, surface: _core.Surface) -> None:
    """
    Apply the chained steps of this operation to a core [`Surface`][xnano_core.Surface].

    A hook has no surface to listen on, so only its chained steps apply.

    Args:
        surface: The buffer or region to modify.
    """
    for step in self._steps:
        if isinstance(step, (ContextualOperation, Customization)):
            step.apply_to_surface(surface)
        else:
            surface.update(step)

apply_to

apply_to(target: Canvas[DepsT, StateT] | Placement[DepsT, StateT] | Surface) -> None

Attach this hook to target, or apply its chained steps.

Parameters:

Source code in xnano/operations.py
def apply_to(
    self,
    target: Canvas[DepsT, StateT] | Placement[DepsT, StateT] | _core.Surface,
) -> None:
    """
    Attach this hook to ``target``, or apply its chained steps.

    Args:
        target: A [`Canvas`][xnano.canvas.Canvas], a
            [`Placement`][xnano.placement.Placement] or a [`Surface`][xnano_core.Surface].
    """
    if isinstance(target, _core.Surface):
        self.apply_to_surface(target)
        return
    if self._steps:
        for step in self._steps:
            if isinstance(step, (ContextualOperation, Customization)):
                step.apply_to(
                    cast('Canvas[object, object] | Placement[object, object]', target)
                )
            else:
                target.update(step)
        return
    callback = self._callback
    if callback is None:
        return
    target.hook(
        callback,
        on=cast('HookKind | None', self._hook_on),
        when=self._when,
        every=self._every,
        after=self._after,
        keys=self._keys or None,
        requires_deps=self._requires_deps,
    )

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
        ```
    """

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')
        ```
    """

fx

fx(kind: Literal['fill'], /, **parameters: Unpack[FillArguments]) -> FillCustomization
fx(kind: Literal['write'], /, **parameters: Unpack[WriteArguments]) -> WriteCustomization
fx(kind: Literal['layout'], /, **parameters: Unpack[LayoutArguments]) -> LayoutCustomization
fx(kind: Literal['fuzz'], /, **parameters: Unpack[FuzzArguments]) -> FuzzCustomization
fx(kind: Literal['pixels'], /, **parameters: Unpack[PixelsArguments]) -> PixelsCustomization
fx(kind: Literal['raster'], /, **parameters: Unpack[RasterArguments]) -> RasterCustomization
fx(kind: Literal['effect.fade_to'], /, **parameters: Unpack[FadeToEffectArguments]) -> FadeToEffectCustomization
fx(kind: Literal['effect.fade_from'], /, **parameters: Unpack[FadeFromEffectArguments]) -> FadeFromEffectCustomization
fx(kind: Literal['effect.paint'], /, **parameters: Unpack[PaintEffectArguments]) -> PaintEffectCustomization
fx(kind: Literal['effect.saturate'], /, **parameters: Unpack[SaturateEffectArguments]) -> SaturateEffectCustomization
fx(kind: Literal['effect.lighten'], /, **parameters: Unpack[LightenEffectArguments]) -> LightenEffectCustomization
fx(kind: Literal['effect.darken'], /, **parameters: Unpack[DarkenEffectArguments]) -> DarkenEffectCustomization
fx(kind: Literal['effect.sweep_in'], /, **parameters: Unpack[SweepInEffectArguments]) -> SweepInEffectCustomization
fx(kind: Literal['effect.sweep_out'], /, **parameters: Unpack[SweepOutEffectArguments]) -> SweepOutEffectCustomization
fx(kind: Literal['effect.slide_in'], /, **parameters: Unpack[SlideInEffectArguments]) -> SlideInEffectCustomization
fx(kind: Literal['effect.slide_out'], /, **parameters: Unpack[SlideOutEffectArguments]) -> SlideOutEffectCustomization
fx(kind: Literal['effect.hsl_shift'], /, **parameters: Unpack[HslShiftEffectArguments]) -> HslShiftEffectCustomization
fx(kind: Literal['effect.dissolve'], /, **parameters: Unpack[DissolveEffectArguments]) -> DissolveEffectCustomization
fx(kind: Literal['effect.coalesce'], /, **parameters: Unpack[CoalesceEffectArguments]) -> CoalesceEffectCustomization
fx(kind: Literal['effect.glitch'], /, **parameters: Unpack[GlitchEffectArguments]) -> GlitchEffectCustomization
fx(kind: Literal['effect.sleep'], /, **parameters: Unpack[SleepEffectArguments]) -> SleepEffectCustomization
fx(kind: Literal['effect.evolve'], /, **parameters: Unpack[EvolveEffectArguments]) -> EvolveEffectCustomization
fx(kind: Literal['effect.evolve_into'], /, **parameters: Unpack[EvolveIntoEffectArguments]) -> EvolveIntoEffectCustomization
fx(kind: Literal['effect.evolve_from'], /, **parameters: Unpack[EvolveFromEffectArguments]) -> EvolveFromEffectCustomization
fx(kind: Literal['effect.expand'], /, **parameters: Unpack[ExpandEffectArguments]) -> ExpandEffectCustomization
fx(kind: Literal['effect.stretch'], /, **parameters: Unpack[StretchEffectArguments]) -> StretchEffectCustomization
fx(kind: Literal['effect.explode'], /, **parameters: Unpack[ExplodeEffectArguments]) -> ExplodeEffectCustomization
fx(kind: Literal['audio.bit_crush'], /, **parameters: Unpack[BitCrushAudioArguments]) -> BitCrushAudioCustomization
fx(kind: Literal['audio.distortion'], /, **parameters: Unpack[DistortionAudioArguments]) -> DistortionAudioCustomization
fx(kind: Literal['audio.low_pass'], /, **parameters: Unpack[LowPassAudioArguments]) -> LowPassAudioCustomization
fx(kind: Literal['audio.high_pass'], /, **parameters: Unpack[HighPassAudioArguments]) -> HighPassAudioCustomization
fx(kind: Literal['audio.delay'], /, **parameters: Unpack[DelayAudioArguments]) -> DelayAudioCustomization
fx(kind: Literal['audio.reverb'], /, **parameters: Unpack[ReverbAudioArguments]) -> ReverbAudioCustomization
fx(kind: Literal['audio.tremolo'], /, **parameters: Unpack[TremoloAudioArguments]) -> TremoloAudioCustomization
fx(kind: CustomizationKind, /, **parameters: object) -> Customization

Create a typed dataclass customization for a fill, layout, pixels, visual effect ('effect.<name>') or audio effect ('audio.<name>').

Each kind overloads the keyword arguments with Unpack over its corresponding TypedDict and returns the matching Customization dataclass. The returned dataclass can be inspected, mutated, returned from an hook, piped with |, or passed to add and update.

Parameters:

  • kind (CustomizationKind) –

    Which customization to create (such as 'fill', 'layout', 'pixels', 'effect.dissolve', 'effect.fade_to' or 'audio.reverb').

  • parameters (object, default: {} ) –

    Keyword arguments for the chosen customization kind.

Raises:

  • ValueError –

    kind is not a recognized customization kind.

  • TypeError –

    A keyword is not a setting of that kind. The message lists its settings.

Examples:

import xnano

from xnano.operations import fx

sparkle = fx('fill', cell='*')
assert sparkle.cell == '*'

fade = fx('effect.fade_to', foreground='red', duration_milliseconds=200)
assert fade.duration_milliseconds == 200

with xnano.new(width=10, height=3) as canvas:
    canvas | sparkle
    assert '*' in canvas.render()
Source code in xnano/_customize.py
def fx(kind: CustomizationKind, /, **parameters: object) -> Customization:
    """
    Create a typed dataclass customization for a fill, layout,
    pixels, visual effect (``'effect.<name>'``) or audio effect (``'audio.<name>'``).

    Each ``kind`` overloads the keyword arguments with ``Unpack`` over its corresponding
    ``TypedDict`` and returns the matching [`Customization`][xnano.operations.Customization]
    dataclass. The returned dataclass can be inspected, mutated, returned from an
    [`hook`][xnano.operations.hook], piped with ``|``, or passed to ``add`` and
    ``update``.

    Args:
        kind: Which customization to create (such as ``'fill'``, ``'layout'``,
            ``'pixels'``, ``'effect.dissolve'``,
            ``'effect.fade_to'`` or ``'audio.reverb'``).
        parameters: Keyword arguments for the chosen customization kind.

    Raises:
        ValueError: ``kind`` is not a recognized customization kind.
        TypeError: A keyword is not a setting of that kind. The message lists its settings.

    Examples:
        ```python
        import xnano

        from xnano.operations import fx

        sparkle = fx('fill', cell='*')
        assert sparkle.cell == '*'

        fade = fx('effect.fade_to', foreground='red', duration_milliseconds=200)
        assert fade.duration_milliseconds == 200

        with xnano.new(width=10, height=3) as canvas:
            canvas | sparkle
            assert '*' in canvas.render()
        ```
    """
    customization_class = _CUSTOMIZATION_TYPES.get(kind)
    if customization_class is None:
        valid = ', '.join(sorted(_CUSTOMIZATION_TYPES))
        raise ValueError(
            f'{kind!r} is not a known customization kind. Choose one of: {valid}.'
        )
    accepted = [field.name for field in fields(customization_class) if field.init]  # type: ignore[arg-type]
    unknown = [name for name in parameters if name not in accepted]
    if unknown:
        what = 'effect' if kind.startswith(('effect.', 'audio.')) else 'customization'
        raise TypeError(
            f'The {what} {kind!r} has no setting called {unknown[0]!r}. Its settings are: '
            f'{", ".join(accepted)}.'
        )
    factory = cast('Callable[..., Customization]', customization_class)
    return factory(**parameters)

hook

hook(function: Hook[DepsT, StateT]) -> ContextualOperation[DepsT, StateT]
hook(*, on: HookKind | None = None, when: When[DepsT, StateT] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False) -> Callable[[Hook[DepsT, StateT]], ContextualOperation[DepsT, StateT]]
hook(function: Hook[DepsT, StateT] | None = None, /, *, on: HookKind | None = None, when: When[DepsT, StateT] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False) -> ContextualOperation[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], ContextualOperation[DepsT, StateT]]

Describe a hook once, to attach to any canvas or placement later.

It takes the same arguments as target.hook(...) and returns an operation: pipe it onto a target with target | operation, or pass it to update. Each target gets its own hook. The function may return an operation, a style or an effect, which is applied to the target it runs on.

Parameters:

  • function (Hook[DepsT, StateT] | None, default: None ) –

    The function to wrap when @xnano.hook is used without parentheses: a function of the Context, or one with no parameters.

  • on (HookKind | None, default: None ) –

    What the hook listens to; see HookKind.

  • when (When[DepsT, StateT] | None, default: None ) –

    A condition that must hold; see When.

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

    Repeat every this many seconds ('tick') or beats ('beat').

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

    Run once after this many seconds ('tick') or beats ('beat').

  • keys (KeyName | Sequence[KeyName] | None, default: None ) –

    The key or keys an on='key' hook reacts to.

  • requires_deps (bool, default: False ) –

    Whether the hook needs the dependencies given to new(deps=...).

Raises:

  • TypeError –

    function cannot be called with a context, keys is not a key name or a list of them, or when is not a condition.

  • ValueError –

    on, every, after, keys or when is not valid, or they do not fit together.

Examples:

import xnano

readings = []

@xnano.hook(on='frame')
def clock_readout(context: xnano.Context) -> None:
    readings.append(round(context.time.elapsed, 1))

with xnano.new(width=12, height=1) as canvas:
    canvas | clock_readout
    canvas.step(delta_seconds=0.5)
assert readings == [0.5]
Source code in xnano/operations.py
def hook(
    function: Hook[DepsT, StateT] | None = None,
    /,
    *,
    on: HookKind | None = None,
    when: When[DepsT, StateT] | None = None,
    every: float | None = None,
    after: float | None = None,
    keys: KeyName | Sequence[KeyName] | None = None,
    requires_deps: bool = False,
) -> (
    ContextualOperation[DepsT, StateT]
    | Callable[
        [Hook[DepsT, StateT]],
        ContextualOperation[DepsT, StateT],
    ]
):
    """
    Describe a hook once, to attach to any canvas or placement later.

    It takes the same arguments as ``target.hook(...)`` and returns an operation: pipe it onto
    a target with ``target | operation``, or pass it to ``update``. Each target gets its own
    hook. The function may return an operation, a style or an effect, which is applied to the
    target it runs on.

    Args:
        function: The function to wrap when ``@xnano.hook`` is used without parentheses: a
            function of the [`Context`][xnano.context.Context], or one with no parameters.
        on: What the hook listens to; see [`HookKind`][xnano.types.HookKind].
        when: A condition that must hold; see [`When`][xnano.types.When].
        every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
        after: Run once after this many seconds (``'tick'``) or beats (``'beat'``).
        keys: The key or keys an ``on='key'`` hook reacts to.
        requires_deps: Whether the hook needs the dependencies given to ``new(deps=...)``.

    Raises:
        TypeError: ``function`` cannot be called with a context, ``keys`` is not a key name
            or a list of them, or ``when`` is not a condition.
        ValueError: ``on``, ``every``, ``after``, ``keys`` or ``when`` is not valid, or they
            do not fit together.

    Examples:
        ```python
        import xnano

        readings = []

        @xnano.hook(on='frame')
        def clock_readout(context: xnano.Context) -> None:
            readings.append(round(context.time.elapsed, 1))

        with xnano.new(width=12, height=1) as canvas:
            canvas | clock_readout
            canvas.step(delta_seconds=0.5)
        assert readings == [0.5]
        ```
    """
    from xnano._when import compile_when

    _check_hook_arguments(
        cast('_Hooked[object, object]', object()), on, every, after, keys
    )
    compile_when(when)
    normalized_keys: tuple[str, ...] = (
        () if keys is None else (keys,) if isinstance(keys, str) else tuple(keys)
    )

    def wrap(
        callback: Hook[DepsT, StateT],
    ) -> ContextualOperation[DepsT, StateT]:
        return ContextualOperation(
            cast(
                'Callable[[Context[DepsT, StateT]], object]',
                _check_hook_function(callback),
            ),
            on=on,
            every=every,
            after=after,
            keys=normalized_keys,
            when=when,
            requires_deps=requires_deps,
        )

    if function is not None:
        return wrap(function)
    return wrap