Skip to content

xnano.buffers

xnano.buffers

xnano.buffers

Buffers: grids of cells that hold text and styles.

A Buffer is what a canvas draws; each Cell holds one symbol with its colors.

Classes:

  • Image –

    An image and how it is shown: what Canvas.write takes

  • Buffer –

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

  • Cell –

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

Attributes:

BufferSize module-attribute

BufferSize: Value[Size]

The dimensions of a buffer as a Size.

Image dataclass

Image(source: TerminalImage | PathLike[str] | str | bytes, *, x: Axis | None = None, y: Axis | None = None, width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, fit: ImageFit | None = None, resampling_filter: ResamplingFilter | None = None, background: ColorValue = (0, 0, 0), speed: float = 1.0, symbol: str | None = None)

An image and how it is shown: what Canvas.write takes to put a picture on the canvas.

Make one from the path of an image file, its bytes, or a TerminalImage. A file is read once, here, where you can see it; write never takes a path. The placement values are what write uses when it is not given its own. An image sized by a percentage (or not sized at all) is converted again whenever the canvas is resized, so it always fits; give it a number, or lock=True, and it keeps its size.

Attributes:

  • image (TerminalImage) –

    The picture.

  • x (Axis | None) –

    The column of the left edge, or None for the top-left corner.

  • y (Axis | None) –

    The row of the top edge, or None.

  • width (Axis | None) –

    The width: cells, a percentage, an expression, or None for the picture's own.

  • height (Axis | None) –

    The height, in the same forms.

  • layer (int) –

    Content with a higher layer is drawn over content with a lower one.

  • lock (bool) –

    Whether the image keeps the size it was shown at when the canvas is resized.

  • fit (ImageFit | None) –

    How the picture sits in a box of width by height: 'contain' (the default), 'cover', 'stretch', 'crop' or 'smart'.

  • resampling_filter (ResamplingFilter | None) –

    How pixels are blended when it is resized. By default a small picture that is enlarged keeps hard pixel edges ('nearest') and any other is smoothed ('lanczos3').

  • background (tuple[int, int, int]) –

    The color behind transparent pixels and padding.

  • symbol (str | None) –

    The name the image is registered under in symbols, or None.

Examples:

import xnano
from xnano.image import TerminalImage

picture = xnano.Image(TerminalImage.from_rgba(2, 2, bytes([255, 0, 0, 255]) * 4), width=8)
with xnano.new(width=20, height=6) as canvas:
    canvas.write(picture, x='center')
# xnano.Image('photo.png', width='100%') loads a file, and refits when the window resizes.

Load an image and set how it is shown.

Parameters:

  • source (TerminalImage | PathLike[str] | str | bytes) –

    The path of an image file (PNG, JPEG, GIF, WebP or XNI), the bytes of one, or an image. An animated file plays on the canvas's clock.

  • x (Axis | None, default: None ) –

    The column of the left edge: cells, a percentage, a word such as 'center', an expression or a range. See Axis.

  • y (Axis | None, default: None ) –

    The row of the top edge, in the same forms.

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

    The width, in the same forms; the picture's own when None.

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

    The height, in the same forms.

  • layer (int, default: 0 ) –

    Content with a higher layer is drawn over content with a lower one.

  • lock (bool, default: False ) –

    Keep the size the image has when it is added, whatever the canvas does.

  • fit (ImageFit | None, default: None ) –

    How the picture sits in a box of width by height.

  • resampling_filter (ResamplingFilter | None, default: None ) –

    How pixels are blended when it is resized.

  • background (ColorValue, default: (0, 0, 0) ) –

    The color behind transparent pixels and padding, as a color name, a hex string, an (r, g, b) tuple or a Color.

  • speed (float, default: 1.0 ) –

    How fast an animated image plays: 2.0 is twice as fast.

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

    A name to register the image under in symbols.

Raises:

  • ImportError –

    xnano-image is not installed. Install it with pip install "xnano[image]".

  • TypeError –

    source is not a path, bytes or an image.

  • FileNotFoundError –

    source is a path with no file at it.

  • ValueError –

    symbol cannot be a symbol name, or another kind of value already has it.

Source code in xnano/_media.py
def __init__(
    self,
    source: TerminalImage | os.PathLike[str] | str | bytes,
    *,
    x: Axis | None = None,
    y: Axis | None = None,
    width: Axis | None = None,
    height: Axis | None = None,
    layer: int = 0,
    lock: bool = False,
    fit: ImageFit | None = None,
    resampling_filter: ResamplingFilter | None = None,
    background: ColorValue = (0, 0, 0),
    speed: float = 1.0,
    symbol: str | None = None,
) -> None:
    """
    Load an image and set how it is shown.

    Args:
        source: The path of an image file (PNG, JPEG, GIF, WebP or XNI), the bytes of one,
            or an image. An animated file plays on the canvas's clock.
        x: The column of the left edge: cells, a percentage, a word such as ``'center'``, an
            expression or a range. See [`Axis`][xnano.types.Axis].
        y: The row of the top edge, in the same forms.
        width: The width, in the same forms; the picture's own when ``None``.
        height: The height, in the same forms.
        layer: Content with a higher layer is drawn over content with a lower one.
        lock: Keep the size the image has when it is added, whatever the canvas does.
        fit: How the picture sits in a box of ``width`` by ``height``.
        resampling_filter: How pixels are blended when it is resized.
        background: The color behind transparent pixels and padding, as a color name, a
            hex string, an ``(r, g, b)`` tuple or a [`Color`][xnano_core.Color].
        speed: How fast an animated image plays: ``2.0`` is twice as fast.
        symbol: A name to register the image under in [`symbols`][xnano.symbols].

    Raises:
        ImportError: ``xnano-image`` is not installed. Install it with
            ``pip install "xnano[image]"``.
        TypeError: ``source`` is not a path, bytes or an image.
        FileNotFoundError: ``source`` is a path with no file at it.
        ValueError: ``symbol`` cannot be a symbol name, or another kind of value
            already has it.
    """
    if is_image(source):
        image = cast('TerminalImage', source)
    else:
        module = require('image', needed_for='xnano.Image')
        if isinstance(source, bytes):
            image = module.TerminalImage.from_bytes(source)
        elif isinstance(source, (str, os.PathLike)):
            path = pathlib.Path(source)
            if not path.is_file():
                raise FileNotFoundError(
                    f'Image could not load {str(path)!r}, because no image file exists '
                    f'there. Check the path, or pass the bytes of the image.'
                )
            image = module.TerminalImage.open(path)
        else:
            raise TypeError(
                f'Image needs the path of an image file, the bytes of an image or an '
                f'image, but got {type(source).__name__}. Pass Image("picture.png").'
            )
    if speed != 1.0:
        image = image.with_speed(speed)
    for name, value in (
        ('image', image),
        ('x', x),
        ('y', y),
        ('width', width),
        ('height', height),
        ('layer', layer),
        ('lock', lock),
        ('fit', fit),
        ('resampling_filter', resampling_filter),
        ('background', to_rgb(background)),
        ('symbol', symbol),
    ):
        object.__setattr__(self, name, value)
    if symbol is not None:
        symbols.register(symbol, self)

Buffer

Buffer(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: Surface

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

A buffer owns its cells, its geometry, its hook registrations and its place in a tree: it has at most one parent and is mounted on at most one runtime. Direct writes and operations share validation and revision tracking. Changing width or height keeps the cells that still fit and blanks new ones. Moving a mounted buffer redraws both its old and new area.

Parameters:

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

    Text to start with. Without width and height the buffer is sized to fit it.

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

    The width in cells.

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

    The height in cells.

  • x (int, default: 0 ) –

    The column of the buffer in its parent.

  • y (int, default: 0 ) –

    The row of the buffer in its parent.

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

    A style applied to the initial content.

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

    The operation registry; defaults to the shared default registry.

Attributes:

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

  • width (int) –

    The width in cells. Assigning resizes the buffer.

  • height (int) –

    The height in cells. Assigning resizes 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.

Examples:

card = Buffer(width=12, height=3, x=2, y=1)
card.update(Border('rounded'))
card.write('hello', x=1, y=1)
print(card.render(format='text'))

sized = Buffer('two\nlines')
assert (sized.width, sized.height) == (5, 2)

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.

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

  • supports –

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

  • __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: 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``.
    """

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.

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.

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

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

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

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

Cell

Cell(symbol: str = ' ', *, style: Style | None = None, foreground: ColorValue | None = None, background: ColorValue | None = None, modifiers: Sequence[Modifier] = (), is_transparent: bool = False)

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

Reading buffer[column, row] returns a Cell snapshot; changing it does not change the buffer until it is written back with buffer[column, row] = cell. A transparent cell lets the content below it show through when buffers are composited with the 'transparent' paste mode.

Maps to ratatui::buffer::Cell.

Parameters:

  • symbol (str, default: ' ' ) –

    A single grapheme cluster. Defaults to one space.

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

    A complete style for the cell. Combined with the color and modifier arguments below, which take precedence.

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

    The foreground color.

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

    The background color.

  • modifiers (Sequence[Modifier], default: () ) –

    Text modifiers such as 'bold' or 'underline'.

  • is_transparent (bool, default: False ) –

    Whether the cell lets lower layers show through.

Attributes:

Raises:

  • ValueError –

    symbol is not exactly one grapheme.

Examples:

cell = Cell('x', foreground='red', modifiers=['bold'])
assert cell.symbol == 'x'
assert cell.foreground == Color('red')

buffer = Buffer(width=3, height=1)
buffer[1, 0] = cell
assert buffer[1, 0].symbol == 'x'

Create a Cell.

Parameters:

  • symbol (str, default: ' ' ) –

    str. Defaults to ' '.

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

    Style | None. Defaults to None.

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

    ColorValue | None. Defaults to None.

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

    ColorValue | None. Defaults to None.

  • modifiers (Sequence[Modifier], default: () ) –

    Sequence[Modifier]. Defaults to ().

  • is_transparent (bool, default: False ) –

    bool. Defaults to False.

Methods:

  • copy –

    Return an independent copy of the cell.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    symbol: str = ' ',
    *,
    style: Style | None = None,
    foreground: ColorValue | None = None,
    background: ColorValue | None = None,
    modifiers: Sequence[Modifier] = (),
    is_transparent: bool = False,
) -> None:
    """
    Create a Cell.

    Args:
        symbol: ``str``. Defaults to ``' '``.
        style: ``Style | None``. Defaults to ``None``.
        foreground: ``ColorValue | None``. Defaults to ``None``.
        background: ``ColorValue | None``. Defaults to ``None``.
        modifiers: ``Sequence[Modifier]``. Defaults to ``()``.
        is_transparent: ``bool``. Defaults to ``False``.
    """

symbol instance-attribute

symbol: str

The grapheme drawn in the cell.

style instance-attribute

style: Style

The cell's style.

is_transparent instance-attribute

is_transparent: bool

Whether the cell lets lower layers show through.

foreground property

foreground: Color

The foreground color of the cell.

background property

background: Color

The background color of the cell.

copy

copy() -> Cell

Return an independent copy of the cell.

Examples:

original = Cell('a')
duplicate = original.copy()
duplicate.symbol = 'b'
assert original.symbol == 'a'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def copy(self) -> Cell:
    """
    Return an independent copy of the cell.

    Examples:
        ```python
        original = Cell('a')
        duplicate = original.copy()
        duplicate.symbol = 'b'
        assert original.symbol == 'a'
        ```
    """