Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/textual/binding.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@

from textual._callback import invoke, invoke_sync
from textual.actions import SkipAction
from textual.keys import DeclaredKey, KeyDeclaration, KeyInvocation, UndecodedKey, _character_to_key
from metaclass_registry.key_declarations import KeyDeclaration, KeyInvocation

from textual.keys import DeclaredKey, UndecodedKey, _character_to_key

if TYPE_CHECKING:
from textual.document._editing import EditingMode
Expand Down
12 changes: 5 additions & 7 deletions src/textual/document/_editing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING

from metaclass_registry.key_declarations import InputMode, ModalInputMode

from textual.binding import Binding, MethodBinding
from textual.cursor_shape import CursorShape, SteadyBlock, TextEntryCursor
from textual.document._document import EditResult, Location, Selection
from textual.document._document import EditResult, Selection
from textual.document._edit import Edit, InsertionPoint

if TYPE_CHECKING:
Expand All @@ -19,11 +21,9 @@ class EditingFailure(RuntimeError):
"""The engine failed; preserve its displayed draft and never replay input."""


class EditingMode:
class EditingMode(InputMode):
"""Native text entry, with overridable document and input ownership."""

modal = False

@classmethod
def navigation_spellings(cls, key: type[NavigationKey]) -> tuple[str, ...]:
return (key.key.value,)
Expand Down Expand Up @@ -164,11 +164,9 @@ def allows_application_commands(self) -> bool:
return self.key_mode().allows_application_commands


class VimMode(EditingMode, ABC):
class VimMode(EditingMode, ModalInputMode, ABC):
"""Modal binding capability, not a second implementation of Vim."""

modal = True

@classmethod
def navigation_spellings(cls, key: type[NavigationKey]) -> tuple[str, ...]:
return (*super().navigation_spellings(key), key.modal)
Expand Down
13 changes: 5 additions & 8 deletions src/textual/dom.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import threading
from weakref import ref
from functools import lru_cache, partial
from dataclasses import replace
from inspect import getfile
from typing import (
TYPE_CHECKING,
Expand Down Expand Up @@ -53,9 +52,8 @@
from textual.geometry import Size
from textual.css.tokenize import IDENTIFIER
from textual.message_pump import MessagePump
from textual.keys import KeyDeclaration
from textual.keys import BindingDeclaration
from textual.reactive import Reactive, ReactiveError, _Mutated, _StoredReactiveAccess, _watch
from textual.style import NULL_STYLE
from textual.timer import Timer
from textual.walk import walk_breadth_first, walk_breadth_search_id, walk_depth_first
from textual.worker_manager import WorkerManager
Expand All @@ -71,7 +69,6 @@
from textual.screen import Screen
from textual.widget import Widget
from textual.events import Key
from textual.widgets import TextArea
from textual.worker import Worker, WorkType, ResultType

from typing_extensions import Literal
Expand Down Expand Up @@ -529,8 +526,8 @@ def _component_styles(self) -> dict[str, RenderStyles]:
return {}

_declared_key_bindings: ClassVar[tuple[MethodBinding, ...]] = ()
_own_key_families: ClassVar[tuple[type[KeyDeclaration], ...]] = ()
key_families: ClassVar[tuple[type[KeyDeclaration], ...]] = ()
_own_key_families: ClassVar[tuple[type[BindingDeclaration], ...]] = ()
key_families: ClassVar[tuple[type[BindingDeclaration], ...]] = ()

@classmethod
def contexts(cls) -> tuple[type[DOMNode], ...]:
Expand All @@ -556,7 +553,7 @@ def native_bindings(cls, mode: type[EditingMode]) -> tuple[ModeBinding, ...]:
for projected in binding.for_mode(mode))

@classmethod
def present_binding(cls, declaration: type[KeyDeclaration], binding: Binding) -> Binding:
def present_binding(cls, declaration: type[BindingDeclaration], binding: Binding) -> Binding:
return binding

@classmethod
Expand Down Expand Up @@ -1005,7 +1002,7 @@ def __init_subclass__(
inherit_css: bool = True,
inherit_bindings: bool = True,
inherit_component_classes: bool = True,
key_families: tuple[type[KeyDeclaration], ...] = (),
key_families: tuple[type[BindingDeclaration], ...] = (),
) -> None:
cls._own_key_families = key_families
cls.key_families = tuple(dict.fromkeys(
Expand Down
125 changes: 7 additions & 118 deletions src/textual/keys.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
from __future__ import annotations

import unicodedata
import inspect
import re
from abc import ABC, ABCMeta, abstractmethod
from typing import TYPE_CHECKING, Callable, ClassVar, Generic, Iterator, TypeVar
from abc import abstractmethod
from typing import TYPE_CHECKING, ClassVar, TypeVar
from enum import Enum
from dataclasses import dataclass
from functools import lru_cache
Expand All @@ -15,130 +13,21 @@
from textual.dom import DOMNode
from textual.events import Key

NodeT = TypeVar("NodeT", bound="DOMNode", contravariant=True)


class KeyDeclarationType(ABCMeta):
"""A key-declaring class, including declarations supplied by a metaclass."""

def permits_key_overlap(cls, other: KeyDeclarationType) -> bool:
"""An explicitly declared alternative may share this declaration's key."""
return False


class KeyInvocation(ABC):
"""The concrete command a binding invokes, independent of its active mode."""

@staticmethod
def qualified(declaration: type | Callable[..., object]) -> str:
return f"{declaration.__module__}.{declaration.__qualname__}"

@abstractmethod
def key_identity(self) -> str: ...

@abstractmethod
def key_title(self) -> str: ...

@abstractmethod
def key_summary(self) -> str: ...

@abstractmethod
def key_system(self) -> bool: ...

def binding_identity(self, mode: type[EditingMode]) -> str:
return self.in_mode(self.key_identity(), mode)

@staticmethod
def in_mode(identity: str, mode: type) -> str:
return f"{identity}:{KeyInvocation.qualified(mode)}"

def visible_for_focus(self, focused: bool) -> bool:
"""Local commands follow their declaration's actual prior-focus membership."""
return focused

def permits_invocation_overlap(self, other: KeyInvocation) -> bool:
return False

def overlaps_declaration(self, other: KeyDeclarationType) -> bool:
return False


class KeyTitle:
"""Human text derived from the declaration rather than a second title roster."""

def __get__(self, instance: object, owner: type[KeyDeclaration]) -> str:
return owner.default_title()

from metaclass_registry.key_declarations import KeyDeclaration, KeyInvocation

class KeyDeclaration(KeyInvocation, Generic[NodeT], metaclass=KeyDeclarationType):
"""Shared metadata for application actions and native editor commands.

Each provider retains its existing family registry. This view discovers the
provider declarations through inheritance; no menu supplies their names.
"""

title = KeyTitle()
system: ClassVar[bool] = False
_declared: ClassVar[list[type[KeyDeclaration]]] = []

def __init_subclass__(cls, **kwargs) -> None:
super().__init_subclass__(**kwargs)
KeyDeclaration._declared.append(cls)

@classmethod
def default_title(cls) -> str:
return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", " ", cls.__name__).capitalize()

@classmethod
def identity(cls) -> str:
return cls.qualified(cls)

@classmethod
def binding_id(cls, mode: type) -> str:
return cls.binding_id_for(cls, mode)

@staticmethod
def binding_id_for(declaration: type | Callable[..., object], mode: type) -> str:
"""Class and native callable declarations use the same mode-qualified identity."""
return KeyInvocation.in_mode(KeyInvocation.qualified(declaration), mode)

def key_identity(self) -> str:
return type(self).identity()

def key_title(self) -> str:
return self.title

def key_summary(self) -> str:
return self.summary()

def key_system(self) -> bool:
return self.system

def permits_invocation_overlap(self, other: KeyInvocation) -> bool:
return other.overlaps_declaration(type(self))
NodeT = TypeVar("NodeT", bound="DOMNode", contravariant=True)

def overlaps_declaration(self, other: KeyDeclarationType) -> bool:
return type(self).permits_key_overlap(other)

@abstractmethod
def __call__(self, node: NodeT) -> object: ...
class BindingDeclaration(KeyDeclaration[NodeT]):
"""A key declaration whose class projects its own Textual bindings, as a DOM node's
key families ask it to."""

@classmethod
@abstractmethod
def bindings_for(cls, mode: type[EditingMode]) -> tuple[Binding, ...]:
"""The declaration's defaults in one active editing mode."""
raise NotImplementedError

@classmethod
def summary(cls) -> str:
return inspect.cleandoc(cls.__doc__ or "")

@classmethod
def declarations(cls) -> Iterator[type[KeyDeclaration]]:
"""Project each key family from the declaration owner's registry."""
return (member for member in KeyDeclaration._declared
if issubclass(member, cls) and not inspect.isabstract(member))


# Adapted from prompt toolkit https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/prompt_toolkit/keys.py
class Keys(str, Enum): # type: ignore[no-redef]
Expand Down
4 changes: 2 additions & 2 deletions src/textual/navigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
from textual.binding import Binding, CommandBinding
from textual.document._editing import EditingMode
from textual.dom import DOMNode
from textual.keys import DeclaredKey, DownKey, KeyDeclaration, LeftKey, RightKey, UndecodedKey, UpKey
from textual.keys import BindingDeclaration, DeclaredKey, DownKey, LeftKey, RightKey, UndecodedKey, UpKey


class NavigationCommand(KeyDeclaration["Navigation"]):
class NavigationCommand(BindingDeclaration["Navigation"]):
"""A list command owns its keys; controls own the operation it requests."""

keys: ClassVar[tuple[str, ...]] = ()
Expand Down
3 changes: 2 additions & 1 deletion tests/input/test_input_key_movement_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@

from textual.app import App, ComposeResult
from textual.document._editing import EditingMode
from textual.keys import KeyInvocation, LeftKey, RightKey
from metaclass_registry.key_declarations import KeyInvocation
from textual.keys import LeftKey, RightKey
from textual.widgets import Input


Expand Down
3 changes: 2 additions & 1 deletion tests/text_area/test_edit_via_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
from textual.app import App, ComposeResult
from textual.document._editing import EditingMode
from textual.events import Paste
from textual.keys import KeyInvocation, LeftKey
from metaclass_registry.key_declarations import KeyInvocation
from textual.keys import LeftKey
from textual.widgets import TextArea
from textual.widgets.text_area import Selection

Expand Down