Skip to content

Latest commit

 

History

History
777 lines (598 loc) · 27.5 KB

API.md

File metadata and controls

777 lines (598 loc) · 27.5 KB

gum Starlark API Reference

This is the complete reference for the gum module's script-facing surface: every builtin (signature, parameters, returns, errors, examples) and every configuration accessor. For an overview and quickstart, see the README.

The module is loaded under the name gum; load individual builtins with load("gum", "input", "select", ...).

Contents

TTY note. Every interactive builtin (input, write, select, multi_select, filter, confirm, file_pick, note, spin) drives the host's controlling terminal. In a headless environment (CI, sandbox, a plain run without a terminal) they fail with could not open a new TTY. The non-interactive builtins (md, colorize, code_block, style, table, tree, compose) and all argument validation work anywhere.

Text input

input

input(value="", prompt="> ", placeholder="Type something...", title="", description="",
      char_limit=0, suggestions=[], password=False, validate=None, width=<config>,
      inline=False, show_help=True, timeout=0)

Creates a single-line text input field.

Parameters:

  • value: Initial value (default: "").
  • prompt: Input prompt (default: "> ").
  • placeholder: Placeholder text (default: "Type something...").
  • title: Title text (default: "").
  • description: Description text (default: "").
  • char_limit: Maximum character limit (default: 0 — no limit).
  • suggestions: A string or list of autocomplete suggestions (default: []).
  • password: True for masked password input, False for normal echo, or None for no echo (default: False).
  • validate: Validation function (default: None). It receives the current string; return None or an empty string for valid input, any other value as the error message.
  • width: Component width (default: the configured width).
  • inline: Display in inline mode (default: False).
  • show_help: Show help key bindings (default: True).
  • timeout: Timeout in seconds (default: 0 — no timeout).

Returns the entered text as a string, or None if the prompt is cancelled or times out.

Errors: password must be a bool or None.

write

write(value="", placeholder="Write something...", title="", description="",
      char_limit=0, validate=None, width=<config>, height=5,
      show_line=False, show_help=True, timeout=0)

Creates a multi-line text area.

Parameters:

  • value: Initial value (default: "").
  • placeholder: Placeholder text (default: "Write something...").
  • title: Title text (default: "").
  • description: Description text (default: "").
  • char_limit: Maximum character limit (default: 0 — no limit).
  • validate: Validation function (default: None); same contract as input.
  • width: Component width (default: the configured width).
  • height: Component height (default: 5).
  • show_line: Show line numbers (default: False).
  • show_help: Show help key bindings (default: True).
  • timeout: Timeout in seconds (default: 0 — no timeout).

The external editor opened with Ctrl+E runs a host-configured editor command (via os/exec). A script cannot name it (no per-call editor argument and no set_editor) nor PATH-hijack it: the command is resolved only from host-controlled sources — the editor config (see Configuration), else the host's $EDITOR captured at module construction, else nano — and frozen to an absolute path at construction.

