package carapace

Import Path
	github.com/carapace-sh/carapace (on go.dev)

Dependency Relation
	imports 47 packages, and imported by one package

Involved Source Files action.go batch.go Package carapace is a command argument completion generator for spf13/cobra command.go compat.go complete.go context.go defaultActions.go diff.go experimental.go internalActions.go invokedAction.go log.go storage.go traverse.go
Package-Level Type Names (total 7)
/* sort by: | */
Action indicates how to complete a flag or positional argument. Cache cashes values of a CompletionCallback for given duration and keys. Chdir changes the current working directory to the named directory for the duration of invocation. ChdirF is like Chdir but uses a function. Escape escapes values so they can be embedded in a double-quoted string literal without adding surrounding quotes. carapace.ActionValues(`say "hi"`).Escape() Filter filters given values. carapace.ActionValues("A", "B", "C").Filter("B") // ["A", "C"] FilterArgs filters Context.Args. FilterArgs filters Context.Parts. Invoke executes the callback of an action if it exists (supports nesting). List wraps the Action in an ActionMultiParts with given divider. MultiParts splits values of an Action by given dividers and completes each segment separately. MultiPartsP is like MultiParts but with placeholders. NoPrefix prevents common prefix insertion for given prefixes (or all if none are given). NoSpace disables space suffix for given characters (or all if none are given). Prefix adds a prefix to values (only the ones inserted, not the display values). carapace.ActionValues("melon", "drop", "fall").Prefix("water") Query TODO experimental QueryF TODO experimental Quote quotes values as double-quoted string literals. carapace.ActionValues(`say "hi"`).Quote() Retain retains given values. carapace.ActionValues("A", "B", "C").Retain("A", "C") // ["A", "C"] Shift shifts positional arguments left `n` times. Split splits `Context.Value` lexicographically and replaces `Context.Args` with the tokens. The optional format is a shlex.Format name ("", "bash", "zsh", ...); omitting it uses the default. SplitP is like Split but supports pipelines. Style sets the style. ActionValues("yes").Style(style.Green) ActionValues("no").Style(style.Red) Style sets the style using a function. ActionValues("dir/", "test.txt").StyleF(style.ForPathExt) ActionValues("true", "false").StyleF(style.ForKeyword) Style sets the style using a reference. ActionValues("value").StyleR(&style.Carapace.Value) ActionValues("description").StyleR(&style.Carapace.Value) Suffix adds a suffx to values (only the ones inserted, not the display values). carapace.ActionValues("apple", "melon", "orange").Suffix("juice") Suppress suppresses specific error messages using regular expressions. Tag sets the tag. ActionValues("192.168.1.1", "127.0.0.1").Tag("interfaces"). Tag sets the tag using a function. ActionValues("192.168.1.1", "127.0.0.1").TagF(func(value string) string { return "interfaces" }) Timeout sets the maximum duration an Action may take to invoke. carapace.ActionCallback(func(c carapace.Context) carapace.Action { time.Sleep(2*time.Second) return carapace.ActionValues("done") }).Timeout(1*time.Second, carapace.ActionMessage("timeout exceeded")) Uid TODO experimental UidF TODO experimental Unique ensures the Action only contains unique values. UniqueList wraps the Action in an ActionMultiParts with given divider. UniqueListF is like UniqueList but uses a function to transform values before filtering. Unless skips invocation if given condition is true. UnlessF skips invocation if given condition returns true. Usage sets the usage. Usage sets the usage using a function. func ActionCallback(callback CompletionCallback) Action func ActionCobra(f func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)) Action func ActionCommands(cmd *cobra.Command) Action func ActionDirectories() Action func ActionExecutables(dirs ...string) Action func ActionExecute(cmd *cobra.Command) Action func ActionFiles(suffix ...string) Action func ActionImport(output []byte) Action func ActionMessage(msg string, args ...any) Action func ActionMultiParts(sep string, callback func(c Context) Action) Action func ActionMultiPartsN(sep string, n int, callback func(c Context) Action) Action func ActionPositional(cmd *cobra.Command) Action func ActionStyleConfig() Action func ActionStyledValues(values ...string) Action func ActionStyledValuesDescribed(values ...string) Action func ActionStyles(styles ...string) Action func ActionValues(values ...string) Action func ActionValuesDescribed(values ...string) Action func Diff(original, new Action) Action func Action.Cache(timeout time.Duration, keys ...key.Key) Action func Action.Chdir(dir string) Action func Action.ChdirF(f func(tc pkgtraverse.Context) (string, error)) Action func Action.Escape() Action func Action.Filter(values ...string) Action func Action.FilterArgs() Action func Action.FilterParts() Action func Action.List(divider string) Action func Action.MultiParts(dividers ...string) Action func Action.MultiPartsP(delimiter string, pattern string, f func(placeholder string, matches map[string]string) Action) Action func Action.NoPrefix(prefixes ...rune) Action func Action.NoSpace(suffixes ...rune) Action func Action.Prefix(prefix string) Action func Action.Query(scheme, host, path string, opts ...string) Action func Action.QueryF(f func(s string, uc uid.Context) (*url.URL, error)) Action func Action.Quote() Action func Action.Retain(values ...string) Action func Action.Shift(n int) Action func Action.Split(formats ...shlex.Format) Action func Action.SplitP(formats ...shlex.Format) Action func Action.Style(s string) Action func Action.StyleF(f func(s string, sc style.Context) string) Action func Action.StyleR(s *string) Action func Action.Suffix(suffix string) Action func Action.Suppress(expr ...string) Action func Action.Tag(tag string) Action func Action.TagF(f func(s string) string) Action func Action.Timeout(d time.Duration, alternative Action) Action func Action.Uid(scheme, host string, opts ...string) Action func Action.UidF(f func(s string, uc uid.Context) (*url.URL, error)) Action func Action.Unique() Action func Action.UniqueList(divider string) Action func Action.UniqueListF(divider string, f func(s string) string) Action func Action.Unless(condition bool) Action func Action.UnlessF(condition func(c Context) bool) Action func Action.Usage(usage string, args ...any) Action func Action.UsageF(f func() string) Action func InvokedAction.ToA() Action func InvokedAction.ToMultiPartsA(dividers ...string) Action func Batch(actions ...Action) batch func Diff(original, new Action) Action func DiffPatch(original, new Action, c Context) []string func Action.Timeout(d time.Duration, alternative Action) Action func Carapace.DashAnyCompletion(action Action) func Carapace.DashCompletion(action ...Action) func Carapace.PositionalAnyCompletion(action Action) func Carapace.PositionalCompletion(action ...Action)
ActionMap maps Actions to an identifier. func Carapace.FlagCompletion(actions ActionMap)
Carapace wraps cobra.Command to define completions. DashAnyCompletion defines completion for any positional arguments after dash (`--`) not already defined. DashCompletion defines completion for positional arguments after dash (`--`) using a list of Actions. Execute intercepts os.Args for multi-completer routing and then calls cmd.Execute(). Call this instead of cmd.Execute(). For single completers (no WithSubcommands), this just calls cmd.Execute(). FlagCompletion defines completion for flags using a map consisting of name and Action. PositionalAnyCompletion defines completion for any positional arguments not already defined. PositionalCompletion defines completion for positional arguments using a list of Actions. PreInvoke sets a function to alter actions before they are invoked. PreRun sets a function to be run before completion. Snippet creates completion script for given shell. For multi-completers, produces a multi-completer snippet (all commands at once). For single completers, produces a standard single-command snippet. Standalone prevents cobra defaults interfering with standalone mode (e.g. implicit help command). func Gen(cmd *cobra.Command, opts ...Option) *Carapace
CompletionCallback is executed during completion of associated flag or positional argument. func ActionCallback(callback CompletionCallback) Action
Context provides information during completion. Args contains the positional arguments of current (sub)command (exclusive the one currently being completed). Dir contains the working directory for current context. Env contains environment variables for current context. Parts contains the splitted Value during an ActionMultiParts (exclusive the part currently being completed). Value contains the value currently being completed (or part of it during an ActionMultiParts). Abs returns an absolute representation of path. Command returns the Cmd struct to execute the named program with the given arguments. Env and Dir are set using the Context. See exec.Command for most details. Envsubst replaces ${var} in the string based on environment variables in current context. Getenv retrieves the value of the environment variable named by the key. LookupEnv retrieves the value of the environment variable named by the key. Setenv sets the value of the environment variable named by the key. Context : github.com/carapace-sh/carapace/pkg/style.Context Context : github.com/carapace-sh/carapace/pkg/traverse.Context Context : github.com/carapace-sh/carapace/pkg/uid.Context func NewContext(args ...string) Context func DiffPatch(original, new Action, c Context) []string func Action.Invoke(c Context) InvokedAction
InvokedAction is a logical alias for an Action whose (nested) callback was invoked. Escape escapes values so they can be embedded in a double-quoted string literal without adding surrounding quotes. Only the inserted values are modified; display values are left untouched. carapace.ActionValues(`say "hi"`).Invoke(c).Escape() Filter filters given values. a := carapace.ActionValues("A", "B", "C").Invoke(c) b := a.Filter([]string{"B"}) // ["A", "C"] ( InvokedAction) MarshalJSON() ([]byte, error) Merge merges InvokedActions (existing values are overwritten) a := carapace.ActionValues("A", "B").Invoke(c) b := carapace.ActionValues("B", "C").Invoke(c) c := a.Merge(b) // ["A", "B", "C"] Prefix adds a prefix to values (only the ones inserted, not the display values) carapace.ActionValues("melon", "drop", "fall").Invoke(c).Prefix("water") ( InvokedAction) QueryS(q string) InvokedAction Quote quotes values as double-quoted string literals. Only the inserted values are modified; display values are left untouched. carapace.ActionValues(`say "hi"`).Invoke(c).Quote() Retain retains given values. a := carapace.ActionValues("A", "B", "C").Invoke(c) b := a.Retain([]string{"A", "C"}) // ["A", "C"] Suffix adds a suffx to values (only the ones inserted, not the display values) carapace.ActionValues("apple", "melon", "orange").Invoke(c).Suffix("juice") ToA casts an InvokedAction to Action. ToMultiPartsA create an ActionMultiParts from values with given dividers a := carapace.ActionValues("A/B/C", "A/C", "B/C", "C").Invoke(c) b := a.ToMultiPartsA("/") // completes segments separately (first one is ["A/", "B/", "C"]) UidF TODO experimental InvokedAction : github.com/goccy/go-json.Marshaler InvokedAction : encoding/json/v2.Marshaler func Action.Invoke(c Context) InvokedAction func InvokedAction.Escape() InvokedAction func InvokedAction.Filter(values ...string) InvokedAction func InvokedAction.Merge(others ...InvokedAction) InvokedAction func InvokedAction.Prefix(prefix string) InvokedAction func InvokedAction.QueryS(q string) InvokedAction func InvokedAction.Quote() InvokedAction func InvokedAction.Retain(values ...string) InvokedAction func InvokedAction.Suffix(suffix string) InvokedAction func InvokedAction.UidF(f func(s string) (*url.URL, error)) InvokedAction func InvokedAction.Merge(others ...InvokedAction) InvokedAction
Option configures completion for a command. Options are applied to the storage entry keyed by the command, so successive Gen() calls on the same command accumulate. func WithDefault(name string) Option func WithSnippetFuncs(funcs map[string]string) Option func WithSubcommands(cmds ...*cobra.Command) Option func Gen(cmd *cobra.Command, opts ...Option) *Carapace
Package-Level Functions (total 30)
ActionCallback invokes a go function during completion.
ActionCora bridges given cobra completion function.
ActionCommands completes (sub)commands of given command. `Context.Args` is used to traverse the command tree further down. Use `Action.Shift` to avoid this. carapace.Gen(helpCmd).PositionalAnyCompletion( carapace.ActionCommands(rootCmd), )
ActionDirectories completes directories.
ActionExecCommand executes an external command. carapace.ActionExecCommand("git", "remote")(func(output []byte) carapace.Action { lines := strings.Split(string(output), "\n") return carapace.ActionValues(lines[:len(lines)-1]...) })
ActionExecCommandE is like ActionExecCommand but with custom error handling. carapace.ActionExecCommandE("supervisorctl", "--configuration", path, "status")(func(output []byte, err error) carapace.Action { if err != nil { const NOT_RUNNING = 3 if exitErr, ok := err.(*exec.ExitError); !ok || exitErr.ExitCode() != NOT_RUNNING { return carapace.ActionMessage(err.Error()) } } return carapace.ActionValues("success") })
ActionExecutables completes executables either from PATH or given directories nvim chmod
ActionExecute executes completion on an internal command TODO example.
ActionFiles completes files with optional suffix filtering.
ActionImport parses the json output from export as Action carapace.Gen(rootCmd).PositionalAnyCompletion( carapace.ActionCallback(func(c carapace.Context) carapace.Action { args := []string{"_carapace", "export", ""} args = append(args, c.Args...) args = append(args, c.Value) return carapace.ActionExecCommand("command", args...)(func(output []byte) carapace.Action { return carapace.ActionImport(output) }) }), )
ActionMessage displays a help messages in places where no completions can be generated.
ActionMultiParts completes parts of an argument separated by sep.
ActionMultiPartsN is like ActionMultiParts but limits the number of parts to `n`.
ActionPositional completes positional arguments for given command ignoring `--` (dash). TODO: experimental - likely gives issues with preinvoke (does not have the full args) carapace.Gen(cmd).DashAnyCompletion( carapace.ActionPositional(cmd), )
ActionStyleConfig completes style configuration carapace.Value=blue carapace.Description=magenta
ActionStyledValues is like ActionValues but also accepts a style.
ActionStyledValuesDescribed is like ActionValues but also accepts a style.
Actionstyles completes styles blue bg-magenta
ActionValues completes arbitrary keywords (values).
ActionValuesDescribed completes arbitrary key (values) with an additional description (value, description pairs).
Batch creates a batch of Actions that can be invoked in parallel.
Diff compares values of two actions. It overrides the style to hightlight changes. red: only present in original dim: present in both green: only present in new
TODO experimental - needs different signature TODO return patch format
Gen initializes Carapace for given command. Options configure snippet enrichment, multi-completer routing, etc.
IsCallback returns true if current program invocation is a callback.
NewContext creates a new context for given arguments.
Test verifies the configuration (e.g. flag name exists) func TestCarapace(t *testing.T) { carapace.Test(t) }
WithDefault sets the name used for the shell completer function in multi-completer snippets (e.g. _carapace_<name>_completer). Defaults to the executable name. No-op without WithSubcommands.
WithSnippetFuncs adds custom shell code to snippets. The map key is the shell name; the value is the code to inject. Multiple calls accumulate per shell in order.
WithSubcommands configures multi-completer support. The listed commands serve as independent completers within one binary. The binary name is automatically included as a pseudo-subcommand for self-completion. When set, Snippet() produces a multi-completer snippet and Execute() handles arg rewriting.
Package-Level Variables (only one)
var LOG *log.Logger