Skip to content

xnano.widgets

xnano.widgets

xnano.widgets

Widgets that draw themselves: text, tables, charts, gauges, canvases and lists.

A widget is a description of something to draw. Pass one to Canvas.write or draw it into a Buffer; every number and text in it can be an Expression that is evaluated again on each frame.

Classes:

  • Bar –

    One labelled value in a bar chart.

  • BarChart –

    Grouped bars with editable values and styles.

  • BarGroup –

    A labelled group of bars.

  • Block –

    Borders, titles and padding shared by retained widgets.

  • Calendar –

    A monthly calendar with editable dates and styles for events.

  • Canvas –

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

  • CanvasCircle –

    A circle outline.

  • CanvasLabel –

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

  • CanvasLine –

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

  • CanvasMap –

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

  • CanvasPoints –

    A set of single points.

  • CanvasRectangle –

    An axis-aligned rectangle outline.

  • Chart –

    Point series drawn against shared editable axes.

  • ChartAxis –

    An editable axis with bounds, labels and a title.

  • ChartDataset –

    An editable series of points displayed by a chart.

  • Gauge –

    A filled progress bar that repaints when its ratio changes.

  • ItemList –

    Selectable styled items with editable selection and scrolling.

  • LineGauge –

    A progress indicator drawn with line symbols.

  • ListItem –

    Styled content displayed by an item list.

  • Paragraph –

    Styled text that can wrap, align and scroll.

  • Scrollbar –

    A scrollbar showing position within content.

  • Sparkline –

    A compact history of numeric samples.

  • SparklineBar –

    A sample with an optional individual style.

  • Table –

    A retained table with row, column and cell selection.

  • TableCell –

    Styled content displayed in a table cell.

  • TableRow –

    A row of cells with height and spacing.

  • Tabs –

    Selectable titles with editable padding, divider and styles.

  • Widget –

    A buffer painted from editable settings or bound expressions.

Bar

Bar(value: int | Expression[int | float], label: TextContent | Expression[str] | None = None, *, text_value: str | Expression[str] | None = None, style: Style | DynamicStyle | None = None, value_style: Style | DynamicStyle | None = None)

One labelled value in a bar chart.

Attributes:

Examples:

bar = Bar(3, 'A')
assert bar.value == 3

Create a Bar.

Parameters:

  • value (int | Expression[int | float]) –

    int | Expression[int | float].

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

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

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

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

    Style | DynamicStyle | None. Defaults to None.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    /,
    value: int | Expression[int | float],
    label: TextContent | Expression[str] | None = None,
    *,
    text_value: str | Expression[str] | None = None,
    style: Style | DynamicStyle | None = None,
    value_style: Style | DynamicStyle | None = None,
) -> None:
    """
    Create a Bar.

    Args:
        value: ``int | Expression[int | float]``.
        label: ``TextContent | Expression[str] | None``. Defaults to ``None``.
        text_value: ``str | Expression[str] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        value_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
    """

label property

label: TextContent | Expression[str] | None

The text displayed as the label, or None to omit it.

style property

The default colors and text modifiers applied to the cells.

value property

value: int | Expression[int | float]

The nonnegative numeric value represented by the bar.

text_value property

text_value: str | Expression[str]

The text drawn for the value, or None to display the numeric value.

value_style property

value_style: Style | DynamicStyle

The colors and text modifiers applied to the displayed value.

BarChart

BarChart(data: Sequence[Bar | BarGroup | int] | None = None, *, bar_width: int | Expression[int | float] | None = None, bar_gap: int | Expression[int | float] | None = None, group_gap: int | Expression[int | float] | None = None, maximum: int | Expression[int | float] | None = None, direction: str | Expression[str] | None = None, bar_style: Style | DynamicStyle | None = None, value_style: Style | DynamicStyle | None = None, label_style: Style | DynamicStyle | None = None, style: Style | DynamicStyle | None = None, bar_set: str | Expression[str] | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

Grouped bars with editable values and styles.

Attributes:

Examples:

chart = BarChart([Bar(3, 'A')], width=12, height=4)
chart.maximum = 6
assert chart.maximum == 6

Create a BarChart.

Parameters:

  • data (Sequence[Bar | BarGroup | int] | None, default: None ) –

    Sequence[Bar | BarGroup | int] | None. Defaults to None.

  • bar_width (int | Expression[int | float] | None, default: None ) –

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

  • bar_gap (int | Expression[int | float] | None, default: None ) –

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

  • group_gap (int | Expression[int | float] | None, default: None ) –

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

  • maximum (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

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

  • block (Block | None, default: None ) –

    Block | None. Defaults to None.

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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,
    /,
    data: Sequence[Bar | BarGroup | int] | None = None,
    *,
    bar_width: int | Expression[int | float] | None = None,
    bar_gap: int | Expression[int | float] | None = None,
    group_gap: int | Expression[int | float] | None = None,
    maximum: int | Expression[int | float] | None = None,
    direction: str | Expression[str] | None = None,
    bar_style: Style | DynamicStyle | None = None,
    value_style: Style | DynamicStyle | None = None,
    label_style: Style | DynamicStyle | None = None,
    style: Style | DynamicStyle | None = None,
    bar_set: str | Expression[str] | None = None,
    block: Block | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a BarChart.

    Args:
        data: ``Sequence[Bar | BarGroup | int] | None``. Defaults to ``None``.
        bar_width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        bar_gap: ``int | Expression[int | float] | None``. Defaults to ``None``.
        group_gap: ``int | Expression[int | float] | None``. Defaults to ``None``.
        maximum: ``int | Expression[int | float] | None``. Defaults to ``None``.
        direction: ``str | Expression[str] | None``. Defaults to ``None``.
        bar_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        value_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        label_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        bar_set: ``str | Expression[str] | None``. Defaults to ``None``.
        block: ``Block | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

label_style property writable

label_style: Style | DynamicStyle

The colors and text modifiers applied to bar and group labels.

group_gap property writable

group_gap: int | Expression[int | float]

The number of empty cells between groups of bars.

bar_gap property writable

bar_gap: int | Expression[int | float]

The number of empty cells between adjacent bars.

block property writable

block: Block | None

The optional border, titles and padding around the content.

style property writable

The default colors and text modifiers applied to the cells.

bar_width property writable

bar_width: int | Expression[int | float]

The thickness of each bar, in cells.

direction property writable

direction: str | Expression[str]

The orientation of the bars: vertical or horizontal.

maximum property writable

maximum: int | Expression[int | float] | None

The value represented by a full bar, or None to use the largest value.

groups property writable

groups: Sequence[BarGroup]

The groups of bars displayed in sequence order.

bar_set property writable

bar_set: str | Expression[str]

The named set of symbols used to draw partial and full bars.

bar_style property writable

bar_style: Style | DynamicStyle

The default colors and text modifiers applied to the bars.

value_style property writable

value_style: Style | DynamicStyle

The colors and text modifiers applied to the displayed value.

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

BarGroup

BarGroup(bars: Sequence[Bar], label: TextContent | Expression[str] | None = None)

A labelled group of bars.

Attributes:

Examples:

group = BarGroup([Bar(3, 'A')], 'Group')
assert len(group.bars) == 1

Create a BarGroup.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self, /, bars: Sequence[Bar], label: TextContent | Expression[str] | None = None
) -> None:
    """
    Create a BarGroup.

    Args:
        bars: ``Sequence[Bar]``.
        label: ``TextContent | Expression[str] | None``. Defaults to ``None``.
    """

label property

label: TextContent | Expression[str] | None

The text displayed as the label, or None to omit it.

bars property

bars: Sequence[Bar]

The bars displayed in their sequence order.

Block

Block(title: str | Expression[str] | None = None, *, borders: str | Sequence[str] | None = None, border_type: str | Expression[str] | None = None, border_style: Style | DynamicStyle | None = None, style: Style | DynamicStyle | None = None, title_style: Style | DynamicStyle | None = None, title_alignment: str = 'left', padding: int | Expression[int | float] | tuple[int | Expression[int | float], int | Expression[int | float], int | Expression[int | float], int | Expression[int | float]] | None = None, merge: str | Expression[str] | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

Borders, titles and padding shared by retained widgets.

Attributes:

Examples:

block = Block('Status', width=12, height=3)
assert 'Status' in block.render(format='text')
block.border_type = 'double'
assert '╔' in block.render(format='text')

Create a Block.

Parameters:

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

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

  • borders (str | Sequence[str] | None, default: None ) –

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

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

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

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

  • title_alignment (str, default: 'left' ) –

    str. Defaults to 'left'.

  • padding (int | Expression[int | float] | tuple[int | Expression[int | float], int | Expression[int | float], int | Expression[int | float], int | Expression[int | float]] | None, default: None ) –

    int | Expression[int | float] | tuple[int | Expression[int | float], int | Expression[int | float], int | Expression[int | float], int | Expression[int | float]] | None. Defaults to None.

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

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

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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.

  • copy –

    Copy the cells, geometry and children into a new, independent buffer.

  • __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,
    /,
    title: str | Expression[str] | None = None,
    *,
    borders: str | Sequence[str] | None = None,
    border_type: str | Expression[str] | None = None,
    border_style: Style | DynamicStyle | None = None,
    style: Style | DynamicStyle | None = None,
    title_style: Style | DynamicStyle | None = None,
    title_alignment: str = 'left',
    padding: int
    | Expression[int | float]
    | tuple[
        int | Expression[int | float],
        int | Expression[int | float],
        int | Expression[int | float],
        int | Expression[int | float],
    ]
    | None = None,
    merge: str | Expression[str] | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a Block.

    Args:
        title: ``str | Expression[str] | None``. Defaults to ``None``.
        borders: ``str | Sequence[str] | None``. Defaults to ``None``.
        border_type: ``str | Expression[str] | None``. Defaults to ``None``.
        border_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        title_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        title_alignment: ``str``. Defaults to ``'left'``.
        padding: ``int | Expression[int | float] | tuple[int | Expression[int | float], int |
            Expression[int | float], int | Expression[int | float], int | Expression[int | float]] | None``.
            Defaults to ``None``.
        merge: ``str | Expression[str] | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

border_type property writable

border_type: str | Expression[str]

The named border-symbol style, such as plain, rounded or double.

title_alignment property writable

title_alignment: str | Expression[str]

The default horizontal alignment of titles: left, center or right.

border_style property writable

border_style: Style | DynamicStyle

The colors and text modifiers applied to the border.

title_style property writable

title_style: Style | DynamicStyle

The default colors and text modifiers applied to titles.

padding property writable

The inner spacing in cells: one value for every edge or a tuple of left, right, top and bottom values.

merge property writable

merge: str | Expression[str]

The border-merging policy used where this block meets another border.

style property writable

The default colors and text modifiers applied to the cells.

titles property writable

titles: Sequence[BlockTitle | str]

The titles placed on the block border, in sequence order.

borders property writable

borders: str | Sequence[str]

The edges on which borders are drawn.

__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 == ()
        ```
    """

copy

copy() -> Buffer

Copy the cells, geometry and children into a new, independent buffer.

Hooks and runtime state are not copied.

Examples:

original = Buffer.with_text('a')
duplicate = original.copy()
duplicate.write('b')
assert original.text == 'a'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def copy(self) -> Buffer:
    """
    Copy the cells, geometry and children into a new, independent buffer.

    Hooks and runtime state are not copied.

    Examples:
        ```python
        original = Buffer.with_text('a')
        duplicate = original.copy()
        duplicate.write('b')
        assert original.text == 'a'
        ```
    """

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

Calendar

Calendar(year: int | Expression[int | float], month: int | Expression[int | float], day: int | Expression[int | float] | None = None, *, events: Mapping[tuple[int, int, int], Style | DynamicStyle] | None = None, style: Style | DynamicStyle | None = None, surrounding_style: Style | DynamicStyle | None = None, weekdays_header_style: Style | DynamicStyle | None = None, month_header_style: Style | DynamicStyle | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

A monthly calendar with editable dates and styles for events.

Attributes:

Examples:

calendar = Calendar(2026, 10, month_header_style=Style(), width=22, height=8)
assert 'October' in calendar.render(format='text')
calendar.month = 11
assert 'November' in calendar.render(format='text')

Create a Calendar.

Parameters:

  • year (int | Expression[int | float]) –

    int | Expression[int | float].

  • month (int | Expression[int | float]) –

    int | Expression[int | float].

  • day (int | Expression[int | float] | None, default: None ) –

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

  • events (Mapping[tuple[int, int, int], Style | DynamicStyle] | None, default: None ) –

    Mapping[tuple[int, int, int], Style | DynamicStyle] | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

  • block (Block | None, default: None ) –

    Block | None. Defaults to None.

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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,
    /,
    year: int | Expression[int | float],
    month: int | Expression[int | float],
    day: int | Expression[int | float] | None = None,
    *,
    events: Mapping[tuple[int, int, int], Style | DynamicStyle] | None = None,
    style: Style | DynamicStyle | None = None,
    surrounding_style: Style | DynamicStyle | None = None,
    weekdays_header_style: Style | DynamicStyle | None = None,
    month_header_style: Style | DynamicStyle | None = None,
    block: Block | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a Calendar.

    Args:
        year: ``int | Expression[int | float]``.
        month: ``int | Expression[int | float]``.
        day: ``int | Expression[int | float] | None``. Defaults to ``None``.
        events: ``Mapping[tuple[int, int, int], Style | DynamicStyle] | None``. Defaults to
            ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        surrounding_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        weekdays_header_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        month_header_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        block: ``Block | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

weekdays_header_style property writable

weekdays_header_style: Style | DynamicStyle

The colors and text modifiers applied to the weekday headings.

events property writable

The styles applied to dates, keyed by year, month and day.

day property writable

day: int | Expression[int | float]

The day of the month selected by the calendar date.

year property writable

year: int | Expression[int | float]

The year of the displayed calendar month.

month_header_style property writable

month_header_style: Style | DynamicStyle

The colors and text modifiers applied to the month heading.

block property writable

block: Block | None

The optional border, titles and padding around the content.

style property writable

The default colors and text modifiers applied to the cells.

surrounding_style property writable

surrounding_style: Style | DynamicStyle

The colors and text modifiers applied to dates outside the displayed month.

month property writable

month: int | Expression[int | float]

The displayed month number, from 1 for January to 12 for December.

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

Canvas

Canvas(x_bounds: Sequence[float | Value[float]] | None = None, y_bounds: Sequence[float | Value[float]] | None = None, *, marker: str | Value[str] | None = None, background_color: ColorValue | None = None, shapes: Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None = None, block: Block | None = None, width: int | None = None, height: int | None = None, x: int = 0, y: int = 0)

Bases: Widget

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

Maps to ratatui::widgets::canvas::Canvas.

Parameters:

  • x_bounds (Sequence[float | Value[float]] | None, default: None ) –

    The lower and upper horizontal coordinates visible on the canvas.

  • y_bounds (Sequence[float | Value[float]] | None, default: None ) –

    The lower and upper vertical coordinates visible on the canvas.

  • marker (str | Value[str] | None, default: None ) –

    How points are drawn; see CanvasMarker. Defaults to 'braille'.

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

    Color behind the shapes, or None.

  • shapes (Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None, default: None ) –

    Shapes drawn in order.

  • block (Block | None, default: None ) –

    A Block framing the canvas.

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

    Width in cells. Defaults to 20.

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

    Height in cells. Defaults to 10.

  • x (int, default: 0 ) –

    Column in the parent.

  • y (int, default: 0 ) –

    Row in the parent.

Raises:

  • ValueError –

    A bound pair does not have two numbers, or the marker is unknown.

  • TypeError –

    A shape is not one of the Canvas shape classes.

Attributes:

Examples:

canvas = Canvas((0, 10), (0, 10), marker='block', width=10, height=5)
canvas.add_shape(CanvasRectangle(0, 0, 10, 10, 'red'))
assert '█' in canvas.render(format='text')
canvas.clear_shapes()
assert '█' not in canvas.render(format='text')

Create a Canvas.

Parameters:

  • x_bounds (Sequence[float | Value[float]] | None, default: None ) –

    Sequence[float | Value[float]] | None. Defaults to None.

  • y_bounds (Sequence[float | Value[float]] | None, default: None ) –

    Sequence[float | Value[float]] | None. Defaults to None.

  • marker (str | Value[str] | None, default: None ) –

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

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

    ColorValue | None. Defaults to None.

  • shapes (Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None, default: None ) –

    Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None. Defaults to None.

  • block (Block | None, default: None ) –

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

  • copy –

    Copy the cells, geometry and children into a new, independent buffer.

  • __call__ –

    Return a lazy render of the buffer.

  • render –

    Compose the visible children and serialize the buffer.

  • add_shape –

    Draw shape after the shapes already on the canvas.

  • extend_shapes –

    Draw every shape of shapes after the shapes already on the canvas.

  • clear_shapes –

    Remove every shape.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    x_bounds: Sequence[float | Value[float]] | None = None,
    y_bounds: Sequence[float | Value[float]] | None = None,
    *,
    marker: str | Value[str] | None = None,
    background_color: ColorValue | None = None,
    shapes: Iterable[
        CanvasLine
        | CanvasRectangle
        | CanvasCircle
        | CanvasPoints
        | CanvasMap
        | CanvasLabel
        | CanvasLayer
        | CanvasMarker
    ]
    | None = None,
    block: Block | None = None,
    width: int | None = None,
    height: int | None = None,
    x: int = 0,
    y: int = 0,
) -> None:
    """
    Create a Canvas.

    Args:
        x_bounds: ``Sequence[float | Value[float]] | None``. Defaults to ``None``.
        y_bounds: ``Sequence[float | Value[float]] | None``. Defaults to ``None``.
        marker: ``str | Value[str] | None``. Defaults to ``None``.
        background_color: ``ColorValue | None``. Defaults to ``None``.
        shapes: ``Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints |
            CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None``. Defaults to
            ``None``.
        block: ``Block | 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.

x_bounds instance-attribute

x_bounds: tuple[float | Value[float], float | Value[float]]

The lower and upper horizontal coordinates visible on the canvas.

y_bounds instance-attribute

y_bounds: tuple[float | Value[float], float | Value[float]]

The lower and upper vertical coordinates visible on the canvas.

marker instance-attribute

marker: str | Value[str]

The default cell marker used to draw shapes.

background_color instance-attribute

background_color: Color | Value[Color] | None

The color filling the canvas behind its shapes.

shapes instance-attribute

shapes: list[CanvasShape]

The shapes and labels drawn in sequence order.

block instance-attribute

block: Block | None

The optional border, titles and padding around the content.

__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 == ()
        ```
    """

copy

copy() -> Buffer

Copy the cells, geometry and children into a new, independent buffer.

Hooks and runtime state are not copied.

Examples:

original = Buffer.with_text('a')
duplicate = original.copy()
duplicate.write('b')
assert original.text == 'a'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def copy(self) -> Buffer:
    """
    Copy the cells, geometry and children into a new, independent buffer.

    Hooks and runtime state are not copied.

    Examples:
        ```python
        original = Buffer.with_text('a')
        duplicate = original.copy()
        duplicate.write('b')
        assert original.text == 'a'
        ```
    """

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

add_shape

add_shape(shape: CanvasShape) -> None

Draw shape after the shapes already on the canvas.

Examples:

canvas = Canvas((0, 10), (0, 10), width=10, height=5)
canvas.add_shape(CanvasCircle(5, 5, 2))
assert len(canvas.shapes) == 1
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def add_shape(self, shape: CanvasShape) -> None:
    """
    Draw ``shape`` after the shapes already on the canvas.

    Examples:
        ```python
        canvas = Canvas((0, 10), (0, 10), width=10, height=5)
        canvas.add_shape(CanvasCircle(5, 5, 2))
        assert len(canvas.shapes) == 1
        ```
    """

extend_shapes

extend_shapes(shapes: Iterable[CanvasShape]) -> None

Draw every shape of shapes after the shapes already on the canvas.

Examples:

canvas = Canvas((0, 10), (0, 10), width=10, height=5)
canvas.extend_shapes([CanvasCircle(5, 5, 2), CanvasLabel(0, 0, 'x')])
assert len(canvas.shapes) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def extend_shapes(self, shapes: Iterable[CanvasShape]) -> None:
    """
    Draw every shape of ``shapes`` after the shapes already on the canvas.

    Examples:
        ```python
        canvas = Canvas((0, 10), (0, 10), width=10, height=5)
        canvas.extend_shapes([CanvasCircle(5, 5, 2), CanvasLabel(0, 0, 'x')])
        assert len(canvas.shapes) == 2
        ```
    """

clear_shapes

clear_shapes() -> None

Remove every shape.

Examples:

canvas = Canvas((0, 10), (0, 10), shapes=[CanvasCircle(5, 5, 2)], width=10, height=5)
canvas.clear_shapes()
assert canvas.shapes == []
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def clear_shapes(self) -> None:
    """
    Remove every shape.

    Examples:
        ```python
        canvas = Canvas((0, 10), (0, 10), shapes=[CanvasCircle(5, 5, 2)], width=10, height=5)
        canvas.clear_shapes()
        assert canvas.shapes == []
        ```
    """

CanvasCircle

CanvasCircle(x: float | Value[float], y: float | Value[float], radius: float | Value[float], color: ColorValue | None = None)

A circle outline.

Parameters:

Attributes:

Examples:

circle = CanvasCircle(5, 5, 3, 'blue')
canvas = Canvas((0, 10), (0, 10), marker='block', shapes=[circle], width=20, height=10)
assert '█' in canvas.render(format='text')
circle.radius = 1

Create a CanvasCircle.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    x: float | Value[float],
    y: float | Value[float],
    radius: float | Value[float],
    color: ColorValue | None = None,
) -> None:
    """
    Create a CanvasCircle.

    Args:
        x: ``float | Value[float]``.
        y: ``float | Value[float]``.
        radius: ``float | Value[float]``.
        color: ``ColorValue | None``. Defaults to ``None``.
    """

x instance-attribute

The horizontal coordinate of the center.

y instance-attribute

The vertical coordinate of the center.

radius instance-attribute

radius: float | Value[float]

The radius in canvas coordinates.

color instance-attribute

color: Color | Value[Color]

The color of the circle outline.

CanvasLabel

CanvasLabel(x: float | Value[float], y: float | Value[float], text: str | Value[str], style: Style | DynamicStyle | None = None)

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

Parameters:

Attributes:

Examples:

label = CanvasLabel(1, 5, 'hello')
canvas = Canvas((0, 10), (0, 10), shapes=[label], width=10, height=5)
assert 'hello' in canvas.render(format='text')
label.text = 'bye'
assert 'bye' in canvas.render(format='text')

Create a CanvasLabel.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    x: float | Value[float],
    y: float | Value[float],
    text: str | Value[str],
    style: Style | DynamicStyle | None = None,
) -> None:
    """
    Create a CanvasLabel.

    Args:
        x: ``float | Value[float]``.
        y: ``float | Value[float]``.
        text: ``str | Value[str]``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
    """

x instance-attribute

The horizontal coordinate where the label starts.

y instance-attribute

The vertical coordinate where the label starts.

text instance-attribute

text: str | Value[str]

The styled text displayed at the given canvas position.

style instance-attribute

The default colors and text modifiers applied to the cells.

CanvasLine

CanvasLine(x1: float | Value[float], y1: float | Value[float], x2: float | Value[float], y2: float | Value[float], color: ColorValue | None = None, *, fill_to_y: float | Value[float] | None = None)

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

Every coordinate and the color accept a plain value or an expression, so a line can follow state. A shape can be edited after it is created; widgets that draw it repaint immediately.

Parameters:

  • x1 (float | Value[float]) –

    Horizontal position of the start.

  • y1 (float | Value[float]) –

    Vertical position of the start.

  • x2 (float | Value[float]) –

    Horizontal position of the end.

  • y2 (float | Value[float]) –

    Vertical position of the end.

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

    A color name, Color or expression. Defaults to the terminal default.

  • fill_to_y (float | Value[float] | None, default: None ) –

    When set, the area between the line and this vertical position is filled.

Attributes:

Examples:

line = CanvasLine(0, 0, 10, 10, 'green')
canvas = Canvas((0, 10), (0, 10), marker='block', shapes=[line], width=10, height=5)
assert '█' in canvas.render(format='text')
line.x2 = 0
assert line.x2 == 0.0

Create a CanvasLine.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    x1: float | Value[float],
    y1: float | Value[float],
    x2: float | Value[float],
    y2: float | Value[float],
    color: ColorValue | None = None,
    *,
    fill_to_y: float | Value[float] | None = None,
) -> None:
    """
    Create a CanvasLine.

    Args:
        x1: ``float | Value[float]``.
        y1: ``float | Value[float]``.
        x2: ``float | Value[float]``.
        y2: ``float | Value[float]``.
        color: ``ColorValue | None``. Defaults to ``None``.
        fill_to_y: ``float | Value[float] | None``. Defaults to ``None``.
    """

x1 instance-attribute

x1: float | Value[float]

The horizontal coordinate of the starting point.

y1 instance-attribute

y1: float | Value[float]

The vertical coordinate of the starting point.

x2 instance-attribute

x2: float | Value[float]

The horizontal coordinate of the ending point.

y2 instance-attribute

y2: float | Value[float]

The vertical coordinate of the ending point.

color instance-attribute

color: Color | Value[Color]

The color of the line.

fill_to_y instance-attribute

fill_to_y: float | Value[float] | None

The vertical coordinate to fill toward, or None to draw only the line.

CanvasMap

CanvasMap(resolution: Literal['low', 'high'] | str | Value[str] | None = None, color: ColorValue | None = None)

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

Parameters:

  • resolution (Literal['low', 'high'] | str | Value[str] | None, default: None ) –

    The detail level of the world map: low or high.

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

    A color name, Color or expression.

Raises:

  • ValueError –

    The resolution is not 'low' or 'high'.

Attributes:

Examples:

world = CanvasMap('low', 'white')
canvas = Canvas((-180, 180), (-90, 90), shapes=[world], width=40, height=12)
assert canvas.render(format='text').strip()

Create a CanvasMap.

Parameters:

  • resolution (Literal['low', 'high'] | str | Value[str] | None, default: None ) –

    Literal['low', 'high'] | str | Value[str] | None. Defaults to None.

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

    ColorValue | None. Defaults to None.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    resolution: Literal['low', 'high'] | str | Value[str] | None = None,
    color: ColorValue | None = None,
) -> None:
    """
    Create a CanvasMap.

    Args:
        resolution: ``Literal['low', 'high'] | str | Value[str] | None``. Defaults to
            ``None``.
        color: ``ColorValue | None``. Defaults to ``None``.
    """

resolution instance-attribute

resolution: str | Value[str]

The detail level of the world map: low or high.

color instance-attribute

color: Color | Value[Color]

The color of the map outline.

CanvasPoints

CanvasPoints(coordinates: Iterable[tuple[float, float]], color: ColorValue | None = None)

A set of single points.

Parameters:

  • coordinates (Iterable[tuple[float, float]]) –

    The horizontal and vertical coordinate pairs to draw.

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

    A color name, Color or expression.

Raises:

Attributes:

Examples:

points = CanvasPoints([(1, 1), (5, 5)], 'yellow')
canvas = Canvas((0, 10), (0, 10), marker='block', shapes=[points], width=10, height=5)
points.coordinates = [(1, 1), (9, 9)]
assert len(points) == 2 and '█' in canvas.render(format='text')

Create a CanvasPoints.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self, coordinates: Iterable[tuple[float, float]], color: ColorValue | None = None
) -> None:
    """
    Create a CanvasPoints.

    Args:
        coordinates: ``Iterable[tuple[float, float]]``.
        color: ``ColorValue | None``. Defaults to ``None``.
    """

coordinates instance-attribute

coordinates: list[tuple[float, float]]

The horizontal and vertical coordinate pairs to draw.

color instance-attribute

color: Color | Value[Color]

The color of the points.

CanvasRectangle

CanvasRectangle(x: float | Value[float], y: float | Value[float], width: float | Value[float], height: float | Value[float], color: ColorValue | None = None)

An axis-aligned rectangle outline.

Parameters:

Attributes:

Examples:

shape = CanvasRectangle(0, 0, 10, 10, 'red')
canvas = Canvas((0, 10), (0, 10), marker='block', shapes=[shape], width=10, height=5)
assert '█' in canvas.render(format='text')

Create a CanvasRectangle.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    x: float | Value[float],
    y: float | Value[float],
    width: float | Value[float],
    height: float | Value[float],
    color: ColorValue | None = None,
) -> None:
    """
    Create a CanvasRectangle.

    Args:
        x: ``float | Value[float]``.
        y: ``float | Value[float]``.
        width: ``float | Value[float]``.
        height: ``float | Value[float]``.
        color: ``ColorValue | None``. Defaults to ``None``.
    """

x instance-attribute

The horizontal coordinate of the left edge.

y instance-attribute

The vertical coordinate of the bottom edge.

width instance-attribute

width: float | Value[float]

The width in canvas coordinates.

height instance-attribute

height: float | Value[float]

The height in canvas coordinates.

color instance-attribute

color: Color | Value[Color]

The color of the rectangle outline.

Chart

Chart(datasets: Sequence[ChartDataset] | None = None, *, x_axis: ChartAxis | None = None, y_axis: ChartAxis | None = None, style: Style | DynamicStyle | None = None, legend_position: str | Expression[str] | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

Point series drawn against shared editable axes.

Attributes:

Examples:

chart = Chart([ChartDataset(data=[(0, 0), (1, 1)])], width=20, height=8)
assert chart.render(format='text')

Create a Chart.

Parameters:

  • datasets (Sequence[ChartDataset] | None, default: None ) –

    Sequence[ChartDataset] | None. Defaults to None.

  • x_axis (ChartAxis | None, default: None ) –

    ChartAxis | None. Defaults to None.

  • y_axis (ChartAxis | None, default: None ) –

    ChartAxis | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

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

  • block (Block | None, default: None ) –

    Block | None. Defaults to None.

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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.

  • copy –

    Copy the cells, geometry and children into a new, independent buffer.

  • __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,
    /,
    datasets: Sequence[ChartDataset] | None = None,
    *,
    x_axis: ChartAxis | None = None,
    y_axis: ChartAxis | None = None,
    style: Style | DynamicStyle | None = None,
    legend_position: str | Expression[str] | None = None,
    block: Block | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a Chart.

    Args:
        datasets: ``Sequence[ChartDataset] | None``. Defaults to ``None``.
        x_axis: ``ChartAxis | None``. Defaults to ``None``.
        y_axis: ``ChartAxis | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        legend_position: ``str | Expression[str] | None``. Defaults to ``None``.
        block: ``Block | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

datasets property writable

The datasets plotted against the chart axes.

style property writable

The default colors and text modifiers applied to the cells.

y_axis property writable

y_axis: ChartAxis

The vertical axis and its bounds, labels and title.

block property writable

block: Block | None

The optional border, titles and padding around the content.

legend_position property writable

legend_position: str | Expression[str] | None

The named position of the legend, or None to omit it.

x_axis property writable

x_axis: ChartAxis

The horizontal axis and its bounds, labels and title.

__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 == ()
        ```
    """

copy

copy() -> Buffer

Copy the cells, geometry and children into a new, independent buffer.

Hooks and runtime state are not copied.

Examples:

original = Buffer.with_text('a')
duplicate = original.copy()
duplicate.write('b')
assert original.text == 'a'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def copy(self) -> Buffer:
    """
    Copy the cells, geometry and children into a new, independent buffer.

    Hooks and runtime state are not copied.

    Examples:
        ```python
        original = Buffer.with_text('a')
        duplicate = original.copy()
        duplicate.write('b')
        assert original.text == 'a'
        ```
    """

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

ChartAxis

ChartAxis(*, title: str | Expression[str] | None = None, bounds: tuple[float | Expression[int | float], float | Expression[int | float]] | None = None, labels: Sequence[str | Expression[str]] | None = None, style: Style | DynamicStyle | None = None, labels_alignment: str | Expression[str] | None = None)

An editable axis with bounds, labels and a title.

Attributes:

Examples:

axis = ChartAxis(bounds=(0, 10), labels=['0', '10'])
axis.bounds = (0, 20)
assert axis.bounds == (0.0, 20.0)

Create a ChartAxis.

Parameters:

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

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

  • bounds (tuple[float | Expression[int | float], float | Expression[int | float]] | None, default: None ) –

    tuple[float | Expression[int | float], float | Expression[int | float]] | None. Defaults to None.

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

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

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

    Style | DynamicStyle | None. Defaults to None.

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

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

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    /,
    *,
    title: str | Expression[str] | None = None,
    bounds: tuple[float | Expression[int | float], float | Expression[int | float]]
    | None = None,
    labels: Sequence[str | Expression[str]] | None = None,
    style: Style | DynamicStyle | None = None,
    labels_alignment: str | Expression[str] | None = None,
) -> None:
    """
    Create a ChartAxis.

    Args:
        title: ``str | Expression[str] | None``. Defaults to ``None``.
        bounds: ``tuple[float | Expression[int | float], float | Expression[int | float]] | None``.
            Defaults to ``None``.
        labels: ``Sequence[str | Expression[str]] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        labels_alignment: ``str | Expression[str] | None``. Defaults to ``None``.
    """

labels property writable

labels: Sequence[str | Expression[str]]

The text labels spaced across the axis range.

style property writable

The default colors and text modifiers applied to the cells.

labels_alignment property writable

labels_alignment: str | Expression[str]

The horizontal alignment used when drawing axis labels.

title property writable

title: str | Expression[str] | None

The optional text displayed as the axis title.

bounds property writable

The lower and upper coordinate values represented by the axis.

ChartDataset

ChartDataset(*, name: str | Expression[str] | None = None, data: Sequence[tuple[float, float]] | None = None, marker: str | Expression[str] | None = None, graph_type: str | Expression[str] | None = None, style: Style | DynamicStyle | None = None, fill_to_y: float | Expression[int | float] | None = None)

An editable series of points displayed by a chart.

Attributes:

Examples:

dataset = ChartDataset(data=[(0, 0), (1, 1)], graph_type='line')
dataset.data = [(0, 1), (1, 0)]
assert dataset.data[0] == (0.0, 1.0)

Create a ChartDataset.

Parameters:

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

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

  • data (Sequence[tuple[float, float]] | None, default: None ) –

    Sequence[tuple[float, float]] | None. Defaults to None.

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

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

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

  • fill_to_y (float | Expression[int | float] | None, default: None ) –

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

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    /,
    *,
    name: str | Expression[str] | None = None,
    data: Sequence[tuple[float, float]] | None = None,
    marker: str | Expression[str] | None = None,
    graph_type: str | Expression[str] | None = None,
    style: Style | DynamicStyle | None = None,
    fill_to_y: float | Expression[int | float] | None = None,
) -> None:
    """
    Create a ChartDataset.

    Args:
        name: ``str | Expression[str] | None``. Defaults to ``None``.
        data: ``Sequence[tuple[float, float]] | None``. Defaults to ``None``.
        marker: ``str | Expression[str] | None``. Defaults to ``None``.
        graph_type: ``str | Expression[str] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        fill_to_y: ``float | Expression[int | float] | None``. Defaults to ``None``.
    """

marker property writable

marker: str | Expression[str]

The named cell marker used to plot points.

style property writable

The default colors and text modifiers applied to the cells.

fill_to_y property writable

fill_to_y: float | Expression[int | float]

The vertical coordinate to which area plots are filled.

data property writable

The horizontal and vertical coordinate pairs to plot.

graph_type property writable

graph_type: str | Expression[str]

The way the points are drawn: scatter, line or area.

name property writable

name: str | Expression[str] | None

The optional dataset label displayed in the legend.

Gauge

Gauge(ratio: float | Expression[int | float] | None = None, *, label: TextContent | Expression[str] | None = None, style: Style | DynamicStyle | None = None, gauge_style: Style | DynamicStyle | None = None, use_unicode: bool | Expression[bool] | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

A filled progress bar that repaints when its ratio changes.

Attributes:

Examples:

gauge = Gauge(0.5, width=10, height=1)
gauge.ratio = 0.75
assert gauge.ratio == 0.75

Create a Gauge.

Parameters:

  • ratio (float | Expression[int | float] | None, default: None ) –

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

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

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

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

  • use_unicode (bool | Expression[bool] | None, default: None ) –

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

  • block (Block | None, default: None ) –

    Block | None. Defaults to None.

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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.

  • copy –

    Copy the cells, geometry and children into a new, independent buffer.

  • __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,
    /,
    ratio: float | Expression[int | float] | None = None,
    *,
    label: TextContent | Expression[str] | None = None,
    style: Style | DynamicStyle | None = None,
    gauge_style: Style | DynamicStyle | None = None,
    use_unicode: bool | Expression[bool] | None = None,
    block: Block | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a Gauge.

    Args:
        ratio: ``float | Expression[int | float] | None``. Defaults to ``None``.
        label: ``TextContent | Expression[str] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        gauge_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        use_unicode: ``bool | Expression[bool] | None``. Defaults to ``None``.
        block: ``Block | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

label property writable

label: TextContent | Expression[str] | None

The text displayed as the label, or None to omit it.

style property writable

The default colors and text modifiers applied to the cells.

use_unicode property writable

use_unicode: bool | Expression[bool]

Whether fractional cells are drawn with Unicode block symbols.

ratio property writable

ratio: float | Expression[int | float]

The filled fraction, from 0.0 (empty) to 1.0 (full).

block property writable

block: Block | None

The optional border, titles and padding around the content.

gauge_style property writable

gauge_style: Style | DynamicStyle

The colors and text modifiers applied to the filled portion.

__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 == ()
        ```
    """

copy

copy() -> Buffer

Copy the cells, geometry and children into a new, independent buffer.

Hooks and runtime state are not copied.

Examples:

original = Buffer.with_text('a')
duplicate = original.copy()
duplicate.write('b')
assert original.text == 'a'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def copy(self) -> Buffer:
    """
    Copy the cells, geometry and children into a new, independent buffer.

    Hooks and runtime state are not copied.

    Examples:
        ```python
        original = Buffer.with_text('a')
        duplicate = original.copy()
        duplicate.write('b')
        assert original.text == 'a'
        ```
    """

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

ItemList

ItemList(items: Sequence[ListItem | TextContent] | None = None, *, selected: int | Expression[int | float] | None = None, offset: int | Expression[int | float] | None = None, style: Style | DynamicStyle | None = None, highlight_style: Style | DynamicStyle | None = None, highlight_symbol: str | Expression[str] | None = None, repeat_highlight_symbol: bool | Expression[bool] | None = None, highlight_spacing: str | Expression[str] | None = None, direction: str | Expression[str] | None = None, scroll_padding: int | Expression[int | float] | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

Selectable styled items with editable selection and scrolling.

Attributes:

Examples:

items = ItemList(['one', 'two'], width=10, height=2)
items.select_first()
items.select_next()
assert items.selected == 1

Create a ItemList.

Parameters:

  • items (Sequence[ListItem | TextContent] | None, default: None ) –

    Sequence[ListItem | TextContent] | None. Defaults to None.

  • selected (int | Expression[int | float] | None, default: None ) –

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

  • offset (int | Expression[int | float] | None, default: None ) –

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

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

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

  • repeat_highlight_symbol (bool | Expression[bool] | None, default: None ) –

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

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

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

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

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

  • scroll_padding (int | Expression[int | float] | None, default: None ) –

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

  • block (Block | None, default: None ) –

    Block | None. Defaults to None.

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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,
    /,
    items: Sequence[ListItem | TextContent] | None = None,
    *,
    selected: int | Expression[int | float] | None = None,
    offset: int | Expression[int | float] | None = None,
    style: Style | DynamicStyle | None = None,
    highlight_style: Style | DynamicStyle | None = None,
    highlight_symbol: str | Expression[str] | None = None,
    repeat_highlight_symbol: bool | Expression[bool] | None = None,
    highlight_spacing: str | Expression[str] | None = None,
    direction: str | Expression[str] | None = None,
    scroll_padding: int | Expression[int | float] | None = None,
    block: Block | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a ItemList.

    Args:
        items: ``Sequence[ListItem | TextContent] | None``. Defaults to ``None``.
        selected: ``int | Expression[int | float] | None``. Defaults to ``None``.
        offset: ``int | Expression[int | float] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        highlight_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        highlight_symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        repeat_highlight_symbol: ``bool | Expression[bool] | None``. Defaults to ``None``.
        highlight_spacing: ``str | Expression[str] | None``. Defaults to ``None``.
        direction: ``str | Expression[str] | None``. Defaults to ``None``.
        scroll_padding: ``int | Expression[int | float] | None``. Defaults to ``None``.
        block: ``Block | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

scroll_padding property writable

scroll_padding: int | Expression[int | float]

The number of items kept visible above and below the selection while scrolling.

highlight_style property writable

highlight_style: Style | DynamicStyle

The colors and text modifiers applied to the selected item.

selected property writable

selected: int | Expression[int | float] | None

The zero-based selected item index, or None when nothing is selected.

style property writable

The default colors and text modifiers applied to the cells.

repeat_highlight_symbol property writable

repeat_highlight_symbol: bool | Expression[bool]

Whether the highlight symbol appears on every line of a selected multiline item.

highlight_spacing property writable

highlight_spacing: str | Expression[str]

When space is reserved for the highlight symbol: always, when_selected or never.

offset property writable

offset: int | Expression[int | float]

The zero-based index of the first item shown when scrolling.

highlight_symbol property writable

highlight_symbol: str | Expression[str]

The text displayed beside the selected item.

visible_range property

visible_range: tuple[int, int]

The first visible index and the exclusive end index from the most recent render, or None before rendering.

direction property writable

direction: str | Expression[str]

The order in which items fill the area: top_to_bottom or bottom_to_top.

items property writable

The styled items displayed in their list order.

block property writable

block: Block | None

The optional border, titles and padding around the content.

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

LineGauge

LineGauge(ratio: float | Expression[int | float] | None = None, *, label: TextContent | Expression[str] | None = None, line_set: str | Expression[str] | None = None, filled_symbol: str | Expression[str] | None = None, unfilled_symbol: str | Expression[str] | None = None, style: Style | DynamicStyle | None = None, filled_style: Style | DynamicStyle | None = None, unfilled_style: Style | DynamicStyle | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

A progress indicator drawn with line symbols.

Attributes:

Examples:

gauge = LineGauge(0.5, width=10, height=1)
gauge.ratio = 0.8
assert gauge.ratio == 0.8

Create a LineGauge.

Parameters:

  • ratio (float | Expression[int | float] | None, default: None ) –

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

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

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

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

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

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

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

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

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

  • block (Block | None, default: None ) –

    Block | None. Defaults to None.

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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,
    /,
    ratio: float | Expression[int | float] | None = None,
    *,
    label: TextContent | Expression[str] | None = None,
    line_set: str | Expression[str] | None = None,
    filled_symbol: str | Expression[str] | None = None,
    unfilled_symbol: str | Expression[str] | None = None,
    style: Style | DynamicStyle | None = None,
    filled_style: Style | DynamicStyle | None = None,
    unfilled_style: Style | DynamicStyle | None = None,
    block: Block | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a LineGauge.

    Args:
        ratio: ``float | Expression[int | float] | None``. Defaults to ``None``.
        label: ``TextContent | Expression[str] | None``. Defaults to ``None``.
        line_set: ``str | Expression[str] | None``. Defaults to ``None``.
        filled_symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        unfilled_symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        filled_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        unfilled_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        block: ``Block | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

block property writable

block: Block | None

The optional border, titles and padding around the content.

unfilled_style property writable

unfilled_style: Style | DynamicStyle

The colors and text modifiers applied to the unfilled line.

ratio property writable

ratio: float | Expression[int | float]

The filled fraction, from 0.0 (empty) to 1.0 (full).

filled_symbol property writable

filled_symbol: str | Expression[str]

The symbol drawn for each filled cell.

filled_style property writable

filled_style: Style | DynamicStyle

The colors and text modifiers applied to the filled line.

style property writable

The default colors and text modifiers applied to the cells.

unfilled_symbol property writable

unfilled_symbol: str | Expression[str]

The symbol drawn for each unfilled cell.

label property writable

label: TextContent | Expression[str] | None

The text displayed as the label, or None to omit it.

line_set property writable

line_set: str | Expression[str]

The named line-symbol set used when explicit filled or unfilled symbols are omitted.

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

ListItem

ListItem(content: TextContent | Expression[str], *, style: Style | DynamicStyle | None = None)

Styled content displayed by an item list.

Attributes:

Examples:

item = ListItem('hello')
assert 'hello' in repr(item)

Create a ListItem.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    /,
    content: TextContent | Expression[str],
    *,
    style: Style | DynamicStyle | None = None,
) -> None:
    """
    Create a ListItem.

    Args:
        content: ``TextContent | Expression[str]``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
    """

height property writable

height: int | Expression[int | float]

The number of terminal rows occupied by this item.

style property writable

The default colors and text modifiers applied to the cells.

content property writable

The styled text displayed by this item.

Paragraph

Paragraph(text: TextContent | Expression[str] | None = None, *, style: Style | DynamicStyle | None = None, alignment: str | Expression[str] | None = None, should_wrap: bool | Expression[bool] | None = None, should_trim: bool | Expression[bool] | None = None, scroll: tuple[int | Expression[int | float], int | Expression[int | float]] | None = None, block: Block | None = None, width: int | None = None, height: int | None = None, x: int = 0, y: int = 0)

Bases: Widget

Styled text that can wrap, align and scroll.

Every setting is a property that accepts a plain value or an expression, so the paragraph repaints when a bound value changes.

Maps to ratatui::widgets::Paragraph.

Parameters:

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

    A str, a StyledText, a sequence of those, or an expression that produces text.

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

    A Style or DynamicStyle for the whole paragraph.

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

    The horizontal alignment: left, center or right.

  • should_wrap (bool | Expression[bool] | None, default: None ) –

    Whether long rows wrap at the widget's width.

  • should_trim (bool | Expression[bool] | None, default: None ) –

    Whether wrapped rows lose their leading whitespace.

  • scroll (tuple[int | Expression[int | float], int | Expression[int | float]] | None, default: None ) –

    A (row, column) pair of the first row and column shown.

  • block (Block | None, default: None ) –

    A Block framing the paragraph. The paragraph follows later edits of the block.

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

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

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

Attributes:

Examples:

paragraph = Paragraph('hello brave new world', width=10, height=3, should_wrap=True)
assert paragraph.render(format='text').split('\n') == ['hello', 'brave new', 'world']
paragraph.alignment = 'right'
assert paragraph.render(format='text').split('\n')[0] == '     hello'
assert paragraph.line_count() == 3

Create a Paragraph.

Parameters:

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

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

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

    Style | DynamicStyle | None. Defaults to None.

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

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

  • should_wrap (bool | Expression[bool] | None, default: None ) –

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

  • should_trim (bool | Expression[bool] | None, default: None ) –

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

  • scroll (tuple[int | Expression[int | float], int | Expression[int | float]] | None, default: None ) –

    tuple[int | Expression[int | float], int | Expression[int | float]] | None. Defaults to None.

  • block (Block | None, default: None ) –

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

  • line_count –

    How many rows the text takes when drawn width columns wide.

  • line_width –

    The width in columns of the widest row.

  • copy –

    A new paragraph with the same settings. A shared Block stays shared.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    text: TextContent | Expression[str] | None = None,
    *,
    style: Style | DynamicStyle | None = None,
    alignment: str | Expression[str] | None = None,
    should_wrap: bool | Expression[bool] | None = None,
    should_trim: bool | Expression[bool] | None = None,
    scroll: tuple[int | Expression[int | float], int | Expression[int | float]]
    | None = None,
    block: Block | None = None,
    width: int | None = None,
    height: int | None = None,
    x: int = 0,
    y: int = 0,
) -> None:
    """
    Create a Paragraph.

    Args:
        text: ``TextContent | Expression[str] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        alignment: ``str | Expression[str] | None``. Defaults to ``None``.
        should_wrap: ``bool | Expression[bool] | None``. Defaults to ``None``.
        should_trim: ``bool | Expression[bool] | None``. Defaults to ``None``.
        scroll: ``tuple[int | Expression[int | float], int | Expression[int | float]] | None``. Defaults to
            ``None``.
        block: ``Block | 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.

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.

text property writable

The text as it was set, which can be styled or an expression.

style property writable

The default colors and text modifiers applied to the cells.

alignment property writable

alignment: str | Expression[str]

The horizontal alignment: left, center or right.

should_wrap property writable

should_wrap: bool | Expression[bool]

Whether lines that exceed the available width continue on following rows.

should_trim property writable

should_trim: bool | Expression[bool]

Whether leading whitespace is removed from wrapped lines.

scroll_row property writable

scroll_row: int | Expression[int | float]

The first row shown, counted in displayed rows.

scroll_column property writable

scroll_column: int | Expression[int | float]

The horizontal scroll offset, in terminal cells.

block property writable

block: Block | None

The optional border, titles and padding around the content.

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

line_count

line_count(width: int | None = None) -> int

How many rows the text takes when drawn width columns wide.

Examples:

assert Paragraph('one two', should_wrap=True).line_count(4) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def line_count(self, width: int | None = None) -> int:
    """
    How many rows the text takes when drawn ``width`` columns wide.

    Examples:
        ```python
        assert Paragraph('one two', should_wrap=True).line_count(4) == 2
        ```
    """

line_width

line_width() -> int

The width in columns of the widest row.

Examples:

assert Paragraph('hello').line_width() == 5
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def line_width(self) -> int:
    """
    The width in columns of the widest row.

    Examples:
        ```python
        assert Paragraph('hello').line_width() == 5
        ```
    """

copy

copy() -> Paragraph

A new paragraph with the same settings. A shared Block stays shared.

Examples:

original = Paragraph('a')
clone = original.copy()
clone.text = 'b'
assert original.text == 'a'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def copy(self) -> Paragraph:
    """
    A new paragraph with the same settings. A shared ``Block`` stays shared.

    Examples:
        ```python
        original = Paragraph('a')
        clone = original.copy()
        clone.text = 'b'
        assert original.text == 'a'
        ```
    """

Scrollbar

Scrollbar(content_length: int | Expression[int | float] | None = None, position: int | Expression[int | float] | None = None, *, orientation: str | Expression[str] | None = None, viewport_content_length: int | Expression[int | float] | None = None, symbols: str | Sequence[str] | None = None, thumb_symbol: str | Expression[str] | None = None, track_symbol: str | Expression[str] | None = None, begin_symbol: str | Expression[str] | None = None, end_symbol: str | Expression[str] | None = None, has_track: bool | Expression[bool] = True, has_begin: bool | Expression[bool] = True, has_end: bool | Expression[bool] = True, style: Style | DynamicStyle | None = None, thumb_style: Style | DynamicStyle | None = None, track_style: Style | DynamicStyle | None = None, begin_style: Style | DynamicStyle | None = None, end_style: Style | DynamicStyle | None = None, is_transparent: bool | Expression[bool] | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

A scrollbar showing position within content.

Attributes:

Examples:

scrollbar = Scrollbar(10, 0, viewport_content_length=3, width=1, height=5)
scrollbar.next()
assert scrollbar.content_position == 1

Create a Scrollbar.

Parameters:

  • content_length (int | Expression[int | float] | None, default: None ) –

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

  • position (int | Expression[int | float] | None, default: None ) –

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

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

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

  • viewport_content_length (int | Expression[int | float] | None, default: None ) –

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

  • symbols (str | Sequence[str] | None, default: None ) –

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

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

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

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

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

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

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

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

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

  • has_track (bool | Expression[bool], default: True ) –

    bool | Expression[bool]. Defaults to True.

  • has_begin (bool | Expression[bool], default: True ) –

    bool | Expression[bool]. Defaults to True.

  • has_end (bool | Expression[bool], default: True ) –

    bool | Expression[bool]. Defaults to True.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

  • is_transparent (bool | Expression[bool] | None, default: None ) –

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

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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,
    /,
    content_length: int | Expression[int | float] | None = None,
    position: int | Expression[int | float] | None = None,
    *,
    orientation: str | Expression[str] | None = None,
    viewport_content_length: int | Expression[int | float] | None = None,
    symbols: str | Sequence[str] | None = None,
    thumb_symbol: str | Expression[str] | None = None,
    track_symbol: str | Expression[str] | None = None,
    begin_symbol: str | Expression[str] | None = None,
    end_symbol: str | Expression[str] | None = None,
    has_track: bool | Expression[bool] = True,
    has_begin: bool | Expression[bool] = True,
    has_end: bool | Expression[bool] = True,
    style: Style | DynamicStyle | None = None,
    thumb_style: Style | DynamicStyle | None = None,
    track_style: Style | DynamicStyle | None = None,
    begin_style: Style | DynamicStyle | None = None,
    end_style: Style | DynamicStyle | None = None,
    is_transparent: bool | Expression[bool] | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a Scrollbar.

    Args:
        content_length: ``int | Expression[int | float] | None``. Defaults to ``None``.
        position: ``int | Expression[int | float] | None``. Defaults to ``None``.
        orientation: ``str | Expression[str] | None``. Defaults to ``None``.
        viewport_content_length: ``int | Expression[int | float] | None``. Defaults to ``None``.
        symbols: ``str | Sequence[str] | None``. Defaults to ``None``.
        thumb_symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        track_symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        begin_symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        end_symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        has_track: ``bool | Expression[bool]``. Defaults to ``True``.
        has_begin: ``bool | Expression[bool]``. Defaults to ``True``.
        has_end: ``bool | Expression[bool]``. Defaults to ``True``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        thumb_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        track_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        begin_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        end_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        is_transparent: ``bool | Expression[bool] | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

content_length property writable

content_length: int | Expression[int | float]

The total length of the scrollable content, in the same units as content_position.

is_transparent property writable

is_transparent: bool | Expression[bool]

Whether cells not drawn by the scrollbar let the content below show through.

end_style property writable

end_style: Style | DynamicStyle

The colors and text modifiers applied to the end symbol.

thumb_symbol property writable

thumb_symbol: str | Expression[str]

The symbol drawn for the movable scroll indicator.

track_style property writable

track_style: Style | DynamicStyle

The colors and text modifiers applied to the track.

end_symbol property writable

end_symbol: str | Expression[str]

The symbol drawn at the end of the track, or None to omit it.

thumb_style property writable

thumb_style: Style | DynamicStyle

The colors and text modifiers applied to the movable scroll indicator.

style property writable

The default colors and text modifiers applied to the cells.

orientation property writable

orientation: str | Expression[str]

The edge holding the scrollbar: vertical_left, vertical_right, horizontal_top or horizontal_bottom.

content_position property writable

content_position: int | Expression[int | float]

The current position within the scrollable content.

begin_style property writable

begin_style: Style | DynamicStyle

The colors and text modifiers applied to the beginning symbol.

viewport_content_length property writable

viewport_content_length: int | Expression[int | float]

The amount of content visible at once, or None to derive it from the area.

symbols property writable

symbols: str | Sequence[str]

The symbol preset name, or None when the symbols do not match a preset.

begin_symbol property writable

begin_symbol: str | Expression[str]

The symbol drawn at the beginning of the track, or None to omit it.

track_symbol property writable

track_symbol: str | Expression[str]

The symbol drawn behind the indicator, or None to omit the track.

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

Sparkline

Sparkline(values: Sequence[int | Expression[int | float] | SparklineBar | None] | None = None, *, maximum: int | Expression[int | float] | None = None, style: Style | DynamicStyle | None = None, absent_value_style: Style | DynamicStyle | None = None, absent_value_symbol: str | Expression[str] | None = None, direction: str | Expression[str] | None = None, bar_set: str | Expression[str] | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

A compact history of numeric samples.

Attributes:

Examples:

sparkline = Sparkline([1, 3, 2], width=3, height=1)
sparkline.append(4)
assert len(sparkline.values) == 4

Create a Sparkline.

Parameters:

  • values (Sequence[int | Expression[int | float] | SparklineBar | None] | None, default: None ) –

    Sequence[int | Expression[int | float] | SparklineBar | None] | None. Defaults to None.

  • maximum (int | Expression[int | float] | None, default: None ) –

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

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

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

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

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

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

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

  • block (Block | None, default: None ) –

    Block | None. Defaults to None.

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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,
    /,
    values: Sequence[int | Expression[int | float] | SparklineBar | None]
    | None = None,
    *,
    maximum: int | Expression[int | float] | None = None,
    style: Style | DynamicStyle | None = None,
    absent_value_style: Style | DynamicStyle | None = None,
    absent_value_symbol: str | Expression[str] | None = None,
    direction: str | Expression[str] | None = None,
    bar_set: str | Expression[str] | None = None,
    block: Block | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a Sparkline.

    Args:
        values: ``Sequence[int | Expression[int | float] | SparklineBar | None] | None``. Defaults
            to ``None``.
        maximum: ``int | Expression[int | float] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        absent_value_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        absent_value_symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        direction: ``str | Expression[str] | None``. Defaults to ``None``.
        bar_set: ``str | Expression[str] | None``. Defaults to ``None``.
        block: ``Block | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

values property writable

values: Sequence[int | Expression[int | float] | SparklineBar | None]

The sequence of values to draw; None entries represent missing samples.

bars property

The styled samples used to draw the sparkline.

maximum property writable

maximum: int | Expression[int | float] | None

The value represented by a full bar, or None to use the largest value.

bar_set property writable

bar_set: str | Expression[str]

The named set of symbols used to draw partial and full bars.

direction property writable

direction: str | Expression[str]

The drawing direction: left_to_right or right_to_left.

absent_value_style property writable

absent_value_style: Style | DynamicStyle

The colors and text modifiers used for missing samples.

style property writable

The default colors and text modifiers applied to the cells.

absent_value_symbol property writable

absent_value_symbol: str | Expression[str]

The symbol drawn where a sample is missing.

block property writable

block: Block | None

The optional border, titles and padding around the content.

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

SparklineBar

SparklineBar(value: int | Expression[int | float], style: Style | DynamicStyle | None = None)

A sample with an optional individual style.

Attributes:

Examples:

bar = SparklineBar(3)
assert bar.value == 3

Create a SparklineBar.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    /,
    value: int | Expression[int | float],
    style: Style | DynamicStyle | None = None,
) -> None:
    """
    Create a SparklineBar.

    Args:
        value: ``int | Expression[int | float]``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
    """

value property

value: int | Expression[int | float]

The nonnegative numeric value represented by the bar.

style property

The default colors and text modifiers applied to the cells.

Table

Table(rows: Sequence[TableRow | Sequence[TableCell | TextContent]] | None = None, *, header: TableRow | Sequence[TableCell | TextContent] | None = None, footer: TableRow | Sequence[TableCell | TextContent] | None = None, widths: Sequence[int | SizeRule | tuple[int, int]] | None = None, column_spacing: int | Expression[int | float] | None = None, flex: str | None = None, selected_row: int | Expression[int | float] | None = None, selected_column: int | Expression[int | float] | None = None, offset: int | Expression[int | float] | None = None, style: Style | DynamicStyle | None = None, row_highlight_style: Style | DynamicStyle | None = None, column_highlight_style: Style | DynamicStyle | None = None, cell_highlight_style: Style | DynamicStyle | None = None, highlight_symbol: str | Expression[str] | None = None, highlight_spacing: str | Expression[str] | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

A retained table with row, column and cell selection.

Attributes:

Examples:

table = Table([TableRow(['one', 'two'])], widths=[5, 5], width=12, height=2)
assert 'one' in table.render(format='text')
table.select_first()
assert table.selected_row == 0

Create a Table.

Parameters:

  • rows (Sequence[TableRow | Sequence[TableCell | TextContent]] | None, default: None ) –

    Sequence[TableRow | Sequence[TableCell | TextContent]] | None. Defaults to None.

  • header (TableRow | Sequence[TableCell | TextContent] | None, default: None ) –

    TableRow | Sequence[TableCell | TextContent] | None. Defaults to None.

  • footer (TableRow | Sequence[TableCell | TextContent] | None, default: None ) –

    TableRow | Sequence[TableCell | TextContent] | None. Defaults to None.

  • widths (Sequence[int | SizeRule | tuple[int, int]] | None, default: None ) –

    Sequence[int | SizeRule | tuple[int, int]] | None. Defaults to None.

  • column_spacing (int | Expression[int | float] | None, default: None ) –

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

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

    str | None. Defaults to None.

  • selected_row (int | Expression[int | float] | None, default: None ) –

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

  • selected_column (int | Expression[int | float] | None, default: None ) –

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

  • offset (int | Expression[int | float] | None, default: None ) –

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

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

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

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

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

  • block (Block | None, default: None ) –

    Block | None. Defaults to None.

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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,
    /,
    rows: Sequence[TableRow | Sequence[TableCell | TextContent]] | None = None,
    *,
    header: TableRow | Sequence[TableCell | TextContent] | None = None,
    footer: TableRow | Sequence[TableCell | TextContent] | None = None,
    widths: Sequence[int | SizeRule | tuple[int, int]] | None = None,
    column_spacing: int | Expression[int | float] | None = None,
    flex: str | None = None,
    selected_row: int | Expression[int | float] | None = None,
    selected_column: int | Expression[int | float] | None = None,
    offset: int | Expression[int | float] | None = None,
    style: Style | DynamicStyle | None = None,
    row_highlight_style: Style | DynamicStyle | None = None,
    column_highlight_style: Style | DynamicStyle | None = None,
    cell_highlight_style: Style | DynamicStyle | None = None,
    highlight_symbol: str | Expression[str] | None = None,
    highlight_spacing: str | Expression[str] | None = None,
    block: Block | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a Table.

    Args:
        rows: ``Sequence[TableRow | Sequence[TableCell | TextContent]] | None``. Defaults to
            ``None``.
        header: ``TableRow | Sequence[TableCell | TextContent] | None``. Defaults to
            ``None``.
        footer: ``TableRow | Sequence[TableCell | TextContent] | None``. Defaults to
            ``None``.
        widths: ``Sequence[int | SizeRule | tuple[int, int]] | None``. Defaults to ``None``.
        column_spacing: ``int | Expression[int | float] | None``. Defaults to ``None``.
        flex: ``str | None``. Defaults to ``None``.
        selected_row: ``int | Expression[int | float] | None``. Defaults to ``None``.
        selected_column: ``int | Expression[int | float] | None``. Defaults to ``None``.
        offset: ``int | Expression[int | float] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        row_highlight_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        column_highlight_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        cell_highlight_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        highlight_symbol: ``str | Expression[str] | None``. Defaults to ``None``.
        highlight_spacing: ``str | Expression[str] | None``. Defaults to ``None``.
        block: ``Block | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

flex property writable

flex: str

The layout policy that distributes unused horizontal space among columns.

widths property writable

widths: Sequence[int | SizeRule | tuple[int, int]]

The width constraints for columns, in cells or proportional size rules.

highlight_symbol property writable

highlight_symbol: str | Expression[str]

The text displayed beside the selected row.

block property writable

block: Block | None

The optional border, titles and padding around the content.

row_highlight_style property writable

row_highlight_style: Style | DynamicStyle

The colors and text modifiers applied to the selected row.

selected_cell property

selected_cell: tuple[int, int] | None

The zero-based row and column indexes of the selected cell, or None.

selected_row property writable

selected_row: int | Expression[int | float] | None

The zero-based selected row index, or None when no row is selected.

offset property writable

offset: int | Expression[int | float]

The zero-based index of the first data row shown when scrolling.

style property writable

The default colors and text modifiers applied to the cells.

column_highlight_style property writable

column_highlight_style: Style | DynamicStyle

The colors and text modifiers applied to the selected column.

selected_column property writable

selected_column: int | Expression[int | float] | None

The zero-based selected column index, or None when no column is selected.

visible_range property

visible_range: tuple[int, int]

The first visible data-row index and the exclusive end index from the most recent render, or None before rendering.

rows property writable

The data rows displayed between the header and footer.

cell_highlight_style property writable

cell_highlight_style: Style | DynamicStyle

The colors and text modifiers applied where the selected row and column intersect.

header property writable

header: TableRow | Sequence[TableCell | TextContent] | None

The optional row displayed above the scrolling data rows.

footer property writable

footer: TableRow | Sequence[TableCell | TextContent] | None

The optional row displayed below the scrolling data rows.

column_spacing property writable

column_spacing: int | Expression[int | float]

The number of empty cells between adjacent columns.

highlight_spacing property writable

highlight_spacing: str | Expression[str]

When space is reserved for the highlight symbol: always, when_selected or never.

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

TableCell

TableCell(content: TextContent | Expression[str], *, style: Style | DynamicStyle | None = None, column_span: int = 1)

Styled content displayed in a table cell.

Attributes:

Examples:

cell = TableCell('hello')
assert 'hello' in repr(cell)

Create a TableCell.

Parameters:

  • content (TextContent | Expression[str]) –

    TextContent | Expression[str].

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

    Style | DynamicStyle | None. Defaults to None.

  • column_span (int, default: 1 ) –

    int. Defaults to 1.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    /,
    content: TextContent | Expression[str],
    *,
    style: Style | DynamicStyle | None = None,
    column_span: int = 1,
) -> None:
    """
    Create a TableCell.

    Args:
        content: ``TextContent | Expression[str]``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        column_span: ``int``. Defaults to ``1``.
    """

column_span property

column_span: int

The number of adjacent table columns occupied by this cell.

content property

The styled text displayed by this item.

style property

The default colors and text modifiers applied to the cells.

TableRow

TableRow(cells: Sequence[TableCell | TextContent], *, height: int | Expression[int | float] = 1, top_margin: int | Expression[int | float] = 0, bottom_margin: int | Expression[int | float] = 0, style: Style | DynamicStyle | None = None)

A row of cells with height and spacing.

Attributes:

Examples:

row = TableRow(['one', 'two'])
assert len(row.cells) == 2

Create a TableRow.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    /,
    cells: Sequence[TableCell | TextContent],
    *,
    height: int | Expression[int | float] = 1,
    top_margin: int | Expression[int | float] = 0,
    bottom_margin: int | Expression[int | float] = 0,
    style: Style | DynamicStyle | None = None,
) -> None:
    """
    Create a TableRow.

    Args:
        cells: ``Sequence[TableCell | TextContent]``.
        height: ``int | Expression[int | float]``. Defaults to ``1``.
        top_margin: ``int | Expression[int | float]``. Defaults to ``0``.
        bottom_margin: ``int | Expression[int | float]``. Defaults to ``0``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
    """

style property

The default colors and text modifiers applied to the cells.

height property

height: int | Expression[int | float]

The height of the row content, in terminal cells.

bottom_margin property

bottom_margin: int | Expression[int | float]

The number of empty lines after this row.

top_margin property

top_margin: int | Expression[int | float]

The number of empty lines before this row.

cells property

The cells displayed from the first column to the last.

Tabs

Tabs(titles: Sequence[TextContent] | None = None, *, selected: int | Expression[int | float] | None = None, style: Style | DynamicStyle | None = None, highlight_style: Style | DynamicStyle | None = None, divider: str | Expression[str] | None = None, padding_left: int | Expression[int | float] | None = None, padding_right: int | Expression[int | float] | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)

Bases: Widget

Selectable titles with editable padding, divider and styles.

Attributes:

Examples:

tabs = Tabs(['one', 'two'], selected=0, width=20, height=1)
tabs.select_next()
assert tabs.selected == 1

Create a Tabs.

Parameters:

  • titles (Sequence[TextContent] | None, default: None ) –

    Sequence[TextContent] | None. Defaults to None.

  • selected (int | Expression[int | float] | None, default: None ) –

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

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

    Style | DynamicStyle | None. Defaults to None.

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

    Style | DynamicStyle | None. Defaults to None.

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

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

  • padding_left (int | Expression[int | float] | None, default: None ) –

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

  • padding_right (int | Expression[int | float] | None, default: None ) –

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

  • block (Block | None, default: None ) –

    Block | None. Defaults to None.

  • width (int | Expression[int | float] | None, default: None ) –

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

  • height (int | Expression[int | float] | None, default: None ) –

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

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

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

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

    int | Expression[int | float]. 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,
    /,
    titles: Sequence[TextContent] | None = None,
    *,
    selected: int | Expression[int | float] | None = None,
    style: Style | DynamicStyle | None = None,
    highlight_style: Style | DynamicStyle | None = None,
    divider: str | Expression[str] | None = None,
    padding_left: int | Expression[int | float] | None = None,
    padding_right: int | Expression[int | float] | None = None,
    block: Block | None = None,
    width: int | Expression[int | float] | None = None,
    height: int | Expression[int | float] | None = None,
    x: int | Expression[int | float] = 0,
    y: int | Expression[int | float] = 0,
) -> None:
    """
    Create a Tabs.

    Args:
        titles: ``Sequence[TextContent] | None``. Defaults to ``None``.
        selected: ``int | Expression[int | float] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        highlight_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
        divider: ``str | Expression[str] | None``. Defaults to ``None``.
        padding_left: ``int | Expression[int | float] | None``. Defaults to ``None``.
        padding_right: ``int | Expression[int | float] | None``. Defaults to ``None``.
        block: ``Block | None``. Defaults to ``None``.
        width: ``int | Expression[int | float] | None``. Defaults to ``None``.
        height: ``int | Expression[int | float] | None``. Defaults to ``None``.
        x: ``int | Expression[int | float]``. Defaults to ``0``.
        y: ``int | Expression[int | float]``. 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.

padding_right property writable

padding_right: int | Expression[int | float]

The number of empty cells after each tab title.

selected property writable

selected: int | Expression[int | float] | None

The zero-based selected tab index, or None when no tab is selected.

highlight_style property writable

highlight_style: Style | DynamicStyle

The colors and text modifiers applied to the selected item.

titles property writable

The tab titles displayed from left to right.

style property writable

The default colors and text modifiers applied to the cells.

block property writable

block: Block | None

The optional border, titles and padding around the content.

padding_left property writable

padding_left: int | Expression[int | float]

The number of empty cells before each tab title.

divider property writable

divider: str | Expression[str]

The text drawn between adjacent tab titles.

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

Widget

Widget(content: TextContent | None = None, *, width: int | None = None, height: int | None = None, x: int = 0, y: int = 0, style: Style | None = None, registry: Registry | None = None)

Bases: Buffer

A buffer painted from editable settings or bound expressions.

Examples:

assert issubclass(Widget, Buffer)

Create a Buffer.

Parameters:

  • content (TextContent | None, default: None ) –

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

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

    Style | None. Defaults to None.

  • registry (Registry | None, default: None ) –

    Registry | None. Defaults to None.

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.

  • copy –

    Copy the cells, geometry and children into a new, independent buffer.

  • __call__ –

    Return a lazy render of the buffer.

  • render –

    Compose the visible children and serialize the buffer.

Attributes:

  • width (int) –

    The width in cells. Assigning resizes the buffer.

  • height (int) –

    The height in cells. Assigning resizes the buffer.

  • x (int) –

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

  • y (int) –

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

  • position (Point) –

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

  • size (Size) –

    The Size of the buffer. Assigning resizes the buffer.

  • bounds (Rectangle) –

    The buffer's rectangle in its parent.

  • layer (int) –

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

  • is_visible (bool) –

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

  • is_focusable (bool) –

    Whether the buffer can receive input focus.

  • content (Region) –

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

  • cells (Region) –

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

  • text (str) –

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

  • revision (int) –

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

  • children (tuple[Buffer, ...]) –

    The attached child buffers in attachment order.

  • registry (Registry) –

    The registry that decides which operations this buffer can apply.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    content: TextContent | None = None,
    *,
    width: int | None = None,
    height: int | None = None,
    x: int = 0,
    y: int = 0,
    style: Style | None = None,
    registry: Registry | None = None,
) -> None:
    """
    Create a Buffer.

    Args:
        content: ``TextContent | 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``.
        style: ``Style | None``. Defaults to ``None``.
        registry: ``Registry | None``. Defaults to ``None``.
    """

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.

__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 == ()
        ```
    """

copy

copy() -> Buffer

Copy the cells, geometry and children into a new, independent buffer.

Hooks and runtime state are not copied.

Examples:

original = Buffer.with_text('a')
duplicate = original.copy()
duplicate.write('b')
assert original.text == 'a'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def copy(self) -> Buffer:
    """
    Copy the cells, geometry and children into a new, independent buffer.

    Hooks and runtime state are not copied.

    Examples:
        ```python
        original = Buffer.with_text('a')
        duplicate = original.copy()
        duplicate.write('b')
        assert original.text == 'a'
        ```
    """

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