Skip to content
Myr

Strip all ANSI sequences

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 8a4ce84 · Browse files · 5 files+254 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+254 added−2 removed

  • tests:+247 added−1 removed
  • other:+7 added−1 removed

5 files+254 added−2 removed

modified:src/click/_compat.py+5 added-1 removed
10 unmodified lines
11from weakref import WeakKeyDictionary1213CYGWIN = sys.platform.startswith("cygwin")14WIN = sys.platform.startswith("win")15# One CSI escape sequence per the ECMA-48 grammar: parameter bytes (0x30-0x3F),16# intermediate bytes (0x20-0x2F), then a final byte (0x40-0x7E). Broader than the17# SGR codes Click emits, so foreign sequences (colon-delimited true-color, mouse18# reporting) are stripped too.15_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")19_ansi_re = re.compile(r"\033\[[0-?]*[ -/]*[@-~]")202122def _make_text_stream(23 stream: t.BinaryIO,
567 unmodified lines
modified:tests/test_utils/test_style.py+16 added-1 removed
105 unmodified lines
106 with pytest.raises(ValueError, match="Unknown color"):107 click.style("x y", **{param: value})108109110@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])110@pytest.mark.parametrize(111 ("text", "expect"),112 [113 ("\x1b[?25lx y\x1b[?25h", "x y"),114 # Colon-delimited true-color SGR (ISO 8613-6).115 ("\x1b[38:2:255:0:0mx y\x1b[0m", "x y"),116 # 256-color with colon sub-parameters.117 ("\x1b[38:5:200mx y\x1b[0m", "x y"),118 # SGR mouse reporting.119 ("\x1b[<0;1;1Mx y\x1b[<0;1;1m", "x y"),120 # Intermediate byte before the final byte.121 ("\x1b[0 qx y", "x y"),122 # Non-letter final byte.123 ("x\x1b[3~y", "xy"),124 ],125)126def test_unstyle_other_ansi(text, expect):127 assert click.unstyle(text) == expect
modified:tests/test_compat.py+215 added
1from __future__ import annotations23import re4import sys56import pytest78import click9from click._compat import _ansi_re10from click._compat import strip_ansi11from click._compat import term_len12from click._textwrap import _truncate_visible1314ESC = "\033"1516# Inventory of every escape sequence Click itself emits. ``strip_ansi`` must17# keep removing all of them.18CLICK_EMITTED = [19 # SGR foreground/background, the basic 16 colors.20 f"{ESC}[30m",21 f"{ESC}[37m",22 f"{ESC}[40m",23 f"{ESC}[47m",24 # SGR 256-color and true-color (Click renders these with semicolons).25 f"{ESC}[38;5;200m",26 f"{ESC}[48;5;91m",27 f"{ESC}[38;2;255;12;128m",28 f"{ESC}[48;2;135;0;175m",29 # SGR attributes and their resets.30 f"{ESC}[1m",31 f"{ESC}[22m",32 f"{ESC}[4m",33 f"{ESC}[24m",34 f"{ESC}[53m",35 f"{ESC}[55m",36 f"{ESC}[9m",37 f"{ESC}[29m",38 # Reset-all appended by style().39 f"{ESC}[0m",40 # Screen clear and cursor home from click.clear().41 f"{ESC}[2J",42 f"{ESC}[1;1H",43 # Cursor hide/show around the progress bar.44 f"{ESC}[?25l",45 f"{ESC}[?25h",46]4748# CSI sequences Click never emits but may receive from other tooling.49CSI_FOREIGN = [50 # Colon-delimited (ISO 8613-6) true-color and 256-color SGR.51 f"{ESC}[38:2:255:0:0m",52 f"{ESC}[38:5:200m",53 f"{ESC}[1;38:2::255:0:0m", # empty colon field is a valid parameter54 # SGR mouse reporting (the ``<`` parameter byte is 0x3C).55 f"{ESC}[<0;30;40M",56 f"{ESC}[<0;30;40m",57 # Private-mode set/reset with a multi-digit parameter.58 f"{ESC}[?1049h",59 f"{ESC}[?1049l",60 # Cursor-shape select: an intermediate byte (space, 0x20) before final ``q``.61 f"{ESC}[0 q",62 f"{ESC}[2 q",63 # Set scrolling region: a non-``m`` letter final byte.64 f"{ESC}[1;24r",65 # Function-key / bracketed-paste codes ending in ``~`` (0x7E).66 f"{ESC}[3~",67 f"{ESC}[200~",68 # Empty parameter list (``ESC [ m`` is a valid reset).69 f"{ESC}[m",70]7172# The previous pattern, kept here to prove the new one is a superset.73_LEGACY_ANSI_RE = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")747576def test_is_jupyter_kernel_output():77 class JupyterKernelFakeStream:78 pass79
38 unmodified lines
118119 if expected_override is not None:120 expected = expected_override121 assert click._compat.should_strip_ansi(stream=stream, color=color) == expected122123124@pytest.mark.parametrize("seq", CLICK_EMITTED + CSI_FOREIGN)125def test_strip_ansi_removes_full_sequence(seq):126 """Every complete CSI sequence is stripped, alone or wrapped in text."""127 assert strip_ansi(seq) == ""128 assert strip_ansi(f"a{seq}b") == "ab"129 assert term_len(f"a{seq}b") == 2130131132@pytest.mark.parametrize("final", ["m", "H", "J", "A", "z"])133@pytest.mark.parametrize("params", ["", "0", "1;2", ";", "?25", "0;0;0"])134def test_strip_ansi_is_superset_of_legacy(params, final):135 """Everything the legacy pattern stripped, the CSI grammar still strips."""136 seq = f"{ESC}[{params}{final}"137 assert _LEGACY_ANSI_RE.fullmatch(seq) is not None138 assert strip_ansi(seq) == ""139 assert strip_ansi(f"a{seq}b") == "ab"140141142@pytest.mark.parametrize(143 ("text", "expected"),144 [145 (f"{ESC}[31mred{ESC}[0m", "red"),146 (f"a{ESC}[38:2:1:2:3mb{ESC}[0mc", "abc"),147 (f"{ESC}[?25l{ESC}[2Jhidden{ESC}[?25h", "hidden"),148 (f"{ESC}[<0;1;1Mclick{ESC}[<0;1;1m", "click"),149 # Several adjacent sequences around each visible character.150 (f"{ESC}[1m{ESC}[31mA{ESC}[0m {ESC}[32mB{ESC}[0m", "A B"),151 # Real terminal captures ported from the boltons strip_ansi tests.152 # ANSI art fragment (its doctest example).153 (f"{ESC}[0m{ESC}[1;36mart{ESC}[46;34m\xdc", "art\xdc"),154 # `ls` color output, ending on a dangling SGR with no text after it.155 (156 f"ls\r\n{ESC}[00m{ESC}[01;31mfile.zip{ESC}[00m\r\n{ESC}[01;31m",157 "ls\r\nfile.zip\r\n",158 ),159 # Tab-separated colorized fields.160 (f"\t{ESC}[0;35mIP{ESC}[0m\t{ESC}[0;36m192.1.0.2{ESC}[0m", "\tIP\t192.1.0.2"),161 # A styled cell inside a box-drawing table.162 (163 f"╒══════╕\n│ {ESC}[1mCell{ESC}[0m │\n╘══════╛",164 "╒══════╕\n│ Cell │\n╘══════╛",165 ),166 # Kaomoji with a bolded run.167 (f"(╯°□°)╯︵ {ESC}[1m┻━┻{ESC}[0m", "(╯°□°)╯︵ ┻━┻"),168 ],169)170def test_strip_ansi_mixed_content(text, expected):171 assert strip_ansi(text) == expected172 assert term_len(text) == len(expected)173174175def test_strip_ansi_stops_at_final_byte():176 """The match ends at the first final byte."""177 assert strip_ansi(f"{ESC}[31mX{ESC}[0mY") == "XY"178 assert strip_ansi(f"{ESC}[1m{ESC}[31mZ") == "Z"179 # The final ``m`` ends the sequence; the following ``;1m`` is plain text.180 assert strip_ansi(f"{ESC}[m;1m") == ";1m"181182183@pytest.mark.parametrize(184 "text",185 [186 "",187 "plain text",188 "100% [done]",189 "array[0] = 1",190 "a;b;c",191 # Looks like SGR parameters but lacks the ESC introducer.192 "[38;5;200m not an escape",193 "[0m",194 ],195)196def test_strip_ansi_leaves_plain_text(text):197 """Text that merely resembles an escape sequence is never stripped."""198 assert strip_ansi(text) == text199 assert term_len(text) == len(text)200201202@pytest.mark.parametrize(203 "text",204 [205 f"{ESC}", # lone ESC206 f"{ESC}[", # CSI introducer with no final byte207 f"{ESC}[31", # parameters but no final byte208 f"{ESC}[38:2:1", # colon parameters, truncated209 f"{ESC}[0 ", # intermediate byte but no final byte210 ],211)212def test_strip_ansi_leaves_incomplete_sequences(text):213 """An unterminated sequence (missing its final byte) is left untouched."""214 assert strip_ansi(text) == text215216217def test_strip_ansi_is_idempotent():218 text = f"{ESC}[38:2:1:2:3mhi{ESC}[0m {ESC}[<0;1;1mthere{ESC}[?25h"219 once = strip_ansi(text)220 assert once == "hi there"221 assert strip_ansi(once) == once222223224@pytest.mark.parametrize(225 ("text", "visible"),226 [227 ("", 0),228 ("plain", 5),229 (f"{ESC}[31mred{ESC}[0m", 3),230 (f"{ESC}[38;2;1;2;3mrgb{ESC}[0m", 3),231 (f"{ESC}[38:2:1:2:3mrgb{ESC}[0m", 3),232 (f"{ESC}[<0;1;1Mx{ESC}[<0;1;1m", 1),233 (f"{ESC}[0 qq", 1),234 (f"{ESC}[?25lvisible{ESC}[?25h", 7),235 (f"{ESC}[1m{ESC}[4m{ESC}[31mhello{ESC}[0m", 5),236 ],237)238def test_term_len(text, visible):239 assert term_len(text) == visible240241242@pytest.mark.parametrize("seq", CLICK_EMITTED + CSI_FOREIGN)243def test_ansi_re_matches_whole_sequence(seq):244 """``_ansi_re`` matches a complete sequence end to end as one token."""245 m = _ansi_re.match(seq)246 assert m is not None247 assert m.start() == 0248 assert m.end() == len(seq)249250251@pytest.mark.parametrize(252 ("text", "n", "expected"),253 [254 # No escapes: behaves like a plain prefix slice.255 ("abcdef", 3, "abc"),256 ("abc", 10, "abc"),257 ("abc", 0, ""),258 ("abc", -1, ""),259 # A leading escape is kept and does not count toward the budget.260 (f"{ESC}[31mabcdef{ESC}[0m", 3, f"{ESC}[31mabc"),261 # A colon true-color escape stays intact; the cut lands after 3 chars.262 (f"{ESC}[38:2:1:2:3mabcdef", 3, f"{ESC}[38:2:1:2:3mabc"),263 # A trailing escape past the cut is not pulled in.264 (f"{ESC}[31mabc{ESC}[0m", 3, f"{ESC}[31mabc"),265 ],266)267def test_truncate_visible(text, n, expected):268 out = _truncate_visible(text, n)269 assert out == expected270 assert term_len(out) <= max(n, 0)
modified:tests/test_formatting.py+16 added
464 unmodified lines
465 5,466 "",467 id="styled-long-word-breaks-on-visible-width",468 ),469 # Colon-delimited true-color (ISO 8613-6) escapes are excluded from the470 # width budget too.471 pytest.param(472 "\x1b[38:2:255:0:0malpha\x1b[0m \x1b[38:2:0:255:0mbeta\x1b[0m"473 " \x1b[38:2:0:0:255mgamma\x1b[0m \x1b[38:2:9:9:9mdelta\x1b[0m",474 15,475 "",476 id="colon-truecolor-body-wraps-on-visible-width",477 ),478 # A mouse-reporting sequence embedded mid-line is zero-width too.479 pytest.param(480 "\x1b[<0;1;1malpha beta gamma delta\x1b[<0;1;1m",481 15,482 "",483 id="mouse-sequence-is-zero-width",484 ),485 ],486)487def test_wrap_text_visible_width(body, width, initial_indent):488 """``wrap_text`` of styled input produces the same line layout as
144 unmodified lines
modified:CHANGES.md+2 added
15 unmodified lines
16 does not. The feature set of {func}`version_option` is now frozen; see17 [discussion #3527](https://github.com/pallets/click/discussions/3527). {pr}`3581`18- `style()` and `secho()` no longer silently drop the 256-color index `0`19 (black) passed as `fg` or `bg`, and now validate color arguments. {pr}`3677`20- `unstyle` and the ANSI handling behind help-text wrapping now strip the full21 CSI escape-sequence grammar.2223## Version 8.4.22425Released 2026-06-24
1561 unmodified lines