Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

carapace-bin

carapace-bin is a multi-shell multi-command argument completer based on carapace-sh/carapace.

Supported shells:

Install

Manually

Download from releases and add carapace to PATH.

AUR

Install carapace-bin from AUR.

# e.g. with pamac
pamac install carapace-bin

DEB

Install from fury.io

# /etc/apt/sources.list.d/fury.list
deb [trusted=yes] https://apt.fury.io/rsteube/ /
apt-get update && apt-get install carapace-bin

Homebrew

Install from homebrew-core

brew install carapace

Install from rsteube/homebrew-tap

brew tap rsteube/homebrew-tap
brew install rsteube/tap/carapace

Mise mise

mise use -g carapace@latest

Nix

Install from nixpkgs

nix-shell -p carapace

PKGX

Install from pkgx.dev

pkgx install carapace

RPM

Install from fury.io

Yum

# /etc/yum.repos.d/fury.repo
[fury]
name=Gemfury Private Repo
baseurl=https://yum.fury.io/rsteube/
enabled=1
gpgcheck=0
yum install carapace-bin

Zypper

zypper ar --gpgcheck-allow-unsigned -f https://yum.fury.io/rsteube/ carapace
zypper install carapace-bin

Scoop

Install from ScoopInstaller/Extras (recommended)

scoop bucket add extras
scoop install extras/carapace-bin

Install from rsteube/scoop-bucket

scoop bucket add rsteube https://github.com/rsteube/scoop-bucket.git
scoop install carapace-bin

Termux

Install from termux/termux-packages

pkg install carapace

Install from carapace-sh/termux (gh_pages)

WIP: repo currently manually created

Manually

# $PREFIX/etc/apt/sources.list.d
deb [trusted=yes] https://termux.carapace.sh termux extras  
apt update && apt install carapace-bin

Script

curl termux.carapace.sh | sh

Winget

Install from winget-pkgs

winget install -e --id rsteube.Carapace

X-CMD

Install from x-cmd.com

x env use carapace-bin

Selfupdate

With carapace --selfupdate specific nightly or stable releases can be installed.

Executable is installed to the GOBIN directory, essentially shadowing any system installation.

export PATH="$HOME/.local/bin:$HOME/go/bin:$PATH"
#            │                │            └system installation (e.g. /usr/bin/carapace)
#            │                └selfupdate/go based installation ($GOBIN)
#            └user binaries

Requirements

Setup

This registers all the available completers. It is also possible to load a single one by replacing _carapace with the completer name (e.g. carapace chmod).

See UserConfigDir for details.

Bash

# ~/.bashrc
export CARAPACE_BRIDGES='zsh,fish,bash,inshellisense' # optional
source <(carapace _carapace)

Cmd

# ~/AppData/Local/clink/carapace.lua
load(io.popen('carapace _carapace cmd-clink'):read("*a"))()

Needs clink.

Elvish

# ${UserConfigDir}/elvish/rc.elv
set-env CARAPACE_BRIDGES 'zsh,fish,bash,inshellisense' # optional
eval (carapace _carapace|slurp)

Fish

# ${UserConfigDir}/fish/config.fish
set -Ux CARAPACE_BRIDGES 'zsh,fish,bash,inshellisense' # optional
carapace _carapace | source

Nushell

## ${UserConfigDir}/nushell/env.nu
$env.CARAPACE_BRIDGES = 'zsh,fish,bash,inshellisense' # optional
mkdir $"($nu.cache-dir)"
carapace _carapace nushell | save --force $"($nu.cache-dir)/carapace.nu"

# ${UserConfigDir}/nushell/config.nu
source $"($nu.cache-dir)/carapace.nu"

Oil

# ${UserConfigDir}/oil/oshrc
export CARAPACE_BRIDGES='zsh,fish,bash,inshellisense' # optional
source <(carapace _carapace)

Powershell

# ${UserConfigDir}/powershell/Microsoft.PowerShell_profile.ps1
$env:CARAPACE_BRIDGES = 'zsh,fish,bash,inshellisense' # optional
Set-PSReadLineOption -Colors @{ "Selection" = "`e[7m" }
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete
carapace _carapace | Out-String | Invoke-Expression

Note: The Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete line is required. The default Complete function (used by PSReadLine's Emacs edit mode) will display raw ANSI escape codes (e.g. ^[[21;22;23;24;25;29m^[[39;49m) in the prompt instead of styled completions.

If you use Set-PSReadLineOption -EditMode Emacs, make sure it is placed before the Set-PSReadlineKeyHandler line above, as it resets key bindings and would override the Tab binding back to Complete.

Tcsh

# ~/.tcshrc
setenv CARAPACE_BRIDGES 'zsh,fish,bash,inshellisense' # optional
set autolist
eval `carapace _carapace`

Xonsh

# ${UserConfigDir}/xonsh/rc.xsh
$CARAPACE_BRIDGES='zsh,fish,bash,inshellisense' # optional
$COMPLETIONS_CONFIRM=True
exec($(carapace _carapace))

Zsh

# ${UserConfigDir}/zsh/.zshrc
autoload -U compinit && compinit
export CARAPACE_BRIDGES='zsh,fish,bash,inshellisense' # optional
zstyle ':completion:*' format $'\e[2;37mCompleting %d\e[m'
source <(carapace _carapace)

Order of groups can be configured with the zstyle group-order.

zstyle ':completion:*:git:*' group-order 'main commands' 'alias commands' 'external commands'

Environment

CARAPACE_BRIDGES

Which implicit bridges to enable.

The list of completers is cached to not impact shell startup time. Clear the cache with carapace --clear-cache if your system changes.

CARAPACE_COLOR

Whether to output color (default).

CARAPACE_COVERDIR

Coverage directory for sandbox tests (internal).

CARAPACE_DESCRIPTION_LENGTH

Maximum length of descriptions.

CARAPACE_ENV

Whether to register get-env, set-env and unset-env functions.

  • 0 - disabled
  • 1 - enabled

CARAPACE_EXCLUDES

Which completers to exclude.

CARAPACE_HIDDEN

Whether to show hidden commands/flags.

  • 0 - disabled
  • 1 - enabled
  • 2 - enabled including _carapace

CARAPACE_LENIENT

Whether to allow unknown flags.

  • 0 - disabled
  • 1 - enabled

CARAPACE_LOG

Whether to enable logging.

  • 0 - disabled
  • 1 - enabled

CARAPACE_MATCH

Whether to match case insensitive.

  • 0 - case sensitive
  • 1 - case insensitive

CARAPACE_MERGEFLAGS

Whether to merge flags to single tag group.

  • 0 - disabled
  • 1 - enabled

Enabled by default in Zsh for side-by-side view.

CARAPACE_NOSPACE

Extend suffixes that prevent space suffix.

  • * - matches all

CARAPACE_SANDBOX

Mock context for sandbox tests (internal).

CARAPACE_TOOLTIP

Whether to enable tooltip style.

  • 0 - disabled
  • 1 - enabled

Only affects Powershell.

CARAPACE_UNFILTERED

Whether to skip the final filtering step.

This enables fuzzy completion in Fish, but only works for (mostly) static values.

CARAPACE_ZSH_HASH_DIRS

Zsh hash directories (internal).

CARAPACE_ZSH_STYLE_LIMIT

Maximum amount of values to be styled.

UserConfigDir

Depending on your operating system the UserConfigDir can vary.

  • On Unix systems, it returns $XDG_CONFIG_HOME as specified by XDG if non-empty, else $HOME/.config.
  • On Darwin, it returns $HOME/Library/Application Support.
  • On Windows, it returns %AppData%.
  • On Plan 9, it returns $home/lib.

Contrary to the above Carapace acknowledges $XDG_CONFIG_HOME on every operating system for its config directory.

carapace --help
# Some completions are cached at [/home/rsteube/.cache/carapace].
# Config is written to [/home/rsteube/.config/carapace].
# Specs are loaded from [/home/rsteube/.config/carapace/specs].

Groups

Completers are organized into groups.

  • android termux completers
  • bridge bridged completers
  • bsd bsd-like completers
  • common common completers
  • darwin macos completers
  • linux linux completers
  • unix unix-like completers
  • user user specs
  • system system specs
  • windows windows completers

You can list available completers of a group with carapace --list @{group}.

Binaries only contain relevant groups unless built with the build tag force_all.

Priority

Multiple groups providing a completer for a command are ordered by priority.

  • darwin

    1. user
    2. system
    3. darwin
    4. bsd
    5. unix
    6. common
    7. bridge
  • linux

    1. user
    2. system
    3. linux
    4. unix
    5. common
    6. bridge
  • termux

    1. user
    2. system
    3. android
    4. linux
    5. unix
    6. common
    7. bridge
  • windows

    1. user
    2. system
    3. windows
    4. common
    5. bridge

You can list available completers of a command with carapace --list {command}.

Variants

Groups can contain multiple completers for the same command.

You can list available variants for a command with carapace --list {name}[/{variant}][@{group}].

Priority

Multiple variants within the same group are ordered by name.

  • tldr
    1. tealdeer
    2. tldr-python-client

Choices

The default priority of completers can be overridden with carapace --choice {name}[/{variant}][@{group}].

Choices are stored as simple text files in your config directory.

carapace
└── choices
    ├── sed  # sed@bsd
    └── tldr # tldr/tldr-python-client

Bridges

Bridges are a special form of choices as they can be added as additional completers otherwise unknown.

With CARAPACE_BRIDGES completers from zsh, fish, bash, and inshellisense can largely determined and act as implicit fallback. But frameworks like cobra need to be set explicitly.

Currently available bridges:

Bridging frameworks should be preferred to shells (e.g. zsh) as these generally work better and have less overhead.

Completers

Style

Transformations can be applied to files and specific values.

This is only supported in elvish, nushell, powershell, xonsh and zsh.

File

Files can be styled with the LS_COLORS environment variable (e.g. using vivid):

# elvish
set-env LS_COLORS (vivid generate dracula)

# powershell
$env:LS_COLORS = (vivid generate dracula)

# zsh
export LS_COLORS=$(vivid generate dracula)

Value

Values can be styled with a comma separated list of transformations:

# set
carapace --style 'carapace.Value=bold,magenta'

# clear
carapace --style 'carapace.Description='

Generic configuration like default value and description style can be found under carapace.{key}

Scheme

How the default colors look depends on your terminal color scheme.

It is recommended to choose one with a high contrast so that every color is well readable.

Transformations

Transformations are adopted from elvish:

Each $style-transformer can be one of the following:

  • A boolean attribute name:
    • One of bold, dim, italic, underlined, blink and inverse for setting the corresponding attribute.
    • An attribute name prefixed by no- for unsetting the attribute.
    • An attribute name prefixed by toggle- for toggling the attribute between set and unset.
  • A color name for setting the text color, which may be one of the following:
    • One of the 8 basic ANSI colors: black, red, green, yellow, blue, magenta, cyan and white.
    • The bright variant of the 8 basic ANSI colors, with a bright- prefix.
    • Any color from the xterm 256-color palette, as colorX (such as color12).
    • A 24-bit RGB color written as #RRGGBB (such as '#778899'). Note: You need to quote such values, since an unquoted # introduces a comment (e.g. use 'bg-#778899' instead of bg-#778899).
  • A color name prefixed by fg- to set the foreground color. This has the same effect as specifying the color name without the fg- prefix.
  • A color name prefixed by bg- to set the background color.

Spec

Custom completions can be defined using yaml files.

see carapace-spec for more documentation

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: mycmd
description: my command
flags:
  --optarg?: optarg flag
  -r, --repeatable*: repeatable flag
  -v=: flag with value
persistentflags:
  --help: bool flag
completion:
  flag:
    optarg: ["one", "two\twith description", "three\twith style\tblue"]
    v: ["$files"]
commands:
- name: sub
  description: subcommand
  completion:
    positional:
      - ["$list(,)", "1", "2", "3"]
      - ["$directories"]

Custom Macros

Carapace provides a range of custom macros:

carapace --macro                       # list macros
carapace --macro color.HexColors       # show macro details
carapace --macro color.HexColors <TAB> # test macro

User

User defined Specs are automatically loaded by carapace _carapace from ${UserConfigDir}/carapace/specs.

Added files initially need a new shell to be started for it to be registered with carapace _carapace. Afterwards any change to it has an immediate effect.

It is mandatory that the file name matches the name defined in the spec (e.g. myspec.yaml for name: myspec).

Override

Specs override an internal completer with the same name. E.g. if the internal kubectl completer does not work as expected it can be bridged instead:

name: kubectl
description: kubectl controls the Kubernetes cluster manager
completion:
  positionalany: ["$carapace.bridge.Cobra([kubectl])"]

JSON Schema

A JSON Schema can be used by adding the following header to the Specs:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json

Bridge

Bridging completions from another engine for shells not natively supported by it is possible with the corresponding Macro.

Even when the command supports your current shell it is still beneficial to bridge it as this enables embedding like sudo [spec.name] <TAB>.

It also avoids the issue of shell startup delay when sourcing the completion in init scripts otherwise circumvented with lazycomplete.

However, bridging is limited to supported commands/frameworks and how well it actually works.

Frameworks

Argcomplete

kislyuk/argcomplete based commands can be bridged with the bridge.Argcomplete macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: az
description: Azure Command-Line Interface
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Argcomplete([az])"]

Carapace

carapace-sh/carapace based commands can be bridged with the bridge.Carapace macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: freckles
description: simple dotfile manager
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Carapace([freckles])"]

CarapaceBin

Completers and Specs registered in carapace-sh/carapace-bin can be bridged with the bridge.CarapaceBin macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: github-cli
description: Work seamlessly with GitHub from the command line
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.CarapaceBin([gh])"]

Clap

clap-rs/clap based commands can be bridged with the bridge.Clap macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: dyamic
description: clap dynamic example
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Clap([dynamic])"]

needs clap-rs/clap#3166

Click

pallets/click based commands can be bridged with the bridge.Click macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: watson
description: Watson is a tool aimed at helping you monitoring your time
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Click([watson])"]

Cobra

spf13/cobra based commands can be bridged with the bridge.Cobra macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: kubectl
description: kubectl controls the Kubernetes cluster manager
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Cobra([kubectl])"]

Complete

posener/complete based commands can be bridged with the bridge.Complete macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: vault
description: Manage Secrets & Protect Sensitive Data
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Complete([vault])"]

Inshellisense

Commands provided by microsoft/inshellisense can be bridged with the bridge.Inshellisense macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: node
description: Run the node interpreter
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Inshellisense([node])"]

Kingpin

alecthomas/kingpin based commands can be bridged with the bridge.Kingpin macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: tsh
description: Teleport Command Line Client
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Kingpin([tsh])"]

Urfavecli

urfave/cli based commands can be bridged with the bridge.Urfavecli macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: tea
description: command line tool to interact with Gitea
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Urfavecli([tea])"]

Yargs

yargs/yargs based commands can be bridged with the bridge.Yargs macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: ng
description: CLI tool for Angular
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Yargs([ng])"]

Shells

For shells custom configurations are loaded from ${UserConfigDir}/carapace/bridge. Invoking completion in shells is quite tricky though and edge cases are likely to fail.

Bash

Commands registered in bash can be bridged with the bridge.Bash macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name:  tail
description: output the last part of files
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Bash([tail])"]

Fish

Commands registered in fish-shell/fish-shell can be bridged with the bridge.Fish macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name:  git
description: the stupid content tracker
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Fish([git])"]

Powershell

Commands registered in powershell can be bridged with the bridge.Powershell macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name:  ConvertTo-Json
description: convert to json
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Powershell([ConvertTo-Json])"]

Zsh

Commands registered in zsh can be bridged with the bridge.Zsh macro:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name:  git
description: the stupid content tracker
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Zsh([git])"]

Embed

The bridged completion can also be embedded as subcommand.

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: embed
commands:
  - name: git
    completion:
      positionalany: ["$carapace.bridge.CarapaceBin([git]) ||| $chdir(~/.password-store)"]

Plugin

Embedding is also internally used to enable plugin completion for tools like cargo-[plugin], gh-[plugin], git-[plugin]. Simply add a Spec with the corresponding name.

E.g. the gh-repo-collab extension for GitHub CLI:

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: gh-repo-collab
description: manage repository collaborators
commands:
  -
    name: list
    completion:
      positional:
        - ["$carapace.tools.gh.OwnerRepositories"]
  -
    name: add
    flags:
      --permission=: set permission
    completion:
      flag:
        permission: ["pull", "triage", "push", "maintain", "admin\t\tred"]
      positional:
        - ["$carapace.tools.gh.OwnerRepositories"]
        - ["$carapace.tools.gh.Users"]
  -
    name: remove
    completion:
      positional:
        - ["$carapace.tools.gh.OwnerRepositories"]
        - ["$carapace.tools.gh.Users"]

Run

Specs containing a run field can be executed using Shims.

Alias

Alias bridges a command while retaining the argument completion.

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: example
run: "[gh, issue, --repo, '${REPO}']"

Script

Script macro is executed with sh on unix systems and pwsh on windows. Flags are used for environment substitution and positional arguments are passed to the script.

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: ls-remote
run: "$(git ls-remote --sort='${C_FLAG_SORT:-HEAD}' $@)"
flags:
  --sort=: field name to sort on
completion:
  flag:
    sort: [version:refname, authordate]
  positional:
    - ["$carapace.tools.git.RepositorySearch"]
  positionalany: ["$carapace.tools.git.LsRemoteRefs({url: '${C_ARG0}', branches: true, tags: true})"]

Shim

When carapace _carapace is invoked it creates shims in ${UserConfigDir}/carapace/bin for runnable specs.

For unix systems this is a simple shell script, but for windows an embedded binary is used.

#!/bin/sh
carapace --run "/home/carapace-sh/.config/carapace/specs/runnable.yaml" "$@"

Scrape

Command structure from various tools can be scraped to Specs.

Clap

For clap use carapace-spec-clap.

Cobra

For cobra use carapace.

Kingpin

For kingpin use carapace-spec-kingpin.

Kong

For kong use carapace-spec-kong.

Man

For manpages use carapace-spec-man.

Urfavecli

For urfavecli use carapce-spec-urfavecli.

Codegen

Specs can be used to generate go code.

carapace --codegen [spec]

Examples

github.yaml

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: github
completion:
  positional:
    - ["$carapace.tools.gh.OwnerRepositories"]  # ${C_ARG0}
    - ["$carapace.tools.git.LsRemoteRefs({url: 'https://github.com/${C_ARG0}', branches: true, tags: true})"]

zipfile.yaml

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: zipfile
completion:
  positional:
    - ["$files([.zip])"] # ${C_ARG0}
  positionalany: ["$carapace.fs.ZipFileContents(${C_ARG0})"] # ${C_ARG1},${C_ARG2},...

refs.yaml

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: refs
flags:
  -t, --tags: include tags # ${C_FLAG_TAGS}
  --localbranches: include local branches # ${C_FLAG_LOCALBRANCHES}
  --c=: amount of commits # ${C_FLAG_C}
completion:
  positional:
    - ["$carapace.tools.git.Refs({tags: ${C_FLAG_TAGS:-false}, localbranches: ${C_FLAG_LOCALBRANCHES:-false}, commits: ${C_FLAG_C:-0}})"]
    - ["$carapace.tools.git.Refs"] # default

g.yaml

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: g
commands:
  - name: log
    description: Show commit logs
    group: git
    run: "[git, log]"

  - name: issue
    description: Manage issues
    group: gh
    run: "[gh, issue]"
    commands:
      - name: bugs
        description: List bugs
        run: "[gh, issue, list, --label, bug]"

  - name: edit
    description: Edit changed files
    run: "$(hx $@)"
    flags:
      -s, --staged: include staged files
    completion:
      positionalany: ["$carapace.tools.git.Changes({staged: ${C_FLAG_STAGED:-false}, unstaged: true})"]

Macros

On top of the base Macros defined in carapace-spec, carapace-bin also provides the following macros:

Overlay

Overlays are essentially Spec files placed in ${UserConfigDir}/carapace/overlays that provide additional completions. These are merged with the existing completion and provide a workaround for issues that have yet to be fixed in upstream.

Overlays implicitly set CARAPACE_LENIENT to allow unknown flags.

Flag

# ${UserConfigDir}/carapace/overlays/doctl.yaml
name: doctl
persistentflags:
  --output=: Desired output format [text|json]
completion:
  flag:
    output: [text, json]
commands:
  - name: compute
    description: Display commands that manage infrastructure
    commands:
      - name: region
        description: Display commands to list datacenter regions
        commands:
          - name: list
            description: List datacenter regions
            flags:
              --format=: Columns for output in a comma-separated list
            completion:
              flag:
                format: ["$uniquelist(,)", Slug, Name, Available]

Command

# ${UserConfigDir}/carapace/overlays/doctl.yaml
name: doctl
commands:
  - name: auth
    description: Display commands for authenticating doctl with an account
    group: management

  - name: compute
    description: Display commands that manage infrastructure
    group: core

  - name: custom
    description: custom command
    group: custom
    flags:
      -h, --help: show help
    completion:
      positional:
        - [one, two, three]

Variable

Complex environment variable completion is provided with get-env, set-env and unset-env.

In elvish the completion is simply overridden. For other shells custom functions are added.

Setting CARAPACE_ENV=0 before sourcing carapace _carapace disables this behaviour.

Custom variables

Custom variables can be defined in ${UserConfigDir}/carapace/variables/{group}.yaml

variables:
  CUSTOM_EXAMPLE: example environment variable
  CUSTOM_MACRO: macro example
  HTTPS_PROXY: override existing variable
completion:
  variable:
    CUSTOM_EXAMPLE: ["0\tdisabled\tred", "1\tenabled\tgreen"]
    CUSTOM_MACRO: ["$carapace.tools.gh.Labels({owner: rsteube, name: carapace}) ||| $uniquelist(,)"]
    HTTPS_PROXY: ["https://localhost:8443\tdevelopment", "https://proxy.company:443\tproduction"]

It is also possible to define conditions.

condition: ["$Parent([.git])"]
variables:
  CUSTOM_CONDITION: condition example
completion:
  variable:
    CUSTOM_CONDITION: ["within", "git", "repo"]

Conditions

  • Arch checks if the given names contain current runtime.GOARCH
  • Os checks if the given names contain current runtime.GOOS
  • Parent checks if any parent directory contains one of the given file/directory
  • Path checks if any of the given executables are in PATH

Slopware

Some food for your clanker.

While the examples use Crush (with Hyper), the extensions should work with any agent.

Models used at time of writing:

  • minimax-m2.7 for small to medium coding tasks, command scraping, spec generation
  • glm-5.1 for complex coding tasks, skill writing, full command generation

MCP

The Model Context Protocol server provides access to Carapace features.

Simply add it to your config.


{
  "$schema": "https://charm.land/crush.json",
  "mcp": {
    "carapace": {
      "type": "stdio",
      "command": "carapace",
      "args": [
        "--mcp"
      ]
    }
  }
}

Tools

  • complete Return context‑aware, dynamic completions for shell commands.
  • list_macros List available macros and their signatures.
  • codegen Generate Go code from a YAML spec file.

Skills

Skills extend agent capabilities. Simply place them into your skills folder.

crush
├── crush.json
└── skills
    ├── carapace-action
    │   └── SKILL.md
    ├── carapace-env
    │   └── SKILL.md
    ├── carapace-integrate
    │   └── SKILL.md
    ├── carapace-scrape
    │   └── SKILL.md
    └── carapace-spec
        └── SKILL.md

carapace-action

The carapace-action describes in detail how to create Custom Actions.

Instructions

  1. start crush in an cobra project
  2. ctrl+p, TAB, then select the skill
  3. run with create (public/private/anoymous) action ...

Public Action

for the repo completion query the api for repos where the current user has permissions to close pull requests.
the repo flag should just accept OWNER/REPO.
create a custom action in pkg/actions.
also, cache it for a day as these shouldn't change often

carapace-env

The carapace-env describes how to define environment variable completion.

Instructions

  1. start crush in an cobra project
  2. ctrl+p, TAB, then select the skill
  3. run with create variable completion ...

Go

look at the manpage of git and add missing environment variable completions for the ones with GIT_ prefix

Spec

look at the output of bat --help and create environment variable completion as user specs

carapace-integrate

The carapace-integrate skill integrates Carapace into a cobra-based CLI application.

Instructions

  1. start crush in an cobra project
  2. ctrl+p, TAB, then select the skill
  3. run with integrate carapace

Create

create a standalone completer for the shell command tail

Modify

i'm building my own git command. create completions for it.

  • positional arguments are git refs
  • default behaviour is to show a prettier git log for them (oneline, graph, make it fancy)
  • add ref completion with a carapace macro (loosely coupled)
  • dynamically embed git plugin commands at root level and bridge completions (executables with git- prefix)
  • add dash completion since refs could clash with subcommands
minigit HEAD~1 master # show log for refs
minigit clang-format  # execute git-clang-format

carapace-scrape

The carapace-scrape skill creates a Spec by scraping the source code of a CLI tool.

Instructions

  1. start crush in an empty directory
  2. ctrl+p, TAB, then select the skill
  3. run with scrape https://github.com/some/repo

Result

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: pgxcli [DBNAME] [USERNAME]
description: Interactive PostgreSQL command-line client for querying and managing databases.
flags:
    --debug: Enable debug mode for verbose logging.
    -U, --user=: Username to connect to the postgres database.
    -W, --password: Force password prompt
    -d, --dbname=: database name to connect to.
    -h, --host=: host address of the postgres database
    -i, --interactive: Interactive connection mode
    -p, --port=: port number at which the postgres server is listening
    -u, --username=: Username to connect to the postgres database.
    -w, --no-password: never prompt for the password
persistentflags:
    --help&: Print usage
commands:
    - name: completion
      description: Generate the autocompletion script for the specified shell
      commands:
        - name: bash
          description: Generate the autocompletion script for bash
          flags:
            --no-descriptions: disable completion descriptions
        - name: fish
          description: Generate the autocompletion script for fish
          flags:
            --no-descriptions: disable completion descriptions
        - name: powershell
          description: Generate the autocompletion script for powershell
          flags:
            --no-descriptions: disable completion descriptions
        - name: zsh
          description: Generate the autocompletion script for zsh
          flags:
            --no-descriptions: disable completion descriptions
    - name: help [command]
      description: Help about any command

Intermediate build

FROM golang
ARG VERSION

WORKDIR /
RUN git clone https://github.com/balajz/pgxcli --branch "${VERSION}" --depth 1

ADD pgxcli.patch /

WORKDIR /pgxcli
RUN git apply ../pgxcli.patch
RUN go get github.com/carapace-sh/carapace
RUN GOBIN=/usr/bin/ go install ./cmd/pgxcli

ENTRYPOINT ["pgxcli", "_carapace", "spec"]
diff --git a/internal/cli/root.go b/internal/cli/root.go
index de82940..0efbec7 100644
--- a/internal/cli/root.go
+++ b/internal/cli/root.go
@@ -1,6 +1,7 @@
 package cli
 
 import (
+	"github.com/carapace-sh/carapace"
 	"context"
 	"fmt"
 	"os"
@@ -115,6 +116,7 @@ func NewRootCmd(ctx context.Context, cliCtx *CliContext) *cobra.Command {
 	interactiveConnFlag.bind(rootCmd)
 
 	rootCmd.MarkFlagsMutuallyExclusive("no-password", "password")
+	carapace.Gen(rootCmd)
 
 	return rootCmd
 }

carapace-spec

The carapace-spec skill creates/modifies Spec files.

Instructions

  1. start crush in an empty directory
  2. ctrl+p, TAB, then select the skill
  3. run with
    • create (runnable) spec ...
    • add completions to spec <name>

Result

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: summarize
description: Summarize the difference between two git refs
run: "$(crush run \"Summarize the difference between git refs ${C_ARG0} and ${C_ARG1}\")"
completion:
  positional:
    - ["$carapace.tools.git.Refs"]
    - ["$carapace.tools.git.Refs"]

LSP

An experimental Bash Language Server with support for Carapace.

Place the single binary release in your PATH and follow the original instructions.

Then add it to your config.

{
  "$schema": "https://charm.land/crush.json",
  "lsp": {
    "bash": {
      "command": "bash-language-server",
      "args": [
        "start"
      ]
    }
  }
}

Not actually recommended at this moment.

Development

Project Layout

.
├── cmd
│  ├── carapace # main application
│  ├── carapace-fmt # simple formatter
│  ├── carapace-generate # executed by `go generate`
│  ├── carapace-lint # simple linter
│  ├── carapace-parse # simple help output parser
│  └── carapace-shim # binary for runnable specs in windows
├── completers # completers
│  └── example_completer # completer for `example`
│    └── cmd
│      └── action # local (coupled) actions
├── completers_release # optimized completers
├── dist # goreleaser dist folder
├── docs # documentation
├── internal # internal packages
└── pkg # public packages
   ├── actions # shared actions that are also exposed as macros
   │  └── tools # shared actions specific to tools
   ├── conditions # conditions for environment variable completion
   ├── env # environment variables
   ├── styles # style configurations
   └── util # util functions

Build

Requirements

  • Go
  • Ensure PATH contains your ~/go/bin folder (see doc)

Development

cd cmd/carapace
go generate ./... # only needed once and when there are new completers or actions
go install

Build with the force_all tag to include all groups.

go install -tags force_all

Release

A build with the release tag uses completers_release which optimizes startup times.

cd cmd/carapace
go generate ./... # always needed for `completers_release` to be updated
go install -ldflags="-s -w" -tags release

Separate

Completers can also be built (and thus maintained) separately.

cd completers/ln_completer
go install -ldflags="-s -w"

Docker

docker-compose run --rm build # build once (will be mounted from `cmd/carapace`)
docker-compose run --rm [bash|elvish|fish|ion|nushell|oil|powershell|tcsh|xonsh|zsh]
[ln|mkdir|chown...] <TAB>

Creating completers

Manually

  • Copy a basic completer for simplicity.
cp -r completers/ln_completer completers/manually_completer
  • Update the package name in main.go.
-import "github.com/carapace-sh/carapace-bin/completers/ln_completer/cmd"
+import "github.com/carapace-sh/carapace-bin/completers/manually_completer/cmd"
  • Create the root command.
echo | carapace-parse -n manually > root.go
  • Add subcommands.
echo | carapace-parse -n subcommand -p root > subcommand.go

Parsing

Scraping

With scrapers the structure of commands can be exported to yaml.

Which then can be converted to go code with codegen.

Examples

Journalctl

asciicast

Updating Completers

Best Practices

Coupled Actions

Use coupled actions to avoid repetition.

Sometimes an Action depends on the same flag values for multiple subcommands. Since ActionCallback is needed to access these the code can become a bit cumbersome and bloated.

carapace.Gen(get_allCmd).PositionalCompletion(
	carapace.ActionCallback(func(c carapace.Context) carapace.Action {
		return helm.ActionReleases(helm.ReleasesOpts{
			Namespace:   rootCmd.Flag("namespace").Value.String(),
			KubeContext: rootCmd.Flag("kube-context").Value.String(),
		})
	}),
)

An alternative to this is creating a local Action that is coupled to the command. Meaning, passing it the command and expecting specific flags to be present.

// completers/helm_completer/cmd/action/release.go
func ActionReleases(cmd *cobra.Command) carapace.Action {
	return carapace.ActionCallback(func(c carapace.Context) carapace.Action {
		return helm.ActionReleases(helm.ReleasesOpts{
			Namespace:   cmd.Root().Flag("namespace").Value.String(),
			KubeContext: cmd.Root().Flag("kube-context").Value.String(),
		})
	})
}

Thus the call becomes quite compact.

carapace.Gen(get_allCmd).PositionalCompletion(
	action.ActionReleases(get_allCmd),
)

Tools

carapace-fmt

carapace-lint

carapace-parse

carapace-generate

Release Notes

Release notes contain noteworthy changes between minor (1.x) releases.

These aren't strictly pinned to tags. So a feature announced as 1.n might already be present in a previous (1.{n-1}.x) or added in a later (1.n.x) patch release.

See releases for an exact changelog.

v1.x - (nightly)

Under development.

v1.7 - Slop Machine

No! NO! NO! Crush! To save the world, I need Crystals! CRYSTALS!

MCP

Added an MCP server.

Skills

Added carapace-scrape to scrape commands.

Added carapace-spec to create and modify specs.

Added carapace-integrate to create and modify applications.

Scrape

Added AGENTS.md to generate scrapers.

Bash Language Server

Created an experimental fork that supports Carapace.

Jujutsu

Improved Jujutsu Revset completion with carapace-jjlex.

v1.6 - GOOS Chase

Shedding some feathers from the release.

Groups

Organized completers into groups.

  • android termux completers
  • bridge bridged completers
  • bsd bsd-like completers
  • common common completers
  • darwin macos completers
  • linux linux completers
  • unix unix-like completers
  • user user specs
  • system system specs
  • windows windows completers

Variants

Added support for variants.

Choices

The default priority of completers can be overridden with choices.

This replaces bridges.yaml which now has no effect and can be removed.

Spec

Added extended flag notation for less common use cases.

  • nargs amount of arguments consumed
name: command
commands:
  - name: extended
    flags:
      --nargs-two=: {description: consumes two arguments, nargs: 2}
      --nargs-any=: {description: consumes multiple arguments, nargs: -1}

Diff

carapace --diff now takes two arguments to compare variants.

Aws

Created carapace-aws to provide enriched completion for aws-cli.

v1.5 - Alter Ego

Oh noes! Run is multiples.

Run

Now also accepts array and shebang.

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: run
commands:
  - name: alias
    commands:
      - name: string
        run: "[tail, --lines, '${NUM:-1}']"

      - name: array
        run: [tail, --lines, "${NUM:-1}"]

  - name: script
    commands:
      - name: macro
        run: "$(tail -n${C_FLAG_LINES:-1} $@) ||| $chdir($tempdir)"
        flags:
          -n, --lines=: output the last NUM lines
        completion:
          positionalany: ["$files ||| $chdir($tempdir)"]

      - name: shebang
        run: |
          #!/usr/bin/env bash -x
          for arg in "$@"; do
            echo "${!arg}${C_FLAG_SUFFIX:-.suffix}"
          done
        flags:
          -s, --suffix=: suffix to add
        completion:
          flag:
            suffix: [.backup, .copy]
          positionalany: [one, two]

Envsubst

Skip expansion with a ! prefix.

ExpressionSubstitution
${HOME}/home/user
${!HOME}${HOME}
${UNSET:-default}default
${!UNSET:-default}${UNSET:-default}

Macro

The $() exec macro now defaults to cmd instead of pwsh on windows.

  • $(<command>) (sh on unix and cmd on windows)
  • $bash(<command>)
  • $cmd(<command>)
  • $elvish(<command>)
  • $fish(<command>)
  • $nu(<command>)
  • $osh(<command>)
  • $pwsh(<command>)
  • $sh(<command>)
  • $xonsh(<command>)
  • $zsh(<command>)

Edit

Added carapace --edit FILE... for convenience.

  • $CARAPACE_EDITOR (highest priority)
  • $GIT_EDITOR
  • $VISUAL
  • $EDITOR

Bridge

Added support for kitten which provides completion for Kitty.

  • kitten - identifier
  • bridge.Kitten - macro

Parsing compdef header for multiple registered commands (instead of just one).

#compdef pulseaudio pactl pacmd pacat paplay parec parecord padsp pasuspender

Dynamically creating list of inshellisense completers.

inshellisense specs list 
# ["act","adb","adr","afplay","aftman","ag","agrippa","airflow",...

v1.4 - Bridge Inspector

Looking into details.

Detect

Added carapace --detect COMMAND to auto-detect bridgeable frameworks.

WARNING: This invokes given command multiple times with various arguments.

Urfavecli

Added support for urfave/cli v3 and updated identifiers.

  • argcomplete
  • argcomplete@v1 (legacy)
  • urfavecli
  • urfavecli@v1 (legacy)

Also renamed ArgcompleteLegacy to ArgcompleteV1.

Termux

Now in official package repo termux/termux-packages.

pkg install carapace

Alias

Added variable substitution to aliases.

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: example
run: "[gh, issue, --repo, '${REPO}']"

Lint

Removed carapace-fmt and integrated formatting into carapace-lint.

Hidden

Updated CARAPACE_HIDDEN for more granular control.

  • 0 - disabled
  • 1 - enabled
  • 2 - enabled including _carapace

v1.3 - Commander Key

Command Prompt is Toast!

Cmd

Experimental support for Cmd through Clink.

# ~/AppData/Local/clink/carapace.lua
load(io.popen('carapace _carapace cmd-clink'):read("*a"))()

Very early version with a lot of fundamental features not yet working.

Fish

With 4.0b1 onwards the following workaround is not needed anymore:

mkdir -p ~/.config/fish/completions
carapace --list | awk '{print $1}' | xargs -I{} touch ~/.config/fish/completions/{}.fish # disable auto-loaded completions (#185)

see fish-shell/fish#6716

Remove the leftover placeholders in ~/.config/fish/completions/.

Bridge

  • Switched to $fish_complete_path to list available completions in the Fish bridge.

    This should fix nix-based installations.

  • Added another call to compinit to adopt changes to fpath in the Zsh bridge.

    At this point it should not be neccessary to call compinit in the .zshrc.

Git

Added reflog completion.

Freckles

Added Freckles as example project.

v1.2 - Sea Change

Moby has grown a little too big.

Docker

Split the carapace container into several smaller ones.

Compose

Updated compose services with the new docker containers. Also added services for specific tools.

Zsh

Reworked the handling of quoted values.

VHS

Added VHS tapes to verify the shell integration.

Variable

Extracted the set-env <NAME> <VALUE> completion as generic action.

Completions use the local environment so there are some limitations.

Spec

In specs it can be used as attached (default) or positional completion.

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: variable
completion:
  positional:
  - ["$carapace.env.NameValues"] # attached (NAME[=VALUE])
  - ["$carapace.env.NameValues(true) ||| $shift(1)"] # positional (NAME)
  - ["$carapace.env.NameValues(true) ||| $shift(1)"] # positional (VALUE)

  • Use shift to skip previous arguments during positional completion.
  • Renamed env.KnownEnvironmentVariables to env.Names.
  • Renamed env.EnvironmentVariableValues to env.Values.

Unfiltered

Added CARAPACE_UNFILTERED environment variable to skip the final filtering step.

This enables fuzzy completion in fish (to a degree), but is limited to mostly static values.

v1.1 - Nightly Bats

Nightly batch release straight from master.

GoReleaser

Updated goreleaser config to adopt defaults across all projects.

This changes the release artifact names slightly and might break some scripts.

Nightly

Added carapace-sh/nightly.

Nightly builds use the same goreleaser config, but in a different environment.

Selfupdate

With carapace --selfupdate specific nightly or stable releases can be installed.

Executable is installed to the GOBIN directory, essentially shadowing any system installation.

export PATH="$HOME/.local/bin:$HOME/go/bin:$PATH"
#            │                │            └system installation (e.g. /usr/bin/carapace)
#            │                └selfupdate/go based installation ($GOBIN)
#            └user binaries

Requirements

Homebrew

Now installable from homebrew-core.

brew install carapace

Nospace

Added CARAPACE_NOSPACE environment variable to control space suffix behaviour.

Tooltip

Added CARAPACE_TOOLTIP environment variable to enable tooltip style.

Only affects Powershell.

v1.0 - Moving Day

Off to a shiny new home.

Organization

Moved repositories to carapace-sh.

import (
- "github.com/rsteube/carapace"
+ "github.com/carapace-sh/carapace"
)

Diff

Added --diff command[/bridge] ...args to track changes.

--- a/zsh/carapace --macro bridge.Zsh git log -
+++ b/carapace/carapace git export git log -
- -- (start file arguments)
  --abbrev (Show the shortest prefix that is at least <n> hexdigits long that uniquely refers)
  --abbrev-commit (Instead of showing the full 40-byte hexadecimal commit object name, show a prefix that names the object uniquely.)
  --after (Show commits more recent than a specific date.)
  --all (Pretend as if all the refs in refs/, along with HEAD, are listed on the command line as <commit>.)
  --all-match (Limit the commits output to ones that match all given --grep, instead of ones that match at least one.)
+ --alternate-refs (Pretend as if all objects mentioned as ref tips of alternate repositories were listed on the command line.)
  --ancestry-path (When given a range of commits to display, only display commits that exist directly on the ancestry chain.)
  --anchored (Generate a diff using the "anchored diff" algorithm.)
  --author (Limit the commits output to ones with author/committer header lines that match the specified pattern)
  --author-date-order (Show no parents before all of its children are shown, but otherwise show commits in the author timestamp order.)
+ --basic-regexp (Consider the limiting patterns to be basic regular expressions; this is the default.)
  --before (Show commits older than a specific date.)
  --binary (In addition to --full-index, output a binary diff that can be applied with git-apply. Implies --patch.)
  --bisect (Pretend as if the bad bisection ref refs/bisect/bad was listed and as if it was followed by --not and the good bisection refs refs/bisect/good-* on the command line.)
  --boundary (Output excluded boundary commits. Boundary commits are prefixed with -.)
  --branches (Pretend as if all the refs in refs/heads are listed on the command line as <commit>.)
  --break-rewrites (Break complete rewrite changes into pairs of delete and create.)
- --cc (combined diff format for merge commits)
  --check (Warn if changes introduce conflict markers or whitespace errors.)
  --cherry (A synonym for --right-only --cherry-mark --no-merges)

The diff simply compares inserted values between completions provided by a bridge with those provided by carapace. It is just an indicator as there can be good reasons why these vary.

Clear Cache

Added --clear-cache to remove cached completions.

Positional Arguments

Positional arguments can now be accessed as script parameters in exec macros .

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: positional
flags:
  -b, --bool: bool flag
completion:
  positionalany: ["$(echo \"$@\tall arguments\")", "$(echo \"$1\tfirst argument\")"]

v0.30 - Wiretap

Tapping into other shells for additional completions.

Implicit Bridges

With CARAPACE_BRIDGES default bridges can be enabled for commands not provided by carapace.

set-env CARAPACE_BRIDGES 'zsh,fish,bash,inshellisense'

Order defines the precedence (e.g. if zsh has a git completer it will be used instead of the one in fish).

Explicit Bridges

Additionally to user specs ~/.config/carapace/bridges.yaml provides a simpler configuration of bridges.

gh: cobra
opentofu: complete
tsh: kingpin

bridges.yaml has a higher precedence than Implicit Bridges but lower than internal completers and specs. So disable an internal completer with Excludes if you want to replace it with a bridge.

Currently available bridges:

Bridging frameworks should be preferred to shells (e.g. zsh) as these generally work better and have less overhead.

Excludes

With CARAPACE_EXCLUDES internal completers can be excluded.

Explicit Parsing Mode

So far flag parsing was implicitly disabled for bridge macros in specs. From now on this needs to be done explicitly.

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json
name: az
description: Azure Command-Line Interface
parsing: disabled
completion:
  positionalany: ["$carapace.bridge.Argcomplete([az])"]
  • interspersed - mixed flags and positional arguments (default)
  • non-interspersed - flag parsing stopped after first positional argument
  • disabled - flag parsing disabled

v0.29 - Art Exchange

One step further to exchange completions between commands.

carapace.sh

Registered the domain carapace.sh.

Root Command

Restructured the carapace root command which was (and still is) a bit of a mess. Some flags (subcommands) were renamed/changed for consistency.

  • --list=json -> --list --format json
  • --macros -> --macro
  • --scrape [spec] -> --codegen [spec]

Specs

The JSON Schema is now hosted at https://carapace.sh/schemas/command.json.

# yaml-language-server: $schema=https://carapace.sh/schemas/command.json

~/.config/carapace/schema.json is now deprecated and can be removed.

Macro

$_ prefix in specs is now deprecated and needs to be replaced with $carapace.

If a macro name contains . the first segment is handled as command that will be invoked.

$carapace.color.HexColors
# invokes `carapace _carapace macro color.HexColors ""`

$carapace-spec.Spec(example.yaml)
# invokes `carapace-spec _carapace macro "Spec(example.yaml)" ""`

This behaviour will change slightly in the future to support custom macros.

With the --in-place flag of sed the specs can be updated directly.

sed 's/$_/$carapace./g' ~/.config/carapace/specs/*.yaml

Inshellisense

Added a bridge for inshellisense (which uses fig under the hood).

Nushell

Support for colored completion (requires nushell#11442).

Xonsh

Support for colored completion.

v0.28 - Greenwashing

This one is messing with your environment.

Variable

Complex environment variable completion is provided with get-env, set-env and unset-env.

In elvish the completion is simply overridden. For other shells custom functions are added.

Setting CARAPACE_ENV=0 before sourcing carapace _carapace disables this behaviour.

Custom variables

Custom variables can be defined in ~/.config/carapace/variables/{group}.yaml

variables:
  CUSTOM_EXAMPLE: example environment variable
  CUSTOM_MACRO: macro example
  HTTPS_PROXY: override existing variable
completion:
  variable:
    CUSTOM_EXAMPLE: ["0\tdisabled\tred", "1\tenabled\tgreen"]
    CUSTOM_MACRO: ["$_tools.gh.Labels({owner: carapace-sh, name: carapace}) ||| $uniquelist(,)"]
    HTTPS_PROXY: ["https://localhost:8443\tdevelopment", "https://proxy.company:443\tproduction"]

It is also possible to define conditions.

condition: ["$Parent([.git])"]
variables:
  CUSTOM_CONDITION: condition example
completion:
  variable:
    CUSTOM_CONDITION: ["within", "git", "repo"]

Specific modifiers

Specs now support specific modifiers using ||| as delimiter.

name: modifier
positionalany: ["$files ||| $chdir(/tmp)"]

Git

Full support for relative refs.

v0.27 - Hulk BASH!

Contains strong changes to the bash integration.

Redirects

Support for redirects. bash passes these to the completion function, so crazy stuff like this is possible:

example action >/tmp/stdout.txt embeddedPositional1 --styles 2>/tmp/stderr.txt red 'embeddedPositional2 with space'

To make this work carapace-shlex is now used to parse COMP_LINE when invoked from a bash completion function.

Wordbreaks

Better support for bash COMP_WORDBREAKS using carapace-shlex. This was originally intended to make multipart completion easier (e.g. colon separated list), but actually makes it very complicated and error-prone.

Case insensitive matching

Added (limited) case insensitive matching.

Set environment variable CARAPACE_MATCH to CASE_INSENSITIVE or 1 to activate it. You might also need to configure your shell, e.g. in elvish:

set-env CARAPACE_MATCH CASE_INSENSITIVE
set edit:completion:matcher[argument] = {|seed| edit:match-prefix $seed &ignore-case=$true }

v0.26 - Overly Attached Argument

Argument

Added support for various attached versions of passing non-optional flag arguments:

--longhand=arg
-l=arg
-larg
-abclarg

Lexer

Added a simple lexer for complex commands passed as single argument:

Nushell

Used the lexer to patch arguments as these are currently passed mostly unprocessed to the completion function. This is a workaround and has some edge cases but should overall improve the Nushell integration.

v0.25 - Window Shopping

Windows

Support for volume prefix in path completion.

v0.24 - Spring Cleaning

carapace-bridge

Moved bridge actions to carapace-bridge. The shell bridges now use custom configs at ${UserConfigDir}/carapace/bridge (e.g. ~/.config/carapace/bridge/fish/config.fish instead of ~/.config/fish/config.fish).

removed flags

Removed --bridge and --spec flags as user specs are preferred and there are carapace-bridge and carapace-spec as well.

v0.23 - First Amendment

Bridge Actions (BREAKING CHANGE)

Bridge actions now take multiple arguments. Analogue to Alias this enables embedding of subcommands in macros. Specs need to be updated though by adding [] brackets to the bridge macro arguments:

completion:
  # positionalany: ["$_bridge.CarapaceBin(git)"]  # OLD
  positionalany: ["$_bridge.CarapaceBin([git])"]  # NEW

Overlay

Overlays are essentially Spec files placed in ${UserConfigDir}/carapace/overlays that provide additional completions.

These are merged with the existing completion and provide a workaround for issues that have yet to be fixed in upstream.

Overlays implicitly set CARAPACE_LENIENT to allow unknown flags.

Flag

# ~/.config/carapace/overlays/doctl.yaml
name: doctl
persistentflags:
  --output=: Desired output format [text|json]
completion:
  flag:
    output: [text, json]
commands:
  - name: compute
    description: Display commands that manage infrastructure
    commands:
      - name: region
        description: Display commands to list datacenter regions
        commands:
          - name: list
            description: List datacenter regions
            flags:
              --format=: Columns for output in a comma-separated list
            completion:
              flag:
                format: ["$uniquelist(,)", Slug, Name, Available]

Windows

Using zip as archive for windows releases for winget compability.

v0.22 - Running Man

Specs now support a run field enabling cross shell aliases and simple nested custom commands.

Run

run can either contain an alias ([command, arg1, arg2]) which bridges completion or a shell macro ($(echo example)) with custom completions / flag parsing.

name: runnable
description: runnable spec
commands:
  -  name: sub1
     description: alias
     run: "[git, log]"

  -  name: sub2
     description: shell
     run: "$(git show $1)"
     completion:
       positional:
         - - "$(git branch --format '%(refname:short)\t%(subject)\tblue')"
           - "$(git tag --format '%(refname:short)\t\tyellow')"

  -  name: sub3
     description: shell with flags
     run: "$(git log --author \"${C_FLAG_AUTHOR}\" $1)"
     flags:
       -a, --author=: limit to author
     completion:
       flag:
         author: ["$(git shortlog --summary --email HEAD | sed -e 's/^.*\t//' -e 's/ </\t</')"]
       positional:
         - - "$(git branch --format '%(refname:short)\t%(subject)\tblue')"
           - "$(git tag --format '%(refname:short)\t\tyellow')"

PATH

carapace _carapace now prepends ${UserConfigDir}/carapace/bin to PATH unless it already exists.

In nushell this needs to be done manually (see output of carapace _carapace nushell):

let-env PATH = ($env.PATH | prepend "/home/rsteube/.config/carapace/bin")

Shim

It also creates Shims in ${UserConfigDir}/carapace/bin to execute the specs. For unix systems this is a simple shell script, but for windows an embedded binary is used.

#!/bin/sh
carapace --run "/home/rsteube/.config/carapace/specs/runnable.yaml" "$@"

The ${UserConfigDir}/carapace/bin directory is fully managed by carapace and unrelated files within it are removed.

Nargs

Initial support for flags consuming multiple arguments as seen in argparse and various nix commands.

XDG

XDG base directories for XDG_CACHE_HOME and XDG_CONFIG_HOME are now supported.

v0.21 - Heart Transplant

Replaced command traversal with a full rewrite. This provides more fine-grained control and improved logging. It is a complex core component though and while tests are looking good so far some edge cases are likely to fail.

Logging

Improved logging output (export CARAPACE_LOG=1):

// /tmp/carapace/carapace.log
2023/01/29 11:46:28.310133 elvish []string{"/home/rsteube/go/bin/carapace", "_carapace", "elvish", "git", "-C", "../carapace-bin/", "log", "--author", ""}
2023/01/29 11:46:28.310165 elvish traverse called for "git" with args []string{"-C", "../carapace-bin/", "log", "--author", ""}
2023/01/29 11:46:28.310167 elvish executing PreRun for "git" with args []string{"-C", "../carapace-bin/", "log", "--author", ""}
2023/01/29 11:46:28.310185 elvish arg "-C" is a flag
2023/01/29 11:46:28.310207 elvish arg "../carapace-bin/" is a flag argument
2023/01/29 11:46:28.310210 elvish arg "log" is a subcommand
2023/01/29 11:46:28.310211 elvish parsing flags for "git" with args []string{"-C", "../carapace-bin/"}
2023/01/29 11:46:28.310215 elvish traverse called for "log" with args []string{"--author", ""}
2023/01/29 11:46:28.310247 elvish arg "--author" is a flag
2023/01/29 11:46:28.310259 elvish removing arg "--author" since it is a flag missing its argument
2023/01/29 11:46:28.310260 elvish parsing flags for "log" with args []string{}
2023/01/29 11:46:28.310262 elvish completing flag argument of "author" for arg ""

Yargs

Added bridge for yargs:

name: ng
description: CLI tool for Angular
completion:
  positionalany: ["$_bridge.Yargs(ng)"]

v0.20 - Blinkers

Export

Contains breaking changes on the export format. Since there is no backward compability any embedded external carapace based completion must be >= v0.31.0.

Lenient

When environment variable CARAPACE_LENIENT is set (e.g. export CARAPACE_LENIENT=1) unknown flags are ignored. Completers are supposed to be aware of all existing flags but can out of date or not yet working correctly. This can be used to suppress the errors until issues are fixed.

v0.19 - Group Therapy

Error messages

Multiple error message are now supported. In elvish and zsh these are shown separate from the completion values.

Usage message

Added Usage message which defaults to flag description / command usage. This is only supported in elvish and zsh. Since notifications are persistent in elvish it is only shown when there are no values to complete.

Tags

Completion values can now be tagged. Based on this they are grouped in zsh.

Command groups

Subcommands can now be grouped and will be highlighted in different colors.

Group names

Group names can be shown in zsh with the following zstyle.

zstyle ':completion:*' format $'\e[2;37mCompleting %d\e[m'

Group ordering

Order of the groups can be configured in zsh with the following zstyle.

zstyle ':completion:*:git:*' group-order 'main commands' 'alias commands' 'external commands'

_describe

_describe is now used in zsh which enables the grouping of tags. With this aliased commands and flags are now also arranged side by side.

v0.18 - Spec Galore

Generate

Specs can now be generated from clap based commands with carapace-spec-clap.

Scrape

For advanced completion these can further be converted to Go code with carapace --scrape [spec].

Json Schema

A JSON Schema is now written to ${UserConfigDir}/carapace/schema.json.

It can be used by adding the following header to a user spec:

# yaml-language-server: $schema=../schema.json

Windows

$(shell command) is now executed in Powershell on windows.

v0.17 - Spec-tacular Citizen

Specs are now first-class citizens in carapace. They are integrated on root level and should behave similar to the existing completers (carapace [spec.name] <TAB>).

List

Completers based on Specs are highlighted in shells that support colors (details: carapace --list=json):

Bridge

Using Specs for bridging is from now on the recommended approach. As these are auto-loaded with carapace _carapace and provide support for embedded completion like sudo [spec.name] <TAB>.

Existing completers with the same name will also be overridden. E.g. kubectl (which is currently a bit outdated) can be configured to use the official completer:

# ${UserConfigDir}/carapace/specs/kubectl.yaml
name: kubectl
description: kubectl controls the Kubernetes cluster manager
completion:
  positionalany: ["$_bridge.Cobra(kubectl)"]

Note that bridging adds a slight overhead (~7-9ms?) for each invocation and is limited to supported frameworks / commands.

Plugin

Taking this one step further plugin completion like cargo-[plugin], gh-[plugin], git-[plugin] can now also be defined by Specs.

E.g. the gh-repo-collab extension for github-cli:

# ${UserConfigDir}/carapace/specs/gh-repo-collab.yaml
name: gh-repo-collab
description: manage repository collaborators
commands:
  -
    name: list
    completion:
      positional:
        - ["$_tools.gh.OwnerRepositories"]
  -
    name: add
    flags:
      --permission=: set permission
    completion:
      flag:
        permission: ["pull", "triage", "push", "maintain", "admin\t\tred"]
      positional:
        - ["$_tools.gh.OwnerRepositories"]
        - ["$_tools.gh.Users"]
  -
    name: remove
    completion:
      positional:
        - ["$_tools.gh.OwnerRepositories"]
        - ["$_tools.gh.Users"]

Nushell

With https://github.com/nushell/nushell/pull/6652 (upcoming v0.70.0) the nushell integration is now working on positional arguments. The recommended configuration is equivalent to the example configuration in config.nu:

let carapace_completer = {|spans| 
  carapace $spans.0 nushell $spans | from json
}

let-env config = {
  external_completer: $carapace_completer
}

Be sure to remove the module completions example so that it won't override the carapace completion

v0.16 - Pandoras Box

Switched to a custom pflag fork with adaptions for non-posix variants like long shorthands (e.g. -shorthand).

So far this has been done by patching os.Args which was rather hacky. Modifications to the flag parser are quite complex though, so there might be some issues.

see #1293

Spec files support non-posix flags now as well:

flags:
  -np: non-posix shorthand
  -np, -nonposix:  non-posix shorthand and longhand
  -np, --nonposix: non-posix shorthand mixed with posix longhand

v0.15 - Porcelain Shop

ZSH (this might break some stuff)

Added support for homedir (~) and static named directories. These are not expanded by zsh for the completion function are thus now handled by carapace. Quoting of special characters is now also done in carapace instead of compadd to skip ~ at appropriate times. Edge cases where this doesn't work and some initial bugs regarding special characters not yet being handled correctly are expected.

see #1277

v0.14 - In A Nutshell

Nushell

https://github.com/nushell/nushell/pull/6295 adds support for external completers to nushell. For this config.nu must be updated manually according to the snippet output of carapace. Here's an example with carapace as default completer and a couple custom completers:

let external_completer = {|spans| 
  {
    $spans.0: { carapace $spans.0 nushell $spans | from json } # default                                                             
    example: { example _carapace nushell $spans | from json }                                                                 
    pkill: { carapace --spec '/home/rsteube/.config/carapace/specs/pkill.yaml' nushell $spans | from json }  
    vault: { carapace --bridge vault/posener nushell $spans | from json }
  } | get $spans.0 | each {|it| do $it}
}

let-env config = {
  external_completer: $external_completer
}

v0.13 - Furious

fury.io

DEB and RPM packages are now published to fury.io (Install)

v0.12 - Preinfusion

Preinvoke

Generic alteration of completion before execution which enables features like directory change in git -C <DIR>:

Spec

Experimental support for simple completions using yaml spec files:

name: example
description:
flags:
  --dynamic=: dynamic value
  -o, --optarg?: optarg flag
  -s, --styled=: styled values
completion:
  flag:
    dynamic: ["$(git branch --all | cut -c 3- | sed 's/$/\t\tblue/')", "static value"]
    optarg: ["first", "second", "third"]
    styled:
    - "blue\tblue\tblue"
    - "cyan\tcyan\tcyan"
  positional:
  -  ["pos1-a", "pos1-b", "pos1-c"]
  -  ["$_files"]

Spec Autoloading

Specs placed in ${UserConfigDir}/carapace/specs/ (UserConfigDir) are now registered with carapace _carapace. File name must be the command to be completed and match ^[0-9a-zA-Z_\-.]+\.yaml$ (sanity check to avoid breakage in scripts).

Custom Macros

Exposed actions as custom macros (list with carapace --macros). Removed the _ prefix from core macros to avoid clashes (e.g. $files, $directories).

Macro Arguments

Arguments are parsed as yaml ($macro(yaml) - e.g.: $_tools.gh.Users({users: true})). Brackets are optional when no argument is passed ($files instead of $files()).

Variable Substitution

Variables are replaced using drone/envsubst for contextual completion:

name: myzip
completion:
  positional:
    - ["$files([.zip])"] # ${C_ARG0}
  positionalany: ["$_fs.ZipFileContents(${C_ARG0})"] # ${C_ARG1},${C_ARG2},...

Flags are only added to env when their value changed (thus: ${C_FLAG_FLAGNAME:-default}):

name: myrefs
flags:
  --tags: list tags # ${C_FLAG_TAGS}
  --localbranches: list local branches # ${C_FLAG_LOCALBRANCHES}
  --commits=: amount of commits # ${C_FLAG_COMMITS}
completion:
  positional:
    - ["$_tools.git.Refs({tags: ${C_FLAG_TAGS:-false}, localbranches: ${C_FLAG_LOCALBRANCHES:-false}, commits: ${C_FLAG_COMMITS:-0}})"] # refs based on flag values with defaults
    - ["$_tools.git.Refs"] # default refs
    - ["$(env)"] # env

v0.11 - Puking Rainbows

This release adds color support for zsh and elvish and thus raises elvish minimum version to v0.18.0.

LS_COLORS

LS_COLORS should now be working correctly - e.g with vivid in elvish:

set E:LS_COLORS = (vivid generate dracula)

Style Config

Styles can now be configured with carapace --style key=value (an empty value restores the default).

Powershell Style

Added color support for powershell.