diff --git a/docs/pages/asking_for_a_choice.rst b/docs/pages/asking_for_a_choice.rst index 8898c31f7..c9f87c497 100644 --- a/docs/pages/asking_for_a_choice.rst +++ b/docs/pages/asking_for_a_choice.rst @@ -25,6 +25,8 @@ from a list of options: .. image:: ../images/choice-input.png +By default, a number key highlights a choice and Enter confirms it. Pass +``accept_on_number=True`` to confirm choices 1 through 9 with a single key. Coloring the options -------------------- diff --git a/src/prompt_toolkit/shortcuts/choice_input.py b/src/prompt_toolkit/shortcuts/choice_input.py index f8aaf5962..b1e952e53 100644 --- a/src/prompt_toolkit/shortcuts/choice_input.py +++ b/src/prompt_toolkit/shortcuts/choice_input.py @@ -81,6 +81,8 @@ class ChoiceInput(Generic[_T]): :class:`~prompt_toolkit.filters.Filter`. When True, surround the input with a frame. :param show_numbers: Whether to show the option numbers in front of each choice. + :param accept_on_number: Accept one of the first nine choices immediately + when its number is pressed. :param enable_interrupt: `bool` or :class:`~prompt_toolkit.filters.Filter`. When True, raise the ``interrupt_exception`` (``KeyboardInterrupt`` by default) when @@ -101,6 +103,7 @@ def __init__( bottom_toolbar: AnyFormattedText = None, show_frame: FilterOrBool = False, show_numbers: bool = True, + accept_on_number: bool = False, enable_suspend: FilterOrBool = False, enable_interrupt: FilterOrBool = True, interrupt_exception: type[BaseException] = KeyboardInterrupt, @@ -117,6 +120,7 @@ def __init__( self.symbol = symbol self.show_frame = show_frame self.show_numbers = show_numbers + self.accept_on_number = accept_on_number self.enable_suspend = enable_suspend self.interrupt_exception = interrupt_exception self.enable_interrupt = enable_interrupt @@ -124,6 +128,12 @@ def __init__( self.key_bindings = key_bindings def _create_application(self) -> Application[_T]: + kb = KeyBindings() + + @kb.add("enter", eager=True) + def _accept_input(event: E) -> None: + event.app.exit(result=radio_list.current_value, style="class:accepted") + radio_list = RadioList( values=self.options, default=self.default, @@ -133,6 +143,7 @@ def _create_application(self) -> Application[_T]: close_character="", show_cursor=False, show_numbers=self.show_numbers, + on_number=_accept_input if self.accept_on_number else None, container_style="class:input-selection", default_style="class:option", selected_style="", @@ -202,13 +213,6 @@ def show_frame_filter() -> bool: focused_element=radio_list, ) - kb = KeyBindings() - - @kb.add("enter", eager=True) - def _accept_input(event: E) -> None: - "Accept input when enter has been pressed." - event.app.exit(result=radio_list.current_value, style="class:accepted") - @Condition def enable_interrupt() -> bool: return to_filter(self.enable_interrupt)() @@ -259,6 +263,7 @@ def choice( symbol: str = ">", bottom_toolbar: AnyFormattedText = None, show_frame: bool = False, + accept_on_number: bool = False, enable_suspend: FilterOrBool = False, enable_interrupt: FilterOrBool = True, interrupt_exception: type[BaseException] = KeyboardInterrupt, @@ -285,6 +290,8 @@ def choice( :param default: Default value. If none is given, the first option is considered the default. :param mouse_support: Enable mouse support. + :param accept_on_number: Accept one of the first nine choices immediately + when its number is pressed. :param style: :class:`.Style` instance for the color scheme. :param symbol: Symbol to be displayed in front of the selected choice. :param bottom_toolbar: Formatted text or callable that returns formatted @@ -308,6 +315,7 @@ def choice( symbol=symbol, bottom_toolbar=bottom_toolbar, show_frame=show_frame, + accept_on_number=accept_on_number, enable_suspend=enable_suspend, enable_interrupt=enable_interrupt, interrupt_exception=interrupt_exception, diff --git a/src/prompt_toolkit/widgets/base.py b/src/prompt_toolkit/widgets/base.py index 6c59fa8ea..96aad65b7 100644 --- a/src/prompt_toolkit/widgets/base.py +++ b/src/prompt_toolkit/widgets/base.py @@ -717,6 +717,7 @@ def __init__( show_scrollbar: bool = True, show_cursor: bool = True, show_numbers: bool = False, + on_number: Callable[[E], None] | None = None, ) -> None: assert len(values) > 0 default_values = default_values or [] @@ -812,6 +813,8 @@ def _select_i(event: E, index: int = i) -> None: self._selected_index = min(len(self.values) - 1, index - 1) if select_on_focus: self._handle_enter() + if on_number is not None and index <= len(self.values): + on_number(event) # Control and window. self.control = FormattedTextControl( @@ -904,6 +907,7 @@ class RadioList(_DialogList[_T]): List of radio buttons. Only one can be checked at the same time. :param values: List of (value, label) tuples. + :param on_number: Handler called after pressing a displayed option number. """ def __init__( @@ -923,6 +927,7 @@ def __init__( multiple_selection: bool = False, show_cursor: bool = True, show_scrollbar: bool = True, + on_number: Callable[[E], None] | None = None, ) -> None: if default is None: default_values = None @@ -934,6 +939,7 @@ def __init__( default_values=default_values, select_on_focus=select_on_focus, show_numbers=show_numbers, + on_number=on_number, open_character=open_character, select_character=select_character, close_character=close_character, diff --git a/tests/test_shortcuts.py b/tests/test_shortcuts.py index 287c6d33a..4135aeb39 100644 --- a/tests/test_shortcuts.py +++ b/tests/test_shortcuts.py @@ -1,10 +1,52 @@ from __future__ import annotations -from prompt_toolkit.shortcuts import print_container +import pytest + +from prompt_toolkit.application import create_app_session +from prompt_toolkit.input import create_pipe_input +from prompt_toolkit.output import DummyOutput +from prompt_toolkit.shortcuts import choice, print_container +from prompt_toolkit.shortcuts.choice_input import ChoiceInput from prompt_toolkit.shortcuts.prompt import _split_multiline_prompt from prompt_toolkit.widgets import Frame, TextArea +@pytest.mark.parametrize( + ("keys", "options", "expected"), + [ + ("21\r", {}, "one"), + ("2\x03", {"accept_on_number": True}, "two"), + ("91\r", {"accept_on_number": True}, "one"), + ("\x1b[B\r", {"accept_on_number": True}, "two"), + ], +) +def test_choice_number(keys, options, expected): + with ( + create_pipe_input() as inp, + create_app_session(input=inp, output=DummyOutput()), + ): + inp.send_text(keys) + assert ( + choice("Pick", options=[("one", "First"), ("two", "Second")], **options) + == expected + ) + + +def test_choice_with_hidden_numbers(): + with ( + create_pipe_input() as inp, + create_app_session(input=inp, output=DummyOutput()), + ): + inp.send_text("2\r") + result = ChoiceInput( + message="Pick", + options=[("one", "First"), ("two", "Second")], + show_numbers=False, + accept_on_number=True, + ).prompt() + assert result == "one" + + def test_split_multiline_prompt(): # Test 1: no newlines: tokens = [("class:testclass", "ab")]