Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
47 changes: 39 additions & 8 deletions cmd2/cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ def __init__(self, msg: str = "") -> None:
Cmd2Completer,
Cmd2History,
Cmd2Lexer,
_CompletionKeyEvent,
pt_filter_style,
pt_resolve_color_depth,
)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -2347,32 +2369,38 @@ 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)

full_value = delimiter.join(match_tokens[: display_token_index + 1])
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
Expand Down Expand Up @@ -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)

Expand Down
12 changes: 11 additions & 1 deletion cmd2/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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

#####################################################################
Expand Down
Loading
Loading