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>_THEME variable 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 with click-extra wrap. It accepts the same values as --theme, the AUTO_THEME directive included.

Read by set_theme() as a last resort, so a --theme flag, a <CLI>_THEME variable and a configuration file each outrank it. See that method for why it is read directly instead of being wired through the option’s envvar.

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: HelpTheme

Extends cloup.HelpTheme with 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_THEMES provide the visual styling by setting the relevant slots; user-defined themes can be authored as plain mappings and loaded via from_dict().

critical()

Style applied to the CRITICAL level name in log records.

Example: CRITICAL: Database connection lost.

Rendered with the default dark theme:

CRITICAL: Database connection lost.
Return type:

T

error()

Style applied to the ERROR level name in log records.

Example: ERROR: Configuration file not found.

Rendered with the default dark theme:

ERROR: Configuration file not found.
Return type:

T

warning()

Style applied to the WARNING level 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 dark theme:

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 INFO level name in log records.

Usually left at identity: INFO is the default verbosity and shouldn’t stand out from regular output.

Rendered with the default dark theme:

INFO: Loaded 23 records.
Return type:

T

debug()

Style applied to the DEBUG level name in log records.

Example: DEBUG: Resolved /etc/myapp/config.toml.

Rendered with the default dark theme:

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 (when cross_ref_highlight is enabled).

Rendered with the default dark theme:

--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 dark theme:

Commands:
  backup        Snapshot the data store.
  restore       Restore from a snapshot.
Return type:

T

choice()

Style applied to each individual value inside a click.Choice metavar (like json, csv, xml within [json|csv|xml]) and to those values referenced in option descriptions.

Rendered with the default dark theme:

--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 dark theme:

--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 at identity. A theme that only sets bracket therefore 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 dark theme:

--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 to bracket when left at identity, so a theme that only styles bracket still gets a consistent rendering inside bracket fields.

Rendered with the default dark theme:

--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 to bracket when left at identity.

Rendered with the default dark theme:

--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 for IntRange and FloatRange options. Falls back to bracket when left at identity.

Rendered with the default dark theme:

--level INTEGER RANGE    Verbosity level.  [0<=x<=9]
--port INTEGER RANGE     Bind port.        [x>=1024]
Return type:

T

required()

Style applied to the required label inside bracket fields on mandatory options. Falls back to bracket when left at identity.

Rendered with the default dark theme:

--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 dark theme:

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 dark theme:

--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 dark theme:

--retry-budget INTEGER    The retry budget.
Return type:

T

success()

Style applied to success glyphs in pre-rendered UI elements (the ✓ in OK_GLYPH) and any text passed through this slot by downstream code.

Rendered with the default dark theme:

✓ 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): subheading is 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 dark theme:

◼ 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. None is a value like any other, not a slot left alone.

Raises:

TypeError – listing every argument that names no slot.

Return type:

Self

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 for BUILTIN_THEMES instead.

Return type:

Self

classmethod light()[source]

A theme assuming a light terminal background color.

Carries cloup’s palette, like dark().

Return type:

Self

to_dict()[source]

Serialize the theme to a plain dict suitable for TOML/JSON/YAML.

Each Style slot is emitted via Style.to_dict. Slots left at their default (identity or None) are omitted, so the output only carries what the theme actually overrides. Pair with from_dict() to round-trip.

Raises:

TypeError – when a slot holds an opaque IStyle callable that is not a Style (those cannot be serialized).

Return type:

dict[str, Any]

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 Style via Style.from_dict, while cross_ref_highlight is read as a plain bool. Unknown keys raise TypeError so typos surface immediately.

Return type:

HelpTheme

cascade(base)[source]

Layer this theme’s set slots on top of base.

Mirrors Style.cascade at 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.

Raises:

TypeError – when base is not a HelpTheme.

Return type:

HelpTheme

click_extra.theme.LITERAL_STYLES: frozenset[str] = frozenset({'alias', 'alias_secondary', 'choice', 'invoked_command', 'option', 'separator', 'subcommand'})

Names of the HelpTheme slots 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 a click.Choice (json in [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 (\fB in roff) “even in the SYNOPSIS section”. Paired with REPLACEABLE_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_STYLES italic, mirroring a man page even in the color palettes. tests/test_theme.py enforces the invariant, and the manpage built-in theme is its pure-monochrome embodiment (bold/italic, no color). The man-page generator of click_extra.command_doc follows the same split, setting each token in \fB or \fI.

click_extra.theme.REPLACEABLE_STYLES: frozenset[str] = frozenset({'argument', 'metavar'})

Names of the HelpTheme slots 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 (\fI in roff). See LITERAL_STYLES for 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 HelpTheme instances.

Each theme is built from its definition in this module on its first lookup, and the same instance is returned from then on. theme_registry starts with the same entries.

Index by name to access any palette, like BUILTIN_THEMES["dark"] or BUILTIN_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-in dark palette; patch_click() overrides it via set_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:

HelpTheme

click_extra.theme.set_default_theme(theme)[source]

Override the process-wide fallback theme.

ThemeOption writes its picked theme to ctx.meta rather 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:

None

click_extra.theme.get_current_theme()[source]

Return the theme active for the current CLI invocation.

Resolution order:

  1. The theme stored on the active Click context under click_extra.context.THEME (set by ThemeOption from --theme).

  2. The process-wide fallback returned by get_default_theme() (the dark default, or whatever patch_click() set at process start).

Falling back through the active context (instead of reading a module attribute) keeps --theme scoped to the invocation that received it, so a second invocation in the same process starts from the default again.

Return type:

HelpTheme

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 HelpTheme instance. It starts with the entries of BUILTIN_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 through ConfigOption, lands on ctx.meta (see click_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.

Parameters:
  • name (str) – Lowercase identifier used as the --theme choice value.

  • theme (HelpTheme) – A HelpTheme instance.

Return type:

None

click_extra.theme.get_theme_registry(ctx=None)[source]

Return the theme registry visible to ctx.

Merges the module-level theme_registry with any per-invocation overrides stored on ctx.meta under click_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-in dark palette for one invocation without touching the global registry.

When ctx is None or 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:

MutableMapping[str, HelpTheme]

click_extra.theme.AUTO_THEME: str = 'auto'

Reserved --theme value resolving the palette from the terminal background.

Unlike the named built-in palettes, auto is not a registry entry: it is a directive handled by ThemeOption, which calls resolve_auto_theme() to pick dark or light from the detected background, mirroring --color=auto.

It is advertised all the same, in the --help metavar 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. --color lists its own auto beside always and never for 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:

HelpTheme | None

Returns:

the chosen HelpTheme, or None when neither the detected palette nor the dark fallback is registered (both were removed from the registry). A None leaves ctx.meta untouched so get_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 HelpTheme via HelpTheme.from_dict(). If name matches an existing key in theme_registry, the new theme is layered on top via HelpTheme.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.

Return type:

dict[str, HelpTheme]

click_extra.theme.validate_themes_config(themes_subtree)[source]

Validate a [tool.<cli>.themes] sub-tree.

Registered as a built-in ConfigValidator by ConfigOption so malformed theme tables surface as ValidationError with a rooted path (my-cli.themes.<name>) rather than a deep TypeError from HelpTheme.from_dict().

Return type:

None

class click_extra.theme.ThemeChoice(case_sensitive=False)[source]

Bases: ParamType

A click.ParamType whose choices track the live theme registry.

Implements the click.Choice-shaped duck interface (choices, case_sensitive, normalize_choice) so click_extra.highlight can collect theme names for per-token highlighting through the same code path it uses for Click’s own Choice. The choices attribute is a property that queries get_theme_registry() at every lookup, so themes registered late (typically by ConfigOption parsing [tool.<cli>.themes.<name>] tables before --theme is processed) are valid choices and appear in the --help metavar.

A plain click.ParamType rather than a click.Choice subclass: click.Choice.__init__ assigns self.choices, which a read-only property cannot take.

name: str = 'choice'

the descriptive name of this type

property choices: tuple[str, ...]

Values --theme takes, 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:

str

get_metavar(param, ctx)[source]

Returns the metavar default for this param if it provides one.

Return type:

str | None

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, None when no themes are registered at all (an inert --theme), and calls fail when value is not a string or does not match any registered theme.

Return type:

str | None

shell_complete(ctx, param, incomplete)[source]

Return a list of CompletionItem objects 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:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

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: ExtraOption

A pre-configured option that adds --theme to select the help-screen palette.

Accepts any name registered in theme_registry or in the per-invocation overrides loaded by ConfigOption from [tool.<cli>.themes.<name>]. Validation goes through ThemeChoice, which reads the live registry at parse time, so config-defined themes appear as valid choices and in the --help metavar without any further wiring.

The resolved HelpTheme lands on the Click context under click_extra.context.THEME and 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. See set_theme() for how it ranks against the flag, the <CLI>_THEME variable 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 via resolve_auto_theme() instead of naming a registered theme. Background detection reads environment variables by default; pass query_background=True to 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.

ThemeChoice has already validated value against the live registry (or accepted the AUTO_THEME directive) by the time this fires. A plain palette name is looked up unconditionally; auto is resolved from the terminal background via resolve_auto_theme(), leaving ctx.meta untouched when no palette can be resolved so get_current_theme() keeps its default.

Before that, THEME_ENVVAR is consulted when the value still comes from the option’s own default, as for every machine-wide variable (see machine_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 explicit envvar before the auto-generated <CLI>_THEME, which would let the machine-wide preference outrank the CLI-specific one, and would list both names in the --params table, making the combined string the widest cell of its column. This mirrors how AccessibleOption reads ACCESSIBLE and ColorOption reads NO_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:

None

click_extra.theme.OK_GLYPH: str = '✓'

Plain check-mark glyph for success indicators.

Style at the call site with the active theme’s success slot: 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.

click_extra.theme.KO_GLYPH: str = '✘'

Plain heavy-ballot-X glyph for failure indicators.

Style at the call site with the active theme’s error slot: get_current_theme().error(KO_GLYPH). See OK_GLYPH for why the glyph is exposed unstyled.

click_extra.theme.SKIP_GLYPH: str = '⊘'

Plain circled-slash glyph for an operation that was skipped: it neither succeeded nor failed.

Style at the call site with the active theme’s warning slot: get_current_theme().warning(SKIP_GLYPH). See OK_GLYPH for why the glyph is exposed unstyled.