Skip to content
Open
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
2 changes: 2 additions & 0 deletions docs/pages/asking_for_a_choice.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
--------------------
Expand Down
22 changes: 15 additions & 7 deletions src/prompt_toolkit/shortcuts/choice_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -117,13 +120,20 @@ 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
self.bottom_toolbar = bottom_toolbar
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,
Expand All @@ -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="",
Expand Down Expand Up @@ -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)()
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions src/prompt_toolkit/widgets/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 []
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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__(
Expand All @@ -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
Expand All @@ -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,
Expand Down
44 changes: 43 additions & 1 deletion tests/test_shortcuts.py
Original file line number Diff line number Diff line change
@@ -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")]
Expand Down
Loading