diff --git a/CHANGELOG.md b/CHANGELOG.md index 291dc0ecc..54d26d372 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ - On Windows, shell command completion now recognizes paths typed with forward slashes, such as `./my` and `C:/tools/my`. Path completion preserves the typed separators so the first Tab extends the shared prefix when several names match. + - Tab completion of a match which needs quotes, such as a file name with a space, no longer + takes a second press of Tab. The opening quote is inserted and the completion carries on in + the same key press. + - A match chosen from the completion menu now closes its quote and adds a trailing space. + Previously the quote was left open and the command failed with + `Invalid syntax: No closing quotation`. A directory still leaves its quote open so the rest of + the path can be completed. See the + [Quotes Added by Completion](docs/features/completion.md#quotes-added-by-completion) + documentation for details. + - `Completions.allow_finalization` used to be ignored when there were several matches. It + now decides whether a match chosen from them closes its quote. If you have written a + completer which offers matches the user keeps completing, like directories, alongside + other matches, return `allow_finalization=False` for those results so the quote stays + open. ## 4.4.3 (2026-11-16) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 942bcd2cd..322297acb 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -207,6 +207,7 @@ def __init__(self, msg: str = "") -> None: Cmd2Completer, Cmd2History, Cmd2Lexer, + _CompletionKeyEvent, pt_filter_style, pt_resolve_color_depth, ) @@ -784,6 +785,27 @@ def _create_key_bindings(self, completekey: str) -> KeyBindings: """Create and configure custom key bindings for the PromptSession.""" key_bindings = KeyBindings() + # Take the place of prompt-toolkit's own binding for Tab, and do what it does. The difference is that + # the request says it comes from this binding, which lets Cmd2Completer insert an opening quote and + # start completion again. It can't tell from prompt-toolkit's request what kind of request it is. + # A session which shows completions like readline has a different binding for Tab, which is left alone. + @filters.Condition + def menu_completion() -> bool: + return self.active_session.complete_style != CompleteStyle.READLINE_LIKE + + @key_bindings.add( + self.DEFAULT_COMPLETEKEY, + filter=(filters.emacs_insert_mode | filters.vi_insert_mode) & menu_completion, + ) + def _complete_or_select_next(event: KeyPressEvent) -> None: # pragma: no cover + """Insert the common prefix of the completions, or select the next completion if a menu is open.""" + b = event.current_buffer + if b.complete_state: + b.complete_next() + else: + b.start_completion(insert_common_part=True, complete_event=_CompletionKeyEvent()) + + # A custom completion key works alongside Tab, as it always has if completekey != self.DEFAULT_COMPLETEKEY: @key_bindings.add(completekey) @@ -2347,9 +2369,9 @@ def delimiter_complete( # Remove from each match everything after where the user is completing. # This approach can result in duplicates so we will filter those out. - unique_results: dict[str, str] = {} + # Each result is stored with its display value and whether it is a full item. + unique_results: dict[str, tuple[str, bool]] = {} - allow_finalization = True for cur_match in match_strings: match_tokens = cur_match.split(delimiter) @@ -2357,22 +2379,28 @@ def delimiter_complete( display_val = match_tokens[display_token_index] # If there are more tokens, then we aren't done completing a full item - if len(match_tokens) > display_token_index + 1: + is_full_item = len(match_tokens) <= display_token_index + 1 + if not is_full_item: full_value += delimiter display_val += delimiter - allow_finalization = False if full_value not in unique_results: - unique_results[full_value] = display_val + unique_results[full_value] = (display_val, is_full_item) + # A match which isn't a full item leaves an open quote for the rest of the item. + # Marking each match lets a full item which is offered alongside it close the quote. items = [ CompletionItem( value=value, display=display, + _allow_finalization=is_full_item, ) - for value, display in unique_results.items() + for value, (display, is_full_item) in unique_results.items() ] + # A single match is finalized according to this flag instead of its own + allow_finalization = not (len(items) == 1 and not items[0]._allow_finalization) + return Completions(items, allow_finalization=allow_finalization) @staticmethod @@ -2464,9 +2492,12 @@ def path_complete( items = [] for match in matches: name = os.path.basename(match) - if add_trailing_sep_if_dir and os.path.isdir(match): + is_dir = os.path.isdir(match) + if add_trailing_sep_if_dir and is_dir: name += trailing_sep - items.append(CompletionItem(value=typed_directory + name, display=name)) + + # A directory is not the end of a path, so it leaves an open quote for the rest of the path + items.append(CompletionItem(value=typed_directory + name, display=name, _allow_finalization=not is_dir)) return Completions(items=items, allow_finalization=allow_finalization) diff --git a/cmd2/completion.py b/cmd2/completion.py index 434f72cd6..05f9b02af 100644 --- a/cmd2/completion.py +++ b/cmd2/completion.py @@ -71,6 +71,13 @@ class CompletionItem: display_plain: str = field(default="", init=False) display_meta_plain: str = field(default="", init=False) + # Used internally by cmd2 and not intended for user modification. + # + # Whether this match may be finalized, meaning an open quote is closed and a trailing space is + # added after it. False for a match which the user will keep completing, such as a directory. + # Completions.allow_finalization has to allow it as well. Not part of an item's identity. + _allow_finalization: bool = True + @classmethod def _clean_display(cls, val: str) -> str: """Clean a string for display in the completion menu. @@ -287,7 +294,10 @@ class Completions(CompletionResultsBase): # # Set this to False for intermediate or hierarchical matches (such as # directories) where the user needs to continue typing the next segment. - # This flag is ignored if there are multiple matches. + # + # If there are multiple matches, a match chosen from them is only finalized + # when a quotation mark is open: it closes the quotation mark and appends a + # trailing space. Set this to False if any of the matches is intermediate. allow_finalization: bool = True ##################################################################### diff --git a/cmd2/pt_utils.py b/cmd2/pt_utils.py index 58ac3cd3e..01319ae64 100644 --- a/cmd2/pt_utils.py +++ b/cmd2/pt_utils.py @@ -1,7 +1,10 @@ """Utilities for integrating prompt_toolkit with cmd2.""" +import asyncio +import dataclasses import os import re +import threading from collections.abc import ( Callable, Iterable, @@ -14,15 +17,22 @@ from prompt_toolkit import print_formatted_text from prompt_toolkit.application import get_app +from prompt_toolkit.buffer import ( + Buffer, + CompletionState, +) from prompt_toolkit.completion import ( + CompleteEvent, Completer, Completion, ) from prompt_toolkit.document import Document +from prompt_toolkit.filters import Never from prompt_toolkit.formatted_text import ANSI from prompt_toolkit.history import History from prompt_toolkit.lexers import Lexer from prompt_toolkit.output.color_depth import ColorDepth +from prompt_toolkit.shortcuts import CompleteStyle from rich.style import Style, StyleType from . import ( @@ -37,6 +47,7 @@ from rich.color import Color from .cmd2 import Cmd + from .completion import Completions BASE_DELIMITERS = " \t\n" + "".join(constants.QUOTES) + "".join(constants.REDIRECTION_CHARS) @@ -136,6 +147,86 @@ def rich_to_pt_style(rich_style: StyleType) -> str: return " ".join(parts) +# How long a completion which runs in a thread waits for the event loop before giving up on it +_EVENT_LOOP_TIMEOUT = 1.0 + + +class _CompletionKeyEvent(CompleteEvent): + """Requests the completion which cmd2's key binding for the default completion key starts. + + prompt-toolkit doesn't tell a completer what a request will do with its matches. This tells + Cmd2Completer that the common prefix of the matches will be inserted, which is the one kind + of request it can start again after inserting an opening quote. + """ + + def __init__(self) -> None: + """Initialize the instance.""" + super().__init__(completion_requested=True) + + +class _QuoteInsertedEvent(CompleteEvent): + """Requests the completion which Cmd2Completer starts after it has inserted an opening quote. + + It carries the matches which were found before the quote was inserted, so cmd2's completion + logic doesn't run a second time. Since the matches travel with the request they were found for, + no other request can be given them. + """ + + def __init__(self, document: Document, completions: "Completions") -> None: + """Initialize the instance. + + :param document: the input, with the quote in it, which the matches are for + :param completions: the matches, changed to what they are once the quote is present + """ + super().__init__(completion_requested=True) + self.document = document + self.completions = completions + + +def _completions_for_quoted_text(completions: "Completions") -> "Completions": + """Change completions which need an opening quote into what they are once the quote is in the buffer. + + The quote goes after a shortcut, so the word being completed no longer includes the shortcut. + """ + offset = completions._search_text_offset + items = [dataclasses.replace(item, text=item.text[offset:]) for item in completions] if offset > 0 else completions.items + return dataclasses.replace( + completions, + items=items, + _add_opening_quote=False, + _search_text_offset=0, + ) + + +def _insert_opening_quote(buffer: Buffer, quote_char: str, search_text_length: int) -> None: + """Insert an opening quote in front of the text being completed and put the cursor back after that text. + + This tells the buffer's listeners about the new text as any other insertion does, so things + like auto-suggest keep up. The exception is completion while typing. It would start a completion + of its own for the quote, which prompt-toolkit would run in place of the one cmd2 is about to start. + + :param buffer: the buffer to insert into + :param quote_char: the quote to insert + :param search_text_length: how much of the text before the cursor the quote goes in front of + """ + complete_while_typing = buffer.complete_while_typing + buffer.complete_while_typing = Never() + try: + buffer.cursor_left(search_text_length) + buffer.insert_text(quote_char) + buffer.cursor_right(search_text_length) + finally: + buffer.complete_while_typing = complete_while_typing + + +def _in_event_loop(loop: asyncio.AbstractEventLoop | None) -> bool: + """Return whether this is running in the event loop, as opposed to a thread which completes for it.""" + try: + return asyncio.get_running_loop() is loop + except RuntimeError: + return False + + class Cmd2Completer(Completer): """Completer that delegates to cmd2's completion logic.""" @@ -148,7 +239,128 @@ def __init__( self._cmd_app = cmd_app self.custom_settings = custom_settings - def get_completions(self, document: Document, complete_event: object) -> Iterable[Completion]: # noqa: ARG002 + def _insert_quote_and_recomplete(self, document: Document, completions: "Completions", search_text_length: int) -> bool: + """Arrange for an opening quote to be inserted and completion started again, once prompt-toolkit is ready. + + prompt-toolkit's async_completer is running the request this is called for. It discards the + results of a request whose input changed while it ran, and it ignores a completion which is + started before it has finished the request. So the buffer is left alone until the request has + finished, and only if it finished without having been cancelled. + + :param document: the input being completed + :param completions: the matches which need an opening quote + :param search_text_length: how much of the text before the cursor the quote goes in front of + :return: True if this has been arranged, in which case the request must return no completions. + False if there is no running event loop to do it. + """ + app = get_app() + loop = app.loop + if loop is None or loop.is_closed(): + return False + + buffer = app.current_buffer + quote_char = completions._quote_char + + # The matches for the document which has the quote in it, so the re-triggered cycle + # doesn't invoke cmd2.complete() a second time. + cached_completions = _completions_for_quoted_text(completions) + + # The request which async_completer is running, once that is known + request_state: CompletionState | None = None + + # Whether async_completer has been seen to reach the end of the request with it still intact + request_ended_intact = False + + def _recomplete() -> None: + buffer.on_completions_changed -= _on_completions_changed + + # The user submitted or edited the line after the request finished + if app.is_done or buffer.document != document: + return + + _insert_opening_quote(buffer, quote_char, search_text_length) + + # The matches go with the request for the re-triggered cycle. If prompt-toolkit + # doesn't run that request, they are dropped along with it. + complete_event = _QuoteInsertedEvent(buffer.document, cached_completions) + buffer.start_completion(insert_common_part=True, complete_event=complete_event) + + def _on_completions_changed(_: Buffer) -> None: + nonlocal request_ended_intact + + # The prompt has ended. Nobody is left to miss a notification, so the handler is removed here. + if app.is_done: + buffer.on_completions_changed -= _on_completions_changed + return + + # When async_completer has all the results of a request, it notifies with the request's + # state still in place. If there were no completions, it then clears the state and + # notifies again. A request which was cancelled, or whose input was edited, had its state + # cleared without a notification, so it is never seen intact here. + if buffer.complete_state is request_state: + request_ended_intact = True + return + + if request_ended_intact and buffer.complete_state is None: + # Run on the next loop tick, after _only_one_at_a_time resets its running flag + loop.call_soon(_recomplete) + else: + # Removing the handler now would make prompt-toolkit skip the handler after it + loop.call_soon(buffer.on_completions_changed.remove_handler, _on_completions_changed) + + def _wait_for_request_to_finish() -> None: + nonlocal request_state + + # async_completer can't have finished the request yet, since it is waiting for + # get_completions() to return. So if the state is already cleared, the request + # was cancelled or the line was edited while cmd2 was completing. + request_state = buffer.complete_state + if request_state is not None: + buffer.on_completions_changed += _on_completions_changed + + if _in_event_loop(loop): + # async_completer is running get_completions() itself (e.g. complete_in_thread=False) + _wait_for_request_to_finish() + else: + # get_completions() is running in a thread (e.g. complete_in_thread=True). Don't return + # until the event loop is watching the request, or async_completer could finish it first. + watching = threading.Event() + + def _wait_for_request_to_finish_in_event_loop() -> None: + try: + _wait_for_request_to_finish() + finally: + watching.set() + + loop.call_soon_threadsafe(_wait_for_request_to_finish_in_event_loop) + watching.wait(timeout=_EVENT_LOOP_TIMEOUT) + + return True + + @staticmethod + def _insert_quote_for_readline_style(document: Document, quote_char: str, search_text_length: int) -> Document | None: + """Insert an opening quote into the buffer right away if completions are being listed like readline. + + The key binding which does that calls get_completions() directly from the event loop. It + reads the buffer again once it has the completions, so the quote can go in before they are + returned and it can then insert the text they share. Nothing which async_completer does + is involved, since it isn't running a request. + + :param document: the input being completed + :param quote_char: the quote to insert + :param search_text_length: how much of the text before the cursor the quote goes in front of + :return: the buffer's document with the quote in it, or None if the request doesn't come + from that key binding and the buffer has been left alone + """ + app = get_app() + buffer = app.current_buffer + if not _in_event_loop(app.loop) or buffer.complete_state is not None or buffer.document != document: + return None + + _insert_opening_quote(buffer, quote_char, search_text_length) + return buffer.document + + def get_completions(self, document: Document, complete_event: object) -> Iterable[Completion]: """Get completions for the current input.""" # Find the beginning of the current word based on delimiters line = document.text @@ -168,14 +380,54 @@ def get_completions(self, document: Document, complete_event: object) -> Iterabl endidx = cursor_pos text = line[begidx:endidx] - completions = self._cmd_app.complete( - text, line=line, begidx=begidx, endidx=endidx, custom_settings=self.custom_settings - ) + # Whether completions are listed like readline. This has to be looked at now, because + # cmd2's completion logic sets the session to one of the menu styles each time it runs. + readline_style = self._cmd_app.active_session.complete_style == CompleteStyle.READLINE_LIKE + + # Reuse cached completions if this cycle was triggered right after inserting an opening quote + if isinstance(complete_event, _QuoteInsertedEvent) and complete_event.document == document: + completions = complete_event.completions + else: + completions = self._cmd_app.complete( + text, line=line, begidx=begidx, endidx=endidx, custom_settings=self.custom_settings + ) if completions.error: print_formatted_text(pt_filter_style(completions.error)) return + # The length of the user's input minus any shortcut. + search_text_length = len(text) - completions._search_text_offset + + # If matches require quoting but the word isn't quoted yet, the opening quote goes in front + # of text the user has typed. If any completions change text before the cursor (like + # prepending a quote), prompt-toolkit will not return a common prefix to the command line. + if completions and completions._add_opening_quote and search_text_length > 0: + # For the completion key, whose request inserts that common prefix, the quote is + # inserted into the buffer and completion is started again with the quote already present. + if isinstance(complete_event, _CompletionKeyEvent) and self._insert_quote_and_recomplete( + document, completions, search_text_length + ): + return + + # The key binding which lists completions like readline gets the quote put in the + # buffer first, and completions for the text as it is with the quote. + quoted_document = None + if readline_style: + quoted_document = self._insert_quote_for_readline_style(document, completions._quote_char, search_text_length) + + if quoted_document is not None: + document = quoted_document + line = document.text + endidx = document.cursor_position + + # The quote went after any shortcut, so the word being completed starts after the quote + text = text[completions._search_text_offset :] + completions = _completions_for_quoted_text(completions) + + # Any other request gets the quote as part of each completion further down, so it + # goes on to do what it was started for, such as selecting a match or inserting all of them. + # Print completion table if present if completions.table is not None: console = ru.Cmd2GeneralConsole(file=self._cmd_app.stdout) @@ -189,22 +441,24 @@ def get_completions(self, document: Document, complete_event: object) -> Iterabl print_formatted_text(pt_filter_style(completions.hint)) return - # The length of the user's input minus any shortcut. - search_text_length = len(text) - completions._search_text_offset - - # If matches require quoting but the word isn't quoted yet, we insert the - # opening quote directly into the buffer. We do this because if any completions - # change text before the cursor (like prepending a quote), prompt-toolkit will - # not return a common prefix to the command line. By modifying the buffer - # and returning early, we trigger a new completion cycle where the quote - # is already present, allowing for proper common prefix calculation. - if completions._add_opening_quote and search_text_length > 0: - buffer = get_app().current_buffer - - buffer.cursor_left(search_text_length) - buffer.insert_text(completions._quote_char) - buffer.cursor_right(search_text_length) - return + # A completion only replaces text before the cursor, so the argument may carry on after it. + # Whether a quote character further along closes this argument or belongs to something else + # can't be told, so nothing here depends on it. A closing quote is added where it is certain + # to be needed, and everywhere else the line is treated as it was before a match chosen from + # several closed its quote at all. + at_end_of_line = endidx == len(line) + next_char = line[endidx : endidx + 1] + + # Never put a closing quote directly in front of one which is already there + closing_quote = completions._quote_char + if next_char == closing_quote: + closing_quote = "" + + # A match chosen from several closes its quote, so that accepting it does not leave the quote + # open, in the two cases where nothing after the cursor can belong to the argument: at the end + # of the line, and when cmd2 opened the quote around a word which ended at the cursor. + quote_opened_by_cmd2 = completions._add_opening_quote or isinstance(complete_event, _QuoteInsertedEvent) + closes_quote_in_menu = at_end_of_line or (quote_opened_by_cmd2 and next_char.isspace()) # Return the completions for item in completions: @@ -212,7 +466,7 @@ def get_completions(self, document: Document, complete_event: object) -> Iterabl start_position = -len(text) match_text = item.text - # If we need a quote but didn't interrupt (because text was empty), + # If the matches need an opening quote which isn't in the buffer, then # prepend the quote here so it's included in the insertion. if completions._add_opening_quote: match_text = ( @@ -221,15 +475,24 @@ def get_completions(self, document: Document, complete_event: object) -> Iterabl + match_text[completions._search_text_offset :] ) - # Finalize if there's only one match - if len(completions) == 1 and completions.allow_finalization: - # Close any open quote - if completions._quote_char: - match_text += completions._quote_char + # A match which the user will keep completing, like a directory, is left as it is + if completions.allow_finalization and item._allow_finalization: + # Finalize if there's only one match + if len(completions) == 1: + # Close any open quote + match_text += closing_quote + + # Add trailing space if the cursor is at the end of the line + if at_end_of_line: + match_text += " " + + elif closing_quote and closes_quote_in_menu: + match_text += closing_quote - # Add trailing space if the cursor is at the end of the line - if endidx == len(line): - match_text += " " + # With its quote closed the argument is finished, so add the trailing space too. + # Otherwise completing again would start a new argument right against the quote. + if at_end_of_line: + match_text += " " yield Completion( match_text, diff --git a/docs/features/completion.md b/docs/features/completion.md index 5c4f94daf..2dd03c3fa 100644 --- a/docs/features/completion.md +++ b/docs/features/completion.md @@ -42,7 +42,8 @@ does in a shell. Completion results are literal names too. `cmd2` does not escape them, because most commands use a path directly in Python, where the literal name is exactly what is wanted. The only thing `cmd2` -adds is quotes around a match which contains a space, so it stays a single argument. +adds is quotes around a match which contains a space, so it stays a single argument. See +[Quotes Added by Completion](#quotes-added-by-completion) for how that works. ### Paths Passed to a Shell @@ -79,6 +80,49 @@ There are limits to this: - Your own commands are not covered, even if they pass their arguments to a shell. Quote or escape those arguments in the command. +## Quotes Added by Completion + +A match which contains a space needs quotes to stay a single argument. So does a match with a +special character in one of the places where it is [passed to a shell](#paths-passed-to-a-shell). If +you have not typed a quote yourself, `cmd2` adds one for you. This applies to everything `cmd2` +completes, not only to paths. + +The opening quote goes in front of the text you typed, and completion carries on in the same press +of Tab. With a file named `my file.txt` in the current directory, pressing Tab once after `edit my` +gives: + +```text +(Cmd) edit "my file.txt" +``` + +When there are several matches, that first press inserts the quote and any text which the matches +have in common, and it opens the completion menu. With `sp ace.txt` and `spare.txt`, pressing Tab +after `edit sp` gives: + +```text +(Cmd) edit "sp + sp ace.txt + spare.txt +``` + +The quote is closed, and a space is added after it, when a match is complete. That is when it is the +only match or when you choose it from the menu. A directory is the exception. Its quote is left open +so you can keep completing the rest of the path: + +```text +(Cmd) edit "my dir/ +``` + +When there is more text after the cursor, that text may already close the quote. So a match chosen +from the menu in the middle of a line only closes a quote which `cmd2` added itself, around a word +which ended at the cursor. A quote which you typed is left for you to close. + +If you write a completer whose matches can be like directories, where the user keeps completing +after choosing one, set `allow_finalization=False` on the [Completions][cmd2.Completions] it returns +whenever such a match is among them. No quote is closed for those results. `path_complete` and +`delimiter_complete` do better than that, closing the quote for every match except the unfinished +ones, but they rely on a marker which is private to `cmd2`. + ## Included Tab Completion Functions [cmd2.Cmd][] provides the following tab completion functions diff --git a/tests/test_completion.py b/tests/test_completion.py index 559e752bb..e4cf830be 100644 --- a/tests/test_completion.py +++ b/tests/test_completion.py @@ -453,7 +453,9 @@ def test_shell_command_completion_windows_forward_slashes(cmd_app, tmp_path, mon assert get_common_complete_suffix(document, matches) == "tool-" completed_lines = {document.text_before_cursor[: match.start_position] + match.text for match in matches} - assert completed_lines == {f'shell "{directory}mytool-one.exe', f'shell "{directory}mytool-two.exe'} + + # Each match closes the quote which the user opened and adds a trailing space + assert completed_lines == {f'shell "{directory}mytool-one.exe" ', f'shell "{directory}mytool-two.exe" '} @pytest.mark.skipif(sys.platform == "win32", reason="'*' and '?' are not legal in Windows file names") diff --git a/tests/test_completion_keys.py b/tests/test_completion_keys.py new file mode 100644 index 000000000..9e5f5515b --- /dev/null +++ b/tests/test_completion_keys.py @@ -0,0 +1,583 @@ +"""Tests which press the completion key at a real prompt and check what ends up on the command line. + +The prompt reads its keys from a pipe, so the key bindings, cmd2's completion logic, and +prompt-toolkit's own handling of the results are all exercised together. +""" + +import asyncio +import shlex +import sys +import threading +import time +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pytest +from prompt_toolkit import PromptSession +from prompt_toolkit.application import get_app +from prompt_toolkit.buffer import Buffer +from prompt_toolkit.enums import EditingMode +from prompt_toolkit.input import create_pipe_input +from prompt_toolkit.output import DummyOutput +from prompt_toolkit.shortcuts import CompleteStyle + +import cmd2 + +pytestmark = pytest.mark.skipif( + sys.platform.startswith("win"), + reason="Don't have a real Windows console with how we are currently running tests in GitHub Actions", +) + +TAB = "\t" +ENTER = "\r" +LEFT = "\x1b[D" +CTRL_P = "\x10" +CTRL_R = "\x12" +CTRL_T = "\x14" + +# What the prompt has to look like before the next keys are sent +Ready = Callable[[Buffer], bool] + + +def shows(text: str) -> Ready: + """Wait for the command line to be exactly this text.""" + return lambda buffer: buffer.text == text + + +def menu(text: str, count: int) -> Ready: + """Wait for the command line to be this text with a menu of this many matches and none selected.""" + + def ready(buffer: Buffer) -> bool: + state = buffer.complete_state + return buffer.text == text and state is not None and len(state.completions) == count and state.complete_index is None + + return ready + + +def no_menu(buffer: Buffer) -> bool: + """Wait for the completion menu to close.""" + return buffer.complete_state is None + + +def press_keys( + app: cmd2.Cmd, + steps: list[tuple[str, Ready | None]], + *, + complete_in_thread: bool = True, + editing_mode: EditingMode = EditingMode.EMACS, + complete_style: CompleteStyle = CompleteStyle.MULTI_COLUMN, + read: Callable[[], str] | None = None, +) -> str: + """Send keys to a prompt and return the line it read. + + :param app: the application whose prompt is being typed into + :param steps: the keys to send, each with what to wait for before sending the next ones. + The last keys have to submit the line. + :param complete_in_thread: whether completion runs in a thread, as it does by default + :param editing_mode: which set of key bindings the prompt uses + :param complete_style: how the prompt shows completions + :param read: function which shows the prompt. Defaults to reading a command line. + """ + + async def send_keys() -> None: + prompt_app = get_app() + buffer = prompt_app.current_buffer + for keys, ready in steps: + pipe_input.send_text(keys) + if ready is None: + continue + for _ in range(500): + await asyncio.sleep(0.01) + try: + if ready(buffer): + break + except AssertionError as ex: + # End the prompt with the failure, since nothing else would end it + prompt_app.exit(exception=ex) + return + else: + state = buffer.complete_state + matches = None if state is None else [completion.text for completion in state.completions] + msg = f"after sending {keys!r} the command line was {buffer.text!r} and the menu had {matches!r}" + prompt_app.exit(exception=AssertionError(msg)) + return + + # The prompt ends this task when the line is submitted. Don't wait forever for that. + await asyncio.sleep(5) + prompt_app.exit(exception=AssertionError(f"the line was never submitted. It was {buffer.text!r}")) + + read_raw_input = app._read_raw_input + + def read_and_send_keys(prompt: Any, session: PromptSession[str], **_kwargs: Any) -> str: + return read_raw_input(prompt, session, pre_run=lambda: get_app().create_background_task(send_keys())) + + with create_pipe_input() as pipe_input, pytest.MonkeyPatch.context() as monkeypatch: + monkeypatch.setattr(app, "_read_raw_input", read_and_send_keys) + app.main_session = PromptSession( + input=pipe_input, + output=DummyOutput(), + completer=app.main_session.completer, + complete_in_thread=complete_in_thread, + complete_while_typing=False, + editing_mode=editing_mode, + complete_style=complete_style, + key_bindings=app.main_session.key_bindings, + ) + if read is None: + return app._read_command_line(app.prompt) + return read() + + +def make_files(directory: Path) -> None: + """Create the files and directories which the tests complete.""" + for name in ("my file.txt", "sp ace.txt", "spare.txt", "long name a.txt", "long name b.txt"): + (directory / name).touch() + for name in ("dd one", "dd two"): + (directory / name).mkdir() + (directory / "dd one" / "inner.txt").touch() + + +class DelimiterApp(cmd2.Cmd): + """Has a command whose argument is completed one segment at a time, like a path.""" + + def do_pick(self, _: cmd2.Statement) -> None: + """Pick something.""" + + def complete_pick(self, text: str, line: str, begidx: int, endidx: int) -> cmd2.Completions: + return self.delimiter_complete(text, line, begidx, endidx, ["some dir/next", "some file"], "/") + + +@pytest.fixture +def app(tmp_path, monkeypatch) -> cmd2.Cmd: + make_files(tmp_path) + monkeypatch.chdir(tmp_path) + return cmd2.Cmd() + + +@pytest.mark.parametrize("complete_in_thread", [True, False]) +def test_one_tab_completes_a_match_which_needs_a_quote(app, complete_in_thread) -> None: + line = press_keys( + app, + [ + ("edit my" + TAB, shows('edit "my file.txt" ')), + (ENTER, None), + ], + complete_in_thread=complete_in_thread, + ) + assert line == 'edit "my file.txt" ' + + +def test_one_tab_adds_the_quote_and_the_shared_prefix_and_opens_the_menu(app) -> None: + line = press_keys( + app, + [ + ("edit lo" + TAB, menu('edit "long name ', 2)), + (ENTER, None), + ], + ) + assert line == 'edit "long name ' + + +def test_one_tab_completes_a_shell_argument_which_needs_a_quote(app) -> None: + line = press_keys( + app, + [ + ("!ls my" + TAB, shows('!ls "my file.txt" ')), + (ENTER, None), + ], + ) + assert line == '!ls "my file.txt" ' + + +@pytest.mark.parametrize( + ("typed", "completed", "search_text"), + [ + ("edit spar", "edit spare.txt ", "spar"), + # The matches found before the quote was inserted are reused afterwards + ("edit my", 'edit "my file.txt" ', "my"), + ], + ids=["no-quote-needed", "quote-needed"], +) +def test_completion_runs_once_for_one_tab(app, monkeypatch, typed, completed, search_text) -> None: + texts = [] + complete = app.complete + + def counting_complete(text: str, *args: Any, **kwargs: Any) -> cmd2.Completions: + texts.append(text) + return complete(text, *args, **kwargs) + + monkeypatch.setattr(app, "complete", counting_complete) + + line = press_keys( + app, + [ + (typed + TAB, shows(completed)), + (ENTER, None), + ], + ) + assert line == completed + assert texts == [search_text] + + +def test_match_chosen_from_the_menu_closes_its_quote(app) -> None: + line = press_keys( + app, + [ + ('edit "sp' + TAB, menu('edit "sp', 2)), + # The trailing space keeps another Tab from completing right against the closing quote + (TAB, shows('edit "sp ace.txt" ')), + # The first Enter accepts the selection and the second one submits the line + (ENTER, no_menu), + (ENTER, None), + ], + ) + assert line == 'edit "sp ace.txt" ' + assert shlex.split(line) == ["edit", "sp ace.txt"] + + +def test_each_match_in_the_menu_closes_its_quote(app) -> None: + line = press_keys( + app, + [ + ("edit sp" + TAB, menu('edit "sp', 2)), + (TAB, shows('edit "sp ace.txt" ')), + (TAB, shows('edit "spare.txt" ')), + (ENTER, no_menu), + (ENTER, None), + ], + ) + assert line == 'edit "spare.txt" ' + + +def complete_at_cursor(app: cmd2.Cmd, line: str, *, choose_from_menu: bool) -> str: + """Type a line, put the cursor where its | is, complete there, and return what the line becomes. + + :param app: the application whose prompt is being typed into + :param line: the line to type, with a | where the cursor goes + :param choose_from_menu: True if several matches are expected, in which case the first one is chosen + """ + before_cursor, after_cursor = line.split("|") + lines = [] + + def menu_is_open(buffer: Buffer) -> bool: + state = buffer.complete_state + return state is not None and len(state.completions) > 1 and state.complete_index is None + + def match_is_selected(buffer: Buffer) -> bool: + state = buffer.complete_state + return state is not None and state.complete_index == 0 + + def match_is_inserted(buffer: Buffer) -> bool: + return buffer.text != before_cursor + after_cursor and buffer.complete_state is None + + def record(buffer: Buffer) -> bool: + lines.append(buffer.text) + return True + + typed = before_cursor + after_cursor + LEFT * len(after_cursor) + if choose_from_menu: + steps: list[tuple[str, Ready | None]] = [(typed + TAB, menu_is_open), (TAB, match_is_selected)] + else: + steps = [(typed + TAB, match_is_inserted)] + + # Clear what is in front of the cursor, which closes any menu, and submit what is left + press_keys(app, [*steps, ("", record), ("\x15" + ENTER, None)]) + return lines[0] + + +@pytest.mark.parametrize( + ("line", "expected"), + [ + # A closing quote right after the cursor is left to do its job + ('edit "my|"', 'edit "my file.txt"'), + # Anywhere else the only match closes its quote, whatever comes after it + ("edit my| other", 'edit "my file.txt" other'), + ('edit "my| other', 'edit "my file.txt" other'), + ("""shell cat my| 'a"b'""", """shell cat "my file.txt" 'a"b'"""), + ('edit my| 5" nail', 'edit "my file.txt" 5" nail'), + ("edit 'my| don't", "edit 'my file.txt' don't"), + ('shell cat "my| --title="x"', 'shell cat "my file.txt" --title="x"'), + ], +) +def test_only_match_in_the_middle_of_a_line(app, line, expected) -> None: + assert complete_at_cursor(app, line, choose_from_menu=False) == expected + + +@pytest.mark.parametrize( + ("line", "expected"), + [ + # A quote which the user typed is closed somewhere after the cursor, so nothing is added + ('edit "sp|"', 'edit "sp ace.txt"'), + ('edit "sp|.bak"', 'edit "sp ace.txt.bak"'), + ('shell cat "sp|.bak">out', 'shell cat "sp ace.txt.bak">out'), + ("""edit "sp| 'copy\"""", """edit "sp ace.txt 'copy\""""), + ('shell cat "sp| backup".txt', 'shell cat "sp ace.txt backup".txt'), + # It isn't closed, and it is left that way as it always has been. Telling this + # apart from the lines above would take guessing what the rest of the line means. + ('edit "sp| other', 'edit "sp ace.txt other'), + ('edit "sp| "spare.txt"', 'edit "sp ace.txt "spare.txt"'), + # cmd2 adds the opening quote around a word which ended at the cursor, so it closes it too + ("edit sp| other", 'edit "sp ace.txt" other'), + ("""shell cat sp| 'a"b'""", """shell cat "sp ace.txt" 'a"b'"""), + # The word carries on after the cursor, where a closing quote was left behind + ('edit sp|"', 'edit "sp ace.txt"'), + ], +) +def test_match_chosen_from_the_menu_in_the_middle_of_a_line(app, line, expected) -> None: + assert complete_at_cursor(app, line, choose_from_menu=True) == expected + + +def test_directory_chosen_from_the_menu_stays_open(app) -> None: + line = press_keys( + app, + [ + ("edit dd" + TAB, menu('edit "dd ', 2)), + (TAB, shows('edit "dd one/')), + (ENTER, no_menu), + # The quote was left open, so completion carries on inside the directory + (TAB, shows('edit "dd one/inner.txt" ')), + (ENTER, None), + ], + ) + assert line == 'edit "dd one/inner.txt" ' + + +def test_directory_chosen_after_a_shortcut_stays_open(app) -> None: + line = press_keys( + app, + [ + # @ is the shortcut for run_script. The quote goes after it. + ("@dd" + TAB, menu('@"dd ', 2)), + (TAB, shows('@"dd one/')), + (ENTER, no_menu), + (ENTER, None), + ], + ) + assert line == '@"dd one/' + + +def test_directory_chosen_in_front_of_a_separator_stays_open(app) -> None: + """A directory is offered without a trailing separator when one already follows the cursor.""" + rest_of_path = "/inner.txt" + line = press_keys( + app, + [ + ('edit "dd ' + rest_of_path + LEFT * len(rest_of_path) + TAB, menu('edit "dd /inner.txt', 2)), + (TAB, shows('edit "dd one/inner.txt')), + (ENTER, no_menu), + (ENTER, None), + ], + ) + assert line == 'edit "dd one/inner.txt' + + +def test_custom_completion_key_opens_the_menu_for_a_match_which_needs_a_quote(tmp_path, monkeypatch) -> None: + make_files(tmp_path) + monkeypatch.chdir(tmp_path) + app = cmd2.Cmd(completekey="c-t") + + line = press_keys( + app, + [ + # A custom key only opens the menu on its first press, whether or not the match needs a quote + ("edit my" + CTRL_T, menu("edit my", 1)), + (CTRL_T, shows('edit "my file.txt" ')), + (ENTER, no_menu), + (ENTER, None), + ], + ) + assert line == 'edit "my file.txt" ' + + +@pytest.mark.parametrize( + ("typed", "ready"), + [ + ("edit my", shows('edit "my file.txt" ')), + ("edit lo", menu('edit "long name ', 2)), + ], + ids=["one-match", "shared-prefix"], +) +def test_tab_still_completes_when_another_key_is_the_completion_key(tmp_path, monkeypatch, typed, ready) -> None: + """Tab goes on doing what it does by default, whatever the completion key is set to.""" + make_files(tmp_path) + monkeypatch.chdir(tmp_path) + app = cmd2.Cmd(completekey="c-t") + lines = [] + + def record(buffer: Buffer) -> bool: + lines.append(buffer.text) + return True + + press_keys( + app, + [ + (typed + TAB, ready), + ("", record), + # Clear the line, which closes any menu, and submit it + ("\x15" + ENTER, None), + ], + ) + assert len(lines) == 1 + + +def test_request_which_selects_the_last_match_does_so_when_matches_need_a_quote(app) -> None: + line = press_keys( + app, + [ + # Ctrl-P asks for the last match to be selected in Vi insert mode + ("edit sp" + CTRL_P, shows('edit "spare.txt" ')), + (ENTER, no_menu), + (ENTER, None), + ], + editing_mode=EditingMode.VI, + ) + assert line == 'edit "spare.txt" ' + + +def test_one_tab_adds_the_quote_and_the_shared_prefix_in_read_input(app) -> None: + line = press_keys( + app, + [ + ("ha" + TAB, menu('"has space ', 2)), + (TAB, shows('"has space one" ')), + (ENTER, no_menu), + (ENTER, None), + ], + read=lambda: app.read_input("> ", choices=["has space one", "has space two"]), + ) + assert line == '"has space one" ' + + +def test_tab_in_a_history_search_does_not_complete_the_search_text(app, monkeypatch) -> None: + texts = [] + monkeypatch.setattr(app, "complete", lambda text, *_args, **_kwargs: texts.append(text) or cmd2.Completions()) + + line = press_keys( + app, + [ + # Enter ends the search and then submits the line, which is empty since nothing was found + (CTRL_R + "my" + TAB + ENTER + ENTER, None), + ], + ) + assert line == "" + assert texts == [] + + +def test_finished_match_closes_its_quote_when_another_match_has_more_segments() -> None: + line = press_keys( + DelimiterApp(), + [ + ("pick so" + TAB, menu('pick "some ', 2)), + # This match has another segment after it, so its quote stays open + (TAB, shows('pick "some dir/')), + (TAB, shows('pick "some file" ')), + (ENTER, no_menu), + (ENTER, None), + ], + ) + assert line == 'pick "some file" ' + + +def test_prompt_ending_during_a_completion_leaves_no_listener_on_the_buffer(app, monkeypatch) -> None: + complete = app.complete + completing = threading.Event() + + def slow_complete(*args: Any, **kwargs: Any) -> cmd2.Completions: + # Find the matches, but don't return them until the user has submitted the line + completions = complete(*args, **kwargs) + completing.set() + prompt_app = get_app() + deadline = time.monotonic() + 5 + while not prompt_app.is_done and time.monotonic() < deadline: + time.sleep(0.005) + return completions + + monkeypatch.setattr(app, "complete", slow_complete) + + def completion_started(_: Buffer) -> bool: + return completing.is_set() + + line = press_keys( + app, + [ + ("edit my" + TAB, completion_started), + (ENTER, None), + ], + ) + assert line == "edit my" + + # Nothing of the abandoned request is attached to the buffer which the next prompt will use + handlers = app.main_session.default_buffer.on_completions_changed._handlers + assert [handler.__qualname__ for handler in handlers if "Cmd2Completer" in handler.__qualname__] == [] + + +def no_menu_after_a_moment() -> Ready: + """Wait a moment for a menu to open if one is going to, and fail if it does.""" + waiting_since: list[float] = [] + + def ready(buffer: Buffer) -> bool: + if not waiting_since: + waiting_since.append(time.monotonic()) + if time.monotonic() - waiting_since[0] < 0.3: + return False + if buffer.complete_state is not None: + raise AssertionError(f"a completion menu opened. The command line was {buffer.text!r}") + return True + + return ready + + +@pytest.mark.parametrize( + ("typed", "expected"), + [ + # Several matches which need no quote are listed above the prompt + ("h", "h"), + # The opening quote and the text the matches share are inserted before the rest is listed + ("edit lo", 'edit "long name '), + ("edit sp", 'edit "sp'), + # A single match is completed + ("edit my", 'edit "my file.txt" '), + # The quote goes after a shortcut, here the one for run_script + ("@my", '@"my file.txt" '), + ("@dd", '@"dd '), + ], +) +def test_tab_completes_like_readline_when_the_session_is_set_up_to(app, typed, expected) -> None: + lines = [] + + def record(buffer: Buffer) -> bool: + lines.append(buffer.text) + return True + + press_keys( + app, + [ + (typed + TAB, no_menu_after_a_moment()), + ("", record), + # Clear the line and submit it + ("\x15" + ENTER, None), + ], + complete_style=CompleteStyle.READLINE_LIKE, + ) + assert lines == [expected] + + +def test_binding_which_inserts_every_match_gets_each_with_its_own_quotes(app) -> None: + """Meta-* in Emacs mode asks for the completions itself and inserts all of them after the cursor.""" + lines = [] + + def record(buffer: Buffer) -> bool: + lines.append(buffer.text) + return True + + press_keys( + app, + [ + ("shell cat sp" + "\x1b*", shows('shell cat sp"sp ace.txt" "spare.txt" ')), + ("", record), + # Clear the line and submit it + ("\x15" + ENTER, None), + ], + ) + assert len(lines) == 1 diff --git a/tests/test_pt_utils.py b/tests/test_pt_utils.py index 69ed44290..e6e33c089 100644 --- a/tests/test_pt_utils.py +++ b/tests/test_pt_utils.py @@ -1,17 +1,31 @@ """Unit tests for cmd2/pt_utils.py""" +import asyncio import io import re +import threading +from collections.abc import Iterable from typing import Any, cast from unittest.mock import Mock import pytest +from prompt_toolkit.application import Application +from prompt_toolkit.application.current import set_app +from prompt_toolkit.auto_suggest import AutoSuggest, Suggestion +from prompt_toolkit.buffer import Buffer +from prompt_toolkit.completion import CompleteEvent, Completer, Completion, ThreadedCompleter from prompt_toolkit.document import Document from prompt_toolkit.formatted_text import ( ANSI, to_formatted_text, ) +from prompt_toolkit.input.defaults import DummyInput +from prompt_toolkit.layout import Layout +from prompt_toolkit.layout.containers import Window +from prompt_toolkit.layout.controls import BufferControl from prompt_toolkit.output.color_depth import ColorDepth +from prompt_toolkit.output.defaults import DummyOutput +from prompt_toolkit.shortcuts import CompleteStyle from rich.table import Table import cmd2 @@ -46,6 +60,8 @@ def __init__(self) -> None: self.aliases = {} self.macros = {} self.all_commands = [] + self.active_session = Mock() + self.active_session.complete_style = CompleteStyle.MULTI_COLUMN def get_all_commands(self) -> list[str]: return self.all_commands @@ -423,17 +439,26 @@ def test_get_completions_with_error(self, mock_cmd_app: MockCmd, monkeypatch) -> @pytest.mark.parametrize( # search_text_offset is the starting index of the user-provided search text within a full match. # This accounts for leading shortcuts (e.g., in '@has', the offset is 1). - ("line", "match", "search_text_offset"), + ("line", "match", "search_text_offset", "expected"), [ - ("has", "has space", 0), - ("@has", "@has space", 1), + ("has", "has space", 0, '"has space" '), + ("@has", "@has space", 1, '@"has space" '), ], ) - def test_get_completions_add_opening_quote_and_abort(self, line, match, search_text_offset, mock_cmd_app) -> None: - """Test case where adding an opening quote changes text before cursor. - - This applies when there is search text. - """ + @pytest.mark.parametrize( + "complete_event", + [ + None, + CompleteEvent(completion_requested=True), + # Not even the completion key's request can be started again without a running application + pt_utils._CompletionKeyEvent(), + ], + ids=["no-event", "requested", "completion-key"], + ) + def test_get_completions_add_opening_quote_in_front_of_search_text( + self, line, match, search_text_offset, expected, complete_event, mock_cmd_app + ) -> None: + """Test that a match carries the opening quote when it goes in front of text which was already typed.""" completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) # Set up document @@ -450,10 +475,542 @@ def test_get_completions_add_opening_quote_and_abort(self, line, match, search_t mock_cmd_app.complete.return_value = cmd2_completions # Call get_completions - completions = list(completer.get_completions(document, None)) + completions = list(completer.get_completions(document, complete_event)) - # get_completions inserted an opening quote in the buffer and then aborted before returning completions - assert not completions + # The completion replaces everything which was typed + assert [(c.text, c.start_position) for c in completions] == [(expected, -len(line))] + + @pytest.mark.parametrize( + ("complete_style", "buffer_line", "requested_line", "cursor_position", "expected_matches", "expected_buffer_line"), + [ + # The quote is put in the buffer, where the readline-style binding reads the line from again, + # so the match doesn't have to change text which is in front of the cursor + (CompleteStyle.READLINE_LIKE, "edit has", "edit has", 8, ['has space" '], 'edit "has'), + # The quote was added by cmd2, so a quote character in a later word doesn't close it + (CompleteStyle.READLINE_LIKE, 'edit has 5" nail', 'edit has 5" nail', 8, ['has space"'], 'edit "has 5" nail'), + # The request is not for what the buffer holds, so the buffer is left alone + (CompleteStyle.READLINE_LIKE, "edit other", "edit has", 8, ['"has space" '], "edit other"), + # Other bindings which ask directly, like Meta-* in Emacs mode, insert what they are given. + # They get whole matches with their own quotes and the buffer is left alone. + (CompleteStyle.MULTI_COLUMN, "edit has", "edit has", 8, ['"has space" '], "edit has"), + (CompleteStyle.COLUMN, "edit has", "edit has", 8, ['"has space" '], "edit has"), + ], + ) + def test_get_completions_add_opening_quote_for_synchronous_request( + self, + complete_style, + buffer_line, + requested_line, + cursor_position, + expected_matches, + expected_buffer_line, + mock_cmd_app: MockCmd, + ) -> None: + """Verify what a request made directly by one of prompt-toolkit's key bindings gets.""" + mock_cmd_app.active_session.complete_style = complete_style + + def complete(*_args: Any, **_kwargs: Any) -> cmd2.Completions: + # cmd2 switches the session to one of its menu styles whenever it completes + mock_cmd_app.active_session.complete_style = CompleteStyle.COLUMN + return cmd2.Completions([cmd2.CompletionItem("has space")], _add_opening_quote=True, _quote_char='"') + + mock_cmd_app.complete.side_effect = complete + completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + + async def run_test() -> tuple[list[str], str]: + buf = Buffer(document=Document(buffer_line, cursor_position=cursor_position), completer=completer) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = asyncio.get_running_loop() + + with set_app(app): + # This is how display_completions_like_readline() and the Emacs Meta-* binding ask for completions + complete_event = CompleteEvent(completion_requested=True) + document = Document(requested_line, cursor_position=cursor_position) + completions = list(completer.get_completions(document, complete_event)) + await self._wait_for_completion(app) + return [c.text for c in completions], buf.text + + assert asyncio.run(run_test()) == (expected_matches, expected_buffer_line) + + @pytest.mark.parametrize("complete_in_thread", [False, True]) + @pytest.mark.parametrize( + ("line", "matches", "search_text_offset", "expected_text", "expected_completion_count"), + [ + # Multiple matches: inserts opening quote + common prefix and displays completions + ("edit has", ["has space 1", "has space 2"], 0, 'edit "has space ', 2), + # Single match: inserts opening quote + match + closing quote + trailing space, no lingering menu + ("edit has", ["has space"], 0, 'edit "has space" ', 0), + # Shortcut prefix: inserts opening quote after shortcut and completes + ("@has", ["@has space"], 1, '@"has space" ', 0), + ], + ) + def test_get_completions_add_opening_quote_retriggers_completion( + self, + complete_in_thread: bool, + line: str, + matches: list[str], + search_text_offset: int, + expected_text: str, + expected_completion_count: int, + mock_cmd_app: MockCmd, + mocker: Any, + ) -> None: + """Verify inserting an opening quote restarts completion using cached results without re-calling complete().""" + table = Table() + table.add_column("Match") + table.add_row("info") + + mock_cmd_app.complete.return_value = cmd2.Completions( + [cmd2.CompletionItem(m) for m in matches], + table=table, + _add_opening_quote=True, + _search_text_offset=search_text_offset, + _quote_char='"', + ) + mock_print = mocker.patch("cmd2.pt_utils.print_formatted_text") + + base_completer: Completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + completer: Completer = ThreadedCompleter(base_completer) if complete_in_thread else base_completer + + async def run_completion() -> tuple[str, int]: + buf = Buffer(document=Document(line, cursor_position=len(line)), completer=completer) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = asyncio.get_running_loop() + + with set_app(app): + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + # Wait for all completion background tasks (first + re-triggered) to finish + for _ in range(20): + tasks = list(app._background_tasks) + if tasks: + await asyncio.gather(*tasks) + await asyncio.sleep(0) + if not app._background_tasks and buf.text != line: + break + + count = len(buf.complete_state.completions) if buf.complete_state else 0 + return buf.text, count + + final_text, completion_count = asyncio.run(run_completion()) + assert final_text == expected_text + assert completion_count == expected_completion_count + # Cached completions were reused on the re-triggered cycle: complete() and table print each ran once + assert mock_cmd_app.complete.call_count == 1 + assert mock_print.call_count == 1 + + @staticmethod + async def _wait_for_completion(app: Application[None]) -> None: + """Wait for a completion, and any completion which it restarts, to finish.""" + for _ in range(10): + tasks = list(app._background_tasks) + if tasks: + await asyncio.gather(*tasks) + await asyncio.sleep(0.005) + + @pytest.mark.parametrize( + ("interruption", "expected_text", "expected_calls"), + [ + ("cancel", "edit has", 2), + # prompt-toolkit completes the edited line itself, which is one more call + ("edit", "edit hasx", 3), + ], + ) + def test_get_completions_add_opening_quote_abandoned_request( + self, interruption: str, expected_text: str, expected_calls: int, mock_cmd_app: MockCmd + ) -> None: + """Verify nothing is inserted or kept for a request which is cancelled or outdated while cmd2 is completing.""" + line = "edit has" + completer = ThreadedCompleter(pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))) + + async def run_test() -> tuple[str, str]: + loop = asyncio.get_running_loop() + completing = asyncio.Event() + interrupted = threading.Event() + + def slow_complete(text: str, *_args: Any, **_kwargs: Any) -> cmd2.Completions: + # Keep the request busy in its thread until it has been interrupted + loop.call_soon_threadsafe(completing.set) + interrupted.wait(timeout=5) + if text != "has": + return cmd2.Completions() + return cmd2.Completions([cmd2.CompletionItem("has space")], _add_opening_quote=True, _quote_char='"') + + mock_cmd_app.complete.side_effect = slow_complete + + buf = Buffer(document=Document(line, cursor_position=len(line)), completer=completer) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = loop + + with set_app(app): + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + await completing.wait() + if interruption == "cancel": + buf.cancel_completion() + else: + buf.insert_text("x") + interrupted.set() + await self._wait_for_completion(app) + text_after_interruption = buf.text + + # The next request for the original line has to ask cmd2 again + buf.set_document(Document(line, cursor_position=len(line))) + mock_cmd_app.complete.side_effect = None + mock_cmd_app.complete.return_value = cmd2.Completions( + [cmd2.CompletionItem("has changed")], _add_opening_quote=True, _quote_char='"' + ) + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + await self._wait_for_completion(app) + return text_after_interruption, buf.text + + text_after_interruption, final_text = asyncio.run(run_test()) + assert text_after_interruption == expected_text + assert final_text == 'edit "has changed" ' + assert mock_cmd_app.complete.call_count == expected_calls + + @pytest.mark.parametrize("complete_in_thread", [False, True]) + def test_get_completions_add_opening_quote_with_complete_while_typing( + self, complete_in_thread: bool, mock_cmd_app: MockCmd + ) -> None: + """Verify inserting the quote doesn't start an automatic completion which takes the place of the restart.""" + line = "edit has" + + def complete(_text: str, *, line: str, **_kwargs: Any) -> cmd2.Completions: + if '"' in line: + return cmd2.Completions([cmd2.CompletionItem("has space")], _quote_char='"') + return cmd2.Completions([cmd2.CompletionItem("has space")], _add_opening_quote=True, _quote_char='"') + + mock_cmd_app.complete.side_effect = complete + base_completer: Completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + completer: Completer = ThreadedCompleter(base_completer) if complete_in_thread else base_completer + + async def run_test() -> str: + buf = Buffer( + document=Document(line, cursor_position=len(line)), + completer=completer, + complete_while_typing=True, + ) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = asyncio.get_running_loop() + + with set_app(app): + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + await self._wait_for_completion(app) + return buf.text + + assert asyncio.run(run_test()) == 'edit "has space" ' + + # The line with only the quote inserted was completed from the matches which had already been found. + # prompt-toolkit then completes the finished line itself, as it does after any text is inserted. + completed_lines = [call.kwargs["line"] for call in mock_cmd_app.complete.call_args_list] + assert completed_lines == [line, 'edit "has space" '] + + @pytest.mark.parametrize("complete_while_typing", [False, True]) + def test_get_completions_add_opening_quote_updates_suggestion( + self, complete_while_typing: bool, mock_cmd_app: MockCmd + ) -> None: + """Verify the line with the quote in it is offered to auto-suggest, as any other inserted text is.""" + line = "edit has" + mock_cmd_app.complete.return_value = cmd2.Completions( + # These have nothing in common past what was typed, so the quote is all which gets inserted + [cmd2.CompletionItem("has space"), cmd2.CompletionItem("hash")], + _add_opening_quote=True, + _quote_char='"', + ) + completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + suggested_for: list[str] = [] + + class RecordsRequests(AutoSuggest): + def get_suggestion(self, _buffer: Buffer, document: Document) -> Suggestion | None: + suggested_for.append(document.text) + return None + + async def run_test() -> str: + buf = Buffer( + document=Document(line, cursor_position=len(line)), + completer=completer, + auto_suggest=RecordsRequests(), + complete_while_typing=complete_while_typing, + ) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = asyncio.get_running_loop() + + with set_app(app): + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + await self._wait_for_completion(app) + return buf.text + + assert asyncio.run(run_test()) == 'edit "has' + assert suggested_for == ['edit "has'] + + # Inserting the quote didn't make the buffer complete the line on its own + assert mock_cmd_app.complete.call_count == 1 + + def test_get_completions_add_opening_quote_waits_for_running_request(self, mock_cmd_app: MockCmd) -> None: + """Verify the quote is inserted once prompt-toolkit has finished a request it was still waiting on. + + This is what happens when a completion which runs in a thread takes a while. prompt-toolkit + ignores a completion which is started before it has finished the request. + """ + line = "edit has" + completer = ThreadedCompleter(pt_utils.Cmd2Completer(cast(Any, mock_cmd_app))) + + async def run_test() -> str: + loop = asyncio.get_running_loop() + completing = asyncio.Event() + waited_on = threading.Event() + + def slow_complete(*_args: Any, **_kwargs: Any) -> cmd2.Completions: + # Don't return until prompt-toolkit is waiting for the results + loop.call_soon_threadsafe(completing.set) + waited_on.wait(timeout=5) + return cmd2.Completions([cmd2.CompletionItem("has space")], _add_opening_quote=True, _quote_char='"') + + mock_cmd_app.complete.side_effect = slow_complete + + buf = Buffer(document=Document(line, cursor_position=len(line)), completer=completer) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = loop + + with set_app(app): + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + await completing.wait() + waited_on.set() + await self._wait_for_completion(app) + + # cmd2 has stopped listening to the buffer + handlers = buf.on_completions_changed._handlers + assert [handler.__qualname__ for handler in handlers if "Cmd2Completer" in handler.__qualname__] == [] + return buf.text + + assert asyncio.run(run_test()) == 'edit "has space" ' + assert mock_cmd_app.complete.call_count == 1 + + def test_get_completions_add_opening_quote_cancelled_before_request_finished(self, mock_cmd_app: MockCmd) -> None: + """Verify nothing is inserted if the request is cancelled after cmd2 has completed it. + + prompt-toolkit hasn't been told that the request is finished at that point. + """ + line = "edit has" + mock_cmd_app.complete.return_value = cmd2.Completions( + [cmd2.CompletionItem("has space")], _add_opening_quote=True, _quote_char='"' + ) + cmd2_completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + + async def run_test() -> str: + loop = asyncio.get_running_loop() + cancelled = False + + class CancelledAfterCompleting(Completer): + """Has the user cancel the first request right after cmd2 has returned its results.""" + + def get_completions(self, document: Document, complete_event: CompleteEvent) -> Iterable[Completion]: + nonlocal cancelled + yield from cmd2_completer.get_completions(document, complete_event) + if not cancelled: + cancelled = True + loop.call_soon_threadsafe(buf.cancel_completion) + + buf = Buffer( + document=Document(line, cursor_position=len(line)), + completer=ThreadedCompleter(CancelledAfterCompleting()), + ) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = loop + + with set_app(app): + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + await self._wait_for_completion(app) + return buf.text + + assert asyncio.run(run_test()) == line + assert mock_cmd_app.complete.call_count == 1 + + @pytest.mark.parametrize("complete_in_thread", [False, True]) + def test_get_completions_add_opening_quote_keeps_selection_of_other_requests( + self, complete_in_thread: bool, mock_cmd_app: MockCmd + ) -> None: + """Verify a request which selects a match gets the quote in each match instead of a restarted completion. + + Starting again would turn it into a request for the common prefix of the matches. That is + only right for a request which comes from the completion key. + """ + line = "edit has" + mock_cmd_app.complete.return_value = cmd2.Completions( + [cmd2.CompletionItem("has space 1"), cmd2.CompletionItem("has space 2")], + _add_opening_quote=True, + _quote_char='"', + ) + base_completer: Completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + completer: Completer = ThreadedCompleter(base_completer) if complete_in_thread else base_completer + + async def run_test() -> tuple[str, int | None]: + buf = Buffer(document=Document(line, cursor_position=len(line)), completer=completer) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = asyncio.get_running_loop() + + with set_app(app): + # What Ctrl-P does in Vi insert mode + buf.start_completion(select_last=True) + await self._wait_for_completion(app) + assert buf.complete_state is not None + return buf.text, buf.complete_state.complete_index + + assert asyncio.run(run_test()) == ('edit "has space 2" ', 1) + assert mock_cmd_app.complete.call_count == 1 + + def test_get_completions_add_opening_quote_does_not_hide_notifications(self, mock_cmd_app: MockCmd) -> None: + """Verify a listener registered after cmd2's own still hears that the first request finished.""" + line = "edit has" + mock_cmd_app.complete.return_value = cmd2.Completions( + [cmd2.CompletionItem("has space")], _add_opening_quote=True, _quote_char='"' + ) + cmd2_completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + + async def run_test() -> list[tuple[str, bool]]: + heard: list[tuple[str, bool]] = [] + listening = False + + def listener(buffer: Buffer) -> None: + heard.append((buffer.text, buffer.complete_state is None)) + + class RegistersListener(Completer): + """Adds a listener once cmd2 has registered its own for the first request.""" + + def get_completions(self, document: Document, complete_event: CompleteEvent) -> Iterable[Completion]: + nonlocal listening + yield from cmd2_completer.get_completions(document, complete_event) + if not listening: + listening = True + buf.on_completions_changed += listener + + buf = Buffer(document=Document(line, cursor_position=len(line)), completer=RegistersListener()) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = asyncio.get_running_loop() + + with set_app(app): + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + await self._wait_for_completion(app) + assert buf.text == 'edit "has space" ' + return heard + + # prompt-toolkit clears the state of the first request and says so before the quote is inserted + assert (line, True) in asyncio.run(run_test()) + + def test_get_completions_add_opening_quote_skips_if_prompt_ended(self, mock_cmd_app: MockCmd) -> None: + """Verify the quote is not inserted if the line is submitted just as the request finishes.""" + line = "edit has" + mock_cmd_app.complete.return_value = cmd2.Completions( + [cmd2.CompletionItem("has space")], _add_opening_quote=True, _quote_char='"' + ) + cmd2_completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + + async def run_test() -> str: + loop = asyncio.get_running_loop() + listening = False + + def end_prompt_when_request_finishes(buffer: Buffer) -> None: + # prompt-toolkit clears the state once the request has returned no matches. cmd2 has been told + # that already, since it listens ahead of this, and is about to insert the quote. + if buffer.complete_state is None and app.future is None: + app.future = loop.create_future() + app.future.set_result(None) + + class RegistersListener(Completer): + """Adds a listener once cmd2 has registered its own for the first request.""" + + def get_completions(self, document: Document, complete_event: CompleteEvent) -> Iterable[Completion]: + nonlocal listening + yield from cmd2_completer.get_completions(document, complete_event) + if not listening: + listening = True + buf.on_completions_changed += end_prompt_when_request_finishes + + buf = Buffer(document=Document(line, cursor_position=len(line)), completer=RegistersListener()) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = loop + + with set_app(app): + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + await self._wait_for_completion(app) + return buf.text + + assert asyncio.run(run_test()) == line + + def test_get_completions_add_opening_quote_skips_if_document_changed(self, mock_cmd_app: MockCmd) -> None: + """Verify deferred quote insertion bails out if the user edits the buffer just as the request finishes.""" + line = "edit has" + mock_cmd_app.complete.return_value = cmd2.Completions( + [cmd2.CompletionItem("has space")], + _add_opening_quote=True, + _search_text_offset=0, + _quote_char='"', + ) + completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + + async def run_test() -> str: + buf = Buffer(document=Document(line, cursor_position=len(line)), completer=completer) + app: Application[None] = Application( + layout=Layout(Window(BufferControl(buffer=buf))), + input=DummyInput(), + output=DummyOutput(), + ) + app.loop = asyncio.get_running_loop() + + def edit_when_request_finishes(_: Buffer) -> None: + # prompt-toolkit clears the completion state once the request has returned no matches. + # The quote has not been inserted yet at that point. + if buf.complete_state is None and buf.text == line: + buf.insert_text("x") + + buf.on_completions_changed += edit_when_request_finishes + + with set_app(app): + buf.start_completion(insert_common_part=True, complete_event=pt_utils._CompletionKeyEvent()) + await self._wait_for_completion(app) + return buf.text + + assert asyncio.run(run_test()) == "edit hasx" + assert mock_cmd_app.complete.call_count == 1 @pytest.mark.parametrize( # search_text_offset is the starting index of the user-provided search text within a full match. @@ -463,9 +1020,9 @@ def test_get_completions_add_opening_quote_and_abort(self, line, match, search_t # Single matches need opening quote, closing quote, and trailing space ("", ["has space"], 0, '"', ['"has space" ']), ("@", ["@has space"], 1, "'", ["@'has space' "]), - # Multiple matches only need opening quote - ("", ["has space", "more space"], 0, '"', ['"has space', '"more space']), - ("@", ["@has space", "@more space"], 1, "'", ["@'has space", "@'more space"]), + # Multiple matches need the same, so choosing one of them leaves it finished + ("", ["has space", "more space"], 0, '"', ['"has space" ', '"more space" ']), + ("@", ["@has space", "@more space"], 1, "'", ["@'has space' ", "@'more space' "]), ], ) def test_get_completions_add_opening_quote_and_return_results( @@ -564,6 +1121,176 @@ def test_get_completions_do_not_allow_finalization( completions = list(completer.get_completions(document, None)) assert completions[0].text == expected + @pytest.mark.parametrize( + ("line", "items", "quote_char", "allow_finalization", "expected"), + [ + # Each match closes a quote which is open and adds a trailing space + ( + '"ma', + [cmd2.CompletionItem("match one"), cmd2.CompletionItem("match two")], + '"', + True, + ['match one" ', 'match two" '], + ), + ( + "'ma", + [cmd2.CompletionItem("match one"), cmd2.CompletionItem("match two")], + "'", + True, + ["match one' ", "match two' "], + ), + # Nothing is added when no quote is open + ("ma", [cmd2.CompletionItem("match"), cmd2.CompletionItem("matter")], "", True, ["match", "matter"]), + # No match closes the quote when the matches are not allowed to be finalized + ( + '"ma', + [cmd2.CompletionItem("match one"), cmd2.CompletionItem("match two")], + '"', + False, + ["match one", "match two"], + ), + # A match which can't be finalized itself, like a directory, leaves the quote open + ( + '"ma', + [cmd2.CompletionItem("match dir/", _allow_finalization=False), cmd2.CompletionItem("match file")], + '"', + True, + ["match dir/", 'match file" '], + ), + ], + ) + def test_get_completions_close_quote_of_each_of_several_matches( + self, line, items, quote_char, allow_finalization, expected, mock_cmd_app: MockCmd + ) -> None: + """Test that a match chosen from several does not leave its quote open.""" + completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + document = Document(line, cursor_position=len(line)) + + mock_cmd_app.complete.return_value = cmd2.Completions( + items, + allow_finalization=allow_finalization, + _quote_char=quote_char, + ) + + completions = list(completer.get_completions(document, None)) + assert [c.text for c in completions] == expected + + @pytest.mark.parametrize( + ("line", "matches", "quote_char", "expected"), + [ + # A closing quote right after the cursor is never doubled + ('"ma"', ["match"], '"', ["match"]), + ('"ma"', ["match one", "match two"], '"', ["match one", "match two"]), + ("'ma' more", ["match one", "match two"], "'", ["match one", "match two"]), + # Otherwise the only match closes its quote + ('"ma.txt"', ["match"], '"', ['match"']), + ('"ma more', ["match"], '"', ['match"']), + ("\"ma'", ["match"], '"', ['match"']), + ('"ma --title="x"', ["match"], '"', ['match"']), + # A match chosen from several leaves a quote which the user typed as it is + ('"ma.txt"', ["match one", "match two"], '"', ["match one", "match two"]), + ('"ma more', ["match one", "match two"], '"', ["match one", "match two"]), + ('"ma "next"', ["match one", "match two"], '"', ["match one", "match two"]), + ], + ) + def test_get_completions_closing_quote_in_the_middle_of_a_line( + self, line, matches, quote_char, expected, mock_cmd_app: MockCmd + ) -> None: + """Test what is added to a match when the user typed the opening quote and text follows the cursor.""" + completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + + # The cursor is right after the search text + document = Document(line, cursor_position=3) + + mock_cmd_app.complete.return_value = cmd2.Completions( + [cmd2.CompletionItem(match) for match in matches], + _quote_char=quote_char, + ) + + completions = list(completer.get_completions(document, None)) + assert [c.text for c in completions] == expected + + @pytest.mark.parametrize( + ("line", "cursor_position", "matches", "expected"), + [ + # The word which cmd2 puts in quotes ended at the cursor, so each match closes the quote + ("ma more", 2, ["match one", "match two"], ['"match one"', '"match two"']), + ("ma 'a\"b'", 2, ["match one", "match two"], ['"match one"', '"match two"']), + ("ma 'a\"b'", 2, ["match"], ['"match"']), + # The word carries on after the cursor, so what follows may be the rest of it + ('ma"', 2, ["match one", "match two"], ['"match one', '"match two']), + ("mab", 2, ["match one", "match two"], ['"match one', '"match two']), + ('ma"', 2, ["match"], ['"match']), + ("mab", 2, ["match"], ['"match"']), + ], + ) + @pytest.mark.parametrize("quote_already_inserted", [False, True]) + def test_get_completions_close_quote_which_cmd2_opened( + self, line, cursor_position, matches, expected, quote_already_inserted, mock_cmd_app: MockCmd + ) -> None: + """Test what is added to a match when cmd2 adds the opening quote and text follows the cursor.""" + completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + items = [cmd2.CompletionItem(match) for match in matches] + + if quote_already_inserted: + # The quote was put in the buffer and completion was started again with the matches found before + document = Document('"' + line, cursor_position=cursor_position + 1) + complete_event: object = pt_utils._QuoteInsertedEvent(document, cmd2.Completions(items, _quote_char='"')) + expected = [text.removeprefix('"') for text in expected] + else: + # The quote is part of each match + document = Document(line, cursor_position=cursor_position) + complete_event = None + mock_cmd_app.complete.return_value = cmd2.Completions(items, _add_opening_quote=True, _quote_char='"') + + completions = list(completer.get_completions(document, complete_event)) + assert [c.text for c in completions] == expected + + @pytest.mark.parametrize( + ("line", "quote_char", "expected"), + [ + ("ma", "", "match dir/"), + ('"ma', '"', "match dir/"), + ], + ) + def test_get_completions_single_match_which_is_not_finished( + self, line, quote_char, expected, mock_cmd_app: MockCmd + ) -> None: + """Test that the only match is left open when it is marked as one the user will keep completing. + + This is what a completer gets if it filters the results of path_complete() or + delimiter_complete() down to a single directory-like match. + """ + completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + document = Document(line, cursor_position=len(line)) + + mock_cmd_app.complete.return_value = cmd2.Completions( + [cmd2.CompletionItem("match dir/", _allow_finalization=False)], + _quote_char=quote_char, + ) + + completions = list(completer.get_completions(document, None)) + assert [c.text for c in completions] == [expected] + + def test_get_completions_ignores_matches_found_for_another_document(self, mock_cmd_app: MockCmd) -> None: + """Verify matches which were found before a quote was inserted are only used for the line they are for.""" + completer = pt_utils.Cmd2Completer(cast(Any, mock_cmd_app)) + quoted_document = Document('edit "has', cursor_position=9) + found = cmd2.Completions([cmd2.CompletionItem("has space")], _quote_char='"') + complete_event = pt_utils._QuoteInsertedEvent(quoted_document, found) + + # They are used for the line which the quote was inserted in + completions = list(completer.get_completions(quoted_document, complete_event)) + assert [c.text for c in completions] == ['has space" '] + assert mock_cmd_app.complete.call_count == 0 + + # The user typed another character before the completion started + mock_cmd_app.complete.return_value = cmd2.Completions([cmd2.CompletionItem("hash value")], _quote_char='"') + edited_document = Document('edit "hash', cursor_position=10) + completions = list(completer.get_completions(edited_document, complete_event)) + assert [c.text for c in completions] == ['hash value" '] + assert mock_cmd_app.complete.call_count == 1 + def test_init_with_custom_settings(self, mock_cmd_app: MockCmd) -> None: """Test initializing with custom settings.""" mock_parser = Mock()