diff --git a/src/textual/_xterm_parser.py b/src/textual/_xterm_parser.py index edf587a3f9..ba37faebfa 100644 --- a/src/textual/_xterm_parser.py +++ b/src/textual/_xterm_parser.py @@ -221,9 +221,7 @@ def reissue_sequence_as_keys(reissue_sequence: str) -> None: for event in sequence_to_key_events(character): on_token(event) - def _sequence_to_key_events( - self, sequence: str, _unicode_name=unicodedata.name - ) -> Iterable[events.Key]: + def _sequence_to_key_events(self, sequence: str) -> Iterable[events.Key]: """Map a sequence of code points on to a sequence of keys. Args: @@ -237,12 +235,5 @@ def _sequence_to_key_events( for key in keys: yield events.Key(key.value, sequence if len(sequence) == 1 else None) elif len(sequence) == 1: - try: - if not sequence.isalnum(): - name = _character_to_key(sequence) - else: - name = sequence - name = KEY_NAME_REPLACEMENTS.get(name, name) - yield events.Key(name, sequence) - except: - yield events.Key(sequence, sequence) + name = _character_to_key(sequence) + yield events.Key(name, sequence) diff --git a/src/textual/keys.py b/src/textual/keys.py index ef32404d16..6631cc9544 100644 --- a/src/textual/keys.py +++ b/src/textual/keys.py @@ -304,10 +304,20 @@ def _get_key_display(key: str) -> str: def _character_to_key(character: str) -> str: """Convert a single character to a key value. + If `character` has no key value, return it unchanged. + This transformation can be undone by the function `_get_unicode_name_from_key`. """ if not character.isalnum(): - key = unicodedata.name(character).lower().replace("-", "_").replace(" ", "_") + try: + key = unicodedata.name(character) + except (TypeError, ValueError): + # ValueError: `character` has no name. Control characters, for + # example, have no name: https://stackoverflow.com/questions/70074668 + # TypeError: `character` is not a single character. + key = character + else: + key = key.lower().replace("-", "_").replace(" ", "_") else: key = character key = KEY_NAME_REPLACEMENTS.get(key, key) diff --git a/tests/test_keys.py b/tests/test_keys.py index 9f13e17d17..3abaf64898 100644 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -17,6 +17,7 @@ ("?", "question_mark"), ("£", "pound_sign"), (",", "comma"), + (r"\t", r"\t"), ], ) def test_character_to_key(character: str, key: str) -> None: