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-spec

Define simple completions using a spec file (based on carapace).

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"]

Usage

Bash

# ~/.bashrc
source <(carapace-spec example/pkill.yaml)

Elvish

# ~/.config/elvish/rc.elv
eval (carapace-spec example/pkill.yaml|slurp)

Fish

# ~/.config/fish/config.fish
carapace-spec example/pkill.yaml | source

Nushell

update config.nu according to Multiple Completer)

#~/.config/nushell/config.nu
carapace-spec example/pkill.yaml

Oil

# ~/.config/oil/oshrc
source <(carapace-spec example/pkill.yaml)

Powershell

# ~/.config/powershell/Microsoft.PowerShell_profile.ps1
carapace-spec example/pkill.yaml | Out-String | Invoke-Expression

Tcsh

## ~/.tcshrc
eval `carapace-spec example/pkill.yaml`

Xonsh

# ~/.config/xonsh/rc.xsh
exec($(carapace-spec example/pkill.yaml))

Zsh

# ~/.zshrc
source <(carapace-spec example/pkill.yaml)

Command

type Command struct {
	Name            string
	Aliases         []string
	Description     string
	Group           string
	Hidden          bool
	Parsing         string
	Flags           map[string]string
	PersistentFlags map[string]string
	ExclusiveFlags  [][]string
	Run             string
	Completion      struct {
		Flag          map[string][]string
		Positional    [][]string
		PositionalAny []string
		Dash          [][]string
		DashAny       []string
	}
	Commands []Command
}

Name

Name of the command.

name: command
commands:
  - name: name

It can also contain the one-line usage message.

name: command
commands:
  - name: usage [-F file | -D dir]... [-f format] profile

Recommended syntax is as follows:

  • [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.
  • ... indicates that you can specify multiple values for the previous argument.
  • | indicates mutually exclusive information. You can use the argument to the left of the separator or the argument to the right of the separator. You cannot use both arguments in a single use of the command.
  • { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are optional, they are enclosed in brackets ([ ]).

Aliases

Aliases of the command.

name: command
commands:
  - name: aliases
    aliases: [a, al]

Description

Description of the command.

name: command
commands:
  - name: description
    description: with description

Group

Group of the command.

name: command
commands:
  - name: group
    group: grouped

Hidden

Hide the command from completion.

name: command
commands:
  - name: hidden
    hidden: true
    completion:
      positional:
        - [p1, positional1]

Flags

Flags of the command.

name: command
commands:
  - name: flags
    flags:
      -b: bool flag
      -v=: shorthand with value
      --repeatable*: longhand repeatable
      -o, --optarg?: shorthand and longhand with optional argument
      --hidden&: longhand hidden
      --required!: longhand required

Modifiers:

Flags can have 0..n modifier suffixes.

  • = flag takes an argument
  • * flag is repeatable
  • ? flag takes an optional argument
  • & flag is hidden
  • ! flag is required

Non-posix

Additional formats when built with carapace-pflag.

name: command
commands:
  - name: nonposix
    flags:
      -single: non-posix shorthand
      -short, -long: non-posix shorthand and longhand
      -mixed, --mixed: non-posix shorthand mixed with posix longhand

PersistentFlags

Same as Flags, but passes them down to subcommands.

name: command
commands:
  - name: persistentflags
    persistentflags:
      -p, --persistent: persistent flag
    commands:
      - name: subcommand
        flags:
          -l, --local: local flag

ExclusiveFlags

Mark flags mutually exclusive.

name: command
commands:
  - name: exclusiveflags
    flags:
      --add: add package
      --delete: delete package
    exclusiveflags:
      - [add, delete]

Completion

Completion for a position is defined by an array of static Values and Macros.

Flag

Define FlagCompletion using the longhand name (if available).

name: command
commands:
  - name: completion
    commands:
      - name: flag
        flags:
          -e?: executables
          -f, --file=: file
        completion:
          flag:
            e: ["$executables"]
            file: ["$files"]

Positional

Define PositionalCompletion.

name: command
commands:
  - name: completion
    commands:
      - name: positional
        completion:
          positional:
            - [pos1, positional1]
            - [pos2, positional2]

PositionalAny

Define PositionalAnyCompletion.

name: command
commands:
  - name: completion
    commands:
      - name: positionalany
        completion:
          positionalany: [posany, positionalany]

Dash

Define DashCompletion.

name: command
commands:
  - name: completion
    commands:
      - name: dash
        completion:
          dash:
            - [d1, dash1]
            - [d2, dash2]

DashAny

Define DashAnyCompletion.

name: command
commands:
  - name: completion
    commands:
      - name: dashany
        completion:
          dashany: [dany, dashany]

Parsing

Sets flag parsing mode. One of:

  • interspersed mixed flags and positional arguments
  • non-interspersed flag parsing stopped after first positional argument
  • disabled flag parsing disabled
name: command
commands:
  - name: parsing
    persistentflags:
      --bool: bool flag
      --string=: string flag
    commands:
      - name: interspersed
        parsing: interspersed
        completion:
          positionalany: [one, two, three]
      - name: non-interspersed
        parsing: non-interspersed
        completion:
          positionalany: [one, two, three]
      - name: disabled
        parsing: disabled
        completion:
          positionalany: [one, two, three]

Run

Command to be executed.

# 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]

Commands

Subcommands of the command.

name: command
commands:
  - name: subcommand
    commands:
      - name: subsubcommand1
      - name: subsubcommand2

Values

Values are defined with an optional description and optional style delimited by \t.

["value", "value\tdescription", "value\tdescription\tblue"]

Macros

Macros are basically Actions exposed to the spec (E.g. $files([.go, go.mod]).

The brackets are optional if no argument is passed (so $files is equivalent to $files()).

Core

Core macros provided by carapace-spec.

directories

$directories completes directories.

["$directories"]

exec

Executes given command in a shell.

["$(echo one two three)"]
  • $(<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>)

Environment contains Variables of parsed flags and arguments.

executables

$executables completes executables either from PATH or given directories.

["$executables", "$executables([~/.local/bin])"]

files

$files([<suffixes>]) completes files with an optional list of suffixes to filter on.

["$files([.go, go.mod, go.sum])"]

message

$message(<message>) adds given error message to completion.

["$message(some error)"]

spec

$spec(<file>) completes arguments using the given spec file. This implicitly disables flag parsing for the corresponding (sub)command.

["$spec(example.yaml)"]

Modifier

Modifiers change the completion of macros and values. These can be set

  • generic ["<macro>", "<value>", "<modifier>"]
  • specific ["<macro> ||| <modifier> ||| <modifier>"].

The delimiter (|||) is currently very strict and not trimmed.

chdir

$chdir(<directory>) changes the directory.

["$files", "$chdir(/tmp)"]

The following macros can be passed as well instead of a static directory:

["$files", "$chdir($gitdir)"]

filter

$filter([<value>]) filters given values.

["one", "two", "three", "$filter([two])"]

filterargs

$filterargs filters Context.Args.

["$files", "$filterargs"]

list

$list(<delimiter>) creates a list with given divider.

["one", "two", "three", "$list(,)"]

multiparts

$multiparts([<delimiter>]) completes values splitted by given delimiter(s) separately.

["one/two/three", "$multiparts([/])"]

nospace

$nospace(<characters>) disables space suffix for given character(s).

["one", "two/", "three,", "$nospace(/,)"]

prefix

$pefix(<prefix>) adds a prefix to the inserted values.

["$files", "$prefix(file://)"]

retain

$retain([<value>]) retains given values.

["one", "two", "three", "$retain([two])"]

shift

$shift(<n>) shifts positional arguments left n times.

["one", "two", "three", "$filterargs", "$shift(1)"]

split

$split splits Context.Value lexicographically and replaces Context.Args with the tokens.

["one", "two", "three", "$filterargs", "$split"]

splitp

$splitp is like Split but supports pipelines.

["one", "two", "three", "$filterargs", "$splitp"]

suffix

$suffix(<suffix>) adds a suffix to the inserted values.

["apple", "melon", "orange", "$suffix(juice)"]

suppress

$suppress(<regex>) suppresses specific error messages using a regular expression.

["$message(fail)", "$suppress(fail)"]

style

$style(<style>) sets the style for all values.

["one", "two", "three", "$style(underlined)"]

tag

$tag(<tag>) sets the tag for all values.

["one", "two", "three", "$tag(numbers)"]

uniquelist

$uniquelist(<delimiter>) creates a unique list with given divider.

["one", "two", "three", "$uniquelist(,)"]

usage

$usage(<usage>) sets the usage message.

["$usage(custom)"]

Custom

Custom macros can be added with AddMacro.

// `$_noarg` without argument
AddMacro("noarg", MacroN(func() carapace.Action { return carapace.ActionValues()}))

// `$_arg({name: example, enabled: true})` with argument (primitive or struct)
AddMacro("arg", MacroI(func(u User) carapace.Action { return carapace.ActionValues()}))

// `$_vararg([another, example])` with variable arguments (primitive or struct)
AddMacro("vararg", MacroV(func(s ...string) carapace.Action { return carapace.ActionValues()}))

Arguments are parsed as yaml so only struct keys deviating from the default need to be set.

Default (experimental)

A Default() method can be added to a struct passed to MacroI.

It will be called when the macro is used without argumeng ($_arg instead of $_arg({user: example})).

type User struct {
	Name   string
	Enabled bool
}

func (u User) Default() User {
	u.Name = "example"
	u.Enabled = true
	return u
}

Variables

Variables are replaced using drone/envsubst.

  • ${C_ARG<position>} positional arguments [0..n]
  • ${C_FLAG_<flagname>} flag values (if modified)
  • ${C_PART<position>} parts of the current word during multipart completion [0..n]
  • ${C_VALUE} the word currently being completed
name: myvar
flags:
  --suffix=: file suffixes
completion:
  flag:
    suffix: ["$list(,)", ".go", "go.sum", "go.mod", ".md", "LICENSE"]
  positional:
    - ["$files([${C_FLAG_SUFFIX//,/, }])"] # replace `,` with `, ` for valid array syntax
    - ["${C_FLAG_SUFFIX:-default}", "${C_ARG0}"] # use default if flag is not set