click_extra.sphinx package

Helpers and utilities for Sphinx.

Note

The MkDocs counterpart lives in click_extra.mkdocs, which achieves the same ANSI color rendering by patching pymdownx.highlight’s formatter classes.

click_extra.sphinx.EXEC_DIRECTIVES_OPT_IN = 'click_extra_enable_exec_directives'

Name of the conf.py config flag that gates every code-execution directive.

Default is False. A project that adds click_extra.sphinx to its extensions list gets the ANSI Pygments formatter and the GitHub-alerts converter unconditionally, but does not gain access to either the click:* or the python:* directive families until the maintainer opts in explicitly. Both families exec user-supplied Python at build time with full Sphinx-process privileges; gating them behind a single explicit flag keeps a transitive import or a doc-only pull request from silently expanding the build’s attack surface.

click_extra.sphinx.setup(app)[source]

Register extensions to Sphinx.

Always-on features (no execution surface):

  • The ANSI-capable HTML formatter for Pygments (replaces sphinx.highlighting.PygmentsBridge with one that renders ANSI colors in code blocks).

  • GitHub-flavored alert syntax (> [!NOTE], etc.) in included and regular source files, converted to MyST/reST admonitions.

Opt-in features (gated behind click_extra_enable_exec_directives):

  • click:source / click:run to define and execute Click CLIs at build time.

  • python:source / python:run to execute arbitrary Python at build time and render its source or captured stdout.

  • python:render / python:render-myst / python:render-rst to execute arbitrary Python and parse the captured stdout as live document content.

All directives in the opt-in group execute user-supplied Python with the same privileges as the Sphinx process. They are therefore disabled by default. Set click_extra_enable_exec_directives = True in conf.py to register them.

Caution

This function forces the Sphinx app to use sphinx.highlighting.PygmentsBridge instead of the default HTML formatter to add support for ANSI colors in code blocks.

Return type:

ExtensionMetadata

Submodules

click_extra.sphinx.alerts module

Utilities to convert GitHub alerts into MyST admonitions for Sphinx.

click_extra.sphinx.alerts.GITHUB_ALERT_PATTERN = re.compile('^\\s*\\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\\]\\s*$')

Regex pattern to match GitHub alert type declaration (without leading >).

click_extra.sphinx.alerts.QUOTE_PREFIX_PATTERN = re.compile('^(\\s*)((?:>\\s*)+)(.*)$')

Regex pattern to extract indent, quote markers, and content.

click_extra.sphinx.alerts.CODE_FENCE_PATTERN = re.compile('^(\\s*)(`{3,}|~{3,})(.*)$')

Regex pattern to match code fence opening/closing lines.

click_extra.sphinx.alerts.INDENTED_CODE_BLOCK_PATTERN = re.compile('^( {4}|\\t)')

Regex pattern to match indented code block lines (4 spaces or 1 tab).

class click_extra.sphinx.alerts.Alert(alert_type, indent, depth, has_nested=False, opening_line_index=0)[source]

Bases: object

Represents a GitHub alert being processed.

alert_type: str
indent: str
depth: int
has_nested: bool = False
opening_line_index: int = 0
class click_extra.sphinx.alerts.FenceState(char, length, indent, is_code_block)[source]

Bases: object

Tracks code fence state.

char: str
length: int
indent: str
is_code_block: bool
class click_extra.sphinx.alerts.ParserState(result=<factory>, alert_stack=<factory>, fence_stack=<factory>, prev_line_blank=True, modified=False, just_opened_fence_directive=False)[source]

Bases: object

Mutable state for the alert parser.

result: list[str]
alert_stack: list[Alert]
fence_stack: list[FenceState]
prev_line_blank: bool = True
modified: bool = False
just_opened_fence_directive: bool = False
in_code_block()[source]

Check if currently inside a code block.

Return type:

bool

current_depth()[source]

Get current alert nesting depth.

Return type:

int

click_extra.sphinx.alerts.check_colon_fence(app: Sphinx) None[source]

Check that colon_fence support is enabled for MyST.

Raises:

ConfigError – If colon_fence is not in myst_enable_extensions.

Return type:

None

click_extra.sphinx.alerts.count_quote_depth(line)[source]

Parse a line to extract indent, quote depth, and content.

Return type:

tuple[str, int, str]

Returns:

Tuple of (indent, depth, content) where depth is the number of > markers.

click_extra.sphinx.alerts.process_fence(state, indent, chars, after)[source]

Process a fence line, updating fence stack.

Return type:

None

click_extra.sphinx.alerts.close_alerts_to_depth(state, target_depth)[source]

Close all alerts deeper than target_depth.

Return type:

None

click_extra.sphinx.alerts.mark_parent_nested(state)[source]

Mark the parent alert as having a nested alert and update its opening.

Return type:

None

click_extra.sphinx.alerts.open_alert(state, alert_type, indent, depth)[source]

Open a new alert at the given depth.

Return type:

None

click_extra.sphinx.alerts.process_quoted_line(state, line)[source]

Process a line that starts with quote markers.

Returns True if the line was handled as part of an alert.

Return type:

bool

click_extra.sphinx.alerts.replace_github_alerts(text)[source]

Transform GitHub alerts into MyST admonitions.

Identify GitHub alerts in the provided text and transform them into colon-fenced ::: MyST admonitions.

Returns None if no transformation was applied, else returns the transformed text.

Return type:

str | None

click_extra.sphinx.alerts.convert_github_alerts(app, *args)[source]

Convert GitHub alerts into MyST admonitions in content blocks.

Return type:

None

click_extra.sphinx.click module

Sphinx rendering of CLI based on Click Extra.

See also

These directives are based on Pallets’ Sphinx Themes, released under a BSD-3-Clause license.

Compared to the latter, it:

  • Add support for MyST syntax.

  • Adds rendering of ANSI codes in CLI results.

  • Has better error handling and reporting which helps you pinpoint the failing code in your documentation.

  • Removes the println function which was used to explicitly print a blank line. This is no longer needed as it is now handled natively.

click_extra.sphinx.click.RST_INDENT = '   '

The indentation used for rST code blocks lines.

class click_extra.sphinx.click.TerminatedEchoingStdin(input, output)[source]

Bases: EchoingStdin

Like click.testing.EchoingStdin but adds a visible ^D in place of the EOT character ().

ClickRunner.invoke() adds  when terminate_input=True.

click_extra.sphinx.click.patch_subprocess()[source]

Patch subprocess to work better with ClickRunner.invoke().

subprocess.call output is redirected to click.echo so it shows up in the example output.

Caution

The replacement is installed on the subprocess module itself (not thread-local), so for the duration of the with block any other code in the same process that calls subprocess.call sees the patched version. With parallel_read_safe = True declared on ClickDomain, a parallel reader running concurrently on a different document gets the patched subprocess.call too. The redirection is benign (output goes to click.echo) but the race is real, and the parallel-safe claim is weaker than it looks for documents that themselves shell out via subprocess.call.

class click_extra.sphinx.click.ClickRunner[source]

Bases: CliRunner

A sub-class of click.testing.CliRunner for Sphinx directive execution.

Produces unfiltered ANSI codes so that the Directive sub-classes below can render colors in the HTML output.

isolation(*args, **kwargs)[source]

A context manager that sets up the isolation for invoking of a command line tool. This sets up <stdin> with the given input data and os.environ with the overrides from the given dictionary. This also rebinds some internals in Click to be mocked (like the prompt functionality).

This is automatically done in the invoke() method.

Parameters:
  • input – the input stream to put into sys.stdin.

  • env – the environment overrides as dictionary.

  • color – whether the output should contain color codes. The application can still override this explicitly.

Added in version 8.2: An additional output stream is returned, which is a mix of <stdout> and <stderr> streams.

Changed in version 8.2: Always returns the <stderr> stream.

Changed in version 8.0: <stderr> is opened with errors="backslashreplace" instead of the default "strict".

Changed in version 4.0: Added the color parameter.

invoke(cli, args=None, prog_name=None, input=None, terminate_input=False, env=None, _output_lines=None, **extra)[source]

Like CliRunner.invoke() but displays what the user would enter in the terminal for env vars, command arguments, and prompts.

Parameters:
  • terminate_input – Whether to display ^D after a list of input.

  • _output_lines – A list used internally to collect lines to be displayed.

Return type:

Result

execute_source(directive)[source]

Execute the given code, adding it to the runner’s namespace.

Return type:

None

run_cli(directive)[source]

Execute the given source_code.

Returns a simulation of terminal execution, including a mix of input, output, prompts and tracebacks.

The execution context is augmented, so you can refer directly to these functions in the provided source_code:

  • invoke(): which is the same as ClickRunner.invoke()

  • isolated_filesystem(): A context manager that changes to a temporary directory while executing the block.

If any local variable in the provided source_code conflicts with these functions, a RuntimeError is raised to help you pinpoint the issue.

Return type:

list[str]

class click_extra.sphinx.click.ClickDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]

Bases: SphinxDirective

has_content = True

May the directive have content?

required_arguments = 0

Number of required directive arguments.

optional_arguments = 1

The optional argument overrides the default Pygments language to use.

final_argument_whitespace = False

May the final argument contain whitespace?

option_spec: ClassVar[OptionSpec] = {'caption': <function unchanged_required>, 'class': <function class_option>, 'dedent': <function optional_int>, 'emphasize-lines': <function unchanged_required>, 'emphasize-result-lines': <function unchanged_required>, 'force': <function flag>, 'hide-results': <function flag>, 'hide-source': <function flag>, 'language': <function unchanged_required>, 'lineno-start': <class 'int'>, 'linenos': <function flag>, 'name': <function unchanged>, 'show-results': <function flag>, 'show-source': <function flag>}