Residual (host/sandbox concern). huh/bubbletea — not gum — construct the subprocesses they run, and gum cannot set their environment. So a host that lets an untrusted script mutate the process environment (e.g. by exposing a runtime module's setenv) leaves two surfaces: the editor subprocess inherits the live environment, so editor env such as VIMINIT executes for editors that honor it (e.g. vim); and bubbletea's color detection execs a bare tmux (via the live PATH) during terminal detection on any form, including spin (whose spinner exposes no environment hook). Close these by not granting untrusted scripts process-environment mutation, or by sandboxing the interpreter.

Returns the entered text as a string, or None if cancelled or timed out.

Example:

load("gum", "write")

# The external editor (Ctrl+E) is whatever the host configured via GUM_EDITOR
# or NewModuleWithConfig; the script cannot change it.
notes = write(
    title = "Meeting Notes",
    description = "Press Ctrl+E to open in your configured editor",
)

print("Notes recorded:", len(notes) if notes else 0, "characters")

Selection

select

select(options, value="", title="Choose:", description="", validate=None,
       width=<config>, height=0, inline=False, show_filter=False,
       show_help=True, timeout=0)

Creates a single-selection component.

Parameters:

  • options: A list/iterable of option values, or a dict (keys are displayed, values are returned). Required and must not be empty.
  • value: Initially selected value (default: "").
  • title: Title text (default: "Choose:").
  • description: Description text (default: "").
  • validate: Validation function (default: None); same contract as input.
  • width: Component width (default: the configured width).
  • height: Maximum visible items (default: 0 — all).
  • inline: Display in inline mode (default: False).
  • show_filter: Enable filtering (default: False).
  • show_help: Show help key bindings (default: True).
  • timeout: Timeout in seconds (default: 0 — no timeout).

Returns the selected value as a string, or None if cancelled or timed out.

Errors: options must be an iterable or mapping, and must not be empty.

multi_select

multi_select(options, value=[], title="Choose:", description="", validate=None,
             limit=0, width=<config>, height=0, show_filter=False,
             show_help=True, timeout=0)

Creates a multi-selection component.

Parameters:

  • options: A list/iterable of option values, or a dict (keys are displayed, values are returned). Required and must not be empty.
  • value: A string or list of initially selected values (default: []).
  • title: Title text (default: "Choose:").
  • description: Description text (default: "").
  • validate: Validation function receiving the list of selected values (default: None); return None/empty string for valid, otherwise the error message.
  • limit: Maximum number of selections (default: 0 — no limit).
  • width: Component width (default: the configured width).
  • height: Maximum visible items (default: 0 — all).
  • show_filter: Enable filtering (default: False).
  • show_help: Show help key bindings (default: True).
  • timeout: Timeout in seconds (default: 0 — no timeout).

Returns a list of selected values, or None if cancelled or timed out.

Errors: options must be an iterable or mapping, and must not be empty.

Example:

load("gum", "select", "multi_select", "note")

# Single selection from a list, with filtering.
color = select(
    options = ["Red", "Green", "Blue", "Yellow", "Purple"],
    title = "Choose your favorite color:",
    show_filter = True,
)

# Multi-selection from a dict (keys shown, values returned).
fruits = multi_select(
    options = {
        "apple": "Apple",
        "banana": "Banana",
        "orange": "Orange",
    },
    value = ["Orange"],
    title = "Select your favorite fruits:",
    limit = 3,
)

if color and fruits:
    note(
        title = "Your Selections",
        description = "Color: " + color + "\nFruits: " + ", ".join(fruits),
        next = "Continue",
    )

filter

filter(options, value="", placeholder="Filter...", title="", fuzzy=True,
       limit=1, height=10)

Interactively filters a list as you type, ranking matches by fuzzy match — distinct from select, whose show_filter is a fixed case-insensitive substring match. options is a list, dict, or iterable (a dict displays its keys and returns the matching value, like select).

Parameters:

  • options: List/dict/iterable of options (required, non-empty).
  • value: Initial filter query (default: "").
  • placeholder: Placeholder for the query input (default: "Filter...").
  • title: Title shown above the input (default: "").
  • fuzzy: Fuzzy match when True; case-insensitive substring when False (default: True).
  • limit: 1 (default) is single-select and returns the chosen string; any other value is multi-select (0 = unlimited) where Tab marks items and it returns a list of strings.
  • height: Maximum visible rows (default: 10).

Returns the selected string (single) or list of strings (multi), or None if cancelled (Ctrl-C / Esc). Requires a TTY.

confirm

confirm(value=False, title="Are you sure?", description="", yes="Yes", no="No",
        inline=False, show_help=True, timeout=0)

Creates a yes/no confirmation dialog.

Parameters:

  • value: Initial value (default: False).
  • title: Title text (default: "Are you sure?").
  • description: Description text (default: "").
  • yes: Text for the affirmative option (default: "Yes").
  • no: Text for the negative option (default: "No").
  • inline: Display in inline mode (default: False).
  • show_help: Show help key bindings (default: True).
  • timeout: Timeout in seconds (default: 0 — no timeout).

Returns a boolean if the user makes a selection, or None if cancelled or timed out.

File picker

file_pick

file_pick(path=".", title="", description="", validate=None, cursor=">",
          allow_ext=[], allow_dir=False, allow_file=True, show_hidden=False,
          show_perm=True, show_size=False, height=10, show_help=True, timeout=0)

Creates a file picker component. The starting path is resolved to an absolute path before the picker opens.

Parameters:

  • path: Initial path to start in (default: ".").
  • title: Title text (default: "").
  • description: Description text (default: "").
  • validate: Validation function (default: None); same contract as input.
  • cursor: Cursor glyph drawn next to the highlighted entry (default: ">").
  • allow_ext: Allowed file extensions as a string or list of strings (default: [] — all). Each entry is normalized to a leading-dot suffix, so "py", ".py", and "*.py" are equivalent; entries with no extension are ignored.
  • allow_dir: Allow directory selection (default: False).
  • allow_file: Allow file selection (default: True).
  • show_hidden: Show hidden files (default: False).
  • show_perm: Show file permissions (default: True).
  • show_size: Show file size (default: False).
  • height: Maximum visible items (default: 10).
  • show_help: Show help key bindings (default: True).
  • timeout: Timeout in seconds (default: 0 — no timeout).

Returns the selected file path as a string, or None if cancelled or timed out.

Errors: an invalid path that cannot be resolved is reported as a script error.

Example:

load("gum", "file_pick", "spin")

selected_file = file_pick(
    title = "Select a configuration file:",
    allow_ext = ["json"],
    show_hidden = False,
)

if selected_file:
    def process_file():
        return "File processed successfully!"

    result = spin(
        title = "Processing " + selected_file,
        style = "dots",
        action = process_file,
    )
    print(result)

Visual elements

note

note(title, description="", height=0, next="", show_help=True, timeout=0)

Displays a note with a title and description.

Parameters:

  • title: Title text (required, must not be empty).
  • description: Description text (default: "").
  • height: Component height (default: 0 — the configured height/automatic).
  • next: Text for the next button (default: "" — no button).
  • show_help: Show help key bindings (default: True).
  • timeout: Timeout in seconds (default: 0 — no timeout).

Returns None.

Errors: title is required and cannot be empty.

md

md(text, style="auto", width=0, emoji=True, word_wrap=True)

Renders Markdown content into formatted terminal text. This builtin is non-interactive and works in headless environments.

Parameters:

  • text: Markdown text to render (required, must not be empty).
  • style: Style to use for rendering (default: "auto"). Standard styles from the glamour package: "auto" (defaults to the dark theme — glamour v2 no longer probes the terminal), "ascii", "dark", "dracula", "light", "notty", "pink", "tokyo-night". A path to a custom style JSON file is also accepted.
  • width: Width to wrap text at (default: 0 — uses the configured width).
  • emoji: Enable emoji support (default: True).
  • word_wrap: Enable word wrapping (default: True).

Returns the rendered Markdown as a string with ANSI escape codes.

Errors: text is required and cannot be empty; a renderer/render failure is reported as a script error.

Example:

load("gum", "md")

rendered = md(
    text = "# Hello World\n\nThis is **bold** and *italic* text.",
    style = "dark",
)
print(rendered)

md_note

md_note(text, title="", style="auto", width=0, height=0, emoji=True,
        word_wrap=True, show_help=False, next="", timeout=0)

Renders Markdown content and displays it in a TUI note. Internally it renders with md and then displays the result with note.

Parameters:

  • text: Markdown text to render (required, must not be empty).
  • title: Title for the note (default: "").
  • style: Style to use for rendering (default: "auto"); same set as md.
  • width: Width to wrap text at (default: 0 — uses the configured width).
  • height: Height of the note (default: 0 — uses the configured height).
  • emoji: Enable emoji support (default: True).
  • word_wrap: Enable word wrapping (default: True).
  • show_help: Show help text (default: False).
  • next: Text for the next button (default: "" — no button).
  • timeout: Timeout in seconds (default: 0 — no timeout).

Returns None.

Errors: same as md and note (text must be non-empty; render failures propagate).

spin

spin(title="Loading...", style="dots", action=None, timeout=1)

Displays a spinner, optionally running an action function while it spins.

Parameters:

  • title: Spinner title (default: "Loading...").
  • style: Spinner style (default: "dots"). Available styles: "line", "dots", "mini_dot", "jump", "points", "pulse", "globe", "moon", "monkey", "meter", "hamburger", "ellipsis" (common aliases such as "dot", "mini", "earth", "burger" are also accepted).
  • action: Function to execute while the spinner is active (default: None). When omitted, the spinner runs for timeout seconds.
  • timeout: Timeout in seconds used only when no action is provided (default: 1).

Returns the result of the action function, or None when there is no action.

Errors: an unsupported style is reported as a script error; an error raised inside action propagates to the caller.

colorize

colorize(text, color="", pattern="CherryBlossoms", render="Column",
         from_color="", to_color="")

Colorizes text with a solid color, a built-in gradient pattern, or a custom two-color gradient. This builtin is non-interactive and works in headless environments.

Parameters:

  • text: Text to colorize (required, must not be empty).
  • color: Solid color (default: "" — use a pattern). When set, text is rendered in this single color.
  • pattern: Built-in gradient pattern (default: "CherryBlossoms"), used when neither color nor a from_color/to_color pair is given.
  • render: Gradient direction, "Column" or "Line" (default: "Column"; case-insensitive, with aliases such as "col"/"c" and "row"/"l"/"r").
  • from_color: Custom gradient start color (default: "").
  • to_color: Custom gradient end color (default: ""). A custom gradient is used only when both from_color and to_color are set.

Returns the colorized text as a string.

Color resolution order: color (if set) → from_color/to_color gradient (if both set) → pattern.

The color, from_color, and to_color arguments accept any case-insensitive color description understood by the module's parser: a preset name (e.g. red, teal, lavender), an rgb(r, g, b) triple, an hsb(h, s, b) triple, a #RRGGBB hex code, or a #RGB short hex code.

Available patterns: Almost, Anamnisar, AnimalCrossing, BrokenHearts, CherryBlossoms, EveningNight, EveningSunshine, IbizaSunset, MiWatch, Nelson, OceanSand, PurpleLove, PurpleParadise, RainbowBlue, RelaxingRed, RoseWater, SublimeVivid.

Errors: text is required and cannot be empty; an unknown pattern or an invalid color string is reported as a script error.

Example:

load("gum", "colorize")

# Built-in pattern.
print(colorize("Hello, Starlark!", pattern = "RainbowBlue"))

# Custom gradient.
print(colorize(
    text = "Hello, Starlark!",
    from_color = "#FF5733",  # orange-red
    to_color = "#33FF57",    # green
    render = "Column",
))

code_block

code_block(text, lang="", style="monokai")

Renders source code with chroma syntax highlighting to ANSI terminal text. Non-interactive and works in headless environments.

Parameters:

  • text: Source code (required, must not be empty).
  • lang: chroma lexer name (e.g. "go", "python", "sql"); empty auto-detects from the source (default: "").
  • style: chroma style name (e.g. "monokai", "dracula", "github-dark"; default: "monokai").

Returns the highlighted code as a string with ANSI escape codes. An unknown lang or style degrades gracefully rather than erroring.

load("gum", "code_block")

print(code_block("print('hello')", lang = "python"))

Layout & static rendering

These builtins render their input to a string and return it. They are non-interactive — no TTY — so they work in headless environments (CI, sandboxes, pipelines). Colors are taken from gum's own color vocabulary (preset names, rgb(...), hsb(...), #RRGGBB/#RGB), the same as colorize. To display the result, print it.

style

style(text, fg="", bg="", bold=False, italic=False, underline=False,
      faint=False, border="", border_fg="", padding=None, margin=None,
      width=0, align="")

Renders text with lipgloss styling — colors, text attributes, a border, and box spacing — the non-interactive counterpart of gum style.

Parameters:

  • text: Text to style (required).
  • fg / bg: Foreground / background color (default: "" — unset).
  • bold / italic / underline / faint: Text attributes (default: False).
  • border: Border style — one of "normal" (a.k.a. "square"), "rounded", "thick" (a.k.a. "bold"), "double", "block", "hidden"/"none" (default: "" — no border).
  • border_fg: Border foreground color (default: "").
  • padding / margin: Inside / outside spacing, as an int (all sides) or a list/tuple of at most 4 ints in CSS order (1, 2, or 4 values; default: None).
  • width: Fixed render width (default: 0 — natural width). Bounded at 10000.
  • align: Horizontal alignment of wrapped/padded text — "left", "center", or "right" (default: "" — left).

Returns the rendered string. Errors on an unknown color, border, or alignment name, a non-int padding/margin, or a positive width/padding/margin above 10000 (a negative padding/margin clamps to 0, as in lipgloss). These are DoS guards so a huge value can't drive lipgloss into a multi-gigabyte allocation, and they close every amplification path: an out-of-range integer (e.g. 1<<100) is rejected rather than silently wrapping to 0; a padding/margin iterable is capped at 4 values so an unbounded one (e.g. range(1e9)) can't be materialized; and the whole rendered area (output lines × output width) is bounded at 10 million cells — accounting for wrap-shrinking padding and the width=0 case where lipgloss equalizes every line to the widest — so no combination of width, padding, and line count can amplify a tiny input into an OOM.

load("gum", "style")

print(style("PASS ✓ all green", fg = "#7D56F4", bold = True,
            border = "rounded", padding = (1, 2)))

table

table(headers, rows, border="rounded", border_fg="")

Renders a bordered table. headers is a list of column titles; rows is a list of rows, each a list of cell values (values are stringified).

Parameters:

  • headers: List of header strings (required).
  • rows: List of rows, each a list of cell values (required).
  • border: Border style (see style; default: "rounded").
  • border_fg: Border foreground color (default: "").

Returns the rendered table string. Errors on a non-list headers/rows, a row that is not a list, or an unknown border/color. Columns size to their content, so the total rendered area (rows × column widths) is bounded at 10 million cells — a DoS guard so many rows or a very wide cell can't amplify a small input into a multi-gigabyte table; a larger table errors.

load("gum", "table")

print(table(
    headers = ["module", "layer", "version"],
    rows = [
        ["starbox", "L4", "v0.2.0"],
        ["starcli", "L5", "-"],
    ],
    border = "rounded",
))

tree

tree(data, root="")

Renders a nested tree. data is a dict, list, or scalar:

  • a dict renders each key as a branch — a scalar value joins onto the key ("key value"), a dict/list value nests beneath it;
  • a list/tuple renders each element as a node (scalars are leaves, nested collections become subtrees);
  • a scalar is a single leaf.

root, if given, labels the top of the tree (otherwise the top-level entries are listed directly).

Returns the rendered tree string. Nesting is bounded at 1000 levels (a guard so a deeply nested structure can't overflow the stack); deeper input errors.

load("gum", "tree")

# A labelled root with leaf children:
print(tree({"L1": "starlight", "L2": "starlet", "L4": "starbox"}, root = "Star*"))

compose

compose(blocks, dir="v", align="left")

Joins already-rendered blocks (e.g. from style) into a layout — stacked vertically or placed side by side — via lipgloss.

Parameters:

  • blocks: List/tuple of pre-rendered string blocks (required).
  • dir: "v"/"vertical" (default) stacks the blocks; "h"/"horizontal" places them side by side.
  • align: Cross-axis alignment — "left"/"center"/"right" when stacking vertically, "top"/"center"/"bottom" when side by side (default: "left").

Returns the composed string. Errors on an unknown dir or align, or a non-list blocks. Joining pads every block to the widest (vertical) or tallest (horizontal) one, so the composed area is bounded at 10 million cells — a DoS guard so one large block among many can't amplify into a huge allocation; a larger composition errors.

load("gum", "style", "compose")

left = style("A", border = "rounded")
right = style("B", border = "rounded")
print(compose([left, right], dir = "h", align = "center"))

Theming

set_theme

set_theme(theme)

Sets the active theme and re-applies it immediately, so subsequent components render with the new theme within the same script run. This overrides the auto-generated set_theme accessor from base (which would only update the stored configuration value); see Configuration.

Parameters:

  • theme: Theme name — one of base, base16, charm, dracula, catppuccin (any other value falls back to charm).

Returns None.

load("gum", "set_theme", "select")

set_theme("dracula")
select(options = ["Red", "Green", "Blue"], title = "Pick a color:")

Configuration

The gum module's configuration is provided by starpkg/base. Each option has a default, can be set from its environment variable (uppercased, prefixed with GUM_), or set programmatically — and every option is also reachable from a script through an auto-generated accessor pair.

For each non-secret option, base generates a get_<key> builtin (returns the current value) and a set_<key> builtin (takes a single value, returns None). width, height, and theme expose both accessors.

editor is host-only: it names the command write runs via os/exec when the user opens the external editor, so a script must not be able to choose it. base generates get_editor (read-only) but no set_editor, and snapshots its environment value at construction — the editor is set host-side only, via GUM_EDITOR or NewModuleWithConfig.

Secret options would expose only a set_<key> builtin and no getter (the value is never readable from a script). The gum module has no secret options.

Host-only options (like editor) expose only a read-only get_<key> and no set_editor — the value can be read but not changed from a script.

Option get_ accessor set_ accessor Env var Default Description
width get_width set_width GUM_WIDTH 50 Default width for TUI components (0 = terminal width).
height get_height set_height GUM_HEIGHT 0 Default height for components (0 = automatic).
theme get_theme set_theme GUM_THEME charm Theme name. set_theme is overridden by gum to re-apply the theme immediately (see above).
editor get_editor host-only, no set_editor GUM_EDITOR [] External editor command for write (e.g. ["vim", "-f"]); empty falls back to the host's $EDITOR snapshot (taken at construction), else nano. Host-only — a script cannot name it (see the residual note in write).

Available themes: base (minimal, monochrome), base16 (simple 16-color), charm (default), dracula, catppuccin.

Note: set_theme is the one accessor gum replaces with its own builtin so the theme change takes effect immediately rather than only updating the stored value; the other set_*/get_* accessors are the standard base ones.

Configuring the module from Go

// Method 1: default settings (width 50, height 0, theme "charm", no editor).
module := gum.NewModule()

// Method 2: custom settings —
// NewModuleWithConfig(width, height int, themeName string, editor []string).
module := gum.NewModuleWithConfig(
    80,               // width
    10,               // height
    "dracula",        // theme
    []string{"vim"},  // default editor command
)