click_extra.capture.screenshot module¶

Run a CLI, capture its colors, and render the result as a static document.

In Sphinx the click:run directive executes each CLI and renders its real output at build time, so a documentation page never needs a screenshot. A README on GitHub or PyPI, a slide, or a social post cannot run code, and those surfaces need a capture instead.

The pipeline is two steps, each replaceable on its own:

  1. capture_output() runs the command through run_cli(), under forced_color() and a pinned terminal width, and hands back its raw ANSI text.

  2. render() turns that text into a document, in one of the CaptureFormat members.

capture() chains both, and is what the click-extra screenshot command calls.

Both formats read the same split_ansi() stream, and neither needs a dependency the package does not already carry: SVG is laid out on a character grid by render_svg(), HTML is inline-styled markup from render_html().

The two are not interchangeable, and neither is a fallback for the other:

  • SVG goes where you do not own the page. GitHub and PyPI render an image and strip inline HTML, so a README has no other option. It is a picture: the text is not selectable, and not searchable.

  • HTML goes where you do own the page. The text stays selectable, searchable and copy-pasteable, and reflows with the container.

click_extra.capture.screenshot.TColumns: TypeAlias¶

Width a capture is taken and rendered at, see AUTO_COLUMNS.

click_extra.capture.screenshot.AUTO_COLUMNS: Literal['auto'] = 'auto'¶

Width asking for the one the captured text itself decides.

Neither end of the pipeline is pinned: the command wraps to whatever terminal it finds (Click’s own 80 when that is a pipe, or a documentation build), and the image is laid out at the longest line that came back, see fit_columns(). Nothing the command printed folds inside the picture then, which is what a line the command does not wrap on its own needs: a prompt, a wide table, a machine-readable dump.

The cost is that the picture stops being a fixed-width terminal, so a capture meant to sit beside others at the same width should name that width instead.

click_extra.capture.screenshot.DEFAULT_COLUMNS = 80¶

Terminal width a capture is taken at, in characters.

Both ends of the pipeline have to agree on it: the command wraps its output to this width, and the renderer lays the image out at the same one. Let them disagree and the rendered lines overrun the image. 80 is the width Click itself falls back to off a terminal, which makes it the value a capture lands on by accident anyway.

click_extra.capture.screenshot.MIN_COLUMNS = 20¶

Narrowest width a capture is rendered at.

A floor on AUTO_COLUMNS as much as on an explicit width: a command printing nothing but blank lines would otherwise ask for an image no glyph fits in.

click_extra.capture.screenshot.AUTO_CURSOR: Literal['auto'] = 'auto'¶

Cursor shape asking for the one the terminal preset decides.

The same bargain as AUTO_COLUMNS and AUTO_HOLD: the caller says a cursor is wanted and leaves what it looks like to whatever knows the terminal. It is what shape of None spells on a command line, which cannot pass None.

click_extra.capture.screenshot.AUTO_TRUNCATION: Literal['auto'] = 'auto'¶

Marker asking for a rule across the width of the picture.

TRUNCATION_LABEL centered in a run of TRUNCATION_RULE, spanning the text column of the window. A bare label sits in the left margin and reads as one more line of output; a rule crosses the picture and reads as a seam, which is what a cut is. It carries no brackets, unlike a rule naming a section: there is nothing to name here, and the label is the cut itself.

Never wider than what decides the image width, so the marker cannot widen the picture it cuts: the pinned columns, or the widest line under AUTO_COLUMNS. See _rule_marker().

click_extra.capture.screenshot.TRUNCATION_LABEL = '✂'¶

What AUTO_TRUNCATION centers in its rule.

click_extra.capture.screenshot.TRUNCATION_RULE = '·'¶

Character AUTO_TRUNCATION draws its rule with.

Broken rather than RULE_GLYPH: a dotted line reads as text missing from that spot, where an unbroken one reads as a section ending.

A dot rather than one of the Box Drawing dashes, which carry two or three strokes inside a single cell. Those strokes and the hairline gaps between them are each a pixel or two wide at a normal capture scale, and a cell advances a fractional number of device pixels, so the gaps land inside a pixel on some cells and on a boundary on others: neighbouring dashes merge here and separate there, and the rule shimmers. One dot per cell has nothing to merge with.

click_extra.capture.screenshot.DEFAULT_TRUNCATION: str = 'auto'¶

Marker standing in for the lines trim_lines() cut away.

click_extra.capture.screenshot.AUTO_WRAP_MARKER: Literal['auto'] = 'auto'¶

Marker asking for WRAP_MARKER_LABEL at every fold.

A terminal folds a line wider than itself silently, so a reader of a picture cannot tell a line that wrapped from one the command printed in pieces, and a break landing mid-word reads as a typo. The marker says which it is. It costs a cell of the row it closes, see grid().

click_extra.capture.screenshot.WRAP_MARKER_LABEL = '↵'¶

What AUTO_WRAP_MARKER writes at the fold.

↵ rather than a right-pointing arrow: the line turns back to the left margin and continues on the row below, which is what the glyph draws. It is also the one convention with a precedent in another pager: delta ships it as its own --wrap-left-symbol, and paints it in a color of its own for the same reason this one is drawn in RULE_COLOR.

click_extra.capture.screenshot.DEFAULT_WRAP_MARKER: str = ''¶

What closes a folded row when nothing asks for a marker.

Empty, so a capture folds the way a terminal does. A reader drawing a terminal window is not owed a mark for something the terminal itself would not show.

click_extra.capture.screenshot.PROMPT_THEMES: dict[TerminalBackground, HelpTheme | None] = {TerminalBackground.DARK: None, TerminalBackground.LIGHT: HelpTheme(invoked_command=Style(fg='black', bold), command_help=<function identity>, heading=Style(fg='magenta', underline), constraint=Style(fg='magenta'), section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=Style(fg='blue', bold), alias_secondary=Style(fg='blue', bold, dim), epilog=<function identity>, critical=Style(fg='red', bold), error=Style(fg='red'), warning=Style(fg='magenta'), info=<function identity>, debug=Style(fg='blue', dim), option=Style(fg='blue', bold), subcommand=Style(fg='blue', bold), choice=Style(fg='magenta', bold), metavar=Style(fg='blue', dim, italic), bracket=Style(dim), envvar=Style(fg='magenta', dim), default=Style(fg='green', dim, italic), range_label=Style(fg='blue', dim), required=Style(fg='red', dim), argument=Style(fg='blue', italic), deprecated=Style(fg='red'), separator=Style(fg='black', bold, dim), search=Style(fg='green'), success=Style(fg='green'), cross_ref_highlight=True, subheading=Style(fg='blue', dim))}¶

Theme the prompt line is drawn with, per chrome.

The captured output arrives already colored by the CLI that produced it, under whatever theme that run was told to use. The prompt is the one line this process draws itself, so it is the one that would otherwise land on white chrome in the dark default’s near-white invoked_command style, invisible.

None keeps whatever theme the invocation already runs under.

click_extra.capture.screenshot.CAPTURE_TERMINAL_HINTS: dict[TerminalBackground, dict[str, str]] = {TerminalBackground.DARK: {'CLITHEME': 'dark', 'COLORFGBG': '15;0'}, TerminalBackground.LIGHT: {'CLITHEME': 'light', 'COLORFGBG': '0;15'}}¶

Environment a terminal of each chrome would carry, handed to the command.

A capture is a terminal simulated for a command that cannot see one: its width is pinned and its colors forced, because a pipe would have it wrap to a guess and print none. Its background is the third thing a terminal states and a pipe does not, through the two variables resolve_background() reads: the cli-theme CLITHEME, and COLORFGBG carrying foreground;background palette indices.

