carapace-sh/carapace-bin / skills/carapace
carapace
VerifiedUse when working with carapace shell completion — integrating into CLIs, writing YAML specs, creating custom actions, building completion-aware lexers for DSLs, looking up macros, setting up shell completion, configuring choices/bridges, using the MCP server, or adding man page documentation.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 4.0 KB |
| references/action.md | markdown | 20.8 KB |
| references/choice.md | markdown | 9.0 KB |
| references/convert.md | markdown | 10.5 KB |
| references/env.md | markdown | 7.8 KB |
| references/integrate.md | markdown | 29.1 KB |
| references/lexer.md | markdown | 24.3 KB |
| references/macro.md | markdown | 19.4 KB |
| references/man.md | markdown | 13.5 KB |
| references/mcp.md | markdown | 14.0 KB |
| references/scrape.md | markdown | 6.3 KB |
| references/setup.md | markdown | 6.8 KB |
| references/spec.md | markdown | 8.0 KB |
| references/update.md | markdown | 11.2 KB |
references/macro.md
View on GitHub# Carapace Macro Format Guide
Macros are completion actions identified by a `$`-prefixed name, optionally taking arguments in parentheses. They are used in user specs (YAML) and in Go code via `spec.ActionMacro`.
## Retrieving Available Macros
Use the carapace MCP tool `list_macros` to get all available macros with their names, descriptions, and argument signatures. For MCP server setup and protocol details, see the **references/mcp.md** skill.
Each entry has:
| Field | Description |
|-------|-------------|
| `name` | Fully qualified macro name (e.g. `carapace.tools.git.Refs`) |
| `description` | What the macro completes |
| `signature` | Argument signature string — see [Signature Format](#signature-format) below |
| `version` | Version of the module providing the action (main module version for in-project packages, dependency version for external packages) |
| `reference` | Go import path to the underlying action function (e.g. `github.com/carapace-sh/carapace-bin/pkg/actions/tools/git#ActionRefs`) |
Use the `reference` field to locate the source code for detailed information about parameters, their effects, and default behavior.
```bash
carapace --macro # list all macros
carapace --macro <name> # show macro details
carapace --macro <name> <TAB> # test macro completion
```
## Signature Format
The `signature` field from `list_macros` encodes the argument type. The signature is generated by reflecting over the Go type — it tells you what kind of argument the macro expects.
| Signature | Macro type | Meaning |
|-----------|------------|---------|
| `""` (empty string) | MacroN | No arguments |
| `""` (quoted empty) | MacroI | Single string argument |
| `false` | MacroI | Single bool argument |
| `{field: value, ...}` | MacroI | Single struct argument — each field is a parameter |
| `[""]` | MacroV | Variadic string arguments |
| `[false]` | MacroV | Variadic bool arguments |
> An empty signature (`""`) is displayed as `—` (dash) in `carapace --macro` and MCP `list_macros` output.
### Struct Parameters (MacroI with struct)
When the signature shows a struct like `{localbranches: false, tags: false}`, the macro accepts named parameters as YAML. This means:
- **All fields are optional** — only set values that differ from the zero/empty default
- **Arguments are parsed as YAML** — use YAML syntax for values
- **Missing fields use zero values** — unless the struct implements `Default()` (see below)
```yaml
# Only override what you need — other fields use zero values
["$carapace.tools.git.Refs({tags: true})"]
```
### Default Behavior for Structs
If a struct argument type implements a `Default()` method, it will be called when the macro is used without arguments. This allows the action to define sane defaults for boolean fields that would otherwise produce empty results:
```go
type RefOption struct {
LocalBranches bool
RemoteBranches bool
Heads bool
Tags bool
Stashes bool
Notes bool
}
func (o RefOption) Default() RefOption {
o.LocalBranches = true
o.RemoteBranches = true
o.Heads = true
o.Tags = true
o.Stashes = true
o.Notes = false
return o
}
```
So `$_.Refs` (no arguments) completes local branches, remote branches, heads, tags, and stashes (everything enabled by `Default()` except notes) — not just a single field.
Check the actual `Default()` of a macro's option struct (via its Go source or `carapace --macro <name>`) rather than assuming a single field.
### Signature Generation Details
The signature string is generated by the carapace-spec library using reflection:
| Go type | Signature output | Example |
|---------|-----------------|---------|
| `string` | `""` | `"arg"` → `""` |
| `bool` | literal value | `false`, `true` |
| struct | YAML block style | `{field1, field2}` |
| `[]string` | `[element]` | `[""]` |
| `[]bool` | `[element]` | `[false]` |
For structs, the output is valid YAML — you can copy it directly into a spec file and only set the fields you need.
### Looking Up Parameter Details
Use the `reference` field from `list_macros` to find the Go source code. For example, `reference: github.com/carapace-sh/carapace-bin/pkg/actions/tools/git#ActionRefs` means:
1. Look up the repository at that import path
2. Find the `ActionRefs` function (or its `Opts` struct if it uses one)
3. Read the struct fields to understand each parameter's purpose and default behavior
## Three Macro Types
### MacroN — No Arguments
Action takes no parameters.
| Context | Format |
|---------|--------|
| User spec | `$macroname` |
| Go register | `spec.MacroN(func() carapace.Action { ... })` |
| Go use | `spec.ActionMacro("$carapace.tools.git.Tags")` |
```yaml
completion:
positional:
- ["$directories"]
- ["$carapace.tools.git.Tags"]
```
### MacroI — Single Argument
Action takes one parameter: a string, bool, or struct.
| Argument type | Signature | Spec format | Go use |
|--------------|-----------|-------------|--------|
| `string` | `""` | `$macroname(arg)` | `spec.ActionMacro("$macroname(\"arg\")")` |
| `bool` | `false` | `$macroname(true)` | `spec.ActionMacro("$macroname(true)")` |
| struct | `{Field: val}` | `$macroname({Field: val})` | `spec.ActionMacro("$macroname({Field: val})")` |
When invoked without arguments, a struct argument's `Default()` method is called if it exists. Use this for boolean fields where zero values produce empty results.
> **Note:** For single string arguments in user specs, quotes are omitted (`$macroname(arg)`) for ease of use. This keeps exec macros simple.
```yaml
# String argument (quotes optional in user specs for ease of use)
completion:
positional:
- ["$files([.go, .mod])"]
- ["$carapace.tools.git.RemoteBranches(origin)"]
# Bool argument
completion:
positional:
- ["$carapace.shell.Functions(true)"]
# Struct argument
completion:
positional:
- ["$carapace.tools.git.Refs({localbranches: true, tags: true})"]
```
Go registration:
```go
spec.AddMacro("Refs", spec.MacroI(ActionRefs), "complete refs")
spec.AddMacro("Tags", spec.MacroN(ActionTags), "complete tags")
// Or use AddMacroI/AddMacroV to infer the name from the function:
spec.AddMacroI(ActionRefs, "complete refs")
// Note: AddMacroI is for single-arg macros, AddMacroV for variadic.
// For no-arg macros, use spec.AddMacro with spec.MacroN explicitly.
```
### MacroV — Variadic Arguments
Action takes a variadic parameter (`...string`, `...bool`, etc.). Arguments are passed as a YAML flow sequence.
| Argument type | Signature | Spec format |
|--------------|-----------|-------------|
| `...string` | `[""]` | `$macroname(["a", "b"])` |
| `...bool` | `[false]` | `$macroname([true, false])` |
```yaml
completion:
positional:
- ["$files"]
- ["$carapace.tools.git.RefDiffs([\"HEAD~1\", \"HEAD~3\"])"]
```
Go registration:
```go
spec.AddMacro("RefDiffs", spec.MacroV(ActionRefDiffs), "complete ref diffs")
// Or use AddMacroV to infer the name from the function:
spec.AddMacroV(ActionRefDiffs, "complete ref diffs")
```
## Macro Name Prefixes
Macro names use a dotted prefix to indicate their source:
| Prefix | Source | Example |
|--------|--------|---------|
| (none) | Core macros from carapace-spec | `$files`, `$directories`, `$message` |
| `<exe>.` | Fully qualified — the executable providing the macro | `$carapace.tools.git.Refs`, `$git.Refs`, `$kubectl.Refs` |
| `$_.` | Self-referencing (current executable) | `$_.Refs` |
### Fully Qualified vs Short Form
- `$carapace.tools.git.Refs` — fully qualified via the `carapace` executable, always works
- `$git.Refs` — fully qualified via the `git` executable (when `git` exposes this macro)
- `$_.Refs` — short form, resolves to the current executable's own macros (avoid unless explicitly asked for)
### Cross-Executable Macros
When a macro name contains a dot and doesn't match the current executable prefix, carapace delegates to that executable:
```yaml
# Delegates to `gh _carapace macro tools.gh.Labels`
["$carapace.tools.gh.Labels({host: \"github.com\"})"]
```
In Go, this is handled by `spec.ActionMacro` automatically:
```go
spec.ActionMacro("$carapace.tools.gh.Labels({host: \"github.com\"})")
```
## Using Macros in User Specs
In YAML specs, macros appear inside completion arrays prefixed with `$`:
```yaml
completion:
flag:
format: ["json", "yaml"] # static values
file: ["$files([.txt, .md])"] # macro with string list arg
branch: ["$carapace.tools.git.Refs({tags: true})"] # macro with struct arg
positional:
- ["$directories"] # macro without args
- ["$carapace.tools.docker.Containers"] # external macro
positionalany: ["$files"]
```
## Using Macros in Go
### spec.ActionMacro
`spec.ActionMacro` resolves a macro string at runtime. Use it for loosely coupled access to macros exposed by other commands:
```go
// Reference a macro from carapace-bin
spec.ActionMacro("$carapace.tools.git.Refs")
spec.ActionMacro("$carapace.tools.git.Refs({tags: true})")
```
### Registering Custom Macros
Register macros before `spec.Register`. `spec.AddMacro` accepts optional `opts ...string` — first string is description, further strings are joined with `"\n"` as example:
```go
// No-argument macro
spec.AddMacro("tools.custom.Dirs", spec.MacroN(func() carapace.Action {
return carapace.ActionDirectories()
}), "complete directories")
// Single-argument macro (struct)
spec.AddMacro("tools.custom.Filter", spec.MacroI(func(s string) carapace.Action {
return carapace.ActionValues().Filter(s)
}), "filter values")
// Variadic-argument macro
spec.AddMacro("tools.custom.Multi", spec.MacroV(func(s ...string) carapace.Action {
return carapace.ActionValues(s...)
}), "complete multiple values")
spec.Register(rootCmd)
```
For convenience, `spec.AddMacroI` and `spec.AddMacroV` infer the macro name from the function using reflection — they strip the `.../actions/` path prefix and `Action` function prefix:
```go
// Infers name "tools.custom.Filter" from the function's package path
spec.AddMacroI(ActionFilter, "filter values")
spec.AddMacroV(ActionMulti, "complete multiple values")
```
### Exposing External Actions via spec.ActionMacro
Bridge actions from carapace-bin into the spec system:
```go
spec.AddMacro("tools.git.Refs", spec.MacroN(
spec.ActionMacro("$carapace.bridge.CarapaceBin(git)"),
))
```
## Action Signature to Macro Type Mapping
The Go action signature determines which macro type to use:
| Action signature | Macro type | Spec usage |
|-----------------|------------|------------|
| `func ActionFoo()` | `spec.MacroN` | `$_.Foo` or `$exe.Foo` |
| `func ActionFoo(opts FooOpts)` | `spec.MacroI` | `$_.Foo({Field: value})` |
| `func ActionFoo(arg string)` | `spec.MacroI` | `$_.Foo("arg")` |
| `func ActionFoo(arg bool)` | `spec.MacroI` | `$_.Foo(true)` |
| `func ActionFoo(args ...string)` | `spec.MacroV` | `$_.Foo(["a", "b"])` |
| `func ActionFoo(args ...bool)` | `spec.MacroV` | `$_.Foo([true, false])` |
## Core Macros (No Prefix)
These are built into carapace-spec:
| Macro | Type | Purpose |
|-------|------|---------|
| `$directories` | MacroN | Complete directories |
| `$files` | MacroV | Complete files, optional suffix filter |
| `$executables` | MacroV | Complete executables, optional directory filter |
| `$message` | MacroI | Show an error/info message |
| `$spec` | MacroI | Embed another spec |
| `$(...)` (bare) | MacroI | Execute shell command — `sh` on Unix, `cmd` on Windows |
| `$sh`, `$bash`, `$zsh`, `$fish`, `$osh` | MacroI | Execute shell command (Unix-only, error on Windows) |
| `$cmd`, `$pwsh`, `$nu`, `$elvish`, `$xonsh` | MacroI | Execute shell command (cross-platform) |
## Modifiers (Applied with `|||`)
Modifiers are special macros that transform the preceding action. Use ` ||| ` to apply a modifier to only the preceding value, or list it without `|||` to apply to all values in the batch:
```yaml
# Apply to all values in the list
["$files", "$chdir(/tmp)"]
# Apply only to the preceding value
["$files ||| $chdir(/tmp)"]
```
Modifier macros are also listed by `list_macros` and follow the same type rules (MacroN/MacroI/MacroV).
### Common Modifier Macros
| Modifier | Type | Purpose |
|----------|------|---------|
| `$chdir(<dir>)` | MacroI | Change working directory |
| `$filter([val])` | MacroV | Remove values |
| `$retain([val])` | MacroV | Keep only these values |
| `$list(,)` | MacroI | Join with delimiter |
| `$multiparts([/])` | MacroV | Split by delimiter |
| `$nospace(/)` | MacroI | No space after character |
| `$prefix(pre)` | MacroI | Prepend to values |
| `$noprefix(pre)` | MacroI | Prevent common-prefix insertion (for given prefixes, or all) |
| `$suffix(suf)` | MacroI | Append to values |
| `$style(name)` | MacroI | Apply style |
| `$tag(name)` | MacroI | Tag values |
| `$usage(msg)` | MacroI | Usage message |
| `$suppress(val)` | MacroI | Suppress specific values |
| `$shift(n)` | MacroI | Remove first `n` positional args from `Context.Args` |
`$shift` reindexes which positional completion slot fires by slicing `Context.Args`. After `$shift(n)`, `Context.Args` becomes `Context.Args[n:]`, so `len(Context.Args)` decreases by `n`. Use it when bridging or recursing where the first arg(s) are routing arguments that shouldn't count as positionals:
```yaml
# Rightmost runs first: $shift(1) (outermost) fires first, shifts Args,
# then $filterargs (innermost) runs last and sees shifted Args
["$carapace.tools.git.Refs", "$filterargs", "$shift(1)"]
# Leftmost runs first: $filterargs (outermost) fires first, captures original Args,
# then $shift(1) (innermost) shifts — $filterargs already captured original Args
["$carapace.tools.git.Refs", "$shift(1)", "$filterargs"]
# Specific form: $shift scoped to one macro via |||
["$carapace.tools.git.Refs ||| $shift(1)"]
```
| `$split` | MacroN | Split command string |
| `$splitp` | MacroN | Split command string with pipes |
| `$filterargs` | MacroN | Filter already-provided positional args |
| `$uniquelist(delim)` | MacroI | Deduplicate delimited list |
### Modifier Chaining Order
The **outermost** modifier fires **first** at invocation time, then bubbles inward. Order matters when modifiers affect the same data (e.g., `$prefix`/`$suffix` change the value text that `$filter`/`$retain` match against):
```yaml
# Rightmost runs first: $prefix adds "p/" to all values, then $filter([x]) removes "p/x" from results
["$files ||| $filter([x]) ||| $prefix(p/)"]
# Leftmost runs first: $filter removes "x" first, then $prefix adds "p/" to remaining ("p/a", "p/b")
["$files ||| $prefix(p/) ||| $filter([x])"]
# Order doesn't matter when modifiers target independent fields
["$files ||| $tag(local) ||| $style(blue)"]
```
### Traverse Modifier Macros (Directory Paths)
| Modifier | Type | Purpose |
|----------|------|---------|
| `$gitdir` | MacroN | Change to .git directory |
| `$gitworktree` | MacroN | Change to git worktree root |
| `$parent([name, ...])` | MacroV | Change to first parent containing names |
| `$tempdir` | MacroN | Change to temp directory |
| `$userhomedir` | MacroN | Change to home directory |
| `$userconfigdir` | MacroN | Change to config directory |
| `$usercachedir` | MacroN | Change to cache directory |
| `$xdgcachehome` | MacroN | Change to XDG cache home |
| `$xdgconfighome` | MacroN | Change to XDG config home |
| `$nixprofile` | MacroN | Change to nix profile directory |
## Environment Variables in Macros
Macros in user specs support environment variable substitution using `drone/envsubst`:
| Variable | Content |
|----------|---------|
| `${C_FLAG_<NAME>}` | Flag value |
| `${C_ARG<n>}` | Positional argument (0-indexed) |
| `${C_VALUE}` | Current word being completed |
| `${C_PART<n>}` | Parts during multipart completion |
```yaml
# Use flag value as macro argument
completion:
positionalany: ["$carapace.tools.git.LsRemoteRefs({url: '${C_ARG0}'})"]
# Default value if not set
${C_FLAG_SORT:-HEAD}
```
### drone/envsubst Functions
Beyond simple substitution, drone/envsubst supports bash-style parameter expansions:
| Syntax | Description |
|--------|-------------|
| `${var}` | Value of `$var` |
| `${#var}` | String length |
| `${var^}` / `${var^^}` | Uppercase first/all |
| `${var,}` / `${var,,}` | Lowercase first/all |
| `${var:n}` / `${var:n:len}` | Substring offset |
| `${var#pattern}` / `${var##pattern}` | Strip prefix |
| `${var%pattern}` / `${var%%pattern}` | Strip suffix |
| `${var:-default}` | Default if unset |
| `${var/pattern/repl}` | Replace first match |
| `${var//pattern/repl}` | Replace all matches |
## The `run` Field
Specs can contain a `run` field to make them executable via shims. The `run` field supports three modes:
### Alias Mode (Array)
Bridges a command while retaining completion:
```yaml
name: gh-issue
run: ["gh", "issue", "--repo", "${REPO}"]
```
Each array element is parsed with `envsubst` before execution.
### Script Mode (String with `$()`)
Executes the script using `sh` on Unix and `cmd` on Windows. Explicit shell macros (e.g. `$bash(...)`, `$pwsh(...)`) override this. Flags become `C_FLAG_*` variables:
```yaml
name: ls-remote
run: "$(git ls-remote --sort='${C_FLAG_SORT:-HEAD}' $@)"
flags:
--sort=: field name to sort on
```
### Shebang Mode (String starting with `#!`)
Executes with the specified interpreter:
```yaml
name: custom-script
run: |
#!/bin/bash
echo "Hello ${C_ARG0}"
```
The shebang is parsed to extract interpreter, optional args, and script body.
### How envsubst Affects the `run` Field
The `run` field is processed through `context.Envsubst()` before execution. This means:
1. **`${C_FLAG_*}`** variables are substituted with flag values
2. **`${C_ARG*n*}`** variables are substituted with positional arguments
3. **`${C_VALUE}`** is the current word being completed
4. **`$@`** passes all positional arguments (in script mode)
### Quoting Rules for `run` Field
Because the `run` field goes through envsubst, quoting in YAML matters:
| YAML quoting | Effect |
|--------------|--------|
| **Double quotes** (`"`) | Variables like `${C_ARG0}` are expanded |
| **Single quotes** (`'`) | Variables are literal — no expansion |
| **No quotes** | Works like double quotes for envsubst |
**Example: protecting a literal `$`**
```yaml
# Wrong — $HOME gets expanded by envsubst
run: ["echo", "$HOME"]
# Correct — single quotes prevent expansion
run: ["echo", '$HOME']
# Or use double $$ to escape
run: ["echo", "$$HOME"]
```
**Example: quoting in script mode**
```yaml
# Single quotes in the shell script preserve literal values
# but envsubst processes the YAML string first
run: |
#!/bin/bash
echo 'Hello ${C_ARG0}' # Literal ${C_ARG0} — envsubst sees it but it has no $
echo "Hello ${C_ARG0}" # envsubst expands ${C_ARG0} before shell sees it
```
### Shebang Argument Parsing
The shebang line uses `carapace-shlex` for argument parsing:
| Syntax | Meaning |
|--------|---------|
| `#!/bin/bash -c 'script'` | Single quotes preserve everything inside |
| `#!/usr/bin/env python` | Spaces separate command and args |
| `#!/bin/bash -c "echo $@"` | Double quotes allow variable expansion |
Arguments after the interpreter are parsed shell-style:
- **Single quotes** (`'...'`) — literal, no variable expansion
- **Double quotes** (`"..."`) — variables expanded
- **Backslash** (`\`) — escape next char
- **Space** — separates arguments
### Order of Operations
1. YAML is parsed
2. `envsubst` expands `${C_*}` variables using drone/envsubst
3. For script/shebang mode: shebang is parsed
4. Temporary script file created
5. Script executed with shell interpreter
6. Original args appended to command line
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file). | Stars: 198k | Updated | Claude CodeCodex | Unverified | Install |
| doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |