Colored help¶
Click Extra extends Cloup’s help formatter and theme to automatically colorize every element of the help screen: options, choices, metavars, arguments, CLI and subcommand names, aliases, environment variables, defaults, ranges, and required labels.
Cross-reference highlighting¶
Notice how --format, --output, and --dry-run light up not only in the synopsis column but also inside other options’ descriptions and the command’s docstring:
from click_extra import Choice, command, option, echo
@command
@option("--format", type=Choice(["json", "csv"]), help="Output format.")
@option("--output", help="Write to file instead of stdout.")
@option(
"--dry-run",
is_flag=True,
help="Preview what would be written to --output without --format validation.",
)
def export(format, output, dry_run):
"""Export data.
Combine --format and --output to write directly to a file.
Use --dry-run to preview without side effects.
"""
echo("Exporting...")
$ export --help
Usage: export [OPTIONS]
Export data.
Combine --format and --output to write directly to a file. Use --dry-run to
preview without side effects.
Options:
--format [json|csv] Output format.
--output TEXT Write to file instead of stdout.
--dry-run Preview what would be written to --output without
--format validation.
--time / --no-time Measure and print elapsed execution time.
[default: no-time]
--config CONFIG_PATH Location of the configuration file. Supports
local path with glob patterns or remote URL.
[default: ~/.config/export/{*.toml,*.yaml,*.yml,*
.json,*.json5,*.jsonc,*.hjson,*.ini,*.xml,pyproje
ct.toml}]
--no-config Ignore all configuration files and only use
command line parameters and environment
variables.
--validate-config FILE Validate the configuration file and exit.
--export-config FORMAT Export the configuration in the selected format
to <stdout>, then exit.
--accessible Accessibility mode: disable colors and render
tables in a plain, screen-reader-friendly format.
--color [auto|always|never] Colorize the output. A bare --color is the same
as --color=always. [default: auto]
--no-color Disable colorization (alias of --color=never).
--progress / --no-progress Show progress indicators during long operations.
Disabled for non-interactive output (pipes, dumb
terminals, CI) and by --accessible. [default:
progress]
--theme [dark|dracula|light|manpage|monokai|nord|solarized_dark]
Color theme used for help screens. [default:
dark]
--show-params Show all CLI parameters, their provenance,
defaults and value, then exit.
--table-format [aligned|asciidoc|colon-grid|csv|csv-excel|csv-excel-tab|csv-unix|double-grid|double-outline|fancy-grid|fancy-outline|github|grid|heavy-grid|heavy-outline|hjson|html|jira|json|json5|jsonc|latex|latex-booktabs|latex-longtable|latex-raw|mediawiki|mixed-grid|mixed-outline|moinmoin|orgtbl|outline|pipe|plain|presto|pretty|psql|rounded-grid|rounded-outline|rst|simple|simple-grid|simple-outline|textile|toml|tsv|unsafehtml|vertical|xml|yaml|youtrack]
Rendering style of tables. [default: rounded-
outline]
--verbosity LEVEL Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
[default: WARNING]
-v, --verbose Increase the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
-q, --quiet Decrease the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
--man Show the command's man page (roff) and exit.
--version Show the version and exit.
-h, --help Show this message and exit.
Every option name in the help screen carries the same style, regardless of where it appears: synopsis column, another option’s description, the command’s docstring. This turns plain-text references into visual links, making it easier to scan for related options. The same applies to choices (highlighted in the metavar list and anywhere the description mentions them), arguments, and subcommand names.
Disabling cross-reference highlighting¶
If the free-text matching produces false positives (option names or choices that coincide with common words), disable it via the theme:
from click_extra import BUILTIN_THEMES, group
safe_theme = BUILTIN_THEMES["dark"].with_(cross_ref_highlight=False)
@group(context_settings={"formatter_settings": {"theme": safe_theme}})
def cli(): ...
With cross_ref_highlight=False, only structural elements are styled: bracket fields ([default: ...], [env var: ...], ranges, [required]), deprecated messages, subcommand names in definition lists, and choice metavars ([json|csv|xml]). Option names, choices in free-form text, arguments, metavars, and CLI names in descriptions and docstrings are left unstyled.
Custom keyword injection¶
Use extra_keywords to inject additional strings for highlighting. Strings are grouped by category in a HelpKeywords dataclass, so each gets the appropriate style:
from click_extra import HelpKeywords, command, echo, option
@command(
extra_keywords=HelpKeywords(long_options={"--profile"}),
)
@option("--output", help="Write to file. See --profile for timing.")
def build(output):
"""Build the project."""
echo("Building...")
$ build --help
Usage: build [OPTIONS]
Build the project.
Options:
--output TEXT Write to file. See --profile for timing.
--time / --no-time Measure and print elapsed execution time.
[default: no-time]
--config CONFIG_PATH Location of the configuration file. Supports
local path with glob patterns or remote URL.
[default: ~/.config/build/{*.toml,*.yaml,*.yml,*.
json,*.json5,*.jsonc,*.hjson,*.ini,*.xml,pyprojec
t.toml}]
--no-config Ignore all configuration files and only use
command line parameters and environment
variables.
--validate-config FILE Validate the configuration file and exit.
--export-config FORMAT Export the configuration in the selected format
to <stdout>, then exit.
--accessible Accessibility mode: disable colors and render
tables in a plain, screen-reader-friendly format.
--color [auto|always|never] Colorize the output. A bare --color is the same
as --color=always. [default: auto]
--no-color Disable colorization (alias of --color=never).
--progress / --no-progress Show progress indicators during long operations.
Disabled for non-interactive output (pipes, dumb
terminals, CI) and by --accessible. [default:
progress]
--theme [dark|dracula|light|manpage|monokai|nord|solarized_dark]
Color theme used for help screens. [default:
dark]
--show-params Show all CLI parameters, their provenance,
defaults and value, then exit.
--table-format [aligned|asciidoc|colon-grid|csv|csv-excel|csv-excel-tab|csv-unix|double-grid|double-outline|fancy-grid|fancy-outline|github|grid|heavy-grid|heavy-outline|hjson|html|jira|json|json5|jsonc|latex|latex-booktabs|latex-longtable|latex-raw|mediawiki|mixed-grid|mixed-outline|moinmoin|orgtbl|outline|pipe|plain|presto|pretty|psql|rounded-grid|rounded-outline|rst|simple|simple-grid|simple-outline|textile|toml|tsv|unsafehtml|vertical|xml|yaml|youtrack]
Rendering style of tables. [default: rounded-
outline]
--verbosity LEVEL Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
[default: WARNING]
-v, --verbose Increase the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
-q, --quiet Decrease the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
--man Show the command's man page (roff) and exit.
--version Show the version and exit.
-h, --help Show this message and exit.
Suppressing keyword highlighting¶
The mirror of extra_keywords: use excluded_keywords to prevent specific strings from being highlighted, even when they are auto-collected from the Click context:
from click_extra import Choice, HelpKeywords, command, echo, option
@command(
excluded_keywords=HelpKeywords(choices={"text"}),
)
@option("--format", type=Choice(["json", "text"]), help="Use json or text.")
def export(format):
"""Export data."""
echo("Exporting...")
$ export --help
Usage: export [OPTIONS]
Export data.
Options:
--format [json|text] Use json or text.
--time / --no-time Measure and print elapsed execution time.
[default: no-time]
--config CONFIG_PATH Location of the configuration file. Supports
local path with glob patterns or remote URL.
[default: ~/.config/export/{*.toml,*.yaml,*.yml,*
.json,*.json5,*.jsonc,*.hjson,*.ini,*.xml,pyproje
ct.toml}]
--no-config Ignore all configuration files and only use
command line parameters and environment
variables.
--validate-config FILE Validate the configuration file and exit.
--export-config FORMAT Export the configuration in the selected format
to <stdout>, then exit.
--accessible Accessibility mode: disable colors and render
tables in a plain, screen-reader-friendly format.
--color [auto|always|never] Colorize the output. A bare --color is the same
as --color=always. [default: auto]
--no-color Disable colorization (alias of --color=never).
--progress / --no-progress Show progress indicators during long operations.
Disabled for non-interactive output (pipes, dumb
terminals, CI) and by --accessible. [default:
progress]
--theme [dark|dracula|light|manpage|monokai|nord|solarized_dark]
Color theme used for help screens. [default:
dark]
--show-params Show all CLI parameters, their provenance,
defaults and value, then exit.
--table-format [aligned|asciidoc|colon-grid|csv|csv-excel|csv-excel-tab|csv-unix|double-grid|double-outline|fancy-grid|fancy-outline|github|grid|heavy-grid|heavy-outline|hjson|html|jira|json|json5|jsonc|latex|latex-booktabs|latex-longtable|latex-raw|mediawiki|mixed-grid|mixed-outline|moinmoin|orgtbl|outline|pipe|plain|presto|pretty|psql|rounded-grid|rounded-outline|rst|simple|simple-grid|simple-outline|textile|toml|tsv|unsafehtml|vertical|xml|yaml|youtrack]
Rendering style of tables. [default: rounded-
outline]
--verbosity LEVEL Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
[default: WARNING]
-v, --verbose Increase the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
-q, --quiet Decrease the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
--man Show the command's man page (roff) and exit.
--version Show the version and exit.
-h, --help Show this message and exit.
Excluded keywords are only suppressed in free-text descriptions and docstrings. They remain styled inside their own choice metavar, which is a structural element (like bracket fields).
Exclusions propagate from parent groups to subcommands. If a group excludes a choice, that exclusion applies to all nested subcommand help screens too. Parent and child exclusions are merged, so you can exclude additional keywords at any level:
from click_extra import Choice, HelpKeywords, echo, group, option
@group(excluded_keywords=HelpKeywords(choices={"version"}))
@option("--sort-by", type=Choice(["name", "version"]))
def cli(sort_by):
"""Sort items."""
@cli.command()
def show():
"""Show the version of each item."""
echo("Showing...")
$ cli show --help
Usage: cli show [OPTIONS]
Show the version of each item.
Options:
-h, --help Show this message and exit.
Both extra_keywords and excluded_keywords accept a HelpKeywords instance. The available category fields are: cli_names, subcommands, command_aliases, arguments, long_options, short_options, choices, choice_metavars, metavars, envvars, and defaults. The choice_metavars field is auto-populated from click.Choice parameters and rarely needs manual specification.
For advanced customization, override collect_keywords() on your command class. Call super() and mutate the returned HelpKeywords to add or remove entries:
from click_extra import Command, HelpKeywords
class MyCommand(Command):
def collect_keywords(self, ctx):
kw = super().collect_keywords(ctx)
kw.choices.discard("internal")
kw.long_options.add("--undocumented-flag")
return kw
Bracket fields¶
Trailing metadata brackets ([default: ...], [env var: ...], [required], and range expressions) each get their own style. All four fields can appear together:
from click_extra import command, option, IntRange
@command
@option(
"--threshold",
type=IntRange(1, 100),
default=50,
required=True,
show_default=True,
envvar="THRESHOLD",
show_envvar=True,
help="Sensitivity level.",
)
def analyze(threshold):
"""Run analysis."""
$ analyze --help
Usage: analyze [OPTIONS]
Run analysis.
Options:
--threshold INTEGER RANGE Sensitivity level. [env var: THRESHOLD,
ANALYZE_THRESHOLD; default: 50; 1<=x<=100;
required]
--time / --no-time Measure and print elapsed execution time.
[default: no-time]
--config CONFIG_PATH Location of the configuration file. Supports
local path with glob patterns or remote URL.
[default: ~/.config/analyze/{*.toml,*.yaml,*.yml,
*.json,*.json5,*.jsonc,*.hjson,*.ini,*.xml,pyproj
ect.toml}]
--no-config Ignore all configuration files and only use
command line parameters and environment
variables.
--validate-config FILE Validate the configuration file and exit.
--export-config FORMAT Export the configuration in the selected format
to <stdout>, then exit.
--accessible Accessibility mode: disable colors and render
tables in a plain, screen-reader-friendly format.
--color [auto|always|never] Colorize the output. A bare --color is the same
as --color=always. [default: auto]
--no-color Disable colorization (alias of --color=never).
--progress / --no-progress Show progress indicators during long operations.
Disabled for non-interactive output (pipes, dumb
terminals, CI) and by --accessible. [default:
progress]
--theme [dark|dracula|light|manpage|monokai|nord|solarized_dark]
Color theme used for help screens. [default:
dark]
--show-params Show all CLI parameters, their provenance,
defaults and value, then exit.
--table-format [aligned|asciidoc|colon-grid|csv|csv-excel|csv-excel-tab|csv-unix|double-grid|double-outline|fancy-grid|fancy-outline|github|grid|heavy-grid|heavy-outline|hjson|html|jira|json|json5|jsonc|latex|latex-booktabs|latex-longtable|latex-raw|mediawiki|mixed-grid|mixed-outline|moinmoin|orgtbl|outline|pipe|plain|presto|pretty|psql|rounded-grid|rounded-outline|rst|simple|simple-grid|simple-outline|textile|toml|tsv|unsafehtml|vertical|xml|yaml|youtrack]
Rendering style of tables. [default: rounded-
outline]
--verbosity LEVEL Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
[default: WARNING]
-v, --verbose Increase the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
-q, --quiet Decrease the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
--man Show the command's man page (roff) and exit.
--version Show the version and exit.
-h, --help Show this message and exit.
Note
When choices are Enum members, Click Extra colorizes their name attribute (not their value), matching Click’s own behavior. Use EnumChoice if you need user-friendly choice strings based on values or custom representations.
--color flag¶
Click Extra adds a tri-state --color[=WHEN] option that follows the GNU coreutils convention: WHEN is one of auto, always or never, and a bare --color (no value) means always. The option is eager, so it takes effect before other eager options like --version.
--no-color is an alias of --color=never.
The resolved choice lands on ctx.color, the standard Click attribute that echo() reads: always keeps ANSI codes, never strips them, and auto (the default) defers to the output stream: colored on a terminal, stripped when piped.
The auto default also respects the NO_COLOR, FORCE_COLOR, CLICOLOR and CLICOLOR_FORCE environment variables. When one of these is set, it overrides the default (but an explicit --color or --no-color on the command line always wins).
A dumb or unknown TERM counts as a disabling signal at the same tier: under auto it strips color even on a terminal that reports as a TTY, since such a terminal cannot render ANSI. An enabling variable like FORCE_COLOR still outranks it.
flowchart TD
start(["echo() must decide: emit ANSI codes?"]) --> cli{"--color=WHEN / --no-color<br/>set on CLI or via config?"}
cli -->|yes| useflag["always → ON<br/>never → OFF<br/>auto → defer to TTY"]
cli -->|"no (built-in default)"| env{"a recognized color signal set?<br/>NO_COLOR, CLICOLOR, CLICOLOR_FORCE,<br/>FORCE_COLOR, LLM, TERM=dumb/unknown, ..."}
env -->|yes| envval["ON if any enabling signal,<br/>OFF otherwise (incl. TERM=dumb)"]
env -->|no| deflt["default: auto<br/>(ON on a TTY, OFF when piped)"]
useflag --> ctxcolor(["ctx.color"])
envval --> ctxcolor
deflt --> ctxcolor
ctxcolor --> strip["echo() strips ANSI when OFF;<br/>NO_COLOR also blanks --theme output"]
All Click Extra commands and groups include the --color and --no-color options by default. Use color_option and no_color_option as standalone decorators when building CLIs with plain click.command:
import click
from click_extra import echo, color_option, no_color_option
@click.command
@color_option
@no_color_option
def greet():
"""Say hello with optional color."""
ctx = click.get_current_context()
if ctx.color:
echo("\x1b[32mHello in green!\x1b[0m")
else:
echo("Hello without color.")
$ greet --color=always
Hello in green!
$ greet --color=never
Hello without color.
--no-color is an alias of --color=never:
$ greet --no-color
Hello without color.
Synonyms and configuration¶
For convenience, WHEN also accepts the GNU coreutils synonyms as hidden aliases, matched case-insensitively:
Canonical |
Synonyms |
|---|---|
|
|
|
|
|
|
$ greet --color=yes
Hello in green!
These synonyms stay out of --help, shell completion and error messages, which only ever advertise auto, always and never. An unknown value, including a bare true or false, is still rejected.
In a configuration file the same string synonyms apply, and a native boolean is accepted too: true maps to always and false to never, mirroring a bare --color and --no-color. Because YAML coerces yes, no, on and off to booleans, a value resolves identically whether it arrives as a string or a boolean.
Caution
A configuration boolean diverges from git’s color.ui, where true means auto. Click Extra keeps true equal to always so the yes synonym and YAML’s coercion of yes to True agree across file formats.
--accessible flag¶
A screen reader consumes a terminal as a linear stream of characters. Several defaults that please sighted users work against that stream: ANSI color codes carry no meaning once flattened to text; tables drawn with Unicode box-drawing characters (│, ╭, ─, …) turn their borders and whitespace-based column alignment into noise; animated progress spinners and bars repeat frames a reader cannot watch advance; and interactive takeovers like a pager or a screen-clear trap or wipe the stream the reader is following.
The --accessible flag folds these concerns into a single switch. Enabling it is equivalent to passing --no-color --no-progress --table-format plain, and additionally streams click_extra.echo_via_pager output straight to stdout instead of spawning a pager and turns click_extra.clear into a no-op: ANSI codes are stripped, progress indicators are silenced, tables render without borders, and no interactive view takes over the screen. The ACCESSIBLE environment variable enables the same mode, so a user can opt in once for every Click Extra command they run.
The flag only lowers the defaults of --color, --progress and --table-format (and publishes its own resolved state for the click_extra.clear and click_extra.echo_via_pager helpers to read). An explicit --color, --progress or --table-format on the command line, or in a configuration file, keeps precedence. The resulting order is: command line > configuration file > --accessible > built-in defaults. There is no --no-accessible: to opt back out of a single value, pass the explicit option you want.
from click_extra import command, pass_context, style, Color
@command
@pass_context
def inventory(ctx):
"""List a fruit stock."""
data = (
("apple", style("red", fg=Color.red)),
("lime", style("green", fg=Color.green)),
)
ctx.print_table(data, headers=("fruit", "color"))
$ inventory --accessible
fruit color
apple red
lime green
Why plain, linear output?
A screen reader is not the only consumer that prefers a linear, minimal-width stream over a terminal-wide 2D layout. Command output is also pasted into bug reports, piped into other tools, and read on narrow screens. A layout that imposes a maximal width (full-width tables, box-drawing borders, whitespace-padded columns) wraps awkwardly or grows a horizontal scrollbar once it leaves the terminal it was sized for, while a stream rendered at the minimal width of its text travels everywhere intact.
This is the same reasoning that keeps Click Extra from routing its help screens through rich-click, a good project integrating Rich with Click whose help is laid out in a table spanning the whole terminal width. --accessible carries that preference from help screens to colors and tables. The two are not mutually exclusive, though: nothing stops you from using rich-click and Click Extra together and taking the best of both.
--help, -h aliases¶
Click Extra defaults help_option_names to ("--help", "-h"), adding the short -h alias that Click does not provide out of the box. This applies to all commands and groups created with Click Extra decorators:
from click_extra import command, echo
@command
def hello():
"""Greet the user."""
echo("Hello!")
$ hello -h
Usage: hello [OPTIONS]
Greet the user.
Options:
--time / --no-time Measure and print elapsed execution time.
[default: no-time]
--config CONFIG_PATH Location of the configuration file. Supports
local path with glob patterns or remote URL.
[default: ~/.config/hello/{*.toml,*.yaml,*.yml,*.
json,*.json5,*.jsonc,*.hjson,*.ini,*.xml,pyprojec
t.toml}]
--no-config Ignore all configuration files and only use
command line parameters and environment
variables.
--validate-config FILE Validate the configuration file and exit.
--export-config FORMAT Export the configuration in the selected format
to <stdout>, then exit.
--accessible Accessibility mode: disable colors and render
tables in a plain, screen-reader-friendly format.
--color [auto|always|never] Colorize the output. A bare --color is the same
as --color=always. [default: auto]
--no-color Disable colorization (alias of --color=never).
--progress / --no-progress Show progress indicators during long operations.
Disabled for non-interactive output (pipes, dumb
terminals, CI) and by --accessible. [default:
progress]
--theme [dark|dracula|light|manpage|monokai|nord|solarized_dark]
Color theme used for help screens. [default:
dark]
--show-params Show all CLI parameters, their provenance,
defaults and value, then exit.
--table-format [aligned|asciidoc|colon-grid|csv|csv-excel|csv-excel-tab|csv-unix|double-grid|double-outline|fancy-grid|fancy-outline|github|grid|heavy-grid|heavy-outline|hjson|html|jira|json|json5|jsonc|latex|latex-booktabs|latex-longtable|latex-raw|mediawiki|mixed-grid|mixed-outline|moinmoin|orgtbl|outline|pipe|plain|presto|pretty|psql|rounded-grid|rounded-outline|rst|simple|simple-grid|simple-outline|textile|toml|tsv|unsafehtml|vertical|xml|yaml|youtrack]
Rendering style of tables. [default: rounded-
outline]
--verbosity LEVEL Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
[default: WARNING]
-v, --verbose Increase the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
-q, --quiet Decrease the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
--man Show the command's man page (roff) and exit.
--version Show the version and exit.
-h, --help Show this message and exit.
Colors and styles¶
The click-extra demo subcommands render matrices of all colors, styles, and palettes, useful for testing terminal capabilities. Based on cloup.styling.Style:
Style matrix¶
$ click-extra --color styles
╭───────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────╮
│ Color ↴ \ Style → │ bold │ dim │ underline │ overline │ italic │ blink │ reverse │ strikethrough │
├───────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┤
│ black │ black │ black │ black │ black │ black │ black │ black │ black │
│ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │
│ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │
│ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │
│ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │
│ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │
│ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │
│ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │
│ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │
│ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │
│ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │
│ green │ green │ green │ green │ green │ green │ green │ green │ green │
│ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │
│ red │ red │ red │ red │ red │ red │ red │ red │ red │
│ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │
│ white │ white │ white │ white │ white │ white │ white │ white │ white │
│ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │
╰───────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────╯
Color matrix¶
$ click-extra --color colors
╭─────────────────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────╮
│ Foreground ↴ \ Background → │ black │ blue │ bright_black │ bright_blue │ bright_cyan │ bright_green │ bright_magenta │ bright_red │ bright_white │ bright_yellow │ cyan │ green │ magenta │ red │ reset │ white │ yellow │
├─────────────────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┤
│ black │ black │ black │ black │ black │ black │ black │ black │ black │ black │ black │ black │ black │ black │ black │ black │ black │ black │
│ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │ blue │
│ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │ bright_black │
│ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │ bright_blue │
│ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │ bright_cyan │
│ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │ bright_green │
│ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │ bright_magenta │
│ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │ bright_red │
│ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │ bright_white │
│ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │ bright_yellow │
│ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │ cyan │
│ green │ green │ green │ green │ green │ green │ green │ green │ green │ green │ green │ green │ green │ green │ green │ green │ green │ green │
│ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │ magenta │
│ red │ red │ red │ red │ red │ red │ red │ red │ red │ red │ red │ red │ red │ red │ red │ red │ red │ red │
│ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │ reset │
│ white │ white │ white │ white │ white │ white │ white │ white │ white │ white │ white │ white │ white │ white │ white │ white │ white │ white │
│ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │ yellow │
╰─────────────────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────╯
256-color indexed palette¶
$ click-extra --color palette
+ 0 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435
0 ████████████████████████████████
16 ████████████████████████████████████████████████████████████████████████
52 ████████████████████████████████████████████████████████████████████████
88 ████████████████████████████████████████████████████████████████████████
124 ████████████████████████████████████████████████████████████████████████
160 ████████████████████████████████████████████████████████████████████████
196 ████████████████████████████████████████████████████████████████████████
232 ████████████████████████████████████████████████
8-color foreground/background combinations¶
$ click-extra --color 8color
40 41 42 43 44 45 46 47
30 gYw gYw gYw gYw gYw gYw gYw gYw gYw
1;30 gYw gYw gYw gYw gYw gYw gYw gYw gYw
31 gYw gYw gYw gYw gYw gYw gYw gYw gYw
1;31 gYw gYw gYw gYw gYw gYw gYw gYw gYw
32 gYw gYw gYw gYw gYw gYw gYw gYw gYw
1;32 gYw gYw gYw gYw gYw gYw gYw gYw gYw
33 gYw gYw gYw gYw gYw gYw gYw gYw gYw
1;33 gYw gYw gYw gYw gYw gYw gYw gYw gYw
34 gYw gYw gYw gYw gYw gYw gYw gYw gYw
1;34 gYw gYw gYw gYw gYw gYw gYw gYw gYw
35 gYw gYw gYw gYw gYw gYw gYw gYw gYw
1;35 gYw gYw gYw gYw gYw gYw gYw gYw gYw
36 gYw gYw gYw gYw gYw gYw gYw gYw gYw
1;36 gYw gYw gYw gYw gYw gYw gYw gYw gYw
37 gYw gYw gYw gYw gYw gYw gYw gYw gYw
1;37 gYw gYw gYw gYw gYw gYw gYw gYw gYw
24-bit RGB vs. 256-color quantization¶
For each gradient, the 24-bit row preserves raw SGR 38;2;r;g;b values; the 8-bit row uses the nearest entry from the 256-color palette. The first row is smooth, the second bands visibly wherever neighboring steps collapse onto the same palette index:
$ export FORCE_COLOR=1
$ click-extra --color gradient
Rainbow:
24-bit ████████████████████████████████████████████████████████████████████████
8-bit ████████████████████████████████████████████████████████████████████████
Grayscale:
24-bit ████████████████████████████████████████████████████████████████████████
8-bit ████████████████████████████████████████████████████████████████████████
Red:
24-bit ████████████████████████████████████████████████████████████████████████
8-bit ████████████████████████████████████████████████████████████████████████
Cyan:
24-bit ████████████████████████████████████████████████████████████████████████
8-bit ████████████████████████████████████████████████████████████████████████
Caution
The rendering of colors and styles in this HTML documentation is not complete, and does not reflect the real output in a terminal. Some SGR attributes (like reverse video) have no direct CSS equivalent and are not rendered. Some terminal emulators also lack support for overline (SGR 53), blink (SGR 5), and strikethrough (SGR 9).
Tip
Run uvx click-extra styles in your terminal to see the real rendering with your color scheme.
click_extra.color API¶
classDiagram
Choice <|-- ColorWhenChoice
ExtraOption <|-- ColorOption
ExtraOption <|-- NoColorOption
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), and the
tri-state WHEN resolution. 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 = {'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}
List of environment variables recognized as flags to switch color rendering on or off.
The key is the name of the variable and the boolean value the value to pass to
--coloroption flag when encountered.Source:
- 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._resolve_enabled) treat these two values as a hard opt-out. Sharing the set 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.resolve_color_env()[source]
Reconcile the recognized color environment variables into a tri-state.
Inspects every variable listed in
color_envvarsand returns:Trueif at least one enabling variable (FORCE_COLOR,CLICOLOR, …) is set. Enabling wins over disabling, so a single one is enough to keep colors.Falseif only disabling variables (NO_COLOR,LLM, …) are set.Nonewhen no recognized variable is present, leaving the caller free to apply its own default (typicallyauto).
A bare variable (no value), or one whose value cannot be parsed as a boolean, counts as activation, in the permissive spirit of the NO_COLOR and FORCE_COLOR conventions.
A
dumborunknownTERM(seeCOLOR_DISABLING_TERMS) casts a disabling vote as well, so a terminal that cannot render ANSI is treated as color-off even when it still reports as a TTY. Because enabling wins, an explicitFORCE_COLORstays authoritative 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 it is the lever we set here. We also clear the color-disabling variables Click Extra recognizes (NO_COLOR,LLM, …) so an opt-out in the build environment cannot suppress the rendering, and pinCOLORTERM=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.
- 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
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(allow_query=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 allow_query 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:
allow_query (
bool) – permit the stdin-reading OSC 11 query. Off by default.
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.COLOR_WHEN = ('auto', 'always', 'never')
GNU-canonical tri-state values accepted by
--color=<WHEN>.autodefers to terminal detection,alwaysforces ANSI on,neverstrips it. 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
COLOR_WHENvalue.GNU
lsacceptsyes/forceforalways,no/noneforneverandtty/if-ttyforauto, alongside the three canonical spellings (seeCOLOR_WHEN). Click Extra mirrors that leniency but keeps the synonyms out of--helpoutput, error messages and shell completion, which only ever advertiseCOLOR_WHEN.
- class click_extra.color.ColorWhenChoice(choices, case_sensitive=True)[source]
Bases:
Choiceclick.ChoiceoverCOLOR_WHENthat 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
COLOR_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 ofCOLOR_WHEN(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--show-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. 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.
- 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.
click_extra.highlight API¶
The help-screen keyword highlighting engine (HelpKeywords, HelpFormatter, highlight) lives in its own module, split out of click_extra.color.
classDiagram
HelpFormatter <|-- HelpFormatter
Help-screen keyword highlighting and the colorized help formatter.
Hosts the engine that collects highlightable keywords from a Click context
(HelpKeywords, _HelpColorsMixin) and renders them with the
active theme: HelpFormatter styles --help output and
highlight() applies a styling function to arbitrary matches. Split out of
click_extra.color, which now focuses on --color/--no-color
resolution.
- class click_extra.highlight.HelpKeywords(cli_names=<factory>, subcommands=<factory>, command_aliases=<factory>, arguments=<factory>, long_options=<factory>, short_options=<factory>, choices=<factory>, choice_metavars=<factory>, metavars=<factory>, envvars=<factory>, defaults=<factory>)[source]
Bases:
objectStructured collection of keywords extracted from a Click context for help screen highlighting.
Each field corresponds to a semantic category with its own styling.
- merge(other)[source]
Merge another
HelpKeywordsinto this one.Each set field is updated with the corresponding set from
other.- Return type:
- class click_extra.highlight.HelpFormatter(*args, **kwargs)[source]
Bases:
HelpFormatterExtends Cloup’s custom HelpFormatter to highlights options, choices, metavars and default values.
This is being discussed for upstream integration at:
Forces theme to the active one for the current Click context.
Also transform Cloup’s standard
HelpThemeto our ownHelpTheme.Resolves the active theme via
click_extra.theme.get_current_theme(), which reads the per-invocation pick from the Click context (set byThemeOption) and falls back to the module-level default when no context is active.- theme: HelpTheme
- write_usage(prog, args='', prefix=None)[source]
ANSI-aware override of
cloup.HelpFormatter.write_usage.On Click
8.3.x,click.formatting.wrap_textmeasures line length with rawlen(), counting every byte of the ANSI escape sequences embedded ininitial_indent(the styledUsage:heading + invoked-command name). With 24-bit RGB themes (like Solarized Dark, Dracula, Nord, Monokai), each styled token carries 17+ extra bytes of escape, which inflates the measured line beyond the width budget and causes premature wraps mid-token:[OPTIONS\n ].Cloup styles
prefixandprogthen delegates to click’sHelpFormatter.write_usage(), inheriting the bug. This override re-applies the same styling, then bypasseswrap_textwhenever the visible content fits on a single line: the common case for short usage strings where wrapping is unnecessary. Lines that genuinely overflow the visible width fall back to click’s implementation: the wrap point may still be sub-optimal but the output stays syntactically valid.Note
Click
8.4.0(PR pallets/click#3420) madeclick.formatting.TextWrapperANSI-aware by counting visible width instead of raw bytes, so this override is a no-op fast path on Click>= 8.4.0and only fixes wrapping on the Click8.3.xreleases click-extra still supports.Todo
Drop this override once the minimum supported Click rises to
8.4.0(which includespallets/click#3420). Theterm_len-based visible-width check below becomes redundant once Click’s own wrapper counts visible width.- Return type:
- keywords: HelpKeywords = HelpKeywords(cli_names=set(), subcommands=set(), command_aliases=set(), arguments=set(), long_options=set(), short_options=set(), choices=set(), choice_metavars=set(), metavars=set(), envvars=set(), defaults=set())
- excluded_keywords: HelpKeywords | None = None
- highlight_extra_keywords(help_text)[source]
Highlight extra keywords in help screens based on the theme.
Uses the
highlight()function for all keyword categories. Each category is processed as a batch of regex patterns with a single styling function, which handles overlapping matches and prevents double-styling.- Return type:
- click_extra.highlight.highlight(content, patterns, styling_func, ignore_case=False)[source]
Highlights parts of the
contentthat matchespatterns.Takes care of overlapping parts within the
content, so that the styling function is applied only once to each contiguous range of matching characters.Todo
Support case-foldeing, so we can have the
Straßestring matching theStrassecontent.This could be tricky as it messes with string length and characters index, which our logic relies on.
Danger
Roundtrip through lower-casing/upper-casing is a can of worms, because some characters change length when their case is changed:
- Return type:
click_extra.accessibility API¶
classDiagram
ExtraOption <|-- AccessibleOption
Accessibility helpers switching CLI output to a screen-reader-friendly mode.
A screen reader consumes a terminal as a linear stream of characters. Several of the defaults that make output pleasant for sighted users actively harm that stream:
ANSI color codes, which carry no meaning once flattened to text;
tables drawn with Unicode box characters (
│,╭,─, …), whose separators and whitespace-based column alignment are read out as noise;animated progress spinners and bars, whose cursor-driven frames repeat endlessly to a reader that cannot watch them advance;
interactive takeovers like a pager or a screen-clear, which trap or wipe the linear stream the reader is following.
The AccessibleOption collapses these concerns into a single
--accessible switch (also driven by the ACCESSIBLE environment variable),
which is the same rationale that leads Click Extra to render help screens as
minimal-width text rather than inside a terminal-wide table. It lowers the
--color, --progress and --table-format defaults and publishes
ACCESSIBLE, which clear() and
echo_via_pager() read to drop their interactive behavior. See the
--accessible section of docs/colorize.md for the full reasoning.
- class click_extra.accessibility.AccessibleOption(param_decls=None, is_flag=True, default=False, is_eager=True, expose_value=False, help='Accessibility mode: disable colors and render tables in a plain, screen-reader-friendly format.', **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured
--accessibleswitch.Turning it on (either via the flag or the
ACCESSIBLEenvironment variable) is equivalent to passing--no-color --no-progress --table-format plain, and additionally streamsecho_via_pager()output without a pager and turnsclear()into a no-op: it strips ANSI codes, silences progress spinners and bars, renders tables without box-drawing characters, and avoids interactive screen takeovers.Note
It is a one-way flag with no
--no-accessiblecounterpart: to opt back out, pass the explicit--color/--table-formatyou want, which take precedence anyway (see below). A negation flag would also be the widest option label in the help screen, pushing every other option’s description column to the right.The switch only adjusts the defaults of the
--colorand--table-formatoptions, through the context’sdefault_map. An explicit--color/--table-formaton the command line (or in a configuration file) therefore keeps precedence over--accessible.This option is eager so it lands its defaults before
--colorand--table-formatare resolved.Note
The values are injected with
dict.setdefault(), so they never clobber a colorization or table format already requested by the user. Combined with theChainMapthatConfigOptionlayers on top ofdefault_map, this yields the precedence: command line > configuration file >--accessible> built-in defaults.- set_accessible(ctx, param, value)[source]¶
Publish the accessibility intent and lower color/progress/table defaults.
Reconciles
--accessiblewith theACCESSIBLEenvironment variable, stores the result atACCESSIBLEfor output helpers (clear(),echo_via_pager()) to read, then lowers the--color/--progress/--table-formatdefaults when active. A CLI that never sees--accessible(norACCESSIBLE) keeps every default untouched.Note
The global
ACCESSIBLEenvironment variable is read here rather than wired through the option’senvvar. Click would otherwise list it alongside the auto-generated<CLI>_ACCESSIBLEvariable in the--show-paramstable, making the combined string the widest cell of the env-var column and pushing every other row’s padding out. This mirrors howColorOptionreadsNO_COLORand friends.- Return type:
- click_extra.accessibility.clear()[source]¶
Drop-in for
click.clear()that becomes a no-op under--accessible.Clearing the screen wipes the scrollback a screen reader relies on and carries no meaning in a linear stream, so accessibility mode skips it entirely. Outside accessibility mode (or with no active context) it defers to
click.clear(), which already no-ops when stdout is not a terminal.- Return type:
- click_extra.accessibility.echo_via_pager(text_or_generator, color=None)[source]¶
Drop-in for
click.echo_via_pager()that streams plainly under –accessible.A pager is a full-screen, cursor-driven TUI: it traps output behind its own keybindings, hostile to a screen reader consuming a linear stream. Under
--accessiblethe text is written straight to stdout viaclick.echo()instead. Outside accessibility mode (or with no active context) it defers toclick.echo_via_pager(), which already falls back to a plain write when stdout is not a terminal.The argument is normalized exactly as
click.echo_via_pager()does (a generator function is called, a string is emitted as-is, anything else is iterated), so the two behave identically on their inputs.- Return type: