Skip to content

textual_adapter

Class info

Re-exported classes

Class Module Description
CommandInput slashed.textual_adapter.command_input Single-line command input with completion support.
CommandTextArea slashed.textual_adapter.command_textarea Multi-line command input with completion support.
SlashedApp slashed.textual_adapter.app Base app with slash command support.
SlashedSuggester slashed.textual_adapter.suggester Adapts a Slashed CompletionProvider to Textual's Suggester interface.
TextualOutputWriter slashed.textual_adapter.app Output writer that routes messages to bound widgets.

🛈 DocStrings

Textual integration for Slashed.

CommandInput

Bases: Input, CommandWidgetMixin[TContext]

Single-line command input with completion support.

Class Type Parameters:

Name Bound or Constraints Description Default
TContext

Type of the context data available to commands via ctx.get_data()

required
Source code in src/slashed/textual_adapter/command_input.py
class CommandInput[TContext](Input, CommandWidgetMixin[TContext]):  # type: ignore[override]
    """Single-line command input with completion support.

    Type Parameters:
        TContext: Type of the context data available to commands via ctx.get_data()
    """

    DEFAULT_CSS = """
    CommandInput {
        height: 3;
        border: solid $primary;
    }
    """

    value: Reactive[str]
    cursor_position: int

    BINDINGS: ClassVar[list[Binding | tuple[str, str] | tuple[str, str, str]]] = [
        Binding("up", "navigate_up", "Previous suggestion", show=False),
        Binding("down", "navigate_down", "Next suggestion", show=False),
        Binding("escape", "hide_dropdown", "Hide suggestions", show=False),
        Binding("tab", "accept_completion", "Accept completion", show=False),
    ]

    def __init__(
        self,
        placeholder: str = "Type a command...",
        *,  # Force keyword arguments
        context_data: TContext | None = None,
        output_id: str = "main-output",
        status_id: str | None = None,
        show_notifications: bool = False,
        enable_system_commands: bool = True,
        # Widget parameters
        name: str | None = None,
        id: str | None = None,  # noqa: A002
        classes: str | None = None,
        disabled: bool = False,
    ) -> None:
        # First initialize CommandWidgetBase
        Input.__init__(
            self,
            placeholder=placeholder,
            name=name,
            id=id,
            classes=classes,
            disabled=disabled,
        )
        # Initialize mixin
        CommandWidgetMixin.__init__(
            self,
            context_data=context_data,
            output_id=output_id,
            status_id=status_id,
            show_notifications=show_notifications,
            enable_system_commands=enable_system_commands,
        )

    # Protocol implementation
    def get_first_line(self) -> str:
        return self.value

    def clear_input(self) -> None:
        self.value = ""

    def get_cursor_screen_position(self) -> tuple[int, int]:
        return self.cursor_screen_offset

    async def _get_completions(self) -> list[CompletionItem]:
        document = Document(text=self.value, cursor_position=self.cursor_position)
        completion_context = CompletionContext(document=document, command_context=self.context)

        parts = self.value[1:].split()
        self.logger.debug("Getting completions for parts: %s", parts)

        # Command name completion
        if not parts or (len(parts) == 1 and not self.value.endswith(" ")):
            text = completion_context.current_word.lstrip("/")
            self.logger.debug("Command completion for: %r", text)
            matches = [cmd for cmd in self.store.list_commands() if cmd.name.startswith(text)]
            return [
                CompletionItem(text=cmd.name, metadata=cmd.description, kind="command")
                for cmd in matches
            ]

        # Argument completion
        command_name = parts[0]
        if command := self.store.get_command(command_name):
            if command_name == "help":
                # Special case for help command - filter by current argument
                arg = parts[-1] if len(parts) > 1 else ""
                self.logger.debug("Help completion for arg: %r", arg)
                matches = [cmd for cmd in self.store.list_commands() if cmd.name.startswith(arg)]
                return [
                    CompletionItem(
                        text=cmd.name,
                        metadata=cmd.description,
                        kind="command-arg",
                    )
                    for cmd in matches
                ]

            # For other commands, use their completer
            if completer := command.get_completer():
                self.logger.debug("Found completer for command: %s", command_name)

                # Create a new document for just the argument part
                arg_text = parts[-1] if len(parts) > 1 else ""
                arg_document = Document(text=arg_text, cursor_position=len(arg_text))
                arg_context = CompletionContext(document=arg_document, command_context=self.context)

                self.logger.debug("Getting completions for argument: %r", arg_text)
                completions = [i async for i in completer.get_completions(arg_context)]
                self.logger.debug("Got %d completions", len(completions))
                return completions

        return []

    async def _update_completions(self) -> None:
        """Update the completion dropdown."""
        self.logger.debug("Updating completions...")

        completions = await self._get_completions()
        self._dropdown.clear_options()

        if completions:
            # Add completion options to dropdown
            options = [CompletionOption(completion) for completion in completions]
            self._dropdown.add_options(options)

            self.logger.debug("Added %s options to dropdown", len(options))

            # Show dropdown
            self._showing_dropdown = True
            self._dropdown.display = True

            # Position dropdown
            x, y = self.get_cursor_screen_position()
            self._dropdown.styles.offset = (x, y + 1)

            # Update selection
            if self._dropdown.option_count:
                self._dropdown.highlighted = 0
        else:
            self.logger.debug("No completions found, hiding dropdown")
            self.action_hide_dropdown()

    def action_hide_dropdown(self) -> None:
        """Hide the completion dropdown."""
        if self._showing_dropdown:
            self._dropdown.display = False
            self._showing_dropdown = False

    def action_navigate_up(self) -> None:
        """Move selection up in dropdown."""
        if self._showing_dropdown and self._dropdown.option_count:
            self._dropdown.action_cursor_up()

    def action_navigate_down(self) -> None:
        """Move selection down in dropdown."""
        if self._showing_dropdown and self._dropdown.option_count:
            self._dropdown.action_cursor_down()

    def action_accept_completion(self) -> None:
        """Accept the currently selected completion."""
        if not self._showing_dropdown or self._dropdown.highlighted is None:
            return

        option = self._dropdown.get_option_at_index(self._dropdown.highlighted)
        if not isinstance(option, CompletionOption):
            return

        completion = option.completion
        parts = self.value[1:].split()

        if not parts or (len(parts) == 1 and not self.value.endswith(" ")):
            # Command completion - replace whole value
            new_value = f"/{completion.text}"
        else:
            # Argument completion - replace just the last part or add new part
            if len(parts) > 1:
                parts[-1] = completion.text
            else:
                parts.append(completion.text)
            new_value = "/" + " ".join(parts)

        self.logger.debug("Accepting completion: %s", new_value)
        self.value = new_value
        self.cursor_position = len(new_value)
        self.action_hide_dropdown()

    # Event handlers
    def on_key(self, event: Key) -> None:
        """Handle special keys."""
        # First handle dropdown-specific keys
        if self._showing_dropdown:
            match event.key:
                case "up":
                    self.action_navigate_up()
                    event.prevent_default()
                    event.stop()
                case "down":
                    self.action_navigate_down()
                    event.prevent_default()
                    event.stop()
                case "escape":
                    self.action_hide_dropdown()
                    event.prevent_default()
                    event.stop()
                case "tab":
                    self.action_accept_completion()
                    event.prevent_default()
                    event.stop()
                case "enter":
                    # Only accept completion, don't execute yet
                    self.action_accept_completion()
                    event.prevent_default()
                    # Don't stop event - let it continue to execute command
                    return

        # Handle enter for command/text submission
        if event.key == "enter":
            if self.value.startswith("/"):
                command = self.value[1:]
                self._create_command_task(command)
                self.clear_input()
            else:
                self.post_message(self.InputSubmitted(self.value))
                self.clear_input()
            event.prevent_default()
            event.stop()

    @on(Input.Submitted)
    async def _handle_submit(self, event: Input.Submitted) -> None:
        """Handle input submission."""
        text = self.get_first_line()
        if text.startswith("/"):
            command = text[1:]  # Remove leading slash
            await self._execute_command(command)
            self.clear_input()
            event.stop()
        else:
            self.post_message(self.InputSubmitted(text))
            self.clear_input()

    async def on_input_changed(self, message: Input.Changed) -> None:
        """Update completions when input changes."""
        self.logger.debug("Input changed: %s", self.value)

        if self.value.startswith("/"):
            await self._update_completions()
        else:
            self.action_hide_dropdown()

action_accept_completion

action_accept_completion() -> None

Accept the currently selected completion.

Source code in src/slashed/textual_adapter/command_input.py
def action_accept_completion(self) -> None:
    """Accept the currently selected completion."""
    if not self._showing_dropdown or self._dropdown.highlighted is None:
        return

    option = self._dropdown.get_option_at_index(self._dropdown.highlighted)
    if not isinstance(option, CompletionOption):
        return

    completion = option.completion
    parts = self.value[1:].split()

    if not parts or (len(parts) == 1 and not self.value.endswith(" ")):
        # Command completion - replace whole value
        new_value = f"/{completion.text}"
    else:
        # Argument completion - replace just the last part or add new part
        if len(parts) > 1:
            parts[-1] = completion.text
        else:
            parts.append(completion.text)
        new_value = "/" + " ".join(parts)

    self.logger.debug("Accepting completion: %s", new_value)
    self.value = new_value
    self.cursor_position = len(new_value)
    self.action_hide_dropdown()

action_hide_dropdown

action_hide_dropdown() -> None

Hide the completion dropdown.

Source code in src/slashed/textual_adapter/command_input.py
def action_hide_dropdown(self) -> None:
    """Hide the completion dropdown."""
    if self._showing_dropdown:
        self._dropdown.display = False
        self._showing_dropdown = False

action_navigate_down

action_navigate_down() -> None

Move selection down in dropdown.

Source code in src/slashed/textual_adapter/command_input.py
def action_navigate_down(self) -> None:
    """Move selection down in dropdown."""
    if self._showing_dropdown and self._dropdown.option_count:
        self._dropdown.action_cursor_down()

action_navigate_up

action_navigate_up() -> None

Move selection up in dropdown.

Source code in src/slashed/textual_adapter/command_input.py
def action_navigate_up(self) -> None:
    """Move selection up in dropdown."""
    if self._showing_dropdown and self._dropdown.option_count:
        self._dropdown.action_cursor_up()

on_input_changed async

on_input_changed(message: Changed) -> None

Update completions when input changes.

Source code in src/slashed/textual_adapter/command_input.py
async def on_input_changed(self, message: Input.Changed) -> None:
    """Update completions when input changes."""
    self.logger.debug("Input changed: %s", self.value)

    if self.value.startswith("/"):
        await self._update_completions()
    else:
        self.action_hide_dropdown()

on_key

on_key(event: Key) -> None

Handle special keys.

Source code in src/slashed/textual_adapter/command_input.py
def on_key(self, event: Key) -> None:
    """Handle special keys."""
    # First handle dropdown-specific keys
    if self._showing_dropdown:
        match event.key:
            case "up":
                self.action_navigate_up()
                event.prevent_default()
                event.stop()
            case "down":
                self.action_navigate_down()
                event.prevent_default()
                event.stop()
            case "escape":
                self.action_hide_dropdown()
                event.prevent_default()
                event.stop()
            case "tab":
                self.action_accept_completion()
                event.prevent_default()
                event.stop()
            case "enter":
                # Only accept completion, don't execute yet
                self.action_accept_completion()
                event.prevent_default()
                # Don't stop event - let it continue to execute command
                return

    # Handle enter for command/text submission
    if event.key == "enter":
        if self.value.startswith("/"):
            command = self.value[1:]
            self._create_command_task(command)
            self.clear_input()
        else:
            self.post_message(self.InputSubmitted(self.value))
            self.clear_input()
        event.prevent_default()
        event.stop()

CommandTextArea

Bases: TextArea, CommandWidgetMixin[TContext]

Multi-line command input with completion support.

Class Type Parameters:

Name Bound or Constraints Description Default
TContext

Type of the context data available to commands via ctx.get_data()

required
Source code in src/slashed/textual_adapter/command_textarea.py
class CommandTextArea[TContext](TextArea, CommandWidgetMixin[TContext]):  # type: ignore[override]
    """Multi-line command input with completion support.

    Type Parameters:
        TContext: Type of the context data available to commands via ctx.get_data()
    """

    DEFAULT_CSS = """
    CommandTextArea {
        height: 5;
        border: solid $primary;
    }
    """

    value: Reactive[str]

    BINDINGS: ClassVar[list[Binding | tuple[str, str] | tuple[str, str, str]]] = [
        Binding("up", "navigate_up", "Previous suggestion", show=False),
        Binding("down", "navigate_down", "Next suggestion", show=False),
        Binding("escape", "hide_dropdown", "Hide suggestions", show=False),
        Binding("tab", "accept_completion", "Accept completion", show=False),
    ]

    def __init__(
        self,
        *,
        context_data: TContext | None = None,
        output_id: str = "main-output",
        status_id: str | None = None,
        show_notifications: bool = False,
        enable_system_commands: bool = False,
        # TextArea specific parameters
        language: str | None = None,
        theme: str = "css",
        soft_wrap: bool = True,
        tab_behavior: Literal["focus", "indent"] = "focus",
        # Widget parameters
        id: str | None = None,  # noqa: A002
        classes: str | None = None,
        disabled: bool = False,
    ) -> None:
        # Initialize TextArea with its parameters
        TextArea.__init__(
            self,
            language=language,
            theme=theme,
            soft_wrap=soft_wrap,
            tab_behavior=tab_behavior,
            id=id,
            classes=classes,
            disabled=disabled,
        )
        # Initialize base with shared parameters
        CommandWidgetMixin.__init__(
            self,
            context_data=context_data,
            output_id=output_id,
            status_id=status_id,
            show_notifications=show_notifications,
            enable_system_commands=enable_system_commands,
        )

    # Protocol implementation
    def get_first_line(self) -> str:
        """Get content of first line."""
        lines = self.text.splitlines()
        return lines[0] if lines else ""

    def clear_input(self) -> None:
        """Clear all input."""
        self.clear()

    def get_cursor_screen_position(self) -> tuple[int, int]:
        """Get cursor position in screen coordinates."""
        return self.cursor_screen_offset

    async def _get_completions(self) -> list[CompletionItem]:
        first_line = self.get_first_line()
        if not first_line.startswith("/"):
            return []

        document = Document(text=first_line, cursor_position=len(first_line))
        completion_context = CompletionContext(document=document, command_context=self.context)

        parts = first_line[1:].split()
        self.logger.debug("Getting completions for parts: %s", parts)

        # Command name completion
        if not parts or (len(parts) == 1 and not first_line.endswith(" ")):
            text = completion_context.current_word.lstrip("/")
            self.logger.debug("Command completion for: %r", text)
            matches = [cmd for cmd in self.store.list_commands() if cmd.name.startswith(text)]
            return [
                CompletionItem(text=cmd.name, metadata=cmd.description, kind="command")
                for cmd in matches
            ]

        # Argument completion
        command_name = parts[0]
        if command := self.store.get_command(command_name):
            if command_name == "help":
                # Special case for help command - filter by current argument
                current_arg = parts[-1] if len(parts) > 1 else ""
                self.logger.debug("Help completion filtering with arg: %r", current_arg)
                matches = [
                    cmd for cmd in self.store.list_commands() if cmd.name.startswith(current_arg)
                ]
                return [
                    CompletionItem(
                        text=cmd.name,
                        metadata=cmd.description,
                        kind="command-arg",
                    )
                    for cmd in matches
                ]

            # For other commands, use their completer
            if completer := command.get_completer():
                self.logger.debug("Found completer for command: %s", command_name)

                # Create a new document for just the argument part
                arg_text = parts[-1] if len(parts) > 1 else ""
                arg_document = Document(text=arg_text, cursor_position=len(arg_text))
                arg_context = CompletionContext(document=arg_document, command_context=self.context)

                self.logger.debug("Getting completions for argument: %r", arg_text)
                completions = [i async for i in completer.get_completions(arg_context)]
                self.logger.debug("Got %d completions", len(completions))
                return completions

        return []

    async def _update_completions(self) -> None:
        """Update the completion dropdown."""
        self.logger.debug("Updating completions...")

        completions = await self._get_completions()
        self._dropdown.clear_options()

        if completions:
            # Add completion options to dropdown
            options = [CompletionOption(completion) for completion in completions]
            self._dropdown.add_options(options)

            self.logger.debug("Added %s options to dropdown", len(options))

            # Show dropdown
            self._showing_dropdown = True
            self._dropdown.display = True

            # Position dropdown below current line
            x, y = self.get_cursor_screen_position()
            self._dropdown.styles.offset = (x, y + 1)

            # Update selection
            if self._dropdown.option_count:
                self._dropdown.highlighted = 0
        else:
            self.logger.debug("No completions found, hiding dropdown")
            self.action_hide_dropdown()

    def action_hide_dropdown(self) -> None:
        """Hide the completion dropdown."""
        if self._showing_dropdown:
            self._dropdown.display = False
            self._showing_dropdown = False

    def action_navigate_up(self) -> None:
        """Move selection up in dropdown."""
        if self._showing_dropdown and self._dropdown.option_count:
            self._dropdown.action_cursor_up()

    def action_navigate_down(self) -> None:
        """Move selection down in dropdown."""
        if self._showing_dropdown and self._dropdown.option_count:
            self._dropdown.action_cursor_down()

    def action_accept_completion(self) -> None:
        """Accept the currently selected completion."""
        if not self._showing_dropdown or self._dropdown.highlighted is None:
            return

        option = self._dropdown.get_option_at_index(self._dropdown.highlighted)
        if not isinstance(option, CompletionOption):
            return

        completion = option.completion
        first_line = self.get_first_line()
        parts = first_line[1:].split()

        if not parts or (len(parts) == 1 and not first_line.endswith(" ")):
            # Command completion - replace first line
            new_line = f"/{completion.text}"
        else:
            # Argument completion - replace just the last part or add new part
            if len(parts) > 1:
                parts[-1] = completion.text
            else:
                parts.append(completion.text)
            new_line = "/" + " ".join(parts)

        # Replace first line while keeping rest of content
        lines = self.text.splitlines()
        if lines:
            lines[0] = new_line
        else:
            lines = [new_line]
        self.load_text("\n".join(lines))

        # Move cursor to end of completed text
        self.move_cursor((0, len(new_line)))

        self.action_hide_dropdown()

    def on_key(self, event: Key) -> None:
        """Handle special keys."""
        # First handle dropdown-specific keys
        if self._showing_dropdown:
            match event.key:
                case "up":
                    self.action_navigate_up()
                    event.prevent_default()
                    event.stop()
                case "down":
                    self.action_navigate_down()
                    event.prevent_default()
                    event.stop()
                case "escape":
                    self.action_hide_dropdown()
                    event.prevent_default()
                    event.stop()
                case "tab":
                    self.action_accept_completion()
                    event.prevent_default()
                    event.stop()
                case "enter":
                    first_line = self.get_first_line()
                    if first_line.startswith("/"):
                        # Check if we have a complete command match
                        command = first_line[1:]
                        commands = [
                            cmd
                            for cmd in self.store.list_commands()
                            if cmd.name.startswith(command)
                        ]
                        if len(commands) == 1:
                            # Complete match - accept and execute
                            self.action_accept_completion()
                            self.action_hide_dropdown()
                            self._create_command_task(commands[0].name)
                            self.clear_input()
                        else:
                            # Just accept completion
                            self.action_accept_completion()
                    event.prevent_default()
                    event.stop()
                    return

        # Handle enter for command/text submission
        if event.key == "enter":
            first_line = self.get_first_line()
            if first_line.startswith("/"):
                command = first_line[1:]  # Remove leading slash
                self._create_command_task(command)
                self.clear_input()
                event.prevent_default()
                event.stop()

    async def on_text_area_changed(self, message: TextArea.Changed) -> None:
        """Handle text changes."""
        if self.is_command_mode:
            await self._update_completions()
        else:
            self.action_hide_dropdown()

action_accept_completion

action_accept_completion() -> None

Accept the currently selected completion.

Source code in src/slashed/textual_adapter/command_textarea.py
def action_accept_completion(self) -> None:
    """Accept the currently selected completion."""
    if not self._showing_dropdown or self._dropdown.highlighted is None:
        return

    option = self._dropdown.get_option_at_index(self._dropdown.highlighted)
    if not isinstance(option, CompletionOption):
        return

    completion = option.completion
    first_line = self.get_first_line()
    parts = first_line[1:].split()

    if not parts or (len(parts) == 1 and not first_line.endswith(" ")):
        # Command completion - replace first line
        new_line = f"/{completion.text}"
    else:
        # Argument completion - replace just the last part or add new part
        if len(parts) > 1:
            parts[-1] = completion.text
        else:
            parts.append(completion.text)
        new_line = "/" + " ".join(parts)

    # Replace first line while keeping rest of content
    lines = self.text.splitlines()
    if lines:
        lines[0] = new_line
    else:
        lines = [new_line]
    self.load_text("\n".join(lines))

    # Move cursor to end of completed text
    self.move_cursor((0, len(new_line)))

    self.action_hide_dropdown()

action_hide_dropdown

action_hide_dropdown() -> None

Hide the completion dropdown.

Source code in src/slashed/textual_adapter/command_textarea.py
def action_hide_dropdown(self) -> None:
    """Hide the completion dropdown."""
    if self._showing_dropdown:
        self._dropdown.display = False
        self._showing_dropdown = False

action_navigate_down

action_navigate_down() -> None

Move selection down in dropdown.

Source code in src/slashed/textual_adapter/command_textarea.py
def action_navigate_down(self) -> None:
    """Move selection down in dropdown."""
    if self._showing_dropdown and self._dropdown.option_count:
        self._dropdown.action_cursor_down()

action_navigate_up

action_navigate_up() -> None

Move selection up in dropdown.

Source code in src/slashed/textual_adapter/command_textarea.py
def action_navigate_up(self) -> None:
    """Move selection up in dropdown."""
    if self._showing_dropdown and self._dropdown.option_count:
        self._dropdown.action_cursor_up()

clear_input

clear_input() -> None

Clear all input.

Source code in src/slashed/textual_adapter/command_textarea.py
def clear_input(self) -> None:
    """Clear all input."""
    self.clear()

get_cursor_screen_position

get_cursor_screen_position() -> tuple[int, int]

Get cursor position in screen coordinates.

Source code in src/slashed/textual_adapter/command_textarea.py
def get_cursor_screen_position(self) -> tuple[int, int]:
    """Get cursor position in screen coordinates."""
    return self.cursor_screen_offset

get_first_line

get_first_line() -> str

Get content of first line.

Source code in src/slashed/textual_adapter/command_textarea.py
def get_first_line(self) -> str:
    """Get content of first line."""
    lines = self.text.splitlines()
    return lines[0] if lines else ""

on_key

on_key(event: Key) -> None

Handle special keys.

Source code in src/slashed/textual_adapter/command_textarea.py
def on_key(self, event: Key) -> None:
    """Handle special keys."""
    # First handle dropdown-specific keys
    if self._showing_dropdown:
        match event.key:
            case "up":
                self.action_navigate_up()
                event.prevent_default()
                event.stop()
            case "down":
                self.action_navigate_down()
                event.prevent_default()
                event.stop()
            case "escape":
                self.action_hide_dropdown()
                event.prevent_default()
                event.stop()
            case "tab":
                self.action_accept_completion()
                event.prevent_default()
                event.stop()
            case "enter":
                first_line = self.get_first_line()
                if first_line.startswith("/"):
                    # Check if we have a complete command match
                    command = first_line[1:]
                    commands = [
                        cmd
                        for cmd in self.store.list_commands()
                        if cmd.name.startswith(command)
                    ]
                    if len(commands) == 1:
                        # Complete match - accept and execute
                        self.action_accept_completion()
                        self.action_hide_dropdown()
                        self._create_command_task(commands[0].name)
                        self.clear_input()
                    else:
                        # Just accept completion
                        self.action_accept_completion()
                event.prevent_default()
                event.stop()
                return

    # Handle enter for command/text submission
    if event.key == "enter":
        first_line = self.get_first_line()
        if first_line.startswith("/"):
            command = first_line[1:]  # Remove leading slash
            self._create_command_task(command)
            self.clear_input()
            event.prevent_default()
            event.stop()

on_text_area_changed async

on_text_area_changed(message: Changed) -> None

Handle text changes.

Source code in src/slashed/textual_adapter/command_textarea.py
async def on_text_area_changed(self, message: TextArea.Changed) -> None:
    """Handle text changes."""
    if self.is_command_mode:
        await self._update_completions()
    else:
        self.action_hide_dropdown()

SlashedApp

Bases: App[TResult]

Base app with slash command support.

This app provides slash command functionality with optional typed context data. Commands can access the context data through self.context.get_data().

Class Type Parameters:

Name Bound or Constraints Description Default
TContext

Type of the command context data. When using typed context, access it via self.context.get_data() to get proper type checking.

required
TResult

Type of value returned by app.run(). Use None if the app doesn't return anything.

required
Example
@dataclass
class AppState:
    count: int = 0

class MyApp(SlashedApp[AppState, None]):
    @SlashedApp.command_input("input-id")
    async def handle_input(self, value: str) -> None:
        state = self.context.get_data()
        state.count += 1
        await self.context.print(f"Count: {state.count}")
Source code in src/slashed/textual_adapter/app.py
class SlashedApp[TContext, TResult](App[TResult]):
    """Base app with slash command support.

    This app provides slash command functionality with optional typed context data.
    Commands can access the context data through self.context.get_data().

    Type Parameters:
        TContext: Type of the command context data. When using typed context,
                 access it via self.context.get_data() to get proper type checking.
        TResult: Type of value returned by app.run(). Use None if the app
                doesn't return anything.

    Example:
        ```python
        @dataclass
        class AppState:
            count: int = 0

        class MyApp(SlashedApp[AppState, None]):
            @SlashedApp.command_input("input-id")
            async def handle_input(self, value: str) -> None:
                state = self.context.get_data()
                state.count += 1
                await self.context.print(f"Count: {state.count}")
        ```
    """

    # Class-level storage for command input handlers
    _command_handlers: ClassVar[dict[str, dict[str, str]]] = {}

    def __init__(
        self,
        store: CommandStore | None = None,
        data: TContext | None = None,
        commands: list[type[SlashedCommand] | BaseCommand] | None = None,
        *args: Any,
        **kwargs: Any,
    ) -> None:
        """Initialize app with command store.

        Args:
            data: Optional context data
            commands: Optional list of commands to register
            store: Optional command store (creates new one if not provided)
            *args: Arguments passed to textual.App
            **kwargs: Keyword arguments passed to textual.App
        """
        super().__init__(*args, **kwargs)
        self.store = store or CommandStore()
        self.store._initialize_sync()
        writer = TextualOutputWriter(self)
        self.context = self.store.create_context(data=data, output_writer=writer)
        if commands:
            for command in commands:
                self.store.register_command(command)

    def get_suggester(self) -> SlashedSuggester:
        """Get a suggester configured for this app's store and context."""
        return SlashedSuggester(store=self.store, context=self.context)

    def bind_output(self, output_id: str, widget_query: str, default: bool = False) -> None:
        """Bind an output stream to a widget.

        Args:
            output_id: ID for this output stream
            widget_query: CSS query to find the target widget
            default: Whether this is the default output
        """
        writer = self.context.output
        if not isinstance(writer, TextualOutputWriter):
            msg = "Output writer is not a TextualOutputWriter"
            raise TypeError(msg)
        writer.bind(output_id, widget_query, default=default)

    @classmethod
    def command_input(
        cls,
        input_id: str,
    ) -> Callable[[Callable[[Any, str], Awaitable[None]]], Callable[[Any, str], Awaitable[None]]]:
        """Register an Input widget to handle commands.

        Args:
            input_id: ID of the Input widget that should handle commands

        Example:
            ```python
            @command_input("my-input")
            async def handle_my_input(self, value: str) -> None:
                # Handle non-command text input here
                await self.context.print(f"Echo: {value}")
            ```
        """

        def decorator(
            method: Callable[[Any, str], Awaitable[None]],
        ) -> Callable[[Any, str], Awaitable[None]]:
            # Store the handler method name for this class and input
            cls._command_handlers.setdefault(cls.__name__, {})[input_id] = getattr(
                method, "__name__", "unknown"
            )
            return method

        return decorator

    async def on_input_submitted(self) -> None:
        """Handle input submission."""
        input_widget = self.query_one("#command-input", Input)
        value = input_widget.value

        if value.startswith("/"):
            # Execute command
            cmd = value[1:]
            try:
                await self.store.execute_command(cmd, self.context)
            except Exception as e:  # noqa: BLE001
                self.log(f"Error: {e}")
            input_widget.value = ""
            return

        # For non-command input, call handler only if registered
        handlers = self._command_handlers.get(self.__class__.__name__, {})
        if input_widget.id in handlers:
            handler_name = handlers[input_widget.id]
            handler = getattr(self, handler_name)
            await handler(value)
            input_widget.value = ""

__init__

__init__(
    store: CommandStore | None = None,
    data: TContext | None = None,
    commands: list[type[SlashedCommand] | BaseCommand] | None = None,
    *args: Any,
    **kwargs: Any,
) -> None

Initialize app with command store.

Parameters:

Name Type Description Default
data TContext | None

Optional context data

None
commands list[type[SlashedCommand] | BaseCommand] | None

Optional list of commands to register

None
store CommandStore | None

Optional command store (creates new one if not provided)

None
*args Any

Arguments passed to textual.App

()
**kwargs Any

Keyword arguments passed to textual.App

{}
Source code in src/slashed/textual_adapter/app.py
def __init__(
    self,
    store: CommandStore | None = None,
    data: TContext | None = None,
    commands: list[type[SlashedCommand] | BaseCommand] | None = None,
    *args: Any,
    **kwargs: Any,
) -> None:
    """Initialize app with command store.

    Args:
        data: Optional context data
        commands: Optional list of commands to register
        store: Optional command store (creates new one if not provided)
        *args: Arguments passed to textual.App
        **kwargs: Keyword arguments passed to textual.App
    """
    super().__init__(*args, **kwargs)
    self.store = store or CommandStore()
    self.store._initialize_sync()
    writer = TextualOutputWriter(self)
    self.context = self.store.create_context(data=data, output_writer=writer)
    if commands:
        for command in commands:
            self.store.register_command(command)

bind_output

bind_output(output_id: str, widget_query: str, default: bool = False) -> None

Bind an output stream to a widget.

Parameters:

Name Type Description Default
output_id str

ID for this output stream

required
widget_query str

CSS query to find the target widget

required
default bool

Whether this is the default output

False
Source code in src/slashed/textual_adapter/app.py
def bind_output(self, output_id: str, widget_query: str, default: bool = False) -> None:
    """Bind an output stream to a widget.

    Args:
        output_id: ID for this output stream
        widget_query: CSS query to find the target widget
        default: Whether this is the default output
    """
    writer = self.context.output
    if not isinstance(writer, TextualOutputWriter):
        msg = "Output writer is not a TextualOutputWriter"
        raise TypeError(msg)
    writer.bind(output_id, widget_query, default=default)

command_input classmethod

command_input(
    input_id: str,
) -> Callable[[Callable[[Any, str], Awaitable[None]]], Callable[[Any, str], Awaitable[None]]]

Register an Input widget to handle commands.

Parameters:

Name Type Description Default
input_id str

ID of the Input widget that should handle commands

required
Example
@command_input("my-input")
async def handle_my_input(self, value: str) -> None:
    # Handle non-command text input here
    await self.context.print(f"Echo: {value}")
Source code in src/slashed/textual_adapter/app.py
@classmethod
def command_input(
    cls,
    input_id: str,
) -> Callable[[Callable[[Any, str], Awaitable[None]]], Callable[[Any, str], Awaitable[None]]]:
    """Register an Input widget to handle commands.

    Args:
        input_id: ID of the Input widget that should handle commands

    Example:
        ```python
        @command_input("my-input")
        async def handle_my_input(self, value: str) -> None:
            # Handle non-command text input here
            await self.context.print(f"Echo: {value}")
        ```
    """

    def decorator(
        method: Callable[[Any, str], Awaitable[None]],
    ) -> Callable[[Any, str], Awaitable[None]]:
        # Store the handler method name for this class and input
        cls._command_handlers.setdefault(cls.__name__, {})[input_id] = getattr(
            method, "__name__", "unknown"
        )
        return method

    return decorator

get_suggester

get_suggester() -> SlashedSuggester

Get a suggester configured for this app's store and context.

Source code in src/slashed/textual_adapter/app.py
def get_suggester(self) -> SlashedSuggester:
    """Get a suggester configured for this app's store and context."""
    return SlashedSuggester(store=self.store, context=self.context)

on_input_submitted async

on_input_submitted() -> None

Handle input submission.

Source code in src/slashed/textual_adapter/app.py
async def on_input_submitted(self) -> None:
    """Handle input submission."""
    input_widget = self.query_one("#command-input", Input)
    value = input_widget.value

    if value.startswith("/"):
        # Execute command
        cmd = value[1:]
        try:
            await self.store.execute_command(cmd, self.context)
        except Exception as e:  # noqa: BLE001
            self.log(f"Error: {e}")
        input_widget.value = ""
        return

    # For non-command input, call handler only if registered
    handlers = self._command_handlers.get(self.__class__.__name__, {})
    if input_widget.id in handlers:
        handler_name = handlers[input_widget.id]
        handler = getattr(self, handler_name)
        await handler(value)
        input_widget.value = ""

SlashedSuggester

Bases: Suggester

Adapts a Slashed CompletionProvider to Textual's Suggester interface.

Source code in src/slashed/textual_adapter/suggester.py
class SlashedSuggester(Suggester):
    """Adapts a Slashed CompletionProvider to Textual's Suggester interface."""

    def __init__(
        self,
        store: CommandStore,
        context: CommandContext[Any],
        case_sensitive: bool = False,
    ) -> None:
        """Initialize suggester with store and context.

        Args:
            store: Command store for looking up commands and completers
            context: Command execution context
            case_sensitive: Whether to use case-sensitive matching
        """
        super().__init__(case_sensitive=case_sensitive)
        self._store = store
        self.context = context

    async def get_suggestion(self, value: str) -> str | None:  # noqa: PLR0911
        """Get completion suggestion for current input value."""
        if not value.startswith("/"):
            return None

        if value == "/":
            return None

        # Create document for current input
        document = Document(text=value, cursor_position=len(value))
        completion_context = CompletionContext(document=document, command_context=self.context)

        try:
            # If we have a command, use its completer
            if " " in value:  # Has arguments
                cmd_name = value.split(maxsplit=1)[0][1:]  # Remove slash
                if command := self._store.get_command(cmd_name):  # noqa: SIM102
                    if completer := command.get_completer():
                        current_word = completion_context.current_word
                        # Find first matching completion
                        async for completion in completer.get_completions(completion_context):
                            if not current_word or completion.text.startswith(current_word):
                                # For argument completion, preserve the cmd part
                                cmd_part = value[: value.find(" ") + 1]
                                # If we have a current word, replace it
                                if current_word:
                                    cmd_part = value[: -len(current_word)]
                                return f"{cmd_part}{completion.text}"
                        return None

                return None

            # Otherwise complete command names
            word = value[1:]  # Remove slash
            for cmd in self._store.list_commands():
                if cmd.name.startswith(word):
                    return f"/{cmd.name}"

        except Exception:  # noqa: BLE001
            return None

        return None

__init__

__init__(store: CommandStore, context: CommandContext[Any], case_sensitive: bool = False) -> None

Initialize suggester with store and context.

Parameters:

Name Type Description Default
store CommandStore

Command store for looking up commands and completers

required
context CommandContext[Any]

Command execution context

required
case_sensitive bool

Whether to use case-sensitive matching

False
Source code in src/slashed/textual_adapter/suggester.py
def __init__(
    self,
    store: CommandStore,
    context: CommandContext[Any],
    case_sensitive: bool = False,
) -> None:
    """Initialize suggester with store and context.

    Args:
        store: Command store for looking up commands and completers
        context: Command execution context
        case_sensitive: Whether to use case-sensitive matching
    """
    super().__init__(case_sensitive=case_sensitive)
    self._store = store
    self.context = context

get_suggestion async

get_suggestion(value: str) -> str | None

Get completion suggestion for current input value.

Source code in src/slashed/textual_adapter/suggester.py
async def get_suggestion(self, value: str) -> str | None:  # noqa: PLR0911
    """Get completion suggestion for current input value."""
    if not value.startswith("/"):
        return None

    if value == "/":
        return None

    # Create document for current input
    document = Document(text=value, cursor_position=len(value))
    completion_context = CompletionContext(document=document, command_context=self.context)

    try:
        # If we have a command, use its completer
        if " " in value:  # Has arguments
            cmd_name = value.split(maxsplit=1)[0][1:]  # Remove slash
            if command := self._store.get_command(cmd_name):  # noqa: SIM102
                if completer := command.get_completer():
                    current_word = completion_context.current_word
                    # Find first matching completion
                    async for completion in completer.get_completions(completion_context):
                        if not current_word or completion.text.startswith(current_word):
                            # For argument completion, preserve the cmd part
                            cmd_part = value[: value.find(" ") + 1]
                            # If we have a current word, replace it
                            if current_word:
                                cmd_part = value[: -len(current_word)]
                            return f"{cmd_part}{completion.text}"
                    return None

            return None

        # Otherwise complete command names
        word = value[1:]  # Remove slash
        for cmd in self._store.list_commands():
            if cmd.name.startswith(word):
                return f"/{cmd.name}"

    except Exception:  # noqa: BLE001
        return None

    return None

TextualOutputWriter

Bases: OutputWriter

Output writer that routes messages to bound widgets.

Supports different widget types: - Labels: Direct update of content - VerticalScroll/Container: Mount new Label with content - Other widgets: Try update() method

Source code in src/slashed/textual_adapter/app.py
class TextualOutputWriter(OutputWriter):
    """Output writer that routes messages to bound widgets.

    Supports different widget types:
    - Labels: Direct update of content
    - VerticalScroll/Container: Mount new Label with content
    - Other widgets: Try update() method
    """

    def __init__(self, app: App[Any]) -> None:
        self.app = app
        self._bindings: dict[str, str] = {}
        self._default_binding: str | None = None

    def bind(self, output_id: str, widget_query: str, default: bool = False) -> None:
        """Bind an output to a widget.

        Args:
            output_id: ID for this output stream
            widget_query: CSS query to find the target widget
            default: Whether this is the default output for unspecified streams
        """
        self._bindings[output_id] = widget_query
        if default:
            self._default_binding = output_id

    async def print(self, message: str, output_id: str | None = None) -> None:
        """Print message to bound widget.

        Args:
            message: Message to display
            output_id: Optional output stream ID. Uses default if not specified.

        The message is handled differently based on widget type:
        - For containers (VerticalScroll/Container): Mount new Label
        - For Label widgets: Update content
        - For other widgets: Try update() method

        Raises:
            ValueError: If no default binding is configured or binding not found
            TypeError: If widget type is not supported
        """
        if output_id is None and self._default_binding is None:
            msg = "No default output binding configured"
            raise ValueError(msg)

        binding = self._bindings.get(
            output_id or self._default_binding,
        )
        if not binding:
            msg = f"No binding found for output: {output_id}"
            raise ValueError(msg)

        widget = self.app.query_one(binding)
        if isinstance(widget, VerticalScroll | Container):
            widget.mount(Label(message))
        elif isinstance(widget, Label):
            widget.update(message)
        else:
            try:
                widget.update(message)  # type: ignore
            except AttributeError as e:
                msg = f"Widget {type(widget).__name__} does not support update()"
                raise TypeError(msg) from e

bind

bind(output_id: str, widget_query: str, default: bool = False) -> None

Bind an output to a widget.

Parameters:

Name Type Description Default
output_id str

ID for this output stream

required
widget_query str

CSS query to find the target widget

required
default bool

Whether this is the default output for unspecified streams

False
Source code in src/slashed/textual_adapter/app.py
def bind(self, output_id: str, widget_query: str, default: bool = False) -> None:
    """Bind an output to a widget.

    Args:
        output_id: ID for this output stream
        widget_query: CSS query to find the target widget
        default: Whether this is the default output for unspecified streams
    """
    self._bindings[output_id] = widget_query
    if default:
        self._default_binding = output_id

print async

print(message: str, output_id: str | None = None) -> None

Print message to bound widget.

Parameters:

Name Type Description Default
message str

Message to display

required
output_id str | None

Optional output stream ID. Uses default if not specified.

None

The message is handled differently based on widget type: - For containers (VerticalScroll/Container): Mount new Label - For Label widgets: Update content - For other widgets: Try update() method

Raises:

Type Description
ValueError

If no default binding is configured or binding not found

TypeError

If widget type is not supported

Source code in src/slashed/textual_adapter/app.py
async def print(self, message: str, output_id: str | None = None) -> None:
    """Print message to bound widget.

    Args:
        message: Message to display
        output_id: Optional output stream ID. Uses default if not specified.

    The message is handled differently based on widget type:
    - For containers (VerticalScroll/Container): Mount new Label
    - For Label widgets: Update content
    - For other widgets: Try update() method

    Raises:
        ValueError: If no default binding is configured or binding not found
        TypeError: If widget type is not supported
    """
    if output_id is None and self._default_binding is None:
        msg = "No default output binding configured"
        raise ValueError(msg)

    binding = self._bindings.get(
        output_id or self._default_binding,
    )
    if not binding:
        msg = f"No binding found for output: {output_id}"
        raise ValueError(msg)

    widget = self.app.query_one(binding)
    if isinstance(widget, VerticalScroll | Container):
        widget.mount(Label(message))
    elif isinstance(widget, Label):
        widget.update(message)
    else:
        try:
            widget.update(message)  # type: ignore
        except AttributeError as e:
            msg = f"Widget {type(widget).__name__} does not support update()"
            raise TypeError(msg) from e