Skip to content

PromptToolkitCompleter

Base classes

Name Children Inherits
Completer
prompt_toolkit.completion.base
Base class for completer implementations.
Generic
typing
Abstract base class for generic types.

⋔ Inheritance diagram

graph TD
  2086554691["prompt_toolkit_completer.PromptToolkitCompleter"]
  611945851["base.Completer"]
  2751680898["builtins.object"]
  3481597255["typing.Generic"]
  611945851 --> 2086554691
  2751680898 --> 611945851
  3481597255 --> 2086554691
  2751680898 --> 3481597255

🛈 DocStrings

Bases: Completer

Adapts our completion system to prompt-toolkit.

Source code in src/slashed/prompt_toolkit_completer.py
class PromptToolkitCompleter[TContextData = Any](Completer):
    """Adapts our completion system to prompt-toolkit."""

    def __init__(
        self,
        store: CommandStore | None = None,
        data: TContextData | None = None,
        output_writer: OutputWriter | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> None:
        """Initialize completer.

        Args:
            store: Command store. Creates an empty one if not provided.
            data: Context data
            output_writer: Optional custom output writer
            metadata: Additional metadata
        """
        self._store = store or CommandStore()
        # Cast to CommandContext[T] since we know the type is preserved
        self._context: CommandContext[TContextData] = self._store.create_context(
            data, output_writer, metadata
        )

    def get_completions(self, document: Document, complete_event: Any) -> Iterable[Completion]:
        """Sync completions - not used but required by interface."""
        return []

    async def get_completions_async(
        self, document: Document, complete_event: Any
    ) -> AsyncGenerator[Completion]:
        """Get completions for the current context."""
        text = document.text.lstrip()

        if not text.startswith("/"):
            return

        completion_context = CompletionContext[TContextData](
            document, command_context=self._context
        )

        try:
            # If we have a command, use its completer
            if " " in text:  # Has arguments
                cmd_name = text.split()[0][1:]  # Remove slash
                if (command := self._store.get_command(cmd_name)) and (
                    completer := command.get_completer()
                ):
                    current_word = completion_context.current_word
                    async for item in completer.get_completions(completion_context):
                        if current_word and not item.text.startswith(current_word):
                            continue
                        start_pos = -len(current_word) if current_word else 0
                        yield Completion(
                            item.text,
                            start_position=start_pos,
                            display_meta=get_first_line(item.metadata),
                        )
                    return

            # Otherwise complete command names
            word = text[1:]  # Remove slash
            for cmd in self._store.list_commands():
                if cmd.name.startswith(word):
                    yield Completion(
                        cmd.name,
                        start_position=-len(word),
                        display_meta=get_first_line(cmd.description),
                    )

        except RuntimeError as e:
            if "No command context available" in str(e):
                logger.debug(
                    "Command completion failed: command context not provided to "
                    "PromptToolkitCompleter. This is required for argument completion "
                    "but command name completion will still work. Text: '%s'",
                    text,
                )
            else:
                msg = "Unexpected RuntimeError during completion for text '%s': %s"
                logger.debug(msg, text, str(e), exc_info=True)
        except Exception as e:
            msg = "Completion failed for text '%s': %s (%s)"
            logger.debug(msg, text, str(e), type(e).__name__, exc_info=True)

__init__

__init__(
    store: CommandStore | None = None,
    data: TContextData | None = None,
    output_writer: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> None

Initialize completer.

Parameters:

Name Type Description Default
store CommandStore | None

Command store. Creates an empty one if not provided.

None
data TContextData | None

Context data

None
output_writer OutputWriter | None

Optional custom output writer

None
metadata dict[str, Any] | None

Additional metadata

None
Source code in src/slashed/prompt_toolkit_completer.py
def __init__(
    self,
    store: CommandStore | None = None,
    data: TContextData | None = None,
    output_writer: OutputWriter | None = None,
    metadata: dict[str, Any] | None = None,
) -> None:
    """Initialize completer.

    Args:
        store: Command store. Creates an empty one if not provided.
        data: Context data
        output_writer: Optional custom output writer
        metadata: Additional metadata
    """
    self._store = store or CommandStore()
    # Cast to CommandContext[T] since we know the type is preserved
    self._context: CommandContext[TContextData] = self._store.create_context(
        data, output_writer, metadata
    )

get_completions

get_completions(document: Document, complete_event: Any) -> Iterable[Completion]

Sync completions - not used but required by interface.

Source code in src/slashed/prompt_toolkit_completer.py
def get_completions(self, document: Document, complete_event: Any) -> Iterable[Completion]:
    """Sync completions - not used but required by interface."""
    return []

get_completions_async async

get_completions_async(document: Document, complete_event: Any) -> AsyncGenerator[Completion]

Get completions for the current context.

Source code in src/slashed/prompt_toolkit_completer.py
async def get_completions_async(
    self, document: Document, complete_event: Any
) -> AsyncGenerator[Completion]:
    """Get completions for the current context."""
    text = document.text.lstrip()

    if not text.startswith("/"):
        return

    completion_context = CompletionContext[TContextData](
        document, command_context=self._context
    )

    try:
        # If we have a command, use its completer
        if " " in text:  # Has arguments
            cmd_name = text.split()[0][1:]  # Remove slash
            if (command := self._store.get_command(cmd_name)) and (
                completer := command.get_completer()
            ):
                current_word = completion_context.current_word
                async for item in completer.get_completions(completion_context):
                    if current_word and not item.text.startswith(current_word):
                        continue
                    start_pos = -len(current_word) if current_word else 0
                    yield Completion(
                        item.text,
                        start_position=start_pos,
                        display_meta=get_first_line(item.metadata),
                    )
                return

        # Otherwise complete command names
        word = text[1:]  # Remove slash
        for cmd in self._store.list_commands():
            if cmd.name.startswith(word):
                yield Completion(
                    cmd.name,
                    start_position=-len(word),
                    display_meta=get_first_line(cmd.description),
                )

    except RuntimeError as e:
        if "No command context available" in str(e):
            logger.debug(
                "Command completion failed: command context not provided to "
                "PromptToolkitCompleter. This is required for argument completion "
                "but command name completion will still work. Text: '%s'",
                text,
            )
        else:
            msg = "Unexpected RuntimeError during completion for text '%s': %s"
            logger.debug(msg, text, str(e), exc_info=True)
    except Exception as e:
        msg = "Completion failed for text '%s': %s (%s)"
        logger.debug(msg, text, str(e), type(e).__name__, exc_info=True)

:fa-brands-github: Show source on GitHub