From 2a9ca6f5e3a1b51d301698254244dbf82b686d88 Mon Sep 17 00:00:00 2001 From: Moksh Upadhyay Date: Thu, 3 Dec 2026 22:21:34 +0530 Subject: [PATCH] Fix macro resolution when an escaped argument follows a normal one --- cmd2/cmd2.py | 7 +++++-- tests/test_cmd2.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index e8e473447..27ad738e6 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -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 :]: diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index 5e39d6640..dac6d65eb 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -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}")