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

auto

tty, if-tty

always

yes, force

never

no, none

$ 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 → │ bolddimunderlineoverlineitalicblinkreversestrikethrough  │
├───────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┤
│ blackblackblackblackblackblackblackblackblack          │
│ blueblueblueblueblueblueblueblueblue           │
│ bright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_black   │
│ bright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_blue    │
│ bright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyan    │
│ bright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_green   │
│ bright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magenta │
│ bright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_red     │
│ bright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_white   │
│ bright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellow  │
│ cyancyancyancyancyancyancyancyancyan           │
│ greengreengreengreengreengreengreengreengreen          │
│ magentamagentamagentamagentamagentamagentamagentamagentamagenta        │
│ redredredredredredredredred            │
│ reset             │ resetresetresetresetresetresetresetreset          │
│ whitewhitewhitewhitewhitewhitewhitewhitewhite          │
│ yellowyellowyellowyellowyellowyellowyellowyellowyellow         │
╰───────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────╯

Color matrix

$ click-extra --color colors
╭─────────────────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────┬────────────────╮
│ Foreground ↴ \ Background → │ blackbluebright_blackbright_bluebright_cyanbright_greenbright_magentabright_redbright_whitebright_yellowcyangreenmagentared            │ reset          │ whiteyellow         │
├─────────────────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┼────────────────┤
│ blackblackblackblackblackblackblackblackblackblackblackblackblackblackblackblackblackblack          │
│ blueblueblueblueblueblueblueblueblueblueblueblueblueblueblueblueblueblue           │
│ bright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_blackbright_black   │
│ bright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_bluebright_blue    │
│ bright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyanbright_cyan    │
│ bright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_greenbright_green   │
│ bright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magentabright_magenta │
│ bright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_redbright_red     │
│ bright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_whitebright_white   │
│ bright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellowbright_yellow  │
│ cyancyancyancyancyancyancyancyancyancyancyancyancyancyancyancyancyancyan           │
│ greengreengreengreengreengreengreengreengreengreengreengreengreengreengreengreengreengreen          │
│ magentamagentamagentamagentamagentamagentamagentamagentamagentamagentamagentamagentamagentamagentamagentamagentamagentamagenta        │
│ redredredredredredredredredredredredredredredredredred            │
│ reset                       │ resetresetresetresetresetresetresetresetresetresetresetresetresetreset          │ reset          │ resetreset          │
│ whitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhitewhite          │
│ yellowyellowyellowyellowyellowyellowyellowyellowyellowyellowyellowyellowyellowyellowyellowyellowyellowyellow         │
╰─────────────────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────┴────────────────╯

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 --color option flag when encountered.

Source:

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._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 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.resolve_color_env()[source]

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

Inspects every variable listed in color_envvars and returns:

  • True if at least one enabling variable (FORCE_COLOR, CLICOLOR, …) is set. Enabling wins over disabling, so a single one is enough to keep colors.

  • False if only disabling variables (NO_COLOR, LLM, …) are set.

  • None when no recognized variable is present, leaving the caller free to apply its own default (typically auto).

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 dumb or unknown TERM (see COLOR_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 explicit FORCE_COLOR stays authoritative 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 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 pin 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:

Iterator[None]

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 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(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 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 allow_query 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:

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

Return type:

Literal['dark', 'light'] | None

click_extra.color.COLOR_WHEN = ('auto', 'always', 'never')

GNU-canonical tri-state values accepted by --color=<WHEN>.

auto defers to terminal detection, always forces ANSI on, never strips 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_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 COLOR_WHEN). Click Extra mirrors that leniency but keeps the synonyms out of --help output, error messages and shell completion, which only ever advertise COLOR_WHEN.

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

Bases: Choice

click.Choice over COLOR_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 COLOR_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 COLOR_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 --show-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. 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.

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.

Return type:

None

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

Structured collection of keywords extracted from a Click context for help screen highlighting.

Each field corresponds to a semantic category with its own styling.

cli_names: set[str]
subcommands: set[str]
command_aliases: set[str]
arguments: set[str]
long_options: set[str]
short_options: set[str]
choices: set[str]
choice_metavars: set[str]
metavars: set[str]
envvars: set[str]
defaults: set[str]
merge(other)[source]

Merge another HelpKeywords into this one.

Each set field is updated with the corresponding set from other.

Return type:

None

subtract(other)[source]

Remove keywords found in other from this instance.

Each set field is difference-updated with the corresponding set from other. Mirror of merge().

Return type:

None

class click_extra.highlight.HelpFormatter(*args, **kwargs)[source]

Bases: HelpFormatter

Extends 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 HelpTheme to our own HelpTheme.

Resolves the active theme via click_extra.theme.get_current_theme(), which reads the per-invocation pick from the Click context (set by ThemeOption) 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_text measures line length with raw len(), counting every byte of the ANSI escape sequences embedded in initial_indent (the styled Usage: 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 prefix and prog then delegates to click’s HelpFormatter.write_usage(), inheriting the bug. This override re-applies the same styling, then bypasses wrap_text whenever 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) made click.formatting.TextWrapper ANSI-aware by counting visible width instead of raw bytes, so this override is a no-op fast path on Click >= 8.4.0 and only fixes wrapping on the Click 8.3.x releases click-extra still supports.

Todo

Drop this override once the minimum supported Click rises to 8.4.0 (which includes pallets/click#3420). The term_len-based visible-width check below becomes redundant once Click’s own wrapper counts visible width.

Return type:

None

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:

str

getvalue()[source]

Wrap original Click.HelpFormatter.getvalue() to force extra-colorization on rendering.

Return type:

str

click_extra.highlight.highlight(content, patterns, styling_func, ignore_case=False)[source]

Highlights parts of the content that matches patterns.

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ße string matching the Strasse content.

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:

str

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

A pre-configured --accessible switch.

Turning it on (either via the flag or the ACCESSIBLE environment variable) is equivalent to passing --no-color --no-progress --table-format plain, and additionally streams echo_via_pager() output without a pager and turns clear() 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-accessible counterpart: to opt back out, pass the explicit --color / --table-format you 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 --color and --table-format options, through the context’s default_map. An explicit --color / --table-format on the command line (or in a configuration file) therefore keeps precedence over --accessible.

This option is eager so it lands its defaults before --color and --table-format are 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 the ChainMap that ConfigOption layers on top of default_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 --accessible with the ACCESSIBLE environment variable, stores the result at ACCESSIBLE for output helpers (clear(), echo_via_pager()) to read, then lowers the --color / --progress / --table-format defaults when active. A CLI that never sees --accessible (nor ACCESSIBLE) keeps every default untouched.

Note

The global ACCESSIBLE environment variable is read here rather than wired through the option’s envvar. Click would otherwise list it alongside the auto-generated <CLI>_ACCESSIBLE variable in the --show-params table, making the combined string the widest cell of the env-var column and pushing every other row’s padding out. This mirrors how ColorOption reads NO_COLOR and friends.

Return type:

None

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:

None

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 --accessible the text is written straight to stdout via click.echo() instead. Outside accessibility mode (or with no active context) it defers to click.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:

None