diff --git a/CHANGELOG b/CHANGELOG index e8afc07cb..df398004d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,15 @@ CHANGELOG ========= +Unreleased +---------- + +New features: +- Stack unfinished input with Escape-Q in ``PromptSession`` Emacs mode and + restore it after the next accepted input. Enabled by default; pass + ``enable_input_stack=False`` to opt out. The one-shot ``prompt()`` helper + keeps stacking disabled. + 3.0.53: 2026-07-26 ------------------ diff --git a/docs/pages/asking_for_input.rst b/docs/pages/asking_for_input.rst index 83da97aea..3dcabe982 100644 --- a/docs/pages/asking_for_input.rst +++ b/docs/pages/asking_for_input.rst @@ -70,6 +70,52 @@ This has mainly two advantages: :meth:`~prompt_toolkit.shortcuts.PromptSession.prompt` method. +Stacking unfinished input +------------------------- + +A :class:`~prompt_toolkit.shortcuts.PromptSession` can keep unfinished input +while you enter something else. Input stacking is enabled by default: + +.. code:: python + + from prompt_toolkit import PromptSession + + session = PromptSession() + while True: + text = session.prompt("> ") + print(text) + +In Emacs editing mode, press Escape followed by ``Q`` (or ``q``) while editing a +draft. The prompt stacks the entire input and clears the buffer. After you +submit another nonempty input, the next call to ``session.prompt()`` restores the draft with +its cursor position. Multiline drafts are supported. Multiple drafts restore +in stack order, with the most recently stacked draft first. + +Pass ``enable_input_stack=False`` to opt out. The option can also be +changed on :meth:`~prompt_toolkit.shortcuts.PromptSession.prompt` and +:meth:`~prompt_toolkit.shortcuts.PromptSession.prompt_async`; changes apply to +later prompts in the same session. Turning it off preserves pending drafts +until it is enabled again. Each session has its own stack. Use a persistent +``PromptSession`` for this feature; the one-shot ``prompt()`` helper creates a +new session on each call, explicitly disables stacking, and does not expose +this option. The stack key bindings are inactive in Vi mode, preserving its +normal macro commands. + +Unsubmitted drafts are not added to history. Blank or whitespace-only input, +rejected validation, Control-C and Control-D do not make a pending draft ready +to restore. Canceling an intervening asynchronous prompt also leaves it pending. +Once a draft has been restored, canceling it discards that current input normally. +Pending drafts remain in memory only while the session exists. + +A nonempty ``default`` takes precedence over a ready draft and leaves it pending +for a later prompt with an empty default. Both an omitted default and an +explicit empty string or empty :class:`~prompt_toolkit.document.Document` allow +restoration. ``accept_default=True`` can automatically submit a restored draft, +just as it submits an ordinary default. Input stacking does not run application +commands: the application still processes each returned input before calling +``prompt()`` again. + + Syntax highlighting ------------------- diff --git a/src/prompt_toolkit/shortcuts/prompt.py b/src/prompt_toolkit/shortcuts/prompt.py index f14ecd80c..859893501 100644 --- a/src/prompt_toolkit/shortcuts/prompt.py +++ b/src/prompt_toolkit/shortcuts/prompt.py @@ -51,6 +51,7 @@ from prompt_toolkit.filters import ( Condition, FilterOrBool, + emacs_mode, has_arg, has_focus, is_done, @@ -301,6 +302,11 @@ class PromptSession(Generic[_T]): :param enable_open_in_editor: `bool` or :class:`~prompt_toolkit.filters.Filter`. Pressing 'v' in Vi mode or C-X C-E in emacs mode will open an external editor. + :param enable_input_stack: Enable Escape-Q (or Escape-q) in Emacs mode + to stack the current input and clear the buffer. After another nonempty input is + accepted, the next prompt without a nonempty default restores the most + recently stacked input, including its cursor position. Enabled by + default; pass ``False`` to opt out. Stack state belongs to this session. :param history: :class:`~prompt_toolkit.history.History` instance. :param clipboard: :class:`~prompt_toolkit.clipboard.Clipboard` instance. (e.g. :class:`~prompt_toolkit.clipboard.InMemoryClipboard`) @@ -370,6 +376,7 @@ class PromptSession(Generic[_T]): "enable_system_prompt", "enable_suspend", "enable_open_in_editor", + "enable_input_stack", "reserve_space_for_menu", "tempfile_suffix", "tempfile", @@ -393,6 +400,7 @@ def __init__( enable_system_prompt: FilterOrBool = False, enable_suspend: FilterOrBool = False, enable_open_in_editor: FilterOrBool = False, + enable_input_stack: bool = True, validator: Validator | None = None, completer: Completer | None = None, complete_in_thread: bool = False, @@ -469,6 +477,7 @@ def __init__( self.enable_system_prompt = enable_system_prompt self.enable_suspend = enable_suspend self.enable_open_in_editor = enable_open_in_editor + self.enable_input_stack = enable_input_stack self.reserve_space_for_menu = reserve_space_for_menu self.tempfile_suffix = tempfile_suffix self.tempfile = tempfile @@ -476,6 +485,10 @@ def __init__( self.interrupt_exception = interrupt_exception self.eof_exception = eof_exception + # Unfinished inputs are session state, independent of input history. + self._input_stack: list[Document] = [] + self._restore_input_stack = False + # Create buffers, layout and Application. self.history = history self.default_buffer = self._create_default_buffer() @@ -510,6 +523,8 @@ def _create_default_buffer(self) -> Buffer: def accept(buff: Buffer) -> bool: """Accept the content of the default buffer. This is called when the validation succeeds.""" + if buff.text.strip() and self._input_stack: + self._restore_input_stack = True cast(Application[str], get_app()).exit( result=buff.document.text, style="class:accepted" ) @@ -821,6 +836,22 @@ def _create_prompt_bindings(self) -> KeyBindings: handle = kb.add default_focused = has_focus(DEFAULT_BUFFER) + input_stack_enabled = ( + default_focused & emacs_mode & self._dyncond("enable_input_stack") + ) + + @handle("escape", "q", filter=input_stack_enabled) + @handle("escape", "Q", filter=input_stack_enabled) + def _push_input(event: E) -> None: + "Stack unfinished input without accepting it or adding it to history." + if self.default_buffer.text: + self._input_stack.append(self.default_buffer.document) + self._restore_input_stack = False + self.default_buffer.go_to_history( + len(self.default_buffer._working_lines) - 1 + ) + self.default_buffer.document = Document() + @Condition def do_accept() -> bool: return not is_true(self.multiline) and self.app.layout.has_focus( @@ -877,6 +908,19 @@ def _suspend(event: E) -> None: return kb + def _get_default_input(self, default: str | Document) -> Document: + """Restore a ready draft only when no explicit nonempty default wins.""" + document = default if isinstance(default, Document) else Document(default) + if ( + self.enable_input_stack + and self._restore_input_stack + and self._input_stack + and not document.text + ): + self._restore_input_stack = False + return self._input_stack.pop() + return document + def prompt( self, # When any of these arguments are passed, this value is overwritten @@ -919,6 +963,7 @@ def prompt( enable_system_prompt: FilterOrBool | None = None, enable_suspend: FilterOrBool | None = None, enable_open_in_editor: FilterOrBool | None = None, + enable_input_stack: bool | None = None, tempfile_suffix: str | Callable[[], str] | None = None, tempfile: str | Callable[[], str] | None = None, show_frame: FilterOrBool | None = None, @@ -948,7 +993,9 @@ class itself. For these, passing in ``None`` will keep the current Additional arguments, specific for this prompt: :param default: The default input text to be shown. (This can be edited - by the user). + by the user). With input stacking enabled, a nonempty default takes + precedence over a pending draft, which remains available for a later + prompt with an empty default. :param accept_default: When `True`, automatically accept the default value without allowing the user to edit the input. :param pre_run: Callable, called at the start of `Application.run`. @@ -1042,6 +1089,8 @@ class itself. For these, passing in ``None`` will keep the current self.enable_suspend = enable_suspend if enable_open_in_editor is not None: self.enable_open_in_editor = enable_open_in_editor + if enable_input_stack is not None: + self.enable_input_stack = enable_input_stack if tempfile_suffix is not None: self.tempfile_suffix = tempfile_suffix if tempfile is not None: @@ -1050,9 +1099,7 @@ class itself. For these, passing in ``None`` will keep the current self.show_frame = show_frame self._add_pre_run_callables(pre_run, accept_default) - self.default_buffer.reset( - default if isinstance(default, Document) else Document(default) - ) + self.default_buffer.reset(self._get_default_input(default)) self.app.refresh_interval = self.refresh_interval # This is not reactive. # If we are using the default output, and have a dumb terminal. Use the @@ -1159,6 +1206,7 @@ async def prompt_async( enable_system_prompt: FilterOrBool | None = None, enable_suspend: FilterOrBool | None = None, enable_open_in_editor: FilterOrBool | None = None, + enable_input_stack: bool | None = None, tempfile_suffix: str | Callable[[], str] | None = None, tempfile: str | Callable[[], str] | None = None, show_frame: FilterOrBool = False, @@ -1239,6 +1287,8 @@ async def prompt_async( self.enable_suspend = enable_suspend if enable_open_in_editor is not None: self.enable_open_in_editor = enable_open_in_editor + if enable_input_stack is not None: + self.enable_input_stack = enable_input_stack if tempfile_suffix is not None: self.tempfile_suffix = tempfile_suffix if tempfile is not None: @@ -1247,9 +1297,7 @@ async def prompt_async( self.show_frame = show_frame self._add_pre_run_callables(pre_run, accept_default) - self.default_buffer.reset( - default if isinstance(default, Document) else Document(default) - ) + self.default_buffer.reset(self._get_default_input(default)) self.app.refresh_interval = self.refresh_interval # This is not reactive. # If we are using the default output, and have a dumb terminal. Use the @@ -1451,9 +1499,11 @@ def prompt( The global `prompt` function. This will create a new `PromptSession` instance for every call. """ - # The history is the only attribute that has to be passed to the - # `PromptSession`, it can't be passed into the `prompt()` method. - session: PromptSession[str] = PromptSession(history=history) + # History must be passed to the session constructor. Disable input + # stacking: this one-shot helper has no later prompt to restore drafts. + session: PromptSession[str] = PromptSession( + history=history, enable_input_stack=False + ) return session.prompt( message, diff --git a/tests/test_input_stack.py b/tests/test_input_stack.py new file mode 100644 index 000000000..50106471a --- /dev/null +++ b/tests/test_input_stack.py @@ -0,0 +1,261 @@ +# Key notation: \x1b is Escape, so "\x1bq" means Escape then lowercase q; +# "\x1bQ" means Escape then uppercase Q. Both stack the current input. +# Similarly, \r is Enter, \x03 is Ctrl-C, and \x04 is Ctrl-D. + +from __future__ import annotations + +import asyncio + +import pytest + +from prompt_toolkit.application import create_app_session +from prompt_toolkit.document import Document +from prompt_toolkit.history import InMemoryHistory +from prompt_toolkit.input import create_pipe_input +from prompt_toolkit.output import DummyOutput +from prompt_toolkit.shortcuts import PromptSession, prompt +from prompt_toolkit.validation import Validator + + +@pytest.fixture +def session_and_input(): + with create_pipe_input() as inp: + session = PromptSession(input=inp, output=DummyOutput()) + yield session, inp + + +@pytest.mark.parametrize("key", ["\x1bq", "\x1bQ"]) +def test_push_input_and_restore_without_premature_history(session_and_input, key): + session, inp = session_and_input + inp.send_text("unfinished" + key + "command\r") + assert session.prompt() == "command" + assert session.history.get_strings() == ["command"] + inp.send_text("\r") + assert session.prompt() == "unfinished" + assert session.history.get_strings() == ["command", "unfinished"] + + +def test_nested_input_stack_is_lifo_and_empty_push_is_ignored(session_and_input): + session, inp = session_and_input + inp.send_text("outer\x1bqinner\x1bQ\x1bQcommand\r") + assert session.prompt() == "command" + inp.send_text("\r") + assert session.prompt() == "inner" + inp.send_text("\r") + assert session.prompt() == "outer" + inp.send_text("\r") + assert session.prompt() == "" + + +def test_multiline_document_preserves_cursor(session_and_input): + session, inp = session_and_input + document = Document("hello world\nnext", cursor_position=5) + inp.send_text("\x1bQcommand\x1b\r") + assert session.prompt(default=document, multiline=True) == "command" + seen = [] + inp.send_text("!\x1b\r") + result = session.prompt( + pre_run=lambda: seen.append(session.default_buffer.document) + ) + assert [(doc.text, doc.cursor_position) for doc in seen] == [ + ("hello world\nnext", 5) + ] + assert result == "hello! world\nnext" + + +@pytest.mark.parametrize( + "default", ["explicit", Document("explicit", cursor_position=2)] +) +def test_nonempty_default_defers_pending_draft(session_and_input, default): + session, inp = session_and_input + inp.send_text("draft\x1bQcommand\r") + assert session.prompt() == "command" + inp.send_text("\r") + assert session.prompt(default=default) == "explicit" + inp.send_text("\r") + assert session.prompt(default=Document()) == "draft" + + +@pytest.mark.parametrize( + "key,exception", [("\x03", KeyboardInterrupt), ("\x04", EOFError)] +) +def test_cancel_or_blank_intervening_input_keeps_draft( + session_and_input, key, exception +): + session, inp = session_and_input + inp.send_text("draft\x1bQ" + key) + with pytest.raises(exception): + session.prompt() + inp.send_text(" \r") + assert session.prompt() == " " + inp.send_text("command\r") + assert session.prompt() == "command" + inp.send_text("\r") + assert session.prompt() == "draft" + + +def test_explicit_default_interrupt_keeps_ready_draft(session_and_input): + session, inp = session_and_input + inp.send_text("draft\x1bQcommand\r") + assert session.prompt() == "command" + inp.send_text("\x03") + with pytest.raises(KeyboardInterrupt): + session.prompt(default="explicit") + inp.send_text("\r") + assert session.prompt() == "draft" + + +def test_failed_validation_does_not_make_draft_ready(session_and_input): + session, inp = session_and_input + validator = Validator.from_callable( + lambda text: text in ("draft", "ok"), error_message="Use ok" + ) + # Rejected Enter followed by interrupt must leave the draft pending. + inp.send_text("draft\x1bQbad\r\x03") + with pytest.raises(KeyboardInterrupt): + session.prompt(validator=validator) + inp.send_text("\x04") + with pytest.raises(EOFError): + session.prompt() + inp.send_text("ok\r") + assert session.prompt() == "ok" + inp.send_text("\r") + assert session.prompt() == "draft" + assert "bad" not in session.history.get_strings() + + +def test_disabling_and_reenabling_preserves_pending_draft(session_and_input): + session, inp = session_and_input + inp.send_text("draft\x1bQcommand\r") + assert session.prompt() == "command" + inp.send_text("disabled\r") + assert session.prompt(enable_input_stack=False) == "disabled" + inp.send_text("still disabled\r") + assert session.prompt() == "still disabled" + inp.send_text("\r") + assert session.prompt(enable_input_stack=True) == "draft" + + +@pytest.mark.parametrize("key", ["\x1bq", "\x1bQ"]) +def test_explicit_opt_out_matches_one_shot_helper(key): + with create_pipe_input() as inp: + session = PromptSession( + input=inp, output=DummyOutput(), enable_input_stack=False + ) + inp.send_text("draft" + key + "command\r") + disabled_result = session.prompt() + inp.send_text("\r") + assert session.prompt() == "" + with create_pipe_input() as inp: + with create_app_session(input=inp, output=DummyOutput()): + inp.send_text("draft" + key + "command\r") + assert prompt() == disabled_result + assert disabled_result != "command" + + +def test_sessions_do_not_share_stacked_input(session_and_input): + session, inp = session_and_input + inp.send_text("draft\x1bQcommand\r") + assert session.prompt() == "command" + with create_pipe_input() as other_input: + other_session = PromptSession( + input=other_input, output=DummyOutput(), enable_input_stack=True + ) + other_input.send_text("\r") + assert other_session.prompt() == "" + inp.send_text("\r") + assert session.prompt() == "draft" + + +def test_history_search_stays_in_its_buffer(session_and_input): + session, inp = session_and_input + session.history.append_string("history match") + inp.send_text("draft\x1bQ\x12history\r\r") + assert session.prompt() == "history match" + inp.send_text("\r") + assert session.prompt() == "draft" + + +def test_accept_default_can_accept_a_restored_draft(session_and_input): + session, inp = session_and_input + inp.send_text("draft\x1bQcommand\r") + assert session.prompt() == "command" + assert session.prompt(accept_default=True) == "draft" + + +def test_input_stack_with_in_thread(session_and_input): + session, inp = session_and_input + inp.send_text("draft\x1bQcommand\r") + assert session.prompt(in_thread=True) == "command" + inp.send_text("\r") + assert session.prompt(in_thread=True) == "draft" + + +def test_async_prompt_stacks_and_restores_documents(session_and_input): + session, inp = session_and_input + + async def run(): + inp.send_text("\x1bQcommand\r") + assert ( + await session.prompt_async(default=Document("draft", cursor_position=2)) + == "command" + ) + inp.send_text("!\r") + assert await session.prompt_async() == "dr!aft" + inp.send_text("outer\x1bqinner\x1bQcommand\r") + assert await session.prompt_async() == "command" + assert ( + await session.prompt_async(default="explicit", accept_default=True) + == "explicit" + ) + assert await session.prompt_async(accept_default=True) == "inner" + assert await session.prompt_async(accept_default=True) == "outer" + inp.send_text("draft\x1bQcommand\r") + assert await session.prompt_async(enable_input_stack=False) != "command" + inp.send_text("new draft\x1bQcommand\r") + assert await session.prompt_async(enable_input_stack=True) == "command" + assert await session.prompt_async(accept_default=True) == "new draft" + + asyncio.run(run()) + + +def test_async_cancellation_keeps_unfinished_stack(session_and_input): + session, inp = session_and_input + + async def run(): + pushed = asyncio.Event() + + def changed(buffer): + if not buffer.text and session._input_stack: + pushed.set() + + session.default_buffer.on_text_changed += changed + inp.send_text("draft\x1bQ") + task = asyncio.create_task(session.prompt_async()) + await asyncio.wait_for(pushed.wait(), timeout=5) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + inp.send_text("command\r") + assert await session.prompt_async() == "command" + inp.send_text("\r") + assert await session.prompt_async() == "draft" + + asyncio.run(run()) + + +@pytest.mark.parametrize("selection", ["\x1b[A", "\x12old\r"]) +def test_push_recalled_entry_preserves_history_and_starts_at_newest(selection): + with create_pipe_input() as inp: + session = PromptSession( + input=inp, + output=DummyOutput(), + history=InMemoryHistory(["old history", "new history"]), + enable_input_stack=True, + ) + # Recall the older entry, stack it, then navigate from a fresh input slot. + inp.send_text("\x1b[A\x1b[A\x1bQ" + selection + "\r") + expected = "new history" if selection == "\x1b[A" else "old history" + assert session.prompt() == expected + inp.send_text("\r") + assert session.prompt() == "old history"