So a CLI asking for –theme auto renders for the chrome its picture is drawn on, instead of falling back to dark inside a light window. A CLI that never asks is unaffected: the variables only answer a question it does not put.

click_extra.capture.screenshot.CAPTURE_HIDDEN_TERMINAL_VARS: tuple[str, ...] = ('TERM_PROGRAM',)¶

Environment variables naming the terminal a capture is taken from.

A capture is drawn for a file, and read in a browser or an image viewer. The terminal that happened to run it is therefore not the terminal it is drawn for, and anything the command would tailor to that terminal has to be kept away from it, or the same capture comes out differently on every machine.

TERM_PROGRAM is the one that bites, through _paints_wider_than_it_advances(): a table carrying an emoji-presentation sequence is padded for the terminal named there, so a capture taken under Apple Terminal is wider than the same capture taken under Ghostty. Committed side by side, the two never stop rewriting each other.

Cleared rather than pinned to a value: no name is the honest answer, since a capture is drawn for no terminal in particular.

class click_extra.capture.screenshot.CaptureFormat(*values)[source]¶

Bases: Enum

Document formats a capture can be rendered to.

The value doubles as the file extension from_path() matches on.

ANSI = 'ansi'¶

The escape sequences themselves, for a terminal to paint.

The one target that needs no rendering, a terminal reading the same stream the capture is carried in. So it is the whole picture minus the window: there is no frame, no chrome and no margin to draw, and every option describing one is ignored, see render().

HTML = 'html'¶

Selectable, searchable text in a self-contained <pre>.

Built on ansi_to_html(), so it needs no extra.

SVG = 'svg'¶

A picture of a terminal window, for a surface that strips inline HTML.

Laid out on a character grid by render_svg().

classmethod from_path(path)[source]¶

Pick the capture format a file name asks for.

A bare STDOUT_SENTINEL names the terminal, whose format is the escape sequences themselves, see is_stdout(). A file named - in some directory is a file like any other, and answers by its extension, which it has none of. It is answered here rather than at the call site so the one question “what does this destination want?” has one answer.

Parameters:

path (Path) – where the capture is to be written.

Return type:

CaptureFormat

Returns:

the CaptureFormat its extension names.

Raises:

ValueError – when the extension names no format.

click_extra.capture.screenshot.capture_environment(background, columns)[source]¶

The environment a capture states to the command it runs.

The overrides env_copy() lays over the inherited environment, which is how run_cli() takes them: the chrome’s CAPTURE_TERMINAL_HINTS, every CAPTURE_HIDDEN_TERMINAL_VARS entry mapped to None so it is removed rather than set, and the width the command wraps to.

Parameters:
Return type:

dict[str, str | None]

Returns:

the overrides, by variable name.

click_extra.capture.screenshot.resolve_wrap_marker(marker)[source]¶

Read a wrap_marker option into the characters written at a fold.

The one reading of the option every entry point shares: the --wrap-marker of the capture commands, and the API those commands call.

Parameters:

marker (str) – the text, AUTO_WRAP_MARKER, or an empty string for no marker at all.

Return type:

str

Returns:

the characters to write at a fold, empty for none.

click_extra.capture.screenshot.parse_columns(value)[source]¶

Read a width written as text into a number, or into AUTO_COLUMNS.

The one reading of a columns option every entry point shares: the --columns of the capture commands and the :screenshot-columns: of the documentation directive. Each wraps the error in the exception its framework reports.

Parameters:

value (str) – the text, an integer or the word AUTO_COLUMNS.

Return type:

int | Literal['auto']

Returns:

the width, in characters, or AUTO_COLUMNS.

Raises:

ValueError – when the text is neither, or names a width under MIN_COLUMNS.

click_extra.capture.screenshot.auto_columns(pictures, cursor=None)[source]¶

Width, in characters, an auto-sized capture of pictures asks for.

The longest line any of them holds, which is what keeps a command’s own wrapping from folding again inside the picture. Frames are stacked in one window, so the widest is what has to fit.

A cursor standing past the end of its row needs a cell of its own on top of that. At exactly the text’s width it would otherwise wrap onto the row below, see cursor_cell(), and an auto-sized capture would show a row holding nothing but a cursor: the width is derived from the text, so the text always ends on the last column.

Parameters:
  • pictures (Sequence[str]) – the captured texts, one per frame, or the one a still draws.

  • cursor (Cursor | None) – the cursor the capture draws, if any.

Return type:

int

Returns:

the width, in characters.

click_extra.capture.screenshot.prompt_line(args, *, prompt=None, background=TerminalBackground.DARK, preset=None)[source]¶

Compose the invocation a capture draws above its output.

The one place three pipelines agree on what a prompt looks like: a still capture, a recording, and a documentation block that records one. Drawing it three times would be three chances for the sigil, the theme or the preset to disagree between an image and the image beside it.

Parameters:
  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – the command line that was run, in the nested form run_cli() accepts.

  • prompt (str | None) – command line to display, when it differs from the one run. An empty string draws no prompt at all; None shows what was run.

  • background (TerminalBackground) – chrome the capture is headed for, which picks the theme the line is styled with.

  • preset (TerminalPreset | None) – terminal being pictured, which names the sigil its shell draws. None keeps this platform’s.

Return type:

str

Returns:

the styled line, or empty when nothing is to be drawn.

click_extra.capture.screenshot.append_prompt(text, *, background=TerminalBackground.DARK, preset=None)[source]¶

Put the shell’s prompt back on the row under a finished command.

What a terminal actually shows once a command exits: the shell comes back and waits, so the row under the output holds its sigil rather than nothing. Paired with a cursor it costs no height at all, the cursor having already claimed that row, see cursor_cell(). It also puts the cursor somewhere that reads: after a prompt, instead of alone on an empty line.

Caution

Only for a screen the command has finished drawing. Mid-animation the shell has not come back, and a sigil there says the command exited when it did not. record_and_render() therefore closes its last frame alone.

Parameters:
  • text (str) – the captured text to close.

  • background (TerminalBackground) – chrome the capture is headed for, which picks the theme the sigil is styled with.

  • preset (TerminalPreset | None) – terminal being pictured, which names the sigil its shell draws. None keeps this platform’s.

Return type:

str

Returns:

the same text, closed by a prompt.

click_extra.capture.screenshot.capture_output(args, *, columns=80, background=TerminalBackground.DARK, merge_stderr=False, timeout=None)[source]¶

Run a command and capture its output, ANSI escape sequences and all.

A command whose output is a pipe rather than a terminal strips its own colors, and wraps to whatever width it can guess. Both are pinned here: forced_color() sets the FORCE_COLOR lever every mainstream color system obeys and clears any opt-out the environment carries, while COLUMNS fixes the width the command wraps to.

Only stdout is captured by default. That is what keeps a capture free of the progress lines and build chatter a wrapper like uv writes to stderr, with no shell redirection to remember.

The terminal this runs from is hidden from the command, see CAPTURE_HIDDEN_TERMINAL_VARS, so one machine’s capture matches another’s.

Parameters:
Return type:

CompletedProcess[str]

Returns:

the completed process, whose stdout holds the captured text.

click_extra.capture.screenshot.trim_lines(text, *, head=None, tail=None, truncation='auto', columns=80, wrap_marker='', width_floor=0, gutter=0)[source]¶

Keep only the first head and last tail lines of text.

Whatever is dropped is replaced by a single truncation line, so the image admits that it was cut rather than pretending to be the whole output. Text short enough to survive both bounds comes back untouched, with no marker.

A cut leaving a style open above it closes that style before the marker, see _leaves_style_open().

Parameters:
  • text (str) – the captured output.

  • head (int | None) – number of leading lines to keep, or None for no head bound.

  • tail (int | None) – number of trailing lines to keep, or None for no tail bound.

  • truncation (str) – line standing in for what was cut.

  • columns (int | Literal['auto']) – width the text is drawn at, which bounds the rule AUTO_TRUNCATION draws, see _rule_marker().

  • wrap_marker (str) – what closes a folded row, see render(). It takes a cell of every row, so it narrows the rule by as much.

  • width_floor (int) – under AUTO_COLUMNS, the width of a line the picture draws besides text, like the prompt, which the rule spans too.

  • gutter (int) – cells the line numbers drawn after the cut take in front of every row, see number_lines(). It narrows the rule by as much.

Return type:

str

Returns:

the trimmed text.

click_extra.capture.screenshot.emphasize_ansi(text, lines, paint)[source]¶

Band the named lines of ANSI text, the way a terminal can.

The picture’s band is a rectangle drawn behind a row. A terminal has no behind, so the band is the row’s own background color, set for the whole row and padded out to the longest line so the marked rows still square up into a block rather than ending ragged.

Caution

The band is restated after every escape sequence in the row, not just at its start. Pygments closes a colored run with a full reset (\x1b[39;00m), which clears the background along with the ink: set once, a band would stop at the row’s first keyword. Restating the same color costs nothing to look at, since the second declaration paints what the first already did.

Parameters:
  • text (str) – the text to band, ANSI escape sequences included.

  • lines (Sequence[int]) – rows to band, counted from 1. Empty bands nothing.

  • paint (str) – the band’s color, as #rrggbb.

Return type:

str

Returns:

the text, banded.

click_extra.capture.screenshot.render(text='', *, format=CaptureFormat.SVG, columns=80, title='', unique_id=None, frames=None, interval=None, hold=0.0, blank=0.0, speed=1.0, emphasize=(), cursor=None, wrap_marker='', full=True, background=TerminalBackground.DARK, preset=None, palette=None, font_stack=None, chrome=Chrome(border=None, border_width=1, radius=None, backdrop='none', shadow=None, margin=48, padding=8, opacity=1.0, watermark='generated with click-extra', watermark_color=None))[source]¶

Render captured terminal text to the document format names.

Parameters:
  • text (str) – captured output, ANSI escape sequences included.

  • format (CaptureFormat) – which document to produce. CaptureFormat.ANSI draws no window, so it ignores everything describing one: the frame, the chrome, the caption, the margin, the credit line and the animation. What it keeps is emphasize, which marks rows rather than surrounding them, and whatever the caller already did to the text itself.

  • columns (int | Literal['auto']) – terminal width, in characters, an SVG is laid out at, or AUTO_COLUMNS for the width its own longest line asks for. HTML reflows and ANSI is the text itself, so both ignore this.

  • title (str) – caption drawn in an SVG’s window chrome, or an HTML document’s <title>.

  • unique_id (str | None) – SVG only. Prefix namespacing the source’s CSS classes and element IDs. Pinning it to something stable (the output file’s name, say) keeps a regenerated capture diffing line by line, instead of renaming every class as soon as a single character of output changes. Characters a CSS class name cannot carry are folded to a dash.

  • frames (Sequence[str] | None) – SVG only. The animation’s frames, see render_svg().

  • interval (float | Sequence[float] | None) – SVG only. How long each of them is shown, see render_svg().

  • hold (float | Literal['auto']) – SVG only. Extra seconds the last frame stays up, or AUTO_HOLD to scale them to that frame’s line count, see render_svg().

  • blank (float) – SVG only. Seconds of empty screen closing the cycle, see render_svg().

  • speed (float) – SVG only. How much faster to play than recorded, see render_svg().

  • emphasize (Sequence[int]) – SVG and ANSI. Lines to draw a band behind, see render_svg() and emphasize_ansi().

  • cursor (Cursor | None) – SVG only. The terminal cursor to draw, see Cursor. None draws none. A cursor naming no shape takes the one the preset says that terminal draws, so --preset windows gets its bar without stating it.

  • wrap_marker (str) – SVG only. What closes each row a fold cut short, AUTO_WRAP_MARKER for WRAP_MARKER_LABEL, or empty to fold silently, see grid(). HTML reflows with the page embedding it, and a terminal reading ANSI folds on its own, so neither has a fold of the capture’s to mark.

  • full (bool) – HTML only. See render_html().

  • background (TerminalBackground) – chrome to draw on, see TerminalBackground.

  • preset (TerminalPreset | None) – terminal to draw the capture as, see TerminalPreset. None keeps the renderer’s own neutral window.

  • palette (TerminalPalette | None) – colors the text resolves against. None takes the ones the preset and chrome name, which is what a terminal capture wants. The window’s decorations keep answering to the chrome either way: a stated palette repaints the terminal’s body, not the desktop’s frame around it.

  • font_stack (str | None) – fonts the text is set in, best first, as CSS writes them, see parse_font_stack(). None takes the preset’s, or the renderer’s own.

  • chrome (Chrome) – how the window around the text is drawn, see Chrome.

Return type:

str

Returns:

the rendered document.

Raises:

ValueError – asking an ANSI or HTML capture to animate.

click_extra.capture.screenshot.capture(args, *, format=CaptureFormat.SVG, columns=80, prompt=None, head=None, tail=None, truncation='auto', merge_stderr=False, timeout=None, line_numbers=False, emphasize=(), cursor=None, wrap_marker='', closing_prompt=False, title='', unique_id=None, full=True, background=TerminalBackground.DARK, preset=None, palette=None, font_stack=None, chrome=Chrome(border=None, border_width=1, radius=None, backdrop='none', shadow=None, margin=48, padding=8, opacity=1.0, watermark='generated with click-extra', watermark_color=None))[source]¶

Run a command and render its output as a document.

Chains capture_output(), trim_lines() and render(). The invocation is drawn above the output as a shell prompt, styled by the active theme through format_cli_prompt(), so the capture shows what to type to reproduce it.

Parameters:
  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – the command line to run.

  • format (CaptureFormat) – which document to produce.

  • columns (int | Literal['auto']) – terminal width, in characters, or AUTO_COLUMNS to pin none and lay the image out at what the command printed.

  • prompt (str | None) – command line to display, when it differs from the one run. uv run --frozen -- my-cli reproduces a capture from a checkout, but my-cli is what a reader types. An empty string draws no prompt at all.

  • head (int | None) – number of leading output lines to keep.

  • tail (int | None) – number of trailing output lines to keep.

  • truncation (str) – line standing in for the lines cut by head or tail.

  • merge_stderr (bool) – fold stderr into the captured output.

  • timeout (float | None) – seconds before the command is killed.

  • line_numbers (bool) – draw each line’s number in a gutter, see number_lines(). The prompt counts as the first of them, being the invocation everything under it came from.

  • emphasize (Sequence[int]) – lines to draw a band behind, see render_svg(). The prompt is line 1 here too, and a gutter does not shift the count.

  • cursor (Cursor | None) – see render(). A still capture leaves its cursor after the last thing the command printed, which is where the shell finds it.

  • wrap_marker (str) – see render().

  • closing_prompt (bool) – draw the shell’s prompt on the row under the output, which is where it comes back once the command exits, see append_prompt().

  • title (str) – see render().

  • unique_id (str | None) – see render().

  • full (bool) – see render().

  • background (TerminalBackground) – see render().

  • preset (TerminalPreset | None) – see render().

  • palette (TerminalPalette | None) – see render().

  • font_stack (str | None) – see render().

  • chrome (Chrome) – see render().

Return type:

tuple[str, int]

Returns:

the rendered document, and the command’s exit code.

Raises:

OSError – when the command cannot start. subprocess.Popen raises a FileNotFoundError for a program it cannot find, and a PermissionError for a file it cannot run.