Skip to content

xnano_core

xnano_core

xnano_core

The terminal engine behind xnano: buffers, widgets, operations, effects, the expression language, events, state and the runtime.

Everything public is importable from here, for example from xnano_core import Buffer, Gauge, Effect, Width. Most programs use these through xnano, which re-exports the everyday ones.

Classes:

  • AnimateDrawing –

    Play a DrawingAnimation on a mounted buffer.

  • ApplyStatePatch –

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

  • ApplyStyle –

    Patch a Style onto every cell of the target.

  • Background –

    Set the background color of every cell of the target.

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

  • BlockTitle –

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

  • Border –

    Draw a border around the edge of the target.

  • Buffer –

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

  • BufferExpressionScope –

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

  • Calendar –

    A monthly calendar with editable dates and styles for events.

  • CancelEffect –

    Stop the running effect that was started with key.

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

  • CanvasLayer –

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

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

  • CanvasMarker –

    Switches the marker the shapes after it are drawn with.

  • CanvasPoints –

    A set of single points.

  • CanvasRectangle –

    An axis-aligned rectangle outline.

  • Cell –

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

  • CellAnimationInfo –

    The header of a packed cell animation.

  • CellFilter –

    A composable selection of cells affected by an animation.

  • CellGridError –

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

  • CellGridInfo –

    The header of a packed cell grid.

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

  • Clear –

    Blank cells that hide whatever is behind them.

  • Clock –

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

  • Color –

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

  • Conditional –

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

  • Cursor –

    The one cursor a terminal has.

  • Customization –

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

  • CustomWidget –

    A widget drawn by a Python function.

  • DecodeLimits –

    Upper bounds checked before packed cell data is accepted.

  • Device –

    The display and terminal a runtime draws on.

  • Dissolve –

    Dissolve the glyphs of the target away cell by cell.

  • Draw –

    Draw a Drawing into the target.

  • Drawing –

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

  • DrawingAnimation –

    A sequence of timed drawings.

  • DrawingFrame –

    One frame of a DrawingAnimation.

  • DynamicStyle –

    A style whose colors may follow expressions.

  • Editor –

    Draw a TextEditor into a buffer.

  • Effect –

    A composable animation with editable and bindable settings.

  • EffectManager –

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

  • ErrorDetail –

    One labelled problem of an ErrorReport.

  • ErrorReport –

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

  • Event –

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

  • EventStream –

    The events a runtime reports, as an iterator.

  • Expression –

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

  • ExpressionScope –

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

  • Fade –

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

  • Fill –

    Fill every cell of the target with one cell.

  • FocusScope –

    A group of input targets, optionally modal.

  • Foreground –

    Set the foreground color of every cell of the target.

  • FrameMetrics –

    Timing of the frames a runtime has drawn.

  • FrameSnapshot –

    An immutable copy of a drawn frame.

  • Fuzz –

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

  • Gauge –

    A filled progress bar that repaints when its ratio changes.

  • Glitch –

    Randomly corrupt and displace glyphs of the target.

  • HitArea –

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

  • Hook –

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

  • InputOptions –

    The input modes a live terminal asks for.

  • InputRouter –

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

  • InputState –

    The keys and pointer position a runtime currently sees.

  • InvalidRegionError –

    A region no longer fits inside its resized buffer.

  • ItemList –

    Selectable styled items with editable selection and scrolling.

  • KeyBinding –

    A key and modifiers to match against key events.

  • KeyboardCapabilities –

    What the terminal's keyboard protocol can report.

  • KeyboardExpressionScope –

    The latest key event, as expressions.

  • KeyEvent –

    A key press, repeat or release.

  • Layout –

    Arrange attached children within the parent's content area.

  • LineGauge –

    A progress indicator drawn with line symbols.

  • ListItem –

    Styled content displayed by an item list.

  • Live –

    Operations that are applied again whenever something they show changes.

  • Margin –

    Horizontal and vertical inset distances.

  • MouseEvent –

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

  • MouseExpressionScope –

    The latest mouse button or motion report, as expressions.

  • Move –

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

  • NumericProperty –

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

  • NumericValue –

    A numeric expression that supports comparisons and arithmetic.

  • Offset –

    A displacement in terminal columns and rows.

  • Operation –

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

  • OperationChain –

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

  • Paragraph –

    Styled text that can wrap, align and scroll.

  • ParentExpressionScope –

    The geometry of the enclosing buffer, as expressions.

  • Paste –

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

  • Pixels –

    Draw ordered RGB pixels into the target.

  • PixelView –

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

  • Place –

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

  • Point –

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

  • Predicate –

    A condition that evaluates to True or False.

  • Property –

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

  • Raster –

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

  • Rectangle –

    A rectangle of cells with half-open bounds.

  • Region –

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

  • RenderError –

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

  • ReportedError –

    An error raised with an ErrorReport as its one argument.

  • Resize –

    Resize the target buffer to width by height cells.

  • RootExpressionScope –

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

  • RunningEffect –

    Playback controls and progress for a started animation.

  • Runtime –

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

  • RuntimeRequiredError –

    An operation needs a buffer mounted on an active runtime.

  • ScheduledCall –

    A callback scheduled on a clock with call_later or call_every.

  • Scrollbar –

    A scrollbar showing position within content.

  • ScrollExpressionScope –

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

  • SequenceOperation –

    Apply several operations in order as one operation.

  • SetState –

    Assign a state branch and publish one validated commit.

  • SetValue –

    Assign a value to a property.

  • SimulationClock –

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

  • Size –

    A width and a height, counted in cells.

  • SizeRule –

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

  • Sparkline –

    A compact history of numeric samples.

  • SparklineBar –

    A sample with an optional individual style.

  • StateReference –

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

  • StepResult –

    What one Runtime.step() did.

  • Style –

    A foreground color, a background color and text modifiers.

  • StyledText –

    Text made of differently styled spans.

  • Surface –

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

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

  • TerminalCapabilities –

    What a terminal can display.

  • TerminalOptions –

    How a live runtime takes over the terminal.

  • TerminalStateAccessError –

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

  • TerminalStateChange –

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

  • TerminalStateConflictError –

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

  • TerminalStateIssue –

    One problem found while validating a value against a schema.

  • TerminalStateObservation –

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

  • TerminalStatePatch –

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

  • TerminalStateSchema –

    A compiled schema that validates state values.

  • TerminalStateSelection –

    Values read from several paths at one consistent revision.

  • TerminalStateSnapshot –

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

  • TerminalStateStore –

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

  • TerminalStateSubscription –

    A registration that delivers state changes until it is cancelled.

  • TerminalStateTransaction –

    Staged edits that publish together or not at all.

  • TerminalStateValidationError –

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

  • TextEditor –

    An editable text buffer with a cursor and undo history.

  • TextLayout –

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

  • TextLine –

    One wrapped line of a TextLayout.

  • TextSpan –

    A run of text with one style.

  • Trigger –

    When something runs, and which events count.

  • UnsupportedOperationError –

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

  • Value –

    An expression that evaluates to a value.

  • Waker –

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

  • Widget –

    A buffer painted from editable settings or bound expressions.

  • Write –

    Write text into the target at a cell position.

  • WriteCellText –

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

  • CoreContext –

    A hook's view of the runtime: device, clock, input and focus.

  • EvaluationContext –

    What an expression or operation handler can see.

  • EventContext –

    A routed input event's view.

  • Extension –

    Something that adds operations to a registry.

  • FrameContext –

    A frame callback's view: every layout and drawing uses this frame's destination.

  • HookSignal –

    Control flow recognized only while the runtime executes a hook.

  • Invalidate –

    End the current hook and request a display frame.

  • Propagate –

    End the current hook and continue with the parent event target.

  • Registry –

    Operation handlers and extension installs for a buffer or runtime.

  • Rendering –

    A lazy static or live render of a buffer.

  • Skip –

    End the current hook and continue dispatch.

  • Stop –

    End the hook and request that the runtime stop.

  • UpdateContext –

    A simulation update's view.

Functions:

Attributes:

FPS module-attribute

The runtime's estimated frames per second.

Bounds module-attribute

Bounds: Value[Rectangle]

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

BufferRegion module-attribute

BufferRegion: Value[Rectangle]

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

BufferScope module-attribute

BufferScope: BufferExpressionScope

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

BufferSize module-attribute

BufferSize: Value[Size]

The dimensions of a buffer as a Size.

DeviceHeight module-attribute

DeviceHeight: NumericValue[int | float]

DeviceWidth module-attribute

DeviceWidth: NumericValue[int | float]

Focused module-attribute

Focused: Value[bool]

Whether the runtime has focus.

Frame module-attribute

The current runtime frame number.

Height module-attribute

Height: NumericValue[int | float]

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

IsVisible module-attribute

IsVisible: Property[bool]

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

KeyboardBinding module-attribute

KeyboardBinding: Value[str | None]

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

KeyboardKey module-attribute

KeyboardKey: Value[str | None]

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

KeyboardKind module-attribute

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

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

KeyboardScope module-attribute

KeyboardScope: KeyboardExpressionScope

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

Layer module-attribute

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

MouseButtonValue module-attribute

MouseButtonValue: Value[MouseButton | None]

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

MouseIsDown module-attribute

MouseIsDown: Predicate

Whether any mouse button is held.

MouseKind module-attribute

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

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

MousePosition module-attribute

MousePosition: Value[Point | None]

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

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

MouseScope module-attribute

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

ParentHeight module-attribute

ParentHeight: NumericValue[int]

The height of the parent buffer, in cells.

ParentScope module-attribute

ParentScope: ParentExpressionScope

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

ParentSize module-attribute

ParentSize: Value[Size]

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

Evaluating it raises TypeError for a buffer without a parent.

ParentWidth module-attribute

ParentWidth: NumericValue[int]

The width of the parent buffer, in cells.

PointerPosition module-attribute

PointerPosition: Value[Point | None]

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

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

Position module-attribute

Position: Value[Point]

The position of a buffer or region as a Point.

RootScope module-attribute

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

Running module-attribute

Running: Value[bool]

Whether the runtime is running.

ScreenBounds module-attribute

ScreenBounds: Value[Rectangle]

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

ScreenPosition module-attribute

ScreenPosition: Value[Point]

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

ScrollScope module-attribute

ScrollScope: ScrollExpressionScope

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

ScrollX module-attribute

ScrollX: NumericValue[int]

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

ScrollY module-attribute

ScrollY: NumericValue[int]

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

TimeDelta module-attribute

TimeDelta: NumericValue[int | float]

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

TimeDeltaMilliseconds module-attribute

TimeDeltaMilliseconds: NumericValue[int | float]

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

TimeElapsed module-attribute

TimeElapsed: NumericValue[int | float]

The elapsed runtime time, in seconds.

TimeElapsedMilliseconds module-attribute

TimeElapsedMilliseconds: NumericValue[int | float]

The elapsed runtime time, in milliseconds.

Width module-attribute

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

X module-attribute

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

Y module-attribute

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

is_optimized_build module-attribute

is_optimized_build: bool

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

CanvasShape module-attribute

CanvasShape: TypeAlias = 'CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker'

ColorName module-attribute

ColorName: TypeAlias = Literal['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'gray', 'grey', 'dark_gray', 'dark_grey', 'darkgray', 'darkgrey', 'light_black', 'light_red', 'bright_red', 'light_green', 'bright_green', 'light_yellow', 'bright_yellow', 'light_blue', 'bright_blue', 'light_magenta', 'bright_magenta', 'light_cyan', 'bright_cyan', 'white', 'reset']

A named ANSI terminal color.

gray and grey are the same color, and so are light_ and bright_. dark_gray is the dim gray. reset restores the terminal default.

ColorProfile module-attribute

ColorProfile: TypeAlias = Literal['no_terminal', 'no_color', 'ansi16', 'ansi256', 'truecolor']

ColorValue module-attribute

ColorValue: TypeAlias = Color | ColorName | str | tuple[int, int, int]

A color, an ANSI color name, a '#rrggbb' string, or a (red, green, blue) tuple.

A Tailwind name such as 'slate-400' is a TailwindColorBinding. It is not parsed by Color.

CursorShape module-attribute

CursorShape: TypeAlias = Literal['block', 'bar', 'underline']

EventKind module-attribute

EventKind: TypeAlias = Literal['key', 'mouse', 'paste', 'resize', 'focus_gained', 'focus_lost', 'tick', 'timer', 'frame', 'wake', 'exit_requested', 'custom']

GraphicsProtocol module-attribute

GraphicsProtocol: TypeAlias = Literal['half_blocks', 'sixel', 'kitty', 'iterm2']

HookDecorator module-attribute

HookDecorator: TypeAlias = 'Callable[[HookCallback], HookCallback]'

A decorator that registers a hook callback and returns it unchanged.

Interpolation module-attribute

Interpolation: TypeAlias = Literal['linear', 'back_in', 'back_out', 'back_in_out', 'bounce_in', 'bounce_out', 'bounce_in_out', 'circ_in', 'circ_out', 'circ_in_out', 'cubic_in', 'cubic_out', 'cubic_in_out', 'elastic_in', 'elastic_out', 'elastic_in_out', 'expo_in', 'expo_out', 'expo_in_out', 'quad_in', 'quad_out', 'quad_in_out', 'quart_in', 'quart_out', 'quart_in_out', 'quint_in', 'quint_out', 'quint_in_out', 'sine_in', 'sine_out', 'sine_in_out', 'smooth_step', 'spring', 'reverse', 'ease_in']

How an effect eases between its start and end; 'ease_in' is 'quad_in'.

KeyBindingText module-attribute

KeyBindingText: TypeAlias = 'KeyName | str'

A key optionally preceded by +-joined modifiers, such as q, ctrl+c or shift+tab.

KeyModifier module-attribute

KeyModifier: TypeAlias = Literal['control', 'shift', 'alt', 'super', 'meta', 'hyper']

KeyName module-attribute

KeyName: TypeAlias = Literal['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'enter', 'escape', 'backspace', 'tab', 'space', 'delete', 'insert', 'up', 'down', 'left', 'right', 'home', 'end', 'page_up', 'page_down', 'caps_lock', 'scroll_lock', 'num_lock', 'print_screen', 'pause', 'menu', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12']

A key name as events report it and bindings accept it, such as q, enter or page_up.

Modifier module-attribute

Modifier: TypeAlias = Literal['bold', 'dim', 'italic', 'underline', 'blink', 'reverse', 'hidden', 'crossed_out']

MouseEventKind module-attribute

MouseEventKind: TypeAlias = Literal['press', 'release', 'drag', 'move', 'scroll']

Orientation module-attribute

Orientation: TypeAlias = Literal['horizontal', 'vertical']

The direction something runs in.

PixelAnchor module-attribute

PixelAnchor: TypeAlias = Literal['top_left', 'center', 'bottom_right']

ScalarExpression module-attribute

ScalarExpression: TypeAlias = 'Expression[bool] | Expression[int | float] | Expression[str]'

Side module-attribute

Side: TypeAlias = Literal['left', 'right', 'top', 'bottom']

A side of a rectangle.

TailwindColorBinding module-attribute

TailwindColorBinding: TypeAlias = Literal['slate-50', 'slate-100', 'slate-200', 'slate-300', 'slate-400', 'slate-500', 'slate-600', 'slate-700', 'slate-800', 'slate-900', 'slate-950', 'gray-50', 'gray-100', 'gray-200', 'gray-300', 'gray-400', 'gray-500', 'gray-600', 'gray-700', 'gray-800', 'gray-900', 'gray-950', 'zinc-50', 'zinc-100', 'zinc-200', 'zinc-300', 'zinc-400', 'zinc-500', 'zinc-600', 'zinc-700', 'zinc-800', 'zinc-900', 'zinc-950', 'neutral-50', 'neutral-100', 'neutral-200', 'neutral-300', 'neutral-400', 'neutral-500', 'neutral-600', 'neutral-700', 'neutral-800', 'neutral-900', 'neutral-950', 'stone-50', 'stone-100', 'stone-200', 'stone-300', 'stone-400', 'stone-500', 'stone-600', 'stone-700', 'stone-800', 'stone-900', 'stone-950', 'red-50', 'red-100', 'red-200', 'red-300', 'red-400', 'red-500', 'red-600', 'red-700', 'red-800', 'red-900', 'red-950', 'orange-50', 'orange-100', 'orange-200', 'orange-300', 'orange-400', 'orange-500', 'orange-600', 'orange-700', 'orange-800', 'orange-900', 'orange-950', 'amber-50', 'amber-100', 'amber-200', 'amber-300', 'amber-400', 'amber-500', 'amber-600', 'amber-700', 'amber-800', 'amber-900', 'amber-950', 'yellow-50', 'yellow-100', 'yellow-200', 'yellow-300', 'yellow-400', 'yellow-500', 'yellow-600', 'yellow-700', 'yellow-800', 'yellow-900', 'yellow-950', 'lime-50', 'lime-100', 'lime-200', 'lime-300', 'lime-400', 'lime-500', 'lime-600', 'lime-700', 'lime-800', 'lime-900', 'lime-950', 'green-50', 'green-100', 'green-200', 'green-300', 'green-400', 'green-500', 'green-600', 'green-700', 'green-800', 'green-900', 'green-950', 'emerald-50', 'emerald-100', 'emerald-200', 'emerald-300', 'emerald-400', 'emerald-500', 'emerald-600', 'emerald-700', 'emerald-800', 'emerald-900', 'emerald-950', 'teal-50', 'teal-100', 'teal-200', 'teal-300', 'teal-400', 'teal-500', 'teal-600', 'teal-700', 'teal-800', 'teal-900', 'teal-950', 'cyan-50', 'cyan-100', 'cyan-200', 'cyan-300', 'cyan-400', 'cyan-500', 'cyan-600', 'cyan-700', 'cyan-800', 'cyan-900', 'cyan-950', 'sky-50', 'sky-100', 'sky-200', 'sky-300', 'sky-400', 'sky-500', 'sky-600', 'sky-700', 'sky-800', 'sky-900', 'sky-950', 'blue-50', 'blue-100', 'blue-200', 'blue-300', 'blue-400', 'blue-500', 'blue-600', 'blue-700', 'blue-800', 'blue-900', 'blue-950', 'indigo-50', 'indigo-100', 'indigo-200', 'indigo-300', 'indigo-400', 'indigo-500', 'indigo-600', 'indigo-700', 'indigo-800', 'indigo-900', 'indigo-950', 'violet-50', 'violet-100', 'violet-200', 'violet-300', 'violet-400', 'violet-500', 'violet-600', 'violet-700', 'violet-800', 'violet-900', 'violet-950', 'purple-50', 'purple-100', 'purple-200', 'purple-300', 'purple-400', 'purple-500', 'purple-600', 'purple-700', 'purple-800', 'purple-900', 'purple-950', 'fuchsia-50', 'fuchsia-100', 'fuchsia-200', 'fuchsia-300', 'fuchsia-400', 'fuchsia-500', 'fuchsia-600', 'fuchsia-700', 'fuchsia-800', 'fuchsia-900', 'fuchsia-950', 'pink-50', 'pink-100', 'pink-200', 'pink-300', 'pink-400', 'pink-500', 'pink-600', 'pink-700', 'pink-800', 'pink-900', 'pink-950', 'rose-50', 'rose-100', 'rose-200', 'rose-300', 'rose-400', 'rose-500', 'rose-600', 'rose-700', 'rose-800', 'rose-900', 'rose-950']

A Tailwind palette and shade, such as 'slate-400'.

Color does not parse these. Pass the palette and shade to Color.from_tailwind.

TailwindColorName module-attribute

TailwindColorName: TypeAlias = Literal['slate', 'gray', 'zinc', 'neutral', 'stone', 'red', 'orange', 'amber', 'yellow', 'lime', 'green', 'emerald', 'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose']

TailwindColorShade module-attribute

TailwindColorShade: TypeAlias = Literal[50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]

TextContent module-attribute

TextContent: TypeAlias = 'str | StyledText | Sequence[str | StyledText]'

Text accepted by writing operations and components.

TriggerKind module-attribute

TriggerKind: TypeAlias = Literal['immediate', 'frame', 'update', 'key', 'key_release', 'click', 'drag', 'mouse', 'paste', 'resize', 'state_change', 'every', 'after']

AnimateDrawing

AnimateDrawing(animation: DrawingAnimation, *, x: int = 0, y: int = 0, encoding: PixelEncoding = 'half_blocks', start_milliseconds: int = 0)

Bases: Operation

Play a DrawingAnimation on a mounted buffer.

The animation runs on the runtime clock, so applying it needs a runtime.

Parameters:

  • animation (DrawingAnimation) –

    The animation to play.

  • x (int, default: 0 ) –

    The column of the picture's top-left cell.

  • y (int, default: 0 ) –

    The row of the picture's top-left cell.

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

    How palette pixels pack into cells.

  • start_milliseconds (int, default: 0 ) –

    Where in the animation to start.

Examples:

runtime = Runtime.offscreen(width=4, height=1)
buffer = Buffer(width=4, height=1)
runtime.mount(buffer, geometry='inherit')
animation = DrawingAnimation(
    [
        DrawingFrame(Drawing(['a']), duration_milliseconds=50),
        DrawingFrame(Drawing(['b']), duration_milliseconds=50),
    ]
)
buffer.update(AnimateDrawing(animation))
runtime.step()
assert runtime.snapshot().lines()[0].strip() == 'a'
runtime.advance_clock(50)
runtime.step()
assert runtime.snapshot().lines()[0].strip() == 'b'

Create a AnimateDrawing.

Parameters:

  • animation (DrawingAnimation) –

    DrawingAnimation.

  • x (int, default: 0 ) –

    int. Defaults to 0.

  • y (int, default: 0 ) –

    int. Defaults to 0.

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

    PixelEncoding. Defaults to 'half_blocks'.

  • start_milliseconds (int, default: 0 ) –

    int. Defaults to 0.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    animation: DrawingAnimation,
    *,
    x: int = 0,
    y: int = 0,
    encoding: PixelEncoding = 'half_blocks',
    start_milliseconds: int = 0,
) -> None:
    """
    Create a AnimateDrawing.

    Args:
        animation: ``DrawingAnimation``.
        x: ``int``. Defaults to ``0``.
        y: ``int``. Defaults to ``0``.
        encoding: ``PixelEncoding``. Defaults to ``'half_blocks'``.
        start_milliseconds: ``int``. Defaults to ``0``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

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

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

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

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

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

ApplyStatePatch

ApplyStatePatch(reference: StateReference[StateType], patch: TerminalStatePatch, *, expected_revision: int | None = None)

Bases: Operation

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

Patch paths are relative to the reference.

Parameters:

  • reference (StateReference[StateType]) –

    A state reference exposing path and native_store.

  • patch (TerminalStatePatch) –

    The patch to apply below the reference's path.

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

    Fail with a conflict error unless the store is at this revision.

Examples:

schema = TerminalStateSchema.compile(
    {
        'type': 'object',
        'properties': {
            'player': {'type': 'object', 'properties': {'x': {'type': 'integer'}}}
        },
    }
)
store = TerminalStateStore({'player': {'x': 0}}, schema=schema)

class Reference:
    path = ('player',)
    native_store = store
    schema = None

patch = TerminalStatePatch.from_value(
    [{'op': 'replace', 'path': '/x', 'value': 9}]
)
Buffer().update(ApplyStatePatch(Reference(), patch))
assert store.snapshot().to_value() == {'player': {'x': 9}}

Create a ApplyStatePatch.

Parameters:

  • reference (StateReference[StateType]) –

    StateReference[StateType].

  • patch (TerminalStatePatch) –

    TerminalStatePatch.

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

    int | None. Defaults to None.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    reference: StateReference[StateType],
    patch: TerminalStatePatch,
    *,
    expected_revision: int | None = None,
) -> None:
    """
    Create a ApplyStatePatch.

    Args:
        reference: ``StateReference[StateType]``.
        patch: ``TerminalStatePatch``.
        expected_revision: ``int | None``. Defaults to ``None``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

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

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

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

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

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

