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:
ANSI_ESCAPE_PATTERNmatches one escape sequence of any kind, in ECMA-48 syntax.strip_ansi()removes all of them from a string.ANSI_SGR_REmatches the SGR escapes that set colors and text attributes.sgr_params()andapply_sgr_codes()decode them, andopen_ansi()returns the ones a string leaves in effect.hex_to_rgb(),rgb_to_hex(),palette_to_rgb(),nearest_256()andresolve_rgb()convert a color between the forms a terminal knows: a hex string, a 24-bit RGB triplet, an index of the 256-color palette and a name of the 16 colors ofANSI_16_RGB.
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_COLORSand_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_NAMESfor 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[mis a valid, parameter-less full reset. It is captured assgr_params: the lexer ofclick_extra.pygmentscomposes 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
coloris 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.
- click_extra.ansi.hex_to_rgb(value)[source]ΒΆ
Parse a hex color (
#rrggbbor shorthand#rgb) to an RGB tuple.
- click_extra.ansi.rgb_to_hex(rgb)[source]ΒΆ
Format an
(r, g, b)tuple as a#rrggbbhex 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:
- 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_RGBtable. Indices 16-231 (the 6x6x6 color cube) and 232-255 (the grayscale ramp) are fixed by the xterm 256-color layout.
- 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 (seesupports_truecolor()), and byclick_extra.pygmentsandclick_extra.clifor the same 24-bit-to-8-bit quantization.See also
Previous implementation of full-color to 8-bit quantization.
- Return type:
- 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:
- 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 themclosing an SGR escape or the~closingESC [ 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.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[mis a full reset, and\x1b[;31mcarries a reset followed by a red foreground.
- 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 defaultresets=True) andfrom_ansi()(withresets=False).Style-setting codes add entries to state, keyed by
Stylefield names. When resets is true, the full0reset 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) and55(overline). When resets is false all of them are ignored, lettingfrom_ansi()merge escapes without wiping already-parsed codes.Unknown codes are silently skipped, like terminals do.
- Return type:
- 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
0reset (its parameter-less\x1b[mform included) empties the accumulator, so the result re-opens what text left dangling and nothing else. Escapes come back verbatim rather than folded into aStyle, 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: