click_extra.styling module¶
classDiagram
Style <|-- Style
Drop-in replacement for cloup.Style with extra features.
The module name mirrors cloup.styling, the upstream module that hosts
the original Style class. Click Extra’s Style is a subclass that
keeps cloup’s runtime contract (calling the instance to apply the style, equality,
hashing) intact and adds:
An equality and a hash shared with
cloup.Style, so aStyleequals thecloup.Stylecarrying the same fields.A compact, single-line
__repr__that hidesNoneand falsy attributes and renders RGB tuples as#rrggbbhex.Hex-string color shorthand:
Style(fg="#f1fa8c")works alongsideStyle(fg=(241, 250, 140)).A
__str__that returns the styled word"sample"so REPL prints and debuggers visualize what the style does, not just its fields.A composition operator
a | bthat merges two styles, with the right operand winning on conflicts.A
Style.cascade()method that fills the style’sNonefields from a base style without overriding any value already set.Style.to_dict()/Style.from_dict()for round-tripping styles through TOML/JSON/YAML.Style.to_css()for emitting CSS-equivalent declarations: useful for HTML renderings of help screens.Style.from_ansi()for parsing an ANSI SGR escape sequence back into aStyleinstance.Style.contrast_ratio()returning the WCAG contrast ratio between two foreground colors. Useful for theme designers checking accessibility.split_ansi()andrender_ansi()for tokenizing a string mixing text and ANSI escapes into styled runs, then re-rendering those runs through a markup emitter. Wrapping them to a width lives inwrap_ansi(), with the rest of the terminal-grid measures.The
ansi_to_html(),ansi_to_jira(),ansi_to_latex()andansi_to_textile()converters, translating ANSI styling to markup languages with native styling support.
The escape grammar, the SGR decoder and the color conversions all of this reads
through live in click_extra.ansi, with
strip_ansi() and open_ansi().
- click_extra.styling.fields_to_dict(instance, *, encode=<function <lambda>>, keep=<function <lambda>>)[source]¶
Serialize a dataclass instance to a dict of its non-default fields.
Skips every field still holding its declared default, then applies keep to decide which of the remaining fields are written, and passes their values through encode.
- Parameters:
instance (
Any) – the dataclass to serialize.encode (
Callable[[Any,Any],Any]) – callable(field, value) -> encoded_valueapplied to every kept value. Use to convert RGB tuples to#rrggbbstrings, nested dataclasses to dicts, etc. Defaults to the identity.keep (
Callable[[Any,Any],bool]) – callable(field, value) -> booldeciding whether a non-default field is emitted. Defaults to keeping all of them.
- Return type:
- click_extra.styling.dict_to_fields(cls, data, *, decode=<function <lambda>>)[source]¶
Validate data’s keys against cls’s dataclass fields and decode them.
Returns a kwargs dict ready to splat into
cls(**kwargs).- Parameters:
- Raises:
TypeError – listing every key that names no field of cls, so callers can build a constructor call without validating first.
- Return type:
- click_extra.styling.supports_truecolor()[source]¶
Whether the terminal is assumed to render 24-bit (truecolor) ANSI.
Drives
Style.__call__’s choice between emitting a 24-bit38;2;r;g;bsequence and quantizing it to the nearest38;5;n256-color index, so a branded theme’s RGB colors degrade gracefully on a terminal that cannot display them.The policy is optimistic: assume truecolor unless the environment positively says otherwise. Precedence, highest first:
COLORTERMoftruecolor/24bit(see_TRUECOLOR_COLORTERMS) keeps 24-bit.Any other non-empty
COLORTERMquantizes: an explicit lower advertisement.A
TERMending in-16colorquantizes: an unambiguous sub-256 terminal.*-256coloris deliberately not treated as a downgrade, since truecolor terminals routinely report it while advertising their 24-bit support throughCOLORTERMinstead. Honoring it would strip truecolor from the very terminals this optimistic default protects.Otherwise keeps 24-bit.
A
dumb/unknownTERMnever reaches this decision for CLI output: it has already disabled color upstream throughresolve_color_env().- Return type:
- class click_extra.styling.Style(fg=None, bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None)[source]¶
Bases:
Stylecloup.Stylewith extra ergonomics.See the module docstring for the full list of additions. The runtime contract (calling the instance to apply the style, equality, hashing) is otherwise identical to
cloup.Style.- fg: str | tuple[int, int, int] | int | None = None¶
Foreground color: named ANSI string,
#rrggbbhex, RGB tuple, or palette index.
- bg: str | tuple[int, int, int] | int | None = None¶
Background color: named ANSI string,
#rrggbbhex, RGB tuple, or palette index.
- cascade(base)[source]¶
Return a copy with
Nonefields filled in from base.The instance’s own non-
Nonevalues always win:cascadeonly fills gaps. Useful for theme inheritance:derived.cascade(parent)keepsderived’s overrides and inherits the rest fromparent.- Return type:
- to_dict()[source]¶
Serialize to a plain dict with only the set fields.
RGB tuples are emitted as
#rrggbbstrings so the result round-trips through TOML/JSON/YAML untouched. Pair withfrom_dict()to rebuild aStyle.
- classmethod from_dict(data)[source]¶
Build a
Stylefrom the plain dict produced byto_dict().Validates that every key in data names a known
Stylefield and raisesTypeErrorotherwise. Pair withto_dict()to round-trip through TOML/JSON/YAML.- Return type:
- to_css()[source]¶
Render the style as a semicolon-separated CSS declaration list.
Style(fg="#f1fa8c", bold=True).to_css()returns"color: #f1fa8c; font-weight: bold". Suitable for inlinestyle="..."attributes on HTML spans.- Return type:
- classmethod from_ansi(escape)[source]¶
Parse one or more consecutive ANSI SGR escapes into a
Style.Supports the standard 8/16-color codes (30–37, 40–47, 90–97, 100–107), the
38;5;n/48;5;n256-color extension, and the38;2;r;g;b/48;2;r;g;b24-bit extension. Reset codes (the full0reset, its parameter-less\x1b[mform included, and selective resets like22,39or49) are ignored, so parsing the full output of a style call (trailing reset included) recovers that style. Multiple back-to-back escapes (as click emits when combining colors with attributes:\x1b[31m\x1b[1m) are merged into a singleStyle.To tokenize a string mixing text and escapes, with resets honored, see
split_ansi().- Return type:
- contrast_ratio(other)[source]¶
Return the WCAG 2.x contrast ratio between this fg and other’s fg.
Result is in
[1, 21]: 1 = identical colors (no contrast), 21 = maximum contrast (black on white). WCAG AA requires 4.5+ for normal text, 3.0+ for large text; AAA wants 7.0+ and 4.5+ respectively.- Return type:
- click_extra.styling.split_ansi(text)[source]¶
Split text into
(style, text)runs at ANSI SGR escape boundaries.A stateful SGR stream parser: each escape updates the current style state (with full and selective resets honored, unlike
Style.from_ansi()), and every maximal run of text sharing the same state is yielded with itsStyle. Unstyled text is yielded with an emptyStyle. Consecutive runs with equal styles are merged and empty runs are dropped, so wrapping each yielded run produces minimal markup.Every other escape carries no style information and is removed from the yielded text by
strip_ansi(), so a terminal hyperlink keeps its display text and loses its URI.
- click_extra.styling.render_ansi(text, emitter)[source]¶
Rebuild text, replacing each ANSI-styled run by emitter’s markup.
Unstyled runs pass through verbatim, so any markup surrounding the styled runs (table borders, tags produced by another renderer) is preserved byte for byte. Styled runs are handed to emitter one line at a time: runs are split on newlines so no markup wrapper ever crosses a line boundary, which keeps line-oriented markup (LaTeX rows, wiki tables) well-formed even when a style spans multiple lines.
- Return type:
- click_extra.styling.ansi_to_html(text)[source]¶
Translate ANSI styling in text to inline-styled HTML
<span>tags.\x1b[34mSummer\x1b[0mbecomes<span style="color: blue">Summer</span>. The spans are self-contained (no stylesheet needed) and also valid in markups accepting inline HTML, like MediaWiki.- Return type:
- click_extra.styling.ansi_to_jira(text)[source]¶
Translate ANSI styling in text to Jira wiki markup.
\x1b[34;1mSummer\x1b[0mbecomes{color:blue}*Summer*{color}.- Return type: