click_extra.ansi moduleΒΆ

Read and write ANSI escape sequences, and convert terminal colors.

A terminal styles its text with escape sequences mixed into the text. Every module of this package that reads or writes such text uses the grammar and the color arithmetic of this module:

Style, the stream parser split_ansi() and the markup converters are built on this module, in click_extra.styling.

click_extra.ansi.RESET = '\x1b[0m'ΒΆ

Escape closing every style a line left open, written before any padding.

click_extra.ansi.ANSI_16_RGB: tuple[tuple[int, int, int], ...] = ((0, 0, 0), (239, 41, 41), (138, 226, 52), (252, 233, 79), (52, 101, 164), (197, 9, 197), (52, 226, 226), (245, 245, 245), (103, 103, 103), (255, 109, 103), (95, 249, 103), (254, 251, 103), (104, 113, 255), (255, 118, 255), (95, 253, 255), (254, 255, 255))ΒΆ

Canonical sRGB values for the 16 ANSI colors.

The single source of truth wherever a named ANSI color, or one of the first 16 slots of the 256-color palette, must materialize as a concrete RGB value: to_css() (bright_* names are not valid CSS keywords), contrast_ratio() (luminance needs RGB), palette_to_rgb() (indices 0-15), and the palettes rendering terminal sessions in the documentation (click_extra.pygments._NAMED_COLORS and _PALETTE_256).

Values are the ones the documentation always rendered: Tango-flavored normal colors and iTerm2’s default brights, picked for legibility on both light and dark backgrounds.

Note

The 8 base named colors keep bypassing this table in markup output: _color_to_css() emits them as plain CSS keywords (and the Jira and LaTeX emitters as macro/xcolor names), delegating the exact shade to the renderer. This table only answers when a concrete value is unavoidable.

click_extra.ansi.ANSI_NAMES: tuple[str, ...] = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')ΒΆ

Names of the 8 base ANSI colors, in palette order.

A bright variant takes the bright_ prefix and the slot 8 places further on.

click_extra.ansi.ANSI_INDEX: dict[str, int] = {'black': 0, 'blue': 4, 'cyan': 6, 'green': 2, 'magenta': 5, 'red': 1, 'white': 7, 'yellow': 3}ΒΆ

Palette index of each base ANSI color name, the O(1) mirror of ANSI_NAMES for the name-to-slot lookups color resolution performs.

click_extra.ansi.ANSI_SGR_RE: Pattern[str] = re.compile('\\x1b\\[(?P<sgr_params>[0-9;]*)m')ΒΆ

Match a single ANSI SGR escape: \x1b[...m.

The parameter substring may be empty: \x1b[m is a valid, parameter-less full reset. It is captured as sgr_params: the lexer of click_extra.pygments composes this pattern into its own tokenizer and reads the parameters by that name.

click_extra.ansi.SGR_ATTRIBUTES: dict[int, str] = {1: 'bold', 2: 'dim', 3: 'italic', 4: 'underline', 5: 'blink', 7: 'reverse', 9: 'strikethrough', 53: 'overline'}ΒΆ

The SGR code switching each boolean style attribute on.

click_extra.ansi.is_rgb(color)[source]ΒΆ

Whether color is a 24-bit (r, g, b) triplet.

The one shape of color this module computes on: a named ANSI color, a palette index or a hex string is resolved to it first.

Return type:

TypeGuard[tuple[int, int, int]]

click_extra.ansi.hex_to_rgb(value)[source]ΒΆ

Parse a hex color (#rrggbb or shorthand #rgb) to an RGB tuple.

Raises:

ValueError – when value holds anything but 3 or 6 hex digits after its #. int alone would take a sign, an underscore or a non-ASCII digit, and turn #-1-1-1 into negative channels.

Return type:

tuple[int, int, int]

click_extra.ansi.rgb_to_hex(rgb)[source]ΒΆ

Format an (r, g, b) tuple as a #rrggbb hex string.

The inverse of hex_to_rgb(). The single source of truth for the RGB-to-hex rendering shared by __repr__, to_css, to_dict, and the documentation palette.

Return type:

str

click_extra.ansi.palette_to_rgb(idx)[source]ΒΆ

Convert a 256-color palette index to its sRGB tuple.

Indices 0-15 are the terminal’s system colors: terminals render them with their theme’s palette, so they resolve through the canonical ANSI_16_RGB table. Indices 16-231 (the 6x6x6 color cube) and 232-255 (the grayscale ramp) are fixed by the xterm 256-color layout.

Return type:

tuple[int, int, int]

click_extra.ansi.nearest_256(r, g, b)[source]ΒΆ

Map a 24-bit RGB triplet to the nearest index in the 256-color palette.

The inverse of palette_to_rgb(). Compares the Euclidean distance in RGB space against both the 6x6x6 color cube (indices 16-231) and the grayscale ramp (indices 232-255), returning whichever is closer.

Used by Style.__call__ to downsample branded-theme colors when the terminal lacks truecolor (see supports_truecolor()), and by click_extra.pygments and click_extra.cli for the same 24-bit-to-8-bit quantization.

See also

Previous implementation of full-color to 8-bit quantization.

Return type:

int

click_extra.ansi.resolve_rgb(color)[source]ΒΆ

Convert a color value to an (r, g, b) tuple.

Accepts RGB tuples, hex strings, named ANSI colors ("red", "bright_blue") and palette indices.

Raises:

ValueError – for any other value.

Return type:

tuple[int, int, int]

click_extra.ansi.CSI_PREFIX_PATTERN = '\\x1b\\[[0-?]*[ -/]*'ΒΆ

A CSI sequence short of its final byte, in ECMA-48 syntax.

ESC [, then the parameter bytes and the intermediate bytes. A stream read in chunks can end on one, the rest of the sequence still to arrive.

click_extra.ansi.CSI_PATTERN = '\\x1b\\[[0-?]*[ -/]*[@-~]'ΒΆ

One CSI sequence, SGR styles included.

CSI_PREFIX_PATTERN, then a final byte, like the m closing an SGR escape or the ~ closing ESC [ 200 ~.

click_extra.ansi.ANSI_ESCAPE_PATTERN = '(?:\\x1b\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)?|\\x1b\\[[0-?]*[ -/]*[@-~]|\\x1b[ -/]*[0-Z\\\\^-~])'ΒΆ

One ANSI escape sequence of any kind, SGR styles included, in ECMA-48 syntax.

click_extra.ansi.strip_ansi(text)[source]ΒΆ

Remove every ANSI escape sequence from text, leaving its plain text.

Overloads:

Styles, cursor movements, screen clearing and OSC commands all go. A terminal hyperlink keeps its display text and loses its URI, which lived in the markers around it. Bytes come back as bytes.

click_extra.ansi.sgr_params(params)[source]ΒΆ

Decode an SGR parameter substring into a sequence of integer codes.

Per ECMA-48, an empty parameter defaults to 0: \x1b[m is a full reset, and \x1b[;31m carries a reset followed by a red foreground.

Return type:

tuple[int, ...]

click_extra.ansi.apply_sgr_codes(codes, state, *, resets=True)[source]ΒΆ

Apply SGR parameter codes to the mutable style state, in place.

The single source of truth for SGR semantics, shared by split_ansi() (with the default resets=True) and from_ansi() (with resets=False).

Style-setting codes add entries to state, keyed by Style field names. When resets is true, the full 0 reset clears the state, and selective resets drop their attribute: 22 (bold and dim), 23 (italic), 24 (underline), 25 (blink), 27 (reverse), 29 (strikethrough), 39 (foreground), 49 (background) and 55 (overline). When resets is false all of them are ignored, letting from_ansi() merge escapes without wiping already-parsed codes.

Unknown codes are silently skipped, like terminals do.

Return type:

None

click_extra.ansi.open_ansi(text, opened='')[source]ΒΆ

Return the ANSI SGR escapes still in effect at the end of text.

Escapes accumulate in the order they were read. A full 0 reset (its parameter-less \x1b[m form included) empties the accumulator, so the result re-opens what text left dangling and nothing else. Escapes come back verbatim rather than folded into a Style, which keeps a code this module does not model.

Use it to splice a styled fragment into styled text: the fragment closes with a reset of its own, which would otherwise strip the surrounding styling from everything after it. See highlight().

Parameters:
  • text (str) – the string to read the escapes from.

  • opened (str) – escapes already in effect before text, as returned by an earlier call. Feeding a string one chunk at a time then costs one pass over it, where re-reading the whole prefix per chunk costs one per chunk. A chunk must not start or end in the middle of an escape: the two halves match nothing, and the escape is lost.

Return type:

str