Options supported by this directive.

Support the same options as sphinx.directives.code.CodeBlock, and some specific to Click directives.

The standard emphasize-lines option applies to the source block only. Use emphasize-result-lines to highlight specific lines in the captured output block, with the same syntax (e.g. :emphasize-result-lines: 1,3-5).

default_language: str

Default highlighting language to use to render the code block.

All Pygments’ languages short names are recognized.

show_source_by_default: bool = True

Whether to render the source code of the example in the code block.

show_results_by_default: bool = True

Whether to render the results of the example in the code block.

runner_method: str

The name of the method to call on the ClickRunner instance.

runner_attr: ClassVar[str] = 'click_runner'

Name of the attribute holding the runner on the doctree.

Subclasses (like PythonDirective) override this so the Click and Python runners don’t collide on the same document.

runner_factory

Class to instantiate for the per-document runner.

Defaults to ClickRunner in ClickDirective (set after the class definition to break the forward reference).

alias of ClickRunner

property runner

Get or create the per-document runner.

Creates one runner per document, keyed by runner_attr.

property language: str[source]

Short name of the Pygments lexer used to highlight the code block.

Returns, in order of precedence, the language specified in the :language: directive options, the first argument of the directive (if any), or the default set in the directive class.

code_block_options(target='source')[source]

Render the options supported by Sphinx’ native code-block directive.

target selects which block these options will be attached to: "source" for the directive’s input source code, "results" for the captured output. emphasize-lines routes to the source block; emphasize-result-lines is rewritten as emphasize-lines on the results block, so authors can highlight different lines in each.

Return type:

list[str]

property show_source: bool[source]

Whether to show the source code of the example in the code block.

The last occurrence of either show-source or hide-source options wins. If neither is set, the default is taken from show_source_by_default.

property show_results: bool[source]

Whether to show the results of running the example in the code block.

The last occurrence of either show-results or hide-results options wins. If neither is set, the default is taken from show_results_by_default.

property is_myst_syntax: bool[source]

Check if the current directive is written with MyST syntax.

render_code_block(lines, language, target='source')[source]

Render the code block with the source code or results.

target is forwarded to code_block_options() so the emphasize-lines / emphasize-result-lines split routes the right highlighting to each block.

Return type:

list[str]

run()[source]
Return type:

list[Node]

class click_extra.sphinx.click.SourceDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]

Bases: ClickDirective

Directive to declare a Click CLI source code.

This directive is used to declare a Click CLI example in the documentation. It renders the source code of the example in a Python code block.

default_language: str = 'python'

Default highlighting language to use to render the code block.

All Pygments’ languages short names are recognized.

show_source_by_default: bool = True

Whether to render the source code of the example in the code block.

show_results_by_default: bool = False

Whether to render the results of the example in the code block.

runner_method: str = 'execute_source'

The name of the method to call on the ClickRunner instance.

class click_extra.sphinx.click.RunDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]

Bases: ClickDirective

Directive to run a Click CLI example.

This directive is used to run a Click CLI example in the documentation. It renders the results of running the example in a shell session code block supporting ANSI colors.

default_language: str = 'ansi-shell-session'

Default highlighting language to use to render the code block.

All Pygments’ languages short names are recognized.

show_source_by_default: bool = False

Whether to render the source code of the example in the code block.

show_results_by_default: bool = True

Whether to render the results of the example in the code block.

runner_method: str = 'run_cli'

The name of the method to call on the ClickRunner instance.

class click_extra.sphinx.click.DeprecatedExampleDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)[source]

Bases: SourceDirective

Deprecated alias for SourceDirective.

Deprecated since version 7.3.0: Use click:source instead of click:example.

run()[source]
Return type:

list[Node]

class click_extra.sphinx.click.ClickDomain(env)[source]

Bases: StatelessDomain

Setup new directives under the same click namespace:

  • click:source which renders a Click CLI source code

  • click:example, an alias to click:source (deprecated)

  • click:run which renders the results of running a Click CLI

name: ClassVar[str] = 'click'

domain name: should be short, but unique

label: ClassVar[str] = 'Click'

domain label: longer, more descriptive (used in messages)

directives: ClassVar[dict] = {'example': <class 'click_extra.sphinx.click.DeprecatedExampleDirective'>, 'run': <class 'click_extra.sphinx.click.RunDirective'>, 'source': <class 'click_extra.sphinx.click.SourceDirective'>}

directive name -> directive class

click_extra.sphinx.click.cleanup_runner(app, doctree)

Drop the ClickRunner from the doctree once the document is read.

Return type:

None