Skip to content
Merged
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
7 changes: 5 additions & 2 deletions cmd2/cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -3395,8 +3395,11 @@ def _resolve_macro(self, statement: Statement) -> str:
to_replace = "{" + macro_arg.number_str + "}"
replacement = statement.argv[int(macro_arg.number_str)]

parts = resolved.rsplit(to_replace, maxsplit=1)
resolved = parts[0] + replacement + parts[1]
# Replace the occurrence at the recorded index instead of searching for the last
# one. A replacement's text can contain what looks like another placeholder (such
# as an unescaped one), which would fool a search and resolve the wrong instance.
end_index = macro_arg.start_index + len(to_replace)
resolved = resolved[: macro_arg.start_index] + replacement + resolved[end_index:]

# Append extra arguments and use statement.arg_list since these arguments need their quotes preserved
for stmt_arg in statement.arg_list[macro.minimum_arg_count :]:
Expand Down
10 changes: 10 additions & 0 deletions tests/test_cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -3932,6 +3932,16 @@ def test_macro_create_with_escaped_args(base_app) -> None:
assert err[0].startswith("No help on {1}")


def test_macro_escaped_arg_after_normal_arg(base_app) -> None:
# Create a macro with a normal argument followed by an escaped one
out, _err = run_cmd(base_app, 'macro create fake {1} "{{1}}"')
assert out == normalize("Macro 'fake' created")

# The normal argument resolves and the escaped one becomes a literal {1}
_out, err = run_cmd(base_app, "fake help")
assert err[0].startswith("No help on {1}")


def test_macro_usage_with_missing_args(base_app) -> None:
# Create the macro
out, err = run_cmd(base_app, "macro create fake help {1} {2}")
Expand Down
Loading