ApplyStyle

ApplyStyle(style: Style)

Bases: Operation

Patch a Style onto every cell of the target.

Colors and modifiers the style leaves unset are kept.

Parameters:

  • style (Style) –

    The style to patch onto each cell.

Examples:

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

Create a ApplyStyle.

Parameters:

  • style (Style) –

    Style.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, style: Style) -> None:
    """
    Create a ApplyStyle.

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

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

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

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

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

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

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

Background

Background(color: ColorValue)

Bases: Operation

Set the background color of every cell of the target.

Parameters:

  • color (ColorValue) –

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

Examples:

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

Create a Background.

Parameters:

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, color: ColorValue) -> None:
    """
    Create a Background.

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

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

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

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

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

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

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

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.

should_fit_width property writable

should_fit_width: bool

Whether the width follows the children: as wide as the farthest right edge.

Only visible children attached with explicit geometry count, and a child whose parent_measured_axes include 'width' (or whose x is placed by this buffer's size) is placed within the width the others give. The width is fitted before every frame, and at once by Runtime.fit_to_content. A buffer that fits its children and is mounted on a runtime with geometry='inherit' decides that runtime's width.

Examples:

with Runtime.offscreen(width=1, height=1) as runtime:
    parent = Buffer(width=1, height=1)
    parent.should_fit_width = True
    parent.should_fit_height = True
    parent.attach(Buffer('hello', x=2, y=1))
    runtime.mount(parent, geometry='inherit')
    assert runtime.fit_to_content() == Size(7, 2)

should_fit_height property writable

should_fit_height: bool

Whether the height follows the children: as tall as the lowest bottom edge.

The rules of should_fit_width apply along the other axis.

fit_padding property writable

fit_padding: tuple[int, int]

The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.

parent_measured_axes property writable

parent_measured_axes: tuple[Literal['x', 'y', 'width', 'height'], ...]

The parts of the buffer's place that its parent's size decides.

Set it to the axes that are a percentage, a word such as 'center' or a formula of the parent's size. A parent that fits its children places such a buffer within the size the other children give it: one placed by the parent's size counts with its own size, and one sized by it does not count along that axis.

Raises:

  • ValueError –

    A name is not 'x', 'y', 'width' or 'height'.

Examples:

parent = Buffer(width=1, height=1)
parent.should_fit_width = True
centered = Buffer('mid')
centered.parent_measured_axes = ('x',)
assert centered.parent_measured_axes == ('x',)

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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, so print shows exactly the buffer.

Examples:

buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
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 the same rows with
            styling escape sequences. Both join the rows with newlines and add
            none after the last row, so ``print`` shows exactly the buffer.

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

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.

should_fit_width property writable

should_fit_width: bool

Whether the width follows the children: as wide as the farthest right edge.

Only visible children attached with explicit geometry count, and a child whose parent_measured_axes include 'width' (or whose x is placed by this buffer's size) is placed within the width the others give. The width is fitted before every frame, and at once by Runtime.fit_to_content. A buffer that fits its children and is mounted on a runtime with geometry='inherit' decides that runtime's width.

Examples:

with Runtime.offscreen(width=1, height=1) as runtime:
    parent = Buffer(width=1, height=1)
    parent.should_fit_width = True
    parent.should_fit_height = True
    parent.attach(Buffer('hello', x=2, y=1))
    runtime.mount(parent, geometry='inherit')
    assert runtime.fit_to_content() == Size(7, 2)

should_fit_height property writable

should_fit_height: bool

Whether the height follows the children: as tall as the lowest bottom edge.

The rules of should_fit_width apply along the other axis.

fit_padding property writable

fit_padding: tuple[int, int]

The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.

parent_measured_axes property writable

parent_measured_axes: tuple[Literal['x', 'y', 'width', 'height'], ...]

The parts of the buffer's place that its parent's size decides.

Set it to the axes that are a percentage, a word such as 'center' or a formula of the parent's size. A parent that fits its children places such a buffer within the size the other children give it: one placed by the parent's size counts with its own size, and one sized by it does not count along that axis.

Raises:

  • ValueError –

    A name is not 'x', 'y', 'width' or 'height'.

Examples:

parent = Buffer(width=1, height=1)
parent.should_fit_width = True
centered = Buffer('mid')
centered.parent_measured_axes = ('x',)
assert centered.parent_measured_axes == ('x',)

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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, so print shows exactly the buffer.

Examples:

buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
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 the same rows with
            styling escape sequences. Both join the rows with newlines and add
            none after the last row, so ``print`` shows exactly the buffer.

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

BlockTitle

BlockTitle(text: TextContent | Expression[str], *, position: str = 'top', alignment: str | Expression[str] | None = None, style: Style | DynamicStyle | None = None)

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

Attributes:

Examples:

title = BlockTitle('Status')
assert title.text == 'Status'

Create a BlockTitle.

Parameters:

  • text (TextContent | Expression[str]) –

    TextContent | Expression[str].

  • position (str, default: 'top' ) –

    str. Defaults to 'top'.

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

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

    Args:
        text: ``TextContent | Expression[str]``.
        position: ``str``. Defaults to ``'top'``.
        alignment: ``str | Expression[str] | None``. Defaults to ``None``.
        style: ``Style | DynamicStyle | None``. Defaults to ``None``.
    """

style property

The default colors and text modifiers applied to the cells.

alignment property

alignment: str | Expression[str]

The horizontal title alignment, or None to use the block setting.

text property

The text displayed on the block border.

position property

position: int | Expression[int | float]

The border holding this title: top or bottom.

Border

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

Bases: Operation

Draw a border around the edge of the target.

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

Parameters:

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

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

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

    The style of the border cells.

Examples:

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

Create a Border.

Parameters:

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

    BorderKind. Defaults to 'plain'.

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

    Style | None. Defaults to None.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
    self,
    kind: BorderKind = 'plain',
    *,
    style: Style | None = None,
) -> None:
    """
    Create a Border.

    Args:
        kind: ``BorderKind``. Defaults to ``'plain'``.
        style: ``Style | None``. Defaults to ``None``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

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

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

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

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

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

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.

  • should_fit_width (bool) –

    Whether the width follows the children it holds.

  • should_fit_height (bool) –

    Whether the height follows the children it holds.

  • fit_padding (tuple[int, int]) –

    The columns and rows a buffer that fits its children adds after them.

  • parent_measured_axes (tuple[Literal['x', 'y', 'width', 'height'], ...]) –

    The parts of the buffer's place that its parent's size decides.

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

should_fit_width property writable

should_fit_width: bool

Whether the width follows the children: as wide as the farthest right edge.

Only visible children attached with explicit geometry count, and a child whose parent_measured_axes include 'width' (or whose x is placed by this buffer's size) is placed within the width the others give. The width is fitted before every frame, and at once by Runtime.fit_to_content. A buffer that fits its children and is mounted on a runtime with geometry='inherit' decides that runtime's width.

Examples:

with Runtime.offscreen(width=1, height=1) as runtime:
    parent = Buffer(width=1, height=1)
    parent.should_fit_width = True
    parent.should_fit_height = True
    parent.attach(Buffer('hello', x=2, y=1))
    runtime.mount(parent, geometry='inherit')
    assert runtime.fit_to_content() == Size(7, 2)

should_fit_height property writable

should_fit_height: bool

Whether the height follows the children: as tall as the lowest bottom edge.

The rules of should_fit_width apply along the other axis.

fit_padding property writable

fit_padding: tuple[int, int]

The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.

parent_measured_axes property writable

parent_measured_axes: tuple[Literal['x', 'y', 'width', 'height'], ...]

The parts of the buffer's place that its parent's size decides.

Set it to the axes that are a percentage, a word such as 'center' or a formula of the parent's size. A parent that fits its children places such a buffer within the size the other children give it: one placed by the parent's size counts with its own size, and one sized by it does not count along that axis.

Raises:

  • ValueError –

    A name is not 'x', 'y', 'width' or 'height'.

Examples:

parent = Buffer(width=1, height=1)
parent.should_fit_width = True
centered = Buffer('mid')
centered.parent_measured_axes = ('x',)
assert centered.parent_measured_axes == ('x',)

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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, so print shows exactly the buffer.

Examples:

buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
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 the same rows with
            styling escape sequences. Both join the rows with newlines and add
            none after the last row, so ``print`` shows exactly the buffer.

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

BufferExpressionScope

Bases: ExpressionScope

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

Attributes:

Examples:

assert BufferScope.width is Width
assert BufferScope.region is BufferRegion

x property

The column in the parent.

y property

The row in the parent.

position property

position: Value[Point]

The position in the parent.

width property

The width in cells.

height property

height: NumericValue[int | float]

The height in cells.

size property

size: Value[Size]

The size in cells.

region property

region: Value[Rectangle]

The rectangle on the screen, counting every parent offset.

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.

should_fit_width property writable

should_fit_width: bool

Whether the width follows the children: as wide as the farthest right edge.

Only visible children attached with explicit geometry count, and a child whose parent_measured_axes include 'width' (or whose x is placed by this buffer's size) is placed within the width the others give. The width is fitted before every frame, and at once by Runtime.fit_to_content. A buffer that fits its children and is mounted on a runtime with geometry='inherit' decides that runtime's width.

Examples:

with Runtime.offscreen(width=1, height=1) as runtime:
    parent = Buffer(width=1, height=1)
    parent.should_fit_width = True
    parent.should_fit_height = True
    parent.attach(Buffer('hello', x=2, y=1))
    runtime.mount(parent, geometry='inherit')
    assert runtime.fit_to_content() == Size(7, 2)

should_fit_height property writable

should_fit_height: bool

Whether the height follows the children: as tall as the lowest bottom edge.

The rules of should_fit_width apply along the other axis.

fit_padding property writable

fit_padding: tuple[int, int]

The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.

parent_measured_axes property writable

parent_measured_axes: tuple[Literal['x', 'y', 'width', 'height'], ...]

The parts of the buffer's place that its parent's size decides.

Set it to the axes that are a percentage, a word such as 'center' or a formula of the parent's size. A parent that fits its children places such a buffer within the size the other children give it: one placed by the parent's size counts with its own size, and one sized by it does not count along that axis.

Raises:

  • ValueError –

    A name is not 'x', 'y', 'width' or 'height'.

Examples:

parent = Buffer(width=1, height=1)
parent.should_fit_width = True
centered = Buffer('mid')
centered.parent_measured_axes = ('x',)
assert centered.parent_measured_axes == ('x',)

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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, so print shows exactly the buffer.

Examples:

buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
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 the same rows with
            styling escape sequences. Both join the rows with newlines and add
            none after the last row, so ``print`` shows exactly the buffer.

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

CancelEffect

CancelEffect(key: str)

Bases: Operation

Stop the running effect that was started with key.

Parameters:

  • key (str) –

    The key the effect was created with.

Examples:

runtime = Runtime.offscreen(width=10, height=1)
buffer = Buffer(width=10, height=1)
buffer.update(Write('hello'))
runtime.mount(buffer, geometry='inherit')
runtime.step()

buffer.update(Dissolve(duration_milliseconds=100, key='fade-out'))
buffer.update(CancelEffect('fade-out'))
runtime.step()
runtime.advance_clock(100)
runtime.step()
assert runtime.snapshot().lines()[0] == 'hello'

Create a CancelEffect.

Parameters:

  • key (str) –

    str.

Methods:

  • evaluate –

    Compute the expression's value.

  • then –

    An operation that applies this operation, then other.

  • when –

    An operation that applies only while condition is true.

  • __or__ –

    Combine this operation with other so both run in sequence.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, key: str) -> None:
    """
    Create a CancelEffect.

    Args:
        key: ``str``.
    """

evaluate

evaluate(context: EvaluationContext) -> ValueType_co

Compute the expression's value.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

then

then(other: Operation) -> Operation

An operation that applies this operation, then other.

Examples:

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

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

when

when(condition: Predicate) -> Operation

An operation that applies only while condition is true.

Examples:

from xnano_core._xnano_core import _reference

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

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

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

__or__

__or__(other: Operation) -> Operation

Combine this operation with other so both run in sequence.

Examples:

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

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

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.

should_fit_width property writable

should_fit_width: bool

Whether the width follows the children: as wide as the farthest right edge.

Only visible children attached with explicit geometry count, and a child whose parent_measured_axes include 'width' (or whose x is placed by this buffer's size) is placed within the width the others give. The width is fitted before every frame, and at once by Runtime.fit_to_content. A buffer that fits its children and is mounted on a runtime with geometry='inherit' decides that runtime's width.

Examples:

with Runtime.offscreen(width=1, height=1) as runtime:
    parent = Buffer(width=1, height=1)
    parent.should_fit_width = True
    parent.should_fit_height = True
    parent.attach(Buffer('hello', x=2, y=1))
    runtime.mount(parent, geometry='inherit')
    assert runtime.fit_to_content() == Size(7, 2)

should_fit_height property writable

should_fit_height: bool

Whether the height follows the children: as tall as the lowest bottom edge.

The rules of should_fit_width apply along the other axis.

fit_padding property writable

fit_padding: tuple[int, int]

The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.

parent_measured_axes property writable

parent_measured_axes: tuple[Literal['x', 'y', 'width', 'height'], ...]

The parts of the buffer's place that its parent's size decides.

Set it to the axes that are a percentage, a word such as 'center' or a formula of the parent's size. A parent that fits its children places such a buffer within the size the other children give it: one placed by the parent's size counts with its own size, and one sized by it does not count along that axis.

Raises:

  • ValueError –

    A name is not 'x', 'y', 'width' or 'height'.

Examples:

parent = Buffer(width=1, height=1)
parent.should_fit_width = True
centered = Buffer('mid')
centered.parent_measured_axes = ('x',)
assert centered.parent_measured_axes == ('x',)

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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, so print shows exactly the buffer.

Examples:

buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
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 the same rows with
            styling escape sequences. Both join the rows with newlines and add
            none after the last row, so ``print`` shows exactly the buffer.

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

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.

CanvasLayer

CanvasLayer()

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

Examples:

canvas = Canvas((0, 10), (0, 10), shapes=[CanvasPoints([(1, 1)]), CanvasLayer(), CanvasPoints([(9, 9)])])
assert CanvasLayer() == CanvasLayer()

Create a CanvasLayer.

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self) -> None:
    """
    Create a CanvasLayer.
    """

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.

CanvasMarker

CanvasMarker(marker: str | Value[str])

Switches the marker the shapes after it are drawn with.

Parameters:

  • marker (str | Value[str]) –

    A marker name ('dot', 'block', 'bar', 'braille', 'half_block', 'quadrant', 'sextant', 'octant') or any single character.

Raises:

  • ValueError –

    The marker is not a known name or a single character.

Attributes:

Examples:

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

Create a CanvasMarker.

Parameters:

Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(self, marker: str | Value[str]) -> None:
    """
    Create a CanvasMarker.

    Args:
        marker: ``str | Value[str]``.
    """

marker instance-attribute

marker: str | Value[str]

The named cell marker used for subsequent shapes.

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.

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

CellAnimationInfo

The header of a packed cell animation.

Attributes:

Examples:

frames = [Buffer.with_text('a').to_cell_grid(), Buffer.with_text('b').to_cell_grid()]
packed = pack_cell_animation(frames, frame_durations_milliseconds=[40, 60])
info = inspect_cell_animation(packed)
assert info.frame_count == 2
assert info.duration_milliseconds == 100
assert info.should_loop

format_version property

format_version: int

The version of the cell animation byte format.

columns property

columns: int

The width of every frame in cells.

rows property

rows: int

The height of every frame in cells.

frame_count property

frame_count: int

The number of frames.

duration_milliseconds property

duration_milliseconds: int

The total duration of one pass in milliseconds.

should_loop property

should_loop: bool

Whether the animation repeats.

CellFilter

A composable selection of cells affected by an animation.

Examples:

filter = CellFilter.text() & ~CellFilter.background_color('blue')
assert isinstance(filter, CellFilter)

CellGridError

Bases: ValueError

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

Examples:

try:
    inspect_cell_grid(b'not a cell grid')
except CellGridError as error:
    assert 'cell grid' in str(error)

CellGridInfo

The header of a packed cell grid.

Attributes:

Examples:

info = inspect_cell_grid(Buffer.with_text('abc').to_cell_grid())
assert (info.columns, info.rows) == (3, 1)
assert info.required_protocol is None

format_version property

format_version: int

The version of the cell grid byte format.

columns property

columns: int

The width in cells.

rows property

rows: int

The height in cells.

has_graphics_protocol_cells property

has_graphics_protocol_cells: bool

Whether the grid carries cells for a terminal graphics protocol.

required_protocol property

required_protocol: GraphicsProtocol | None

The graphics protocol the grid needs, or None for plain cells.

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.

should_fit_width property writable

should_fit_width: bool

Whether the width follows the children: as wide as the farthest right edge.

Only visible children attached with explicit geometry count, and a child whose parent_measured_axes include 'width' (or whose x is placed by this buffer's size) is placed within the width the others give. The width is fitted before every frame, and at once by Runtime.fit_to_content. A buffer that fits its children and is mounted on a runtime with geometry='inherit' decides that runtime's width.

Examples:

with Runtime.offscreen(width=1, height=1) as runtime:
    parent = Buffer(width=1, height=1)
    parent.should_fit_width = True
    parent.should_fit_height = True
    parent.attach(Buffer('hello', x=2, y=1))
    runtime.mount(parent, geometry='inherit')
    assert runtime.fit_to_content() == Size(7, 2)

should_fit_height property writable

should_fit_height: bool

Whether the height follows the children: as tall as the lowest bottom edge.

The rules of should_fit_width apply along the other axis.

fit_padding property writable

fit_padding: tuple[int, int]

The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.

parent_measured_axes property writable

parent_measured_axes: tuple[Literal['x', 'y', 'width', 'height'], ...]

The parts of the buffer's place that its parent's size decides.

Set it to the axes that are a percentage, a word such as 'center' or a formula of the parent's size. A parent that fits its children places such a buffer within the size the other children give it: one placed by the parent's size counts with its own size, and one sized by it does not count along that axis.

Raises:

  • ValueError –

    A name is not 'x', 'y', 'width' or 'height'.

Examples:

parent = Buffer(width=1, height=1)
parent.should_fit_width = True
centered = Buffer('mid')
centered.parent_measured_axes = ('x',)
assert centered.parent_measured_axes == ('x',)

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)