From 6c435c19b3ed1b37a32fc4e4cee1880abdddee9f Mon Sep 17 00:00:00 2001 From: Dang Pham Date: Wed, 2 Dec 2026 14:40:31 +0700 Subject: [PATCH] Strip ANSI style sequences for external pager on legacy Windows console --- cmd2/cmd2.py | 6 +++++- tests/test_cmd2.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 653942444..eed8ed117 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -2088,8 +2088,12 @@ def ppaged( soft_wrap=pager_soft_wrap, **(rich_print_kwargs if rich_print_kwargs is not None else {}), ) + output = capture.get() + if console.legacy_windows: + # A legacy Windows console prints ANSI style sequences as text when an external pager writes them. + output = su.strip_style(output) # As for a pipe: the pager gets UTF-8, and on Windows the console is UTF-8 while it runs. - output_bytes = capture.get().encode("utf-8", "replace") + output_bytes = output.encode("utf-8", "replace") # Prevent KeyboardInterrupts while in the pager. The pager application will # still receive the SIGINT since it is in the same process group as us. diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index c7e4b6286..5e39d6640 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -4237,6 +4237,49 @@ def utf8_console(): assert events == ["utf-8 console", "pager started", "pager exited", "restored"] +@pytest.mark.parametrize( + ("legacy_windows", "allow_style", "expect_ansi"), + [ + (True, ru.AllowStyle.TERMINAL, False), + (False, ru.AllowStyle.TERMINAL, True), + (False, ru.AllowStyle.NEVER, False), + (True, ru.AllowStyle.ALWAYS, False), + ], +) +def test_ppaged_strips_style_only_on_legacy_windows( + outsim_app, + monkeypatch, + legacy_windows: bool, + allow_style: ru.AllowStyle, + expect_ansi: bool, +) -> None: + """An external pager on a legacy Windows console cannot interpret ANSI style sequences.""" + stdin_mock = mock.MagicMock() + stdin_mock.isatty.return_value = True + monkeypatch.setattr(outsim_app, "stdin", stdin_mock) + stdout_mock = mock.MagicMock() + stdout_mock.isatty.return_value = True + monkeypatch.setattr(outsim_app, "stdout", stdout_mock) + if not sys.platform.startswith("win") and os.environ.get("TERM") is None: + monkeypatch.setenv("TERM", "simulated") + monkeypatch.setattr("rich.console.detect_legacy_windows", lambda: legacy_windows) + monkeypatch.setattr(ru, "ALLOW_STYLE", allow_style) + + popen_mock = mock.MagicMock(name="Popen") + monkeypatch.setattr("subprocess.Popen", popen_mock) + + outsim_app.ppaged( + su.stylize("row 0", Color.GREEN), + "plain", + Text("bold red", style="bold red"), + ) + paged = popen_mock.return_value.communicate.call_args.args[0] + if expect_ansi: + assert paged == b"\x1b[32mrow 0\x1b[0m plain \x1b[1;31mbold red\x1b[0m\n" + else: + assert paged == b"row 0 plain bold red\n" + + class FakeTerminal(io.TextIOWrapper): """A real file which says it is a terminal, so that a pager's shell can be given it to write to."""