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
6 changes: 5 additions & 1 deletion cmd2/cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
43 changes: 43 additions & 0 deletions tests/test_cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
Loading