click_extra.theme module¶
classDiagram
ExtraOption <|-- ThemeOption
HelpTheme <|-- HelpTheme
MutableMapping <|-- _LazyThemes
ParamType <|-- ThemeChoice
Help-screen color themes for Click Extra.
Holds the HelpTheme dataclass, the NOCOLOR_THEME constant,
the process-wide fallback accessed via
get_default_theme() / set_default_theme(), the named-theme
theme_registry plus register_theme() helper, and the
ThemeOption that exposes --theme on every Click Extra command.
The built-in themes (dark, dracula, light, manpage,
monokai, nord, solarized-dark) are plain mappings declared in this module,
each built through HelpTheme.from_dict() on its first lookup: importing
the package builds none of them, and a help screen builds only the one it
renders with. manpage is a colorless theme that
shadows man-pages(7) typography (bold literals, italic replaceable); the
others apply that same bold/italic split on top of their color palettes.
Those mappings follow the schema of user-defined themes loaded from
configuration: see Themes for the user guide.
Note
The active theme for a CLI invocation is stored on the Click context’s
meta dict under click_extra.context.THEME by
ThemeOption. Use get_current_theme() to retrieve it: that
helper consults the active Click context first and falls back to
get_default_theme() when no context is in flight (like at import
time, in wrap patching, or in bare REPL usage). Per-invocation
context storage means concurrent invocations of the same CLI in one
process (Sphinx builds, test runners, REPLs) do not leak --theme
choices into each other.
- click_extra.theme.THEME_ENVVAR: Final[str] = 'CLICK_EXTRA_THEME'¶
Environment variable naming the help-screen palette of every Click Extra CLI.
Global and CLI-agnostic, unlike the
<CLI>_THEMEvariable Click derives from the option itself: exporting it once from a shell profile themes every Click Extra command installed on the machine, including the ones a user wraps withclick-extra wrap. It accepts the same values as--theme, theAUTO_THEMEdirective included.Read by
set_theme()as a last resort, so a--themeflag, a<CLI>_THEMEvariable and a configuration file each outrank it. See that method for why it is read directly instead of being wired through the option’senvvar.
- class click_extra.theme.HelpTheme(invoked_command=<function identity>, command_help=<function identity>, heading=<function identity>, constraint=<function identity>, section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=<function identity>, alias_secondary=None, epilog=<function identity>, critical=<function identity>, error=<function identity>, warning=<function identity>, info=<function identity>, debug=<function identity>, option=<function identity>, subcommand=<function identity>, choice=<function identity>, metavar=<function identity>, bracket=<function identity>, envvar=<function identity>, default=<function identity>, range_label=<function identity>, required=<function identity>, argument=<function identity>, deprecated=<function identity>, separator=<function identity>, search=<function identity>, success=<function identity>, cross_ref_highlight=True, subheading=<function identity>)[source]¶
Bases:
HelpThemeExtends
cloup.HelpThemewith slots for log levels and the structural elements Click Extra highlights in help screens.Each slot below documents what it colors. The built-in themes shipped in
BUILTIN_THEMESprovide the visual styling by setting the relevant slots; user-defined themes can be authored as plain mappings and loaded viafrom_dict().- critical()¶
Style applied to the
CRITICALlevel name in log records.Example:
CRITICAL: Database connection lost.Rendered with the default
darktheme:CRITICAL: Database connection lost.- Return type:
T
- error()¶
Style applied to the
ERRORlevel name in log records.Example:
ERROR: Configuration file not found.Rendered with the default
darktheme:ERROR: Configuration file not found.- Return type:
T
- warning()¶
Style applied to the
WARNINGlevel name in log records.Example:
WARNING: Requested 16 jobs exceeds the 8 logical CPUs: honored, but pays only for I/O-bound work.Rendered with the default
darktheme:WARNING: Requested 16 jobs exceeds the 8 logical CPUs: honored, but pays only for I/O-bound work.- Return type:
T
- info()¶
Style applied to the
INFOlevel name in log records.Usually left at
identity:INFOis the default verbosity and shouldn’t stand out from regular output.Rendered with the default
darktheme:INFO: Loaded 23 records.
- Return type:
T
- debug()¶
Style applied to the
DEBUGlevel name in log records.Example:
DEBUG: Resolved /etc/myapp/config.toml.Rendered with the default
darktheme:DEBUG: Resolved /etc/myapp/config.toml.- Return type:
T
- option()¶
Style applied to option names (
--config,-v,--color/--no-color) wherever they appear: synopsis column, free-form descriptions, and docstrings (whencross_ref_highlightis enabled).Rendered with the default
darktheme:--config LOCATION Location of the configuration file. -v, --verbose Increase verbosity.
- Return type:
T
- subcommand()¶
Style applied to subcommand names: in a group’s command list and wherever they are referenced in prose.
Rendered with the default
darktheme:Commands: backup Snapshot the data store. restore Restore from a snapshot.
- Return type:
T
- choice()¶
Style applied to each individual value inside a
click.Choicemetavar (likejson,csv,xmlwithin[json|csv|xml]) and to those values referenced in option descriptions.Rendered with the default
darktheme:--format [json|csv|xml] Output format. Defaults to json.
- Return type:
T
- metavar()¶
Style applied to type metavars (
INTEGER,TEXT,PATH,FILE, …) that follow an option name in the synopsis column.Rendered with the default
darktheme:--output TEXT Destination file. --workers INTEGER Worker count.
- Return type:
T
- bracket()¶
Style applied to the literal bracket characters and label prefixes of trailing fields:
[,],default:,env var:, and the field separators between them. Also acts as the fallback for the four inner bracket-field slots (envvar,default,required,range_label) whenever any of them is left atidentity. A theme that only setsbrackettherefore renders the whole bracket field with a single uniform style; richer themes layer specific colors on top by setting the inner slots.Rendered with the default
darktheme:--port INTEGER [env var: PORT; default: 8080; required]- Return type:
T
- envvar()¶
Style applied to environment-variable values inside
[env var: ...]bracket fields, and to envvar names mentioned in option descriptions. Falls back tobracketwhen left atidentity, so a theme that only stylesbracketstill gets a consistent rendering inside bracket fields.Rendered with the default
darktheme:--threshold INTEGER Acceptable error rate. [env var: THRESHOLD, TEST_THRESHOLD]- Return type:
T
- default()¶
Style applied to the default-value content inside
[default: ...]bracket fields. Falls back tobracketwhen left atidentity.Rendered with the default
darktheme:--output FILENAME Destination file. [default: out.csv] --retries INTEGER Retry budget. [default: 5]
- Return type:
T
- range_label()¶
Style applied to range expressions (
0<=x<=9,x>=1024,0<=x<100) that appear inside bracket fields forIntRangeandFloatRangeoptions. Falls back tobracketwhen left atidentity.Rendered with the default
darktheme:--level INTEGER RANGE Verbosity level. [0<=x<=9] --port INTEGER RANGE Bind port. [x>=1024]
- Return type:
T
- required()¶
Style applied to the
requiredlabel inside bracket fields on mandatory options. Falls back tobracketwhen left atidentity.Rendered with the default
darktheme:--token TEXT Authentication token. [required]- Return type:
T
- argument()¶
Style applied to argument metavars (positional parameter names like
MY_ARG,SCRIPT,[FILENAMES]...) in the synopsis column and when referenced in prose.Rendered with the default
darktheme:Usage: cp [OPTIONS] SRC DST Usage: pack [OPTIONS] [FILES]... [OUTPUT]
- Return type:
T
- deprecated()¶
Style applied to
(DEPRECATED)/(Deprecated: reason)markers appended to options and commands.Rendered with the default
darktheme:--old-api Legacy endpoint. (DEPRECATED: use --new-api instead) --legacy Kept for compatibility. (deprecated: removed in v9)
- Return type:
T
- separator()¶
Style applied to the
--end-of-options separator, wherever a help screen writes it on its own:my-cli wrap -- target-cli --help.It is punctuation rather than a word, and it reads as one of the target CLI’s own options until something tells the two apart.
- Return type:
T
- search()¶
Style applied to substring matches in <cli> help --search output, so users can spot where their query matched.
Rendered with the default
darktheme:--retry-budget INTEGER The retry budget.
- Return type:
T
- success()¶
Style applied to success glyphs in pre-rendered UI elements (the
✓inOK_GLYPH) and any text passed through this slot by downstream code.Rendered with the default
darktheme:✓ database migration completed ✓ 1,245 records imported
- Return type:
T
- cross_ref_highlight: bool = True¶
Highlight options, choices, arguments, metavars and CLI names in free-form text (descriptions, docstrings).
When
False, only structural elements are styled: bracket fields ([default: ...],[env var: ...], ranges,[required]), deprecated messages, and subcommand names in definition lists.
- subheading()¶
Style for sub-section headings inside log output or inline help.
Distinct from
heading(which styles the top-level help-screen section titles):subheadingis intended for downstream code that wants a second styling level for its own narrative output.See also
Used by mail-deduplicate to style
◼ N mails sharing hash …log lines.Rendered with the default
darktheme:◼ 3 mails sharing hash a1b2c3d4 ◼ 7 mails sharing hash e5f6a7b8
- Return type:
T
- with_(**kwargs)[source]¶
Derive a new theme from this one, with some slots overridden.
Returns the same instance when every slot keeps its value, where cloup’s version builds a copy whatever it is given.
Noneis a value like any other, not a slot left alone.
- classmethod dark()[source]¶
A theme assuming a dark terminal background color.
Carries cloup’s palette, each style widened to
Style, and leaves the slots this subclass adds at their default. For a theme coloring those too, reach forBUILTIN_THEMESinstead.- Return type:
- classmethod light()[source]¶
A theme assuming a light terminal background color.
Carries cloup’s palette, like
dark().- Return type:
- to_dict()[source]¶
Serialize the theme to a plain dict suitable for TOML/JSON/YAML.
Each
Styleslot is emitted viaStyle.to_dict. Slots left at their default (identityorNone) are omitted, so the output only carries what the theme actually overrides. Pair withfrom_dict()to round-trip.
- classmethod from_dict(data)[source]¶
Build a theme from the plain dict produced by
to_dict().Each value is interpreted by field type: a mapping becomes a
StyleviaStyle.from_dict, whilecross_ref_highlightis read as a plainbool. Unknown keys raiseTypeErrorso typos surface immediately.- Return type:
- cascade(base)[source]¶
Layer this theme’s set slots on top of base.
Mirrors
Style.cascadeat the slot level: this theme’s non-default slots win, base fills the rest. Useful for layering a sparse override (typically parsed from a config file’s[tool.<cli>.themes.<name>]table) on top of a full built-in palette.
- click_extra.theme.LITERAL_STYLES: frozenset[str] = frozenset({'alias', 'alias_secondary', 'choice', 'invoked_command', 'option', 'separator', 'subcommand'})¶
Names of the
HelpThemeslots that color literal tokens: text the user types verbatim on the command line.Covers the command and subcommand names, their aliases, option flags (
--config,-v), the concrete values of aclick.Choice(jsonin[json|csv|xml]), and the--separator.These map to the bold font of the man-pages(7) typographic convention, which sets text “typed literally” in bold (
\fBin roff) “even in the SYNOPSIS section”. Paired withREPLACEABLE_STYLES: the two are disjoint, and every remaining slot is an annotation, prose, or chrome style that the literal/replaceable dichotomy does not classify (log levels,[default: ...]/[env var: ...]fields, headings, …).Note
Every built-in theme applies this classification: literal slots render bold and
REPLACEABLE_STYLESitalic, mirroring a man page even in the color palettes.tests/test_theme.pyenforces the invariant, and themanpagebuilt-in theme is its pure-monochrome embodiment (bold/italic, no color). The man-page generator ofclick_extra.command_docfollows the same split, setting each token in\fBor\fI.
- click_extra.theme.REPLACEABLE_STYLES: frozenset[str] = frozenset({'argument', 'metavar'})¶
Names of the
HelpThemeslots that color replaceable tokens: placeholders the user substitutes with a real value.Covers type metavars on options (
INTEGER,PATH) and positional argument metavars (SOURCE,[FILENAMES]...).These map to the italic font of the man-pages(7) convention, which sets replaceable arguments in italic (
\fIin roff). SeeLITERAL_STYLESfor the bold counterpart and the full rationale.
- click_extra.theme.NOCOLOR_THEME: HelpTheme = HelpTheme(invoked_command=<function identity>, command_help=<function identity>, heading=<function identity>, constraint=<function identity>, section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=<function identity>, alias_secondary=None, epilog=<function identity>, critical=<function identity>, error=<function identity>, warning=<function identity>, info=<function identity>, debug=<function identity>, option=<function identity>, subcommand=<function identity>, choice=<function identity>, metavar=<function identity>, bracket=<function identity>, envvar=<function identity>, default=<function identity>, range_label=<function identity>, required=<function identity>, argument=<function identity>, deprecated=<function identity>, separator=<function identity>, search=<function identity>, success=<function identity>, cross_ref_highlight=True, subheading=<function identity>)¶
Color theme for Click Extra to force no colors.
All style slots default to
identity, so styling calls return the raw text unchanged.
- click_extra.theme.BUILTIN_THEMES: Mapping[str, HelpTheme] = _LazyThemes(['dark', 'dracula', 'light', 'manpage', 'monokai', 'nord', 'solarized-dark'])¶
Mapping of built-in theme names to their
HelpThemeinstances.Each theme is built from its definition in this module on its first lookup, and the same instance is returned from then on.
theme_registrystarts with the same entries.Index by name to access any palette, like
BUILTIN_THEMES["dark"]orBUILTIN_THEMES["solarized-dark"].
- click_extra.theme.get_default_theme()[source]¶
Return the process-wide fallback theme.
Read by
get_current_theme()when no Click context is active or when the active context has no theme set. The default is the built-indarkpalette;patch_click()overrides it viaset_default_theme()for the duration of a patched session.Resolved through a function rather than a module attribute so callers always observe the current value: a module attribute bound once, like a default parameter value, keeps whatever was set at import time.
- Return type:
- click_extra.theme.set_default_theme(theme)[source]¶
Override the process-wide fallback theme.
ThemeOptionwrites its picked theme toctx.metarather than calling this helper, so per-invocation choices do not leak across invocations sharing the same process. Use this only for genuinely process-wide overrides:patch_click()is the canonical caller.- Return type:
- click_extra.theme.get_current_theme()[source]¶
Return the theme active for the current CLI invocation.
Resolution order:
The theme stored on the active Click context under
click_extra.context.THEME(set byThemeOptionfrom--theme).The process-wide fallback returned by
get_default_theme()(the dark default, or whateverpatch_click()set at process start).
Falling back through the active context (instead of reading a module attribute) keeps
--themescoped to the invocation that received it, so a second invocation in the same process starts from the default again.- Return type:
- click_extra.theme.theme_registry: MutableMapping[str, HelpTheme] = _LazyThemes(['dark', 'dracula', 'light', 'manpage', 'monokai', 'nord', 'solarized-dark'])¶
Process-wide registry of named themes used by
ThemeOption.Each entry maps a theme name to its
HelpThemeinstance. It starts with the entries ofBUILTIN_THEMES, each built on its first lookup.Use
register_theme()to add your own at import time, or declare them in your CLI’s config file under[tool.<cli>.themes.<name>]: the latter goes throughConfigOption, lands onctx.meta(seeclick_extra.context.THEME_OVERRIDES), and never mutates this module-level dict, so per-invocation choices don’t leak between sibling invocations sharing the same process.
- click_extra.theme.register_theme(name, theme)[source]¶
Register a named theme in the module-level
theme_registry.
- click_extra.theme.get_theme_registry(ctx=None)[source]¶
Return the theme registry visible to ctx.
Merges the module-level
theme_registrywith any per-invocation overrides stored onctx.metaunderclick_extra.context.THEME_OVERRIDES. Per-invocation entries win on key collisions, which is what lets a config file’s[tool.<cli>.themes.dark]table override the built-indarkpalette for one invocation without touching the global registry.When ctx is
Noneor has no overrides, returns a copy of the module-level registry. Either way, a built-in theme is built only when its value is read.- Return type:
- click_extra.theme.AUTO_THEME: str = 'auto'¶
Reserved
--themevalue resolving the palette from the terminal background.Unlike the named built-in palettes,
autois not a registry entry: it is a directive handled byThemeOption, which callsresolve_auto_theme()to pickdarkorlightfrom the detected background, mirroring--color=auto.It is advertised all the same, in the
--helpmetavar and in shell completion (ThemeChoice.choices), because it works on every Click Extra CLI whether or not that CLI knows about it: a value accepted everywhere and named nowhere is one nobody finds.--colorlists its ownautobesidealwaysandneverfor the same reason.
- click_extra.theme.resolve_auto_theme(ctx=None, query_background=False)[source]¶
Pick a built-in palette from the detected terminal background.
Resolves the background mode via
resolve_background()and maps"dark"/"light"to the same-named theme in the registry visible to ctx (built-ins plus any[tool.<cli>.themes.<name>]config overlays). An undetected background falls back to"dark", preserving Click Extra’s default.- Parameters:
ctx (
Context|None) – context whose theme registry is consulted.query_background (
bool) – when true, allow the live OSC 11 terminal query (query_osc_background()) on top of the environment-variable signals. Off by default because the query reads stdin.
- Return type:
- Returns:
the chosen
HelpTheme, orNonewhen neither the detected palette nor thedarkfallback is registered (both were removed from the registry). ANoneleavesctx.metauntouched soget_current_theme()keeps the default theme.
- click_extra.theme.themes_from_config(table)[source]¶
Build a
{name: HelpTheme}mapping from a[tool.<cli>.themes]sub-tree.For each entry, build a
HelpThemeviaHelpTheme.from_dict(). If name matches an existing key intheme_registry, the new theme is layered on top viaHelpTheme.cascade()so partial overrides (like just one slot) inherit the rest from the built-in palette. Stand-alone names produce theme instances with the unset slots left at their defaults.
- click_extra.theme.validate_themes_config(themes_subtree)[source]¶
Validate a
[tool.<cli>.themes]sub-tree.Registered as a built-in
ConfigValidatorbyConfigOptionso malformed theme tables surface asValidationErrorwith a rooted path (my-cli.themes.<name>) rather than a deepTypeErrorfromHelpTheme.from_dict().- Return type:
- class click_extra.theme.ThemeChoice(case_sensitive=False)[source]¶
Bases:
ParamTypeA
click.ParamTypewhosechoicestrack the live theme registry.Implements the
click.Choice-shaped duck interface (choices,case_sensitive,normalize_choice) soclick_extra.highlightcan collect theme names for per-token highlighting through the same code path it uses for Click’s ownChoice. Thechoicesattribute is a property that queriesget_theme_registry()at every lookup, so themes registered late (typically byConfigOptionparsing[tool.<cli>.themes.<name>]tables before--themeis processed) are valid choices and appear in the--helpmetavar.A plain
click.ParamTyperather than aclick.Choicesubclass:click.Choice.__init__assignsself.choices, which a read-only property cannot take.- property choices: tuple[str, ...]¶
Values
--themetakes, alphabetically sorted.The theme names visible in the current context, plus
AUTO_THEME, which says why a directive is listed among them.
- normalize_choice(choice, ctx)[source]¶
Mirrors
click.Choice.normalize_choice()for highlight compatibility.- Return type:
- convert(value, param, ctx)[source]¶
Resolve value to a canonical theme name from the live registry.
Normalizes value and looks it up against the names visible in ctx. Returns the canonical name,
Nonewhen no themes are registered at all (an inert--theme), and callsfailwhen value is not a string or does not match any registered theme.
- shell_complete(ctx, param, incomplete)[source]¶
Return a list of
CompletionItemobjects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.- Parameters:
- Return type:
Added in version 8.0.
- class click_extra.theme.ThemeOption(param_decls=None, *, default='dark', is_eager=True, expose_value=False, query_background=False, help='Color theme used for help screens.', **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured option that adds
--themeto select the help-screen palette.Accepts any name registered in
theme_registryor in the per-invocation overrides loaded byConfigOptionfrom[tool.<cli>.themes.<name>]. Validation goes throughThemeChoice, which reads the live registry at parse time, so config-defined themes appear as valid choices and in the--helpmetavar without any further wiring.The resolved
HelpThemelands on the Click context underclick_extra.context.THEMEand applies for the duration of the current invocation only.A user who never passes the flag can still pick a palette by exporting
THEME_ENVVAR(CLICK_EXTRA_THEME), which is honored by every Click Extra CLI at once. Seeset_theme()for how it ranks against the flag, the<CLI>_THEMEvariable and the configuration file.The reserved value
AUTO_THEME(--theme=auto) is also accepted on every CLI: it resolves the palette from the terminal background viaresolve_auto_theme()instead of naming a registered theme. Background detection reads environment variables by default; passquery_background=Trueto additionally allow the live OSC 11 terminal query (query_osc_background()), which is opt-in because it reads stdin.- set_theme(ctx, param, value)[source]¶
Resolve the chosen theme name and store it on the Click context.
ThemeChoicehas already validated value against the live registry (or accepted theAUTO_THEMEdirective) by the time this fires. A plain palette name is looked up unconditionally;autois resolved from the terminal background viaresolve_auto_theme(), leavingctx.metauntouched when no palette can be resolved soget_current_theme()keeps its default.Before that,
THEME_ENVVARis consulted when the value still comes from the option’s own default, as for every machine-wide variable (seemachine_envvars_apply()). This yields the precedence:--theme><CLI>_THEME> configuration file >CLICK_EXTRA_THEME> built-in default. The global variable therefore only names the palette of the CLIs nothing else has an opinion about.Note
The variable is read here rather than wired through the option’s
envvar. Click resolves an explicitenvvarbefore the auto-generated<CLI>_THEME, which would let the machine-wide preference outrank the CLI-specific one, and would list both names in the--paramstable, making the combined string the widest cell of its column. This mirrors howAccessibleOptionreadsACCESSIBLEandColorOptionreadsNO_COLOR.An unparsable palette name is a warning, not an error: a typo in a shell profile would otherwise break every Click Extra CLI on the machine at once, including the ones needed to fix it.
- Return type:
- click_extra.theme.OK_GLYPH: str = '✓'¶
Plain check-mark glyph for success indicators.
Style at the call site with the active theme’s
successslot:get_current_theme().success(OK_GLYPH). Stored as a raw string so downstream code can render it under whichever theme is active rather than the (frozen) theme that happened to be loaded at import time.