bootstack.CodeEditor#

class bootstack.CodeEditor(value='', *, textsignal=None, language=None, theme='auto', light_theme='default', dark_theme='monokai', read_only=False, wrap=False, tab_width=4, insert_spaces=True, auto_indent=True, show_line_numbers=True, show_indent_guides=False, height=20, scrollbars='both', font='code', show_border=True, accent='primary', extensions=None, parent=None, **kwargs)#

Bases: PublicWidgetBase

A full-featured code editor with line numbers, bracket matching, and syntax highlighting.

Not Field-wrapped — use TextArea for labeled form inputs.

Parameters:
  • value (str) – Initial text content.

  • textsignal (Signal[str] | None) – Reactive Signal[str] bound to the editor content.

  • language (str | None) – Pygments lexer name for syntax highlighting (e.g. 'python', 'json', 'sql'). Any Pygments lexer name works; unknown names fall back to plain text. None disables highlighting. See the full list at https://pygments.org/languages/.

  • theme (str) – Pygments color scheme. 'auto' (default) switches between light_theme and dark_theme when the bootstack theme changes. Pass an explicit Pygments style name (e.g. 'monokai', 'dracula') to pin the scheme. See the full list at https://pygments.org/styles/.

  • light_theme (str) – Pygments style used when theme='auto' and the active bootstack theme is light. Default 'default'.

  • dark_theme (str) – Pygments style used when theme='auto' and the active bootstack theme is dark. Default 'monokai'.

  • read_only (bool) – If True, content is visible but not editable.

  • wrap (bool) – If True, long lines wrap. Default False (horizontal scroll).

  • tab_width (int) – Number of spaces per tab stop. Default 4.

  • insert_spaces (bool) – If True, Tab inserts spaces instead of a tab character.

  • auto_indent (bool) – If True, Return replicates the current line’s indentation.

  • show_line_numbers (bool) – If True (default), shows a line-number gutter.

  • show_indent_guides (bool) – If True, draws subtle vertical guide marks at each indent stop.

  • height (int) – Visible row count. Default 20.

  • scrollbars (Literal['both', 'auto', 'vertical', 'none']) – Scrollbar visibility. Default 'both'. Horizontal scrolling requires wrap=False.

  • font (str) – Semantic font token for the editor. Default 'code' (the monospace token). See Typography.

  • show_border (bool) – If True (default), styles the editor frame as a themed border with a focus ring.

  • accent (AccentToken | str) – Accent token applied to the focus border. Default 'primary'.

  • extensions (list[EditFilter] | None) – Additional EditFilter instances to install on top of the built-in set.

  • parent (Any) – Override the context-stack parent.

  • **kwargs (Any) – Layout placement options applied by the parent container — fill, expand, anchor, margin, row, column, sticky. See Arranging Widgets.

property cursor_position: tuple[int, int]#

The insertion cursor as a 1-indexed (line, col) tuple.

(1, 1) is the start of the content — the same coordinates insert() and goto() accept. Read it in an on_cursor_move handler to drive a status-bar readout. Read-only — use goto() to move the cursor.

property error: Signal[str]#

Reactive Signal[str] — current validation error message.

Empty string when the editor is valid. Updates in lockstep with valid.

property is_attached: bool#

Whether the widget is currently placed in its layout.

True while the widget occupies space in its parent; False after detach (or before it has ever been placed). A detached widget keeps its state and can be returned to the layout with attach.

property is_dirty: bool#

True if content has changed since the last mark_saved() call.

property language: str | None#

Active syntax highlighting language, or None if disabled.

property read_only: bool#

Whether the editor content is visible but not editable.

property schedule: Schedule#

Scheduler tied to this widget’s lifetime.

All jobs are automatically cancelled when the widget is destroyed. First access creates the Schedule instance; subsequent accesses return the same instance.

Usage:

self.schedule.delay(500, callback)
self.schedule.every(1000, tick)
job = self.schedule.idle(refresh)
job.cancel()
property selected_text: str#

The currently selected text, or an empty string when nothing is selected.

property selection: tuple[tuple[int, int], tuple[int, int]] | None#

The current text selection as ((start_line, start_col), (end_line, end_col)).

Both lines and columns are 1-indexed — the same coordinates cursor_position reports and goto() / insert() accept. Returns None when no text is selected. Set to a pair of (line, col) tuples to select a range, or set to None to clear the selection.

property signal: Signal[str] | None#

The reactive Signal bound to this editor, or None if unbound.

property text: str#

The current display text. Same as value for a code editor (no formatting layer). Read-only — assign to value to change it.

property theme: str#

Active Pygments color scheme, or 'auto' if tracking the bootstack theme.

property valid: Signal[bool]#

Reactive Signal[bool]True when all validation rules pass.

Starts True. Updates after every validation run (blur or manual validate() call). Subscribe a named handler to react immediately when validity changes (a lambda cannot assign, so define a function): def on_valid(ok): btn.disabled = not ok then editor.valid.subscribe(on_valid).

property value: str#

Full text content (trailing newline stripped).

add_validation_rule(rule_type, **kwargs)#

Attach a validation rule to this editor.

Parameters:
  • rule_type (RuleType) – The kind of validation rule to apply.

  • **kwargs (Any) – Rule options such as message=, min=, max=, trigger=.

append(text)#

Append text to the end of the content.

Applies even when read_only=True, leaving the editor read-only afterward.

Parameters:

text (str) – Text to add at the end of the content.

attach(**kwargs)#

Return a detached widget to its layout, optionally moving it.

With no arguments, restores the widget to exactly where detach took it from. Any layout kwargs accepted by the original placement (e.g. fill, expand, anchor, sticky, margin) override the stored options. For stacked widgets, index= sets the position among the currently attached siblings (or pass an explicit before=/after= sibling); without one, the snapshotted position is used.

Calling attach on a widget that is already attached moves it (the kwargs are re-applied). Fires on_attach.

Parameters:

**kwargs (Any) – Layout placement options to override for this placement.

Raises:

ParentResolutionError – If the widget was never placed in a layout.

capture(path, *, inset=0, settle=0.1)#

Save a picture of this widget to an image file.

Captures the area this widget occupies on screen — one widget, a whole window, or the entire application, depending on what you call it on. The file extension selects the format, so .png, .jpg, and .pdf all work.

The widget has to be visible. A capture reads pixels from the display, so the window is brought to the front first and a hidden or detached widget cannot be captured at all. Any always-on-top setting the window already had is left as it was found.

Pair it with a save dialog to let the user choose where it goes:

import bootstack as bs

def on_export():
    chosen = bs.ask_save_file(initial_file="dashboard.png")
    if chosen:
        app.capture(chosen)
Parameters:
  • path (str | Path) – Where to write the image. Missing parent folders are created, and the extension chooses the format.

  • inset (int) – Pixels to trim from every edge, zero or more. Use 2 on a whole window to drop the native border artifact.

  • settle (float) – Seconds to let the desktop finish repainting before the pixels are read. The default covers the common case of a dialog closing just beforehand. The interface pauses for this long, so a second click on the control that started the capture waits its turn rather than starting an overlapping one.

Returns:

The path that was written.

Raises:

BootstackError – If the widget is not visible on screen or has been scrolled out of view, if inset is negative, if no capture backend is available, or if the file cannot be written.

Return type:

Path

Added in version 0.3.0.

clear()#

Clear all text content.

dedent()#

Dedent selected lines (or the current line) by one tab stop.

Removes up to one tab stop of leading whitespace from each line in the selection. With no selection, dedents the line the cursor is on. The affected lines stay selected afterward (a partial-line selection is re-selected to span the whole lines).

destroy()#

Destroy the widget and release the resources it holds.

Removes the widget from its parent, destroys its children, and cancels any pending or repeating jobs on its schedule. After this the widget must not be used again. Destroying a container destroys everything inside it.

detach()#

Remove the widget from its layout without destroying it.

The widget stops occupying space but keeps its state, children, and event bindings, ready to be returned with attach. The current position is snapshotted so a plain attach() restores it exactly — for stacked siblings this is the index among the currently attached siblings, so detaching other siblings first shifts that index.

Calling detach on a widget that is already detached, or one that was never placed in a layout, does nothing. Fires on_detach.

emit(event, *, data=None)#

Fire a named event on this widget, as if it produced the event itself.

This is how a composite widget surfaces high-level activity to its listeners, and the generic counterpart to the on_*() shorthands for firing events that have no dedicated method.

It is meant for the framework’s own events — 'change', 'select', 'input' and the rest of the data-carrying names. A handler registered through on() or an on_<event>() shorthand receives what is emitted.

Names that map onto a native event instead ('click', 'focus', 'blur', 'submit', …) are a different matter: emitting one asks the toolkit to deliver a real input event, which carries no payload and can reach handlers the widget installed for its own use. Emitting those is not a way to notify listeners, and a listener bound through on() may not see it. Drive the widget through its properties and methods instead.

Parameters:
  • event (str) – The event name, unprefixed — the same name you pass to on() or an on_<event>() shorthand (e.g. 'change', 'select').

  • data (Any) – The payload delivered to handlers. Pass the matching payload dataclass from bootstack.events — the same object an on_<event>() handler receives.

Example

from bootstack.events import ChangeEvent

field.emit("change", data=ChangeEvent(value=new_value))
focus()#

Move keyboard focus to the editor.

goto(line, col=1)#

Move the cursor to a position and scroll it into view.

Both are 1-indexed — (1, 1) is the start of the content, the same coordinates cursor_position reports and insert() accepts. Omit col to land at the start of the line.

Parameters:
  • line (int) – 1-indexed line number.

  • col (int) – 1-indexed column, or omit for the start of the line. Defaults to 1.

Hide the find/replace bar.

indent()#

Indent selected lines by one tab stop, or insert a tab stop at the cursor.

With a selection, every selected line is indented by one tab stop (spaces or a tab character, depending on the editor’s insert_spaces setting). The affected lines stay selected afterward (a partial-line selection is re-selected to span the whole lines).

Without a selection, inserts spaces to the next tab stop at the cursor (same as pressing Tab with no selection).

insert(text, line=None, col=None)#

Insert text at a position, defaulting to the cursor.

With no line/col, inserts at the current cursor. Pass line to insert at the start of that line, or line and col together for an exact position. Both are 1-indexed — (1, 1) is the start of the content, the same coordinates cursor_position reports and goto() accepts.

Read-only blocks user edits, not programmatic ones: this applies even when read_only=True, leaving the editor read-only afterward.

Parameters:
  • text (str) – Text to insert.

  • line (int | None) – 1-indexed line, or None to use the cursor’s line. Defaults to None.

  • col (int | None) – 1-indexed column, or None for the start of the line. Defaults to None.

install(f)#

Install a custom filter extension.

Parameters:

f (EditFilter) – The EditFilter to add.

mark_saved()#

Mark the current state as the saved baseline (clears is_dirty).

on(event, handler=None)#

Bind handler to event, or return a composable Stream.

With a handler — binds immediately and returns a Subscription:

sub = widget.on("change", handler)
sub.cancel()

Without a handler — returns a Stream for operator chaining. The Tk binding is created lazily when .listen() is called:

sub = widget.on("change").debounce(300).listen(handler)
sub.cancel()
Parameters:
  • event (str) – Event name (e.g. "change", "click").

  • handler (Callable[[Any], Any] | None) – Optional callback. If omitted, a Stream is returned.

Returns:

Subscription when a handler is provided; Stream otherwise.

Return type:

Stream | Subscription

on_attach(handler=None)#

Register a callback fired when the widget enters the layout.

Fires each time the widget becomes visible in its parent — on initial placement and on every attach. Pair it with on_detach to keep per-visibility resources (timers, observers) tied to the widget’s presence on screen. The handler receives a curated Event.

Parameters:

handler (Callable[[Event], Any] | None) – Called when the widget is attached. Omit to get a composable Stream.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_blur() Stream#
on_blur(handler: Callable[[Event], Any]) Subscription

Register a callback fired when the editor loses focus.

Parameters:

handler (Callable[[Event], Any] | None) – Called with an Event. Omit to get a composable Stream instead.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_change() Stream#
on_change(handler: Callable[[ChangeEvent], Any]) Subscription

Register a callback fired on every edit.

Parameters:

handler (Callable[[ChangeEvent], Any] | None) – Called with a ChangeEvent whose value is the editor text. Omit to get a composable Stream.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_cursor_move() Stream#
on_cursor_move(handler: Callable[[Event], Any]) Subscription

Register a callback fired when the cursor position changes.

Parameters:

handler (Callable[[Event], Any] | None) – Called with an Event. Omit to get a composable Stream instead.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_destroy(handler=None)#

Register a callback fired when the widget is destroyed.

Fires once, as the widget is torn down — the place to release resources the widget owns that aren’t cleaned up automatically (file handles, observers, external subscriptions). The handler receives a curated Event.

Parameters:

handler (Callable[[Event], Any] | None) – Called as the widget is destroyed. Omit to get a composable Stream.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_detach(handler=None)#

Register a callback fired when the widget leaves the layout.

Fires each time the widget stops occupying space in its parent — on detach and when an ancestor hides it. Pair it with on_attach to release per-visibility resources. The handler receives a curated Event.

Parameters:

handler (Callable[[Event], Any] | None) – Called when the widget is detached. Omit to get a composable Stream.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_focus() Stream#
on_focus(handler: Callable[[Event], Any]) Subscription

Register a callback fired when the editor gains focus.

Parameters:

handler (Callable[[Event], Any] | None) – Called with an Event. Omit to get a composable Stream instead.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_input() Stream#
on_input(handler: Callable[[InputEvent], Any]) Subscription

Register a callback fired on every edit, before commit.

Parameters:

handler (Callable[[InputEvent], Any] | None) – Called with an InputEvent whose text is the current content. Omit to get a composable Stream.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_invalid() Stream#
on_invalid(handler: Callable[[ValidationEvent], Any]) Subscription

Register a callback fired when validation fails.

Parameters:

handler (Callable[[ValidationEvent], Any] | None) – Called with a ValidationEvent. Omit to get a composable Stream instead.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_modified() Stream#
on_modified(handler: Callable[[TextModifiedEvent], Any]) Subscription

Register a callback fired when is_dirty changes.

Parameters:

handler (Callable[[TextModifiedEvent], Any] | None) – Called with a TextModifiedEvent. Omit to get a composable Stream instead.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_redo() Stream#
on_redo(handler: Callable[[InputEvent], Any]) Subscription

Register a callback fired after a redo operation.

Parameters:

handler (Callable[[InputEvent], Any] | None) – Called with an InputEvent. Omit to get a composable Stream instead.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_undo() Stream#
on_undo(handler: Callable[[InputEvent], Any]) Subscription

Register a callback fired after an undo operation.

Parameters:

handler (Callable[[InputEvent], Any] | None) – Called with an InputEvent. Omit to get a composable Stream instead.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_valid() Stream#
on_valid(handler: Callable[[ValidationEvent], Any]) Subscription

Register a callback fired when validation passes.

Parameters:

handler (Callable[[ValidationEvent], Any] | None) – Called with a ValidationEvent. Omit to get a composable Stream instead.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

on_validate() Stream#
on_validate(handler: Callable[[ValidationEvent], Any]) Subscription

Register a callback fired after any validation run.

Parameters:

handler (Callable[[ValidationEvent], Any] | None) – Called with a ValidationEvent. Omit to get a composable Stream instead.

Returns:

A cancellable Subscription when a handler is given, otherwise a Stream.

Return type:

Stream | Subscription

redo()#

Redo the last undone edit.

select_all()#

Select all text content.

show_replace()#

Show the find/replace bar with the replace row visible.

Show the find bar and focus the search input.

undo()#

Undo the last edit.

undo_block()#

Context manager that groups edits into a single undo step.

Usage:

with editor.undo_block():
    editor.insert("# header\n", 1, 1)
    editor.value = new_content
uninstall(f)#

Remove a previously installed filter extension.

Parameters:

f (EditFilter) – The EditFilter to remove.

validate()#

Run validation rules against the current content.

Returns:

True if all rules pass, False otherwise.

Return type:

bool