click_extra.color module¶

        classDiagram
  Choice <|-- ColorWhenChoice
  ExtraOption <|-- ColorOption
  ExtraOption <|-- NoColorOption
  StrEnum <|-- TerminalBackground
    

Resolve whether terminal output should be colored.

Owns the --color[=WHEN] and --no-color options, the color environment variables (NO_COLOR, FORCE_COLOR, CLICOLOR, and friends), the tri-state WHEN resolution the live displays share, and the detection of what the terminal can render: a dumb TERM, and a dark or light background. The actual styling lives elsewhere: click_extra.styling (the Style primitive), click_extra.theme (palettes), and click_extra.highlight (help-screen rendering).

click_extra.color.COLOR_ENVVARS: dict[str, bool] = {'CLICOLOR': True, 'CLICOLORS': True, 'CLICOLORS_FORCE': True, 'CLICOLOR_FORCE': True, 'COLOR': True, 'COLORS': True, 'FORCE_COLOR': True, 'FORCE_COLORS': True, 'LLM': False, 'NOCOLOR': False, 'NOCOLORS': False, 'NO_COLOR': False, 'NO_COLORS': False}¶

Environment variables recognized as flags to switch color rendering on or off.

The key is the name of the variable, and the boolean the direction its convention leans: True for a variable asking for color, False for one refusing it. Each value is read by the convention of its variable, not as a plain boolean: see resolve_color_env().

Source:

click_extra.color.WHEN: tuple[Literal['auto', 'always', 'never'], ...] = ('auto', 'always', 'never')¶

GNU-canonical tri-state saying when a terminal feature is used.

auto decides from the terminal, always uses the feature on any stream, and never leaves it off. The values of --color=<WHEN>, where the feature is ANSI color, and of the live argument of Spinner and OperationTrail, where it is an animation. See GNU coreutils and this discussion.

click_extra.color.COLOR_WHEN_ALIASES: dict[str, str] = {'force': 'always', 'if-tty': 'auto', 'no': 'never', 'none': 'never', 'tty': 'auto', 'yes': 'always'}¶

GNU coreutils synonyms accepted as hidden aliases for each WHEN value.

GNU ls accepts yes/force for always, no/none for never and tty/if-tty for auto, alongside the three canonical spellings (see WHEN). Click Extra mirrors that leniency but keeps the synonyms out of --help output, error messages and shell completion, which only ever advertise WHEN.

click_extra.color.COLOR_DISABLING_TERMS = frozenset({'dumb', 'unknown'})¶

TERM values marking a terminal too limited for ANSI niceties.

A dumb or unknown terminal advertises neither SGR color nor the cursor-control codes (carriage return, clear-line) an animation relies on, so both Click Extra’s color resolution (resolve_color_env()) and the spinner’s animation gating (spinner._can_draw()) treat these two values as a hard opt-out. Both read them through is_dumb_terminal(), which keeps the color and animation axes from drifting apart.

An unset TERM is deliberately excluded: it is common on legitimately color-capable streams (subprocesses, some IDEs) where defaulting to off would be a regression. This matches Rich, which keys its own dumb-terminal detection on the same two values and not on absence.

click_extra.color.is_dumb_terminal()[source]¶

Whether TERM names a terminal in COLOR_DISABLING_TERMS.

Such a terminal renders neither color nor the cursor movements of an animation. Case does not matter, and an unset TERM is no dumb terminal.

Return type:

bool

click_extra.color.is_a_tty(stream)[source]¶

Whether stream reports itself as an interactive terminal.

Probes isatty defensively through getattr(): not every stream object exposes the method (a bare buffer, an in-memory capture, a test double), and a plain stream.isatty() would raise there instead of answering “not a terminal”.

Return type:

bool

click_extra.color.resolve_color_env()[source]¶

Reconcile the recognized color environment variables into a tri-state.

Reads every variable listed in COLOR_ENVVARS by its own convention, and returns:

  • True if at least one variable asks for color. A variable asking for color wins over one refusing it, as in the reference code of FORCE_COLOR.

  • False if variables only refuse color.

  • None if no variable casts a vote, which leaves the caller free to apply its own default (typically auto).

An empty value never votes: both NO_COLOR and FORCE_COLOR treat it as unset. Each family then follows its convention:

  • NO_COLOR refuses color whatever its value, 0 and false included. It never asks for color.

  • FORCE_COLOR asks for color, except for 0, false, no and off, which refuse it, as Node.js tools read them.

  • CLICOLOR refuses color when falsy. Any other value only allows color on a terminal, which is the auto default: it casts no vote.

  • CLICOLOR_FORCE asks for color unless it is falsy, which casts no vote.

  • LLM refuses color unless it is falsy, which casts no vote: it marks an AI agent, not a color preference.

  • COLOR takes the words of --color (see WHEN and COLOR_WHEN_ALIASES) and booleans. Any other value casts no vote.

The plural and unspaced spellings in COLOR_ENVVARS follow the variable they spell.

A dumb or unknown TERM (see COLOR_DISABLING_TERMS) refuses color as well, so a terminal that cannot render ANSI is treated as color-off even when it reports as a TTY. A variable asking for color still wins over it.

Return type:

bool | None

click_extra.color.forced_color()[source]¶

Force ANSI color while Click Extra captures CLI text for documentation.

Click Extra renders CLI help and output into docs from both the MkDocs plugin (click_extra.mkdocs) and the Sphinx directives (click_extra.sphinx.click). During a build that output is a pipe, not a TTY, so the underlying renderers strip their escape codes. Two independent color systems have to be defeated:

  • Click’s, gated by should_strip_ansi / ctx.color (what click.echo and the Click and Click Extra help formatters consult). Sphinx’s runner additionally flips this one with click.testing.CliRunner(color=True).

  • Rich’s, gated by rich.console.Console.is_terminal, which ignores the above and reads FORCE_COLOR (https://force-color.org). This is the system rich-click uses, and color=True never reaches it.

FORCE_COLOR is the only signal common to both systems (Rich reads it directly; Click Extra recognizes it through COLOR_ENVVARS), so this sets it. It also clears the color-disabling variables Click Extra recognizes (NO_COLOR, LLM, …) so an opt-out in the build environment cannot suppress the rendering, and pins COLORTERM=truecolor so the branded 24-bit themes render at full depth instead of being quantized to the 256-color palette (see supports_truecolor()). The previous environment is restored on exit, so the override never leaks beyond a single capture.

Return type:

Generator[None, None, None]

class click_extra.color.TerminalBackground(*values)[source]¶

Bases: StrEnum

Shade of the background of a terminal.

What resolve_background() detects of the terminal a CLI runs in, and the chrome of a capture, which pictures a terminal: see click_extra.capture.presets. A capture tells the command it pictures which one it is drawn on through the same variables resolve_background() reads, see CAPTURE_TERMINAL_HINTS, so a command run for a picture picks the palette its picture needs.

A capture freezes the colors of the run it pictures, so its chrome has to answer to the palette that run was colored for. Neither direction survives the other: a screen colored for a dark terminal is unreadable on white, and click-extra’s own light and manpage themes wash out on the dark chrome a renderer defaults to.

A member is the string it names, so it also selects the built-in theme of the same name, and doubles as the --background choice of the capture commands.

DARK = 'dark'¶

What a terminal, and this package’s default theme, usually look like.

LIGHT = 'light'¶

For a CLI rendered with a light-background theme.

click_extra.color.query_osc_background(timeout=0.2)[source]¶

Ask the terminal for its background color with an xterm OSC 11 query.

Writes ESC ] 11 ; ? BEL to the terminal and reads back its rgb:RRRR/GGGG/BBBB reply, returning the color as an 8-bit (r, g, b) tuple. Returns None whenever the query cannot run or the terminal stays silent:

  • on non-POSIX platforms, or when termios / tty are missing;

  • when stdin or stdout is not a terminal (piped, redirected, captured);

  • when no reply arrives within timeout seconds.

Caution

The query reads stdin in cbreak mode. If the user has typed ahead, or another reader competes for stdin, those bytes may be consumed here or interleave with the reply (a leading run is harmless: the reply is located with a re.search()). The terminal mode is always restored through termios.tcsetattr(). Because of this contention, the query is opt-in: it runs only when a caller explicitly allows it (see resolve_background() and ThemeOption’s query_background).

Return type:

tuple[int, int, int] | None

click_extra.color.resolve_background(query_background=False)[source]¶

Detect whether the terminal has a dark or light background.

Consults each signal in turn and returns the first that resolves, or None when none does (callers then keep their own default). Precedence, highest first:

  1. CLITHEME — the cli-theme convention. A dark or light value (optionally suffixed with a :variant) is a deliberate override and wins outright; auto and anything unrecognized fall through.

  2. The live OSC 11 query (query_osc_background()), but only when query_background is true. It is the most accurate and the only real-time signal, yet it reads stdin, so it stays opt-in.

  3. COLORFGBG — set by a handful of terminals (rxvt, Konsole) and cached by shell-term-background at shell startup. Read last because it is frequently stale: it reflects the value at terminal launch and is not refreshed when the user switches themes.

Parameters:

query_background (bool) – permit the stdin-reading OSC 11 query. Off by default, as on ThemeOption.

Return type:

TerminalBackground | None

See also

“Is this terminal dark or light?” has a small ecosystem of prior art, mixing the same two strategies this function does (a cached environment variable versus a live OSC query):

click_extra.color.publish_invocation_color(ctx)[source]¶

Mirror ctx.color into _invocation_color for cross-thread readers.

Called by every color callback after it settled its part of the resolution: whichever fires last leaves the final tri-state in the mirror.

The first call ties the mirror to ctx’s own lifetime, so the value does not leak into a later invocation in the same process. A close callback resets it on the normal path, and click_extra.context._queue_run_cleanup on the abort path: a callback raising during parameter processing leaves the context never entered, and therefore never closed. Click’s UsageError holds that context, and the traceback holds the error, so the pair sits in a reference cycle and the finalizer of that path runs at the next collection rather than immediately. Ordinary allocation churn reaches it within a few hundred objects, but it is not deterministic.

Command does not depend on that timing: its main() runs within the _scoped_run block that calls the cleanup as the run ends, which covers every Click Extra command. The finalizer is what carries a plain click.command that merely borrows the color options.

Return type:

None

click_extra.color.invocation_color()[source]¶

The invocation’s resolved color tri-state, reachable from any thread.

Prefers the pinned ctx.color of the calling thread’s own Click context, then the process-wide mirror published by the color callbacks (publish_invocation_color()). None means auto: defer to the output stream’s TTY status, exactly like ctx.color’s own default.

This is what makes --no-color reach output produced outside the main thread, like the subprocess lines click_extra.execution.run_cli() streams through click_extra.logging.StreamHandler.

Return type:

bool | None

class click_extra.color.ColorWhenChoice(choices, case_sensitive=True)[source]¶

Bases: Choice

click.Choice over WHEN that also accepts the hidden GNU synonyms (COLOR_WHEN_ALIASES) and native configuration booleans, folding them to a canonical value before validation.

Only the three canonical WHEN values reach --help, error messages and shell completion, because the public choices stay canonical. Synonyms and booleans are accepted silently and normalized, so downstream code (ColorOption.set_color(), _WHEN_TO_TRISTATE) only ever sees auto, always or never.

Matching is case-insensitive and whitespace-tolerant, which also makes the canonical values forgiving, such as --color=ALWAYS.

convert(value, param, ctx)[source]¶

Fold synonyms and booleans to canonical, then defer to click.Choice.

A native bool only reaches this method from a structured configuration file: TOML or JSON booleans, or YAML’s coercion of yes/no/on/off/true/false. True maps to always and False to never, consistent with a bare --color and --no-color. The command line always delivers strings, so this never turns --color=true into a valid CLI spelling.

Caution

A configuration boolean therefore diverges from git’s color.ui, where true means auto. Click Extra keeps true equal to always so the yes string synonym and YAML’s coercion of yes to True resolve identically across file formats.

Return type:

Any

class click_extra.color.ColorOption(param_decls=None, *, is_flag=False, flag_value='always', default='auto', is_eager=True, expose_value=False, help='Colorize the output. A bare --color is the same as --color=always.', **kwargs)[source]¶

Bases: ExtraOption

A pre-configured --color[=WHEN] tri-state option.

Mirrors the GNU coreutils convention: WHEN is one of WHEN (auto, always or never), and a bare --color (no value) means always. The negative alias --no-color is carried by the separate NoColorOption, because Click forbids attaching /--no-x secondary flags to a value option.

The resolved tri-state lands on ctx.color, the Click-standard attribute that echo() reads through its resolve_color_default() → should_strip_ansi() chain: True keeps ANSI codes, False strips them, None (auto) defers to the output stream’s TTY status.

This option is eager by default, so other eager options (like --version) are rendered with the resolved color state.

Note

--color is deliberately not wired to an envvar. The color environment variables (NO_COLOR, FORCE_COLOR, …) are read manually through resolve_color_env(). Letting Click manage them would dump the whole COLOR_ENVVARS set into the --params env-var column, and only bind one variable per option anyway.

add_to_parser(parser, ctx)[source]¶

Register the option, then teach the parser GNU optional-argument rules.

Click’s optional-value parser binds --color to the next token whenever it does not look like an option, so mycli --color subcommand would consume subcommand as the color value and fail. GNU instead binds an optional argument only when it is attached with =.

This wraps the parser’s long-option matcher so a bare --color replays as --color=<flag_value> (always) and leaves the following argument untouched, while --color=<when> keeps working. The wrapper stays inert for every option that does not carry _gnu_optional_value, so it is safe to install on the shared parser.

Return type:

None

set_color(ctx, param, value)[source]¶

Resolve --color=<WHEN> against the environment and pin ctx.color.

Precedence, highest first:

  1. An explicit --color on the command line.

  2. The color environment variables, but only when the value comes from the built-in default, as for every machine-wide variable (see machine_envvars_apply()). A configuration file or --accessible (both seen here as a non-DEFAULT source) therefore wins over the environment, matching AccessibleOption.

  3. A color state already pinned by --no-color, a forced test runner, or an explicit Context(color=...): preserved when this option only resolves to auto from its default.

  4. The auto default, leaving ctx.color at None for TTY detection.

Whatever branch settles it, the resolution is mirrored process-wide by publish_invocation_color() so output produced from background threads honors it too.

Stays dormant under resilient parsing, like every other eager callback: an introspection context (make_resilient_context(), behind the man-page, tree and completion-spec exporters) is never closed, so publishing from one would leave the process-wide mirror pinned to that context’s environment resolution. A NO_COLOR build environment would then strip the output of every later CLI carrying no color option of its own.

Return type:

None

class click_extra.color.NoColorOption(param_decls=None, *, is_flag=True, default=False, is_eager=True, expose_value=False, help='Disable colorization (alias of --color=never).', **kwargs)[source]¶

Bases: ExtraOption

--no-color flag that forces --color=never.

Click rejects /--no-x secondary flags on a value option, so the negative alias of the tri-state ColorOption cannot live on it and is provided here as a standalone boolean flag. When set, it pins ctx.color to False; when absent it is a no-op, leaving the resolution to ColorOption.

Shown on its own line directly below --color (mirroring --no-config below --config), since every other negative in the default option set is visible too. Eager by default, like ColorOption, so the color state is settled before other eager options render.

set_no_color(ctx, param, value)[source]¶

Force ctx.color off when a negative alias is passed; no-op otherwise.

Dormant under resilient parsing, for the same reason as ColorOption.set_color(): a never-closed introspection context must not publish the process-wide color mirror.

Return type:

None