Skip to content

completion

Class info

Classes

Name Children Inherits
CommandCompleter
slashed.completion
Main command completion implementation.
    CompletionContext
    slashed.completion
    Context for completion operations.
      CompletionItem
      slashed.completion
      Single completion suggestion.
        CompletionProvider
        slashed.completion
        Base class for completion providers.

        🛈 DocStrings

        Command completion system.

        CommandCompleter

        Main command completion implementation.

        Source code in src/slashed/completion.py
        class CommandCompleter:
            """Main command completion implementation."""
        
            def __init__(self, commands: dict[str, BaseCommand]) -> None:
                """Initialize command completer.
        
                Args:
                    commands: Mapping of command names to command instances
                """
                self._commands = commands
                self._global_providers: list[CompletionProvider] = []
        
            def add_global_provider(self, provider: CompletionProvider) -> None:
                """Add a global completion provider."""
                self._global_providers.append(provider)
        
            async def get_completions(
                self,
                context: CompletionContext[Any],
            ) -> AsyncIterator[CompletionItem]:
                """Get completions for the current context."""
                # If at start of command, complete command names
                logger.debug("Getting completions for command %s", context.command_name)
                if not context.command_name:
                    word = context.current_word.lstrip("/")  # Remove slash for matching
                    matching_commands = [name for name in self._commands if name.startswith(word)]
        
                    # If exactly one match, complete it
                    if len(matching_commands) == 1:
                        meta = self._commands[matching_commands[0]].description
                        cmd = matching_commands[0]
                        yield CompletionItem(text=cmd, metadata=meta, kind="command")
                    # If multiple matches, show all
                    elif len(matching_commands) > 1:
                        for name in matching_commands:
                            meta = self._commands[name].description
                            yield CompletionItem(text=name, metadata=meta, kind="command")
                    return
                # Get command-specific completions
                # Get command-specific completions
                command = self._commands.get(context.command_name)
                if command and (completer := command.get_completer()):
                    logger.debug("Fetching completions for command %s", command.name)
                    async for item in completer.get_completions(context):
                        yield item
        
                # Get global completions
                for provider in self._global_providers:
                    logger.debug("Fetching completions for provider %r", provider)
                    async for item in provider.get_completions(context):
                        yield item
        

        __init__

        __init__(commands: dict[str, BaseCommand]) -> None
        

        Initialize command completer.

        Parameters:

        Name Type Description Default
        commands dict[str, BaseCommand]

        Mapping of command names to command instances

        required
        Source code in src/slashed/completion.py
        def __init__(self, commands: dict[str, BaseCommand]) -> None:
            """Initialize command completer.
        
            Args:
                commands: Mapping of command names to command instances
            """
            self._commands = commands
            self._global_providers: list[CompletionProvider] = []
        

        add_global_provider

        add_global_provider(provider: CompletionProvider) -> None
        

        Add a global completion provider.

        Source code in src/slashed/completion.py
        def add_global_provider(self, provider: CompletionProvider) -> None:
            """Add a global completion provider."""
            self._global_providers.append(provider)
        

        get_completions async

        get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]
        

        Get completions for the current context.

        Source code in src/slashed/completion.py
        async def get_completions(
            self,
            context: CompletionContext[Any],
        ) -> AsyncIterator[CompletionItem]:
            """Get completions for the current context."""
            # If at start of command, complete command names
            logger.debug("Getting completions for command %s", context.command_name)
            if not context.command_name:
                word = context.current_word.lstrip("/")  # Remove slash for matching
                matching_commands = [name for name in self._commands if name.startswith(word)]
        
                # If exactly one match, complete it
                if len(matching_commands) == 1:
                    meta = self._commands[matching_commands[0]].description
                    cmd = matching_commands[0]
                    yield CompletionItem(text=cmd, metadata=meta, kind="command")
                # If multiple matches, show all
                elif len(matching_commands) > 1:
                    for name in matching_commands:
                        meta = self._commands[name].description
                        yield CompletionItem(text=name, metadata=meta, kind="command")
                return
            # Get command-specific completions
            # Get command-specific completions
            command = self._commands.get(context.command_name)
            if command and (completer := command.get_completer()):
                logger.debug("Fetching completions for command %s", command.name)
                async for item in completer.get_completions(context):
                    yield item
        
            # Get global completions
            for provider in self._global_providers:
                logger.debug("Fetching completions for provider %r", provider)
                async for item in provider.get_completions(context):
                    yield item
        

        CompletionContext

        Context for completion operations.

        Class Type Parameters:

        Name Bound or Constraints Description Default
        TCommandData

        Type of the data in the associated CommandContext. Used when completions need to access the command context data.

        required
        Source code in src/slashed/completion.py
        class CompletionContext[TCommandData]:
            """Context for completion operations.
        
            Type Parameters:
                TCommandData: Type of the data in the associated CommandContext. Used when
                             completions need to access the command context data.
            """
        
            def __init__(
                self,
                document: Document,
                command_context: CommandContext[TCommandData] | None = None,
            ) -> None:
                """Initialize completion context.
        
                Args:
                    document: Current document being completed
                    command_context: Optional command execution context
                """
                self._document = document
                self._command_context = command_context
                self._command_name: str | None = None
                self._args: list[str] = []
                self._current_word: str = ""
                self._arg_position: int = 0
                self._parse_document()
        
            @property
            def command_context(self) -> CommandContext[TCommandData]:
                """Get command execution context.
        
                Returns:
                    Command context
        
                Raises:
                    RuntimeError: If command context is not set
                """
                if self._command_context is None:
                    msg = "No command context available"
                    raise RuntimeError(msg)
                return self._command_context
        
            def has_command_context(self) -> bool:
                """Check if command context is available."""
                return self._command_context is not None
        
            def _parse_document(self) -> None:
                """Parse document into command and arguments."""
                text = self._document.text.lstrip()
        
                if not text.startswith("/"):
                    self._command_name = None
                    self._args = []
                    self._current_word = self._document.get_word_before_cursor()
                    self._arg_position = 0
                    return
        
                parts = text[1:].split()
                self._command_name = parts[0] if parts else None
                self._args = parts[1:]
                self._current_word = self._document.get_word_before_cursor()
                self._arg_position = len(text[: self._document.cursor_position].split()) - 1
                logger.info(
                    "Parsed command %s with args %s. Current word: %s (position %d)",
                    self._command_name,
                    self._args,
                    self._current_word,
                    self._arg_position,
                )
        
            @property
            def command_name(self) -> str | None:
                """Get current command name if any."""
                return self._command_name
        
            @property
            def current_word(self) -> str:
                """Get word being completed."""
                return self._current_word
        
            @property
            def arg_position(self) -> int:
                """Get current argument position."""
                return self._arg_position
        
            @property
            def command_args(self) -> list[str]:
                """Get current command arguments."""
                return self._args
        

        arg_position property

        arg_position: int
        

        Get current argument position.

        command_args property

        command_args: list[str]
        

        Get current command arguments.

        command_context property

        command_context: CommandContext[TCommandData]
        

        Get command execution context.

        Returns:

        Type Description
        CommandContext[TCommandData]

        Command context

        Raises:

        Type Description
        RuntimeError

        If command context is not set

        command_name property

        command_name: str | None
        

        Get current command name if any.

        current_word property

        current_word: str
        

        Get word being completed.

        __init__

        __init__(document: Document, command_context: CommandContext[TCommandData] | None = None) -> None
        

        Initialize completion context.

        Parameters:

        Name Type Description Default
        document Document

        Current document being completed

        required
        command_context CommandContext[TCommandData] | None

        Optional command execution context

        None
        Source code in src/slashed/completion.py
        def __init__(
            self,
            document: Document,
            command_context: CommandContext[TCommandData] | None = None,
        ) -> None:
            """Initialize completion context.
        
            Args:
                document: Current document being completed
                command_context: Optional command execution context
            """
            self._document = document
            self._command_context = command_context
            self._command_name: str | None = None
            self._args: list[str] = []
            self._current_word: str = ""
            self._arg_position: int = 0
            self._parse_document()
        

        has_command_context

        has_command_context() -> bool
        

        Check if command context is available.

        Source code in src/slashed/completion.py
        def has_command_context(self) -> bool:
            """Check if command context is available."""
            return self._command_context is not None
        

        CompletionItem dataclass

        Single completion suggestion.

        Source code in src/slashed/completion.py
        @dataclass
        class CompletionItem:
            """Single completion suggestion."""
        
            text: str
            """Text to insert"""
        
            display: str | None = None
            """Optional display text (defaults to text)"""
        
            metadata: str | None = None
            """Additional information to show"""
        
            kind: CompletionKind | None = None
            """Type of completion item"""
        
            sort_text: str | None = None
            """Optional text to use for sorting (defaults to text)"""
        

        display class-attribute instance-attribute

        display: str | None = None
        

        Optional display text (defaults to text)

        kind class-attribute instance-attribute

        kind: CompletionKind | None = None
        

        Type of completion item

        metadata class-attribute instance-attribute

        metadata: str | None = None
        

        Additional information to show

        sort_text class-attribute instance-attribute

        sort_text: str | None = None
        

        Optional text to use for sorting (defaults to text)

        text instance-attribute

        text: str
        

        Text to insert

        CompletionProvider

        Bases: ABC

        Base class for completion providers.

        Source code in src/slashed/completion.py
        class CompletionProvider(ABC):
            """Base class for completion providers."""
        
            @abstractmethod
            def get_completions(
                self,
                context: CompletionContext[Any],
            ) -> AsyncIterator[CompletionItem]:
                """Get completion suggestions."""
        

        get_completions abstractmethod

        get_completions(context: CompletionContext[Any]) -> AsyncIterator[CompletionItem]
        

        Get completion suggestions.

        Source code in src/slashed/completion.py
        @abstractmethod
        def get_completions(
            self,
            context: CompletionContext[Any],
        ) -> AsyncIterator[CompletionItem]:
            """Get completion suggestions."""