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:
Truefor a variable asking for color,Falsefor one refusing it. Each value is read by the convention of its variable, not as a plain boolean: seeresolve_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.
autodecides from the terminal,alwaysuses the feature on any stream, andneverleaves it off. The values of--color=<WHEN>, where the feature is ANSI color, and of theliveargument ofSpinnerandOperationTrail, 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
WHENvalue.GNU
lsacceptsyes/forceforalways,no/noneforneverandtty/if-ttyforauto, alongside the three canonical spellings (seeWHEN). Click Extra mirrors that leniency but keeps the synonyms out of--helpoutput, error messages and shell completion, which only ever advertiseWHEN.
- click_extra.color.COLOR_DISABLING_TERMS = frozenset({'dumb', 'unknown'})¶
TERMvalues marking a terminal too limited for ANSI niceties.A
dumborunknownterminal 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 throughis_dumb_terminal(), which keeps the color and animation axes from drifting apart.An unset
TERMis 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
TERMnames a terminal inCOLOR_DISABLING_TERMS.Such a terminal renders neither color nor the cursor movements of an animation. Case does not matter, and an unset
TERMis no dumb terminal.- Return type:
- click_extra.color.is_a_tty(stream)[source]¶
Whether
streamreports itself as an interactive terminal.Probes
isattydefensively throughgetattr(): not every stream object exposes the method (a bare buffer, an in-memory capture, a test double), and a plainstream.isatty()would raise there instead of answering “not a terminal”.- Return type:
- click_extra.color.resolve_color_env()[source]¶
Reconcile the recognized color environment variables into a tri-state.
Reads every variable listed in
COLOR_ENVVARSby its own convention, and returns:Trueif 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.Falseif variables only refuse color.Noneif no variable casts a vote, which leaves the caller free to apply its own default (typicallyauto).
An empty value never votes: both NO_COLOR and FORCE_COLOR treat it as unset. Each family then follows its convention:
NO_COLORrefuses color whatever its value,0andfalseincluded. It never asks for color.FORCE_COLORasks for color, except for0,false,noandoff, 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
autodefault: it casts no vote.CLICOLOR_FORCE asks for color unless it is falsy, which casts no vote.
LLMrefuses color unless it is falsy, which casts no vote: it marks an AI agent, not a color preference.COLORtakes the words of--color(seeWHENandCOLOR_WHEN_ALIASES) and booleans. Any other value casts no vote.
The plural and unspaced spellings in
COLOR_ENVVARSfollow the variable they spell.A
dumborunknownTERM(seeCOLOR_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.
- 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(whatclick.echoand the Click and Click Extra help formatters consult). Sphinx’s runner additionally flips this one withclick.testing.CliRunner(color=True).Rich’s, gated by
rich.console.Console.is_terminal, which ignores the above and readsFORCE_COLOR(https://force-color.org). This is the systemrich-clickuses, andcolor=Truenever reaches it.
FORCE_COLORis the only signal common to both systems (Rich reads it directly; Click Extra recognizes it throughCOLOR_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 pinsCOLORTERM=truecolorso the branded 24-bit themes render at full depth instead of being quantized to the 256-color palette (seesupports_truecolor()). The previous environment is restored on exit, so the override never leaks beyond a single capture.
- class click_extra.color.TerminalBackground(*values)[source]¶
Bases:
StrEnumShade 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: seeclick_extra.capture.presets. A capture tells the command it pictures which one it is drawn on through the same variablesresolve_background()reads, seeCAPTURE_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
lightandmanpagethemes 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
--backgroundchoice 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 ; ? BELto the terminal and reads back itsrgb:RRRR/GGGG/BBBBreply, returning the color as an 8-bit(r, g, b)tuple. ReturnsNonewhenever the query cannot run or the terminal stays silent: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 throughtermios.tcsetattr(). Because of this contention, the query is opt-in: it runs only when a caller explicitly allows it (seeresolve_background()andThemeOption’squery_background).
- 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
Nonewhen none does (callers then keep their own default). Precedence, highest first:CLITHEME— the cli-theme convention. Adarkorlightvalue (optionally suffixed with a:variant) is a deliberate override and wins outright;autoand anything unrecognized fall through.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.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 onThemeOption.- Return type:
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):
shell-term-background (POSIX shell) runs the OSC query once at shell startup and caches the answer into
COLORFGBG, with term-background as its Python reader.terminal-light, termbg and terminal-colorsaurus (Rust) query OSC 10/11 live, like
query_osc_background(); the latter two also read the Windows console.
- click_extra.color.publish_invocation_color(ctx)[source]¶
Mirror
ctx.colorinto_invocation_colorfor 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, andclick_extra.context._queue_run_cleanupon the abort path: a callback raising during parameter processing leaves the context never entered, and therefore never closed. Click’sUsageErrorholds 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.Commanddoes not depend on that timing: itsmain()runs within the_scoped_runblock that calls the cleanup as the run ends, which covers every Click Extra command. The finalizer is what carries a plainclick.commandthat merely borrows the color options.- Return type:
- click_extra.color.invocation_color()[source]¶
The invocation’s resolved color tri-state, reachable from any thread.
Prefers the pinned
ctx.colorof the calling thread’s own Click context, then the process-wide mirror published by the color callbacks (publish_invocation_color()).Nonemeans auto: defer to the output stream’s TTY status, exactly likectx.color’s own default.This is what makes
--no-colorreach output produced outside the main thread, like the subprocess linesclick_extra.execution.run_cli()streams throughclick_extra.logging.StreamHandler.
- class click_extra.color.ColorWhenChoice(choices, case_sensitive=True)[source]¶
Bases:
Choiceclick.ChoiceoverWHENthat 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
WHENvalues reach--help, error messages and shell completion, because the publicchoicesstay canonical. Synonyms and booleans are accepted silently and normalized, so downstream code (ColorOption.set_color(),_WHEN_TO_TRISTATE) only ever seesauto,alwaysornever.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
boolonly reaches this method from a structured configuration file: TOML or JSON booleans, or YAML’s coercion ofyes/no/on/off/true/false.Truemaps toalwaysandFalsetonever, consistent with a bare--colorand--no-color. The command line always delivers strings, so this never turns--color=trueinto a valid CLI spelling.Caution
A configuration boolean therefore diverges from git’s color.ui, where
truemeansauto. Click Extra keepstrueequal toalwaysso theyesstring synonym and YAML’s coercion ofyestoTrueresolve identically across file formats.- Return type:
- 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:
ExtraOptionA pre-configured
--color[=WHEN]tri-state option.Mirrors the GNU coreutils convention:
WHENis one ofWHEN(auto,alwaysornever), and a bare--color(no value) meansalways. The negative alias--no-coloris carried by the separateNoColorOption, because Click forbids attaching/--no-xsecondary flags to a value option.The resolved tri-state lands on
ctx.color, the Click-standard attribute thatecho()reads through itsresolve_color_default()→should_strip_ansi()chain:Truekeeps ANSI codes,Falsestrips 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
--coloris deliberately not wired to anenvvar. The color environment variables (NO_COLOR,FORCE_COLOR, …) are read manually throughresolve_color_env(). Letting Click manage them would dump the wholeCOLOR_ENVVARSset into the--paramsenv-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
--colorto the next token whenever it does not look like an option, somycli --color subcommandwould consumesubcommandas 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
--colorreplays 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:
- set_color(ctx, param, value)[source]¶
Resolve
--color=<WHEN>against the environment and pinctx.color.Precedence, highest first:
An explicit
--coloron the command line.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-DEFAULTsource) therefore wins over the environment, matchingAccessibleOption.A color state already pinned by
--no-color, a forced test runner, or an explicitContext(color=...): preserved when this option only resolves toautofrom its default.The
autodefault, leavingctx.coloratNonefor 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. ANO_COLORbuild environment would then strip the output of every later CLI carrying no color option of its own.- Return type:
- 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-colorflag that forces--color=never.Click rejects
/--no-xsecondary flags on a value option, so the negative alias of the tri-stateColorOptioncannot live on it and is provided here as a standalone boolean flag. When set, it pinsctx.colortoFalse; when absent it is a no-op, leaving the resolution toColorOption.Shown on its own line directly below
--color(mirroring--no-configbelow--config), since every other negative in the default option set is visible too. Eager by default, likeColorOption, so the color state is settled before other eager options render.- set_no_color(ctx, param, value)[source]¶
Force
ctx.coloroff